diff --git a/.circleci/config.yml b/.circleci/config.yml index 8c4869fb1..babe0bb39 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -148,8 +148,6 @@ jobs: steps: - checkout - yarn-install - - run: yarn codegen - - run: yarn build:ts - run: git diff --name-only --exit-code - run: yarn typecheck @@ -204,94 +202,6 @@ jobs: path: 'governance/cypress/cypress/videos' destination: 'videos' - liquidity-e2e: - parameters: - chainId: - type: integer - preset: - type: string - provider-url: - type: string - working_directory: /tmp/app - docker: - - image: cypress/included:<< pipeline.parameters.cypress-version >> - resource_class: large - environment: - NODE_ENV: test - CYPRESS_CHAIN_ID: << parameters.chainId >> - CYPRESS_PRESET: << parameters.preset >> - steps: - - checkout - - install-foundry - - yarn-install - - - run: - name: Run server localhost:3000 - working_directory: /tmp/app/liquidity/ui - command: yarn start - background: true - - - run: - name: Run anvil localhost:8545 - command: anvil --fork-url "<< parameters.provider-url >>" - background: true - - - run: - name: Wait for server localhost:3000 - command: wget --retry-connrefused --waitretry=20 --read-timeout=20 --timeout=15 -t 10 http://localhost:3000 - - - run: - name: Wait for anvil localhost:8545 - command: wget -q -O - --retry-connrefused --waitretry=20 --read-timeout=20 --timeout=15 -t 10 --post-data='{"method":"eth_chainId","params":[],"id":1,"jsonrpc":"2.0"}' --header='Content-Type:application/json' http://localhost:8545 - - - run: - working_directory: /tmp/app/liquidity/cypress - command: cypress run --e2e --browser chrome - - - store_test_results: - path: 'liquidity/cypress/cypress/reports' - - - store_artifacts: - path: 'liquidity/cypress/.nyc_output' - destination: 'coverage' - - - store_artifacts: - path: 'liquidity/cypress/cypress/screenshots' - destination: 'screenshots' - - - store_artifacts: - path: 'liquidity/cypress/cypress/videos' - destination: 'videos' - - liquidity-cy: - working_directory: /tmp/app - docker: - - image: cypress/included:<< pipeline.parameters.cypress-version >> - environment: - NODE_ENV: test - steps: - - checkout - - yarn-install - - - run: - working_directory: /tmp/app/liquidity/cypress - command: cypress run --component - - - store_test_results: - path: 'liquidity/cypress/cypress/reports' - - - store_artifacts: - path: 'liquidity/cypress/.nyc_output' - destination: 'coverage' - - - store_artifacts: - path: 'liquidity/cypress/cypress/screenshots' - destination: 'screenshots' - - - store_artifacts: - path: 'liquidity/cypress/cypress/videos' - destination: 'videos' - combine-coverage: working_directory: /tmp/app docker: @@ -301,10 +211,7 @@ jobs: - yarn-install - run: rm -rf /tmp/cov - run: yarn download-cci-coverage tests /tmp/cov || true - - run: yarn download-cci-coverage liquidity-cy /tmp/cov || true - # - run: yarn download-cci-coveragegovernance-cy /tmp/cov || true - - run: yarn download-cci-coverage liquidity-e2e-base-mainnet /tmp/cov || true - - run: yarn download-cci-coverage liquidity-e2e-optimism-mainnet /tmp/cov || true + # - run: yarn download-cci-coverage governance-cy /tmp/cov || true - run: mkdir -p /tmp/cov - run: ls -alR /tmp/cov - run: mkdir -p /tmp/cov/combined @@ -314,21 +221,6 @@ jobs: chmod +x codecov ./codecov -t ${CODECOV_TOKEN} --file /tmp/cov/combined/coverage.json - liquidity-ipfs: - working_directory: /tmp/app - docker: - - image: cimg/node:<< pipeline.parameters.node-version >> - resource_class: large - steps: - - checkout - - yarn-install - - run: yarn workspace @snx-v3/liquidity build - - ipfs-deploy: - source-dir: './liquidity/ui/dist' - ipfs-api: 'https://ipfs.synthetix.io:5001/api/v0' - ipfs-cluster-api: 'https://ipfs.synthetix.io/api/v0' - ipns-key: 'v3.synthetix.eth' - workflows: ui: unless: @@ -339,39 +231,7 @@ workflows: - checks - typecheck - tests - - liquidity-cy - governance-e2e: name: governance-e2e-snax-testnet - - liquidity-e2e: - name: liquidity-e2e-base-mainnet - chainId: 8453 - preset: andromeda - provider-url: https://base-mainnet.infura.io/v3/$INFURA_KEY - #- liquidity-e2e: - # name: liquidity-e2e-sepolia - # chainId: 11155111 - # preset: main - # provider-url: https://sepolia.infura.io/v3/$INFURA_KEY - combine-coverage: - requires: [ - tests, - liquidity-cy, - governance-e2e-snax-testnet, - liquidity-e2e-base-mainnet, - #liquidity-e2e-sepolia, - ] - - - liquidity-ipfs: - requires: - - checks - - typecheck - - tests - - liquidity-cy - - liquidity-e2e-base-mainnet - #- liquidity-e2e-sepolia - filters: - branches: - only: - - release - - master - - ipfs-deploy + requires: [tests, governance-e2e-snax-testnet] diff --git a/.eslintrc.js b/.eslintrc.js index 1d1661ba3..66c3bec89 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -47,13 +47,7 @@ module.exports = { overrides: [ { - files: [ - 'liquidity/ui/**/*', - 'liquidity/components/**/*', - 'liquidity/lib/**/*', - 'theme/**/*', - 'governance/ui/**/*', - ], + files: ['governance/ui/**/*', 'governance/components/**/*', 'governance/lib/**/*'], env: { browser: true, diff --git a/.github/workflows/release-liquidity.yml b/.github/workflows/release-liquidity.yml deleted file mode 100644 index 4528e7706..000000000 --- a/.github/workflows/release-liquidity.yml +++ /dev/null @@ -1,55 +0,0 @@ -name: release-liquidity - -on: - push: - tags: - - 'release-liquidity-*' - branches: - - 'liquidity-synthetix-eth' - - 'releases' - -jobs: - release-liquidity: - runs-on: ubuntu-latest - steps: - - run: git config --global user.email engineering@snxdao.io - - run: git config --global user.name synthetix-team - - - uses: actions/checkout@v4 - with: - path: liquidity - repository: 'Synthetixio/liquidity.synthetix.eth' - ref: 'master' - ssh-key: '${{ secrets.LIQUIDITY_SSH_KEY }}' - - - uses: actions/checkout@v4 - with: - path: v3ui - ref: '${{ github.sha }}' - ssh-key: '${{ secrets.V3UI_SSH_KEY }}' - - - run: yarn workspaces focus @snx-v3/liquidity - working-directory: v3ui - - - run: yarn workspace @snx-v3/liquidity build - working-directory: v3ui - - - run: rm -rf ./liquidity/* - - - run: git checkout HEAD -- CNAME || true - working-directory: liquidity - - - run: cp -r ./v3ui/liquidity/ui/dist/* ./liquidity/ - - - run: git add . - working-directory: liquidity - - - run: | - git commit -m "Release ${{ github.event.release.name }}" \ - --allow-empty \ - -m "Source: ${{ github.server_url}}/${{ github.repository }}" \ - -m "Commit: ${{ github.sha }}" - working-directory: liquidity - - - run: git push origin master - working-directory: liquidity diff --git a/babel.config.js b/babel.config.js index c913048c7..22224bd3c 100644 --- a/babel.config.js +++ b/babel.config.js @@ -12,17 +12,6 @@ module.exports = { }, ], ], - plugins: [ - [ - require.resolve('babel-plugin-module-resolver'), - { - root: ['.'], - alias: { - '@synthetixio/v3-theme': './theme/src', - }, - }, - ], - ], }, }, }; diff --git a/liquidity/components/Tooltip/Tooltip.tsx b/governance/components/Tooltip/Tooltip.tsx similarity index 100% rename from liquidity/components/Tooltip/Tooltip.tsx rename to governance/components/Tooltip/Tooltip.tsx diff --git a/liquidity/components/Tooltip/index.ts b/governance/components/Tooltip/index.ts similarity index 100% rename from liquidity/components/Tooltip/index.ts rename to governance/components/Tooltip/index.ts diff --git a/liquidity/components/Tooltip/package.json b/governance/components/Tooltip/package.json similarity index 100% rename from liquidity/components/Tooltip/package.json rename to governance/components/Tooltip/package.json diff --git a/liquidity/components/icons/ArbitrumIcon/ArbitrumIcon.tsx b/governance/components/icons/ArbitrumIcon/ArbitrumIcon.tsx similarity index 100% rename from liquidity/components/icons/ArbitrumIcon/ArbitrumIcon.tsx rename to governance/components/icons/ArbitrumIcon/ArbitrumIcon.tsx diff --git a/liquidity/components/icons/ArbitrumIcon/index.tsx b/governance/components/icons/ArbitrumIcon/index.tsx similarity index 100% rename from liquidity/components/icons/ArbitrumIcon/index.tsx rename to governance/components/icons/ArbitrumIcon/index.tsx diff --git a/liquidity/components/icons/ArrowLeft/ArrowLeft.tsx b/governance/components/icons/ArrowLeft/ArrowLeft.tsx similarity index 100% rename from liquidity/components/icons/ArrowLeft/ArrowLeft.tsx rename to governance/components/icons/ArrowLeft/ArrowLeft.tsx diff --git a/liquidity/components/icons/ArrowLeft/index.tsx b/governance/components/icons/ArrowLeft/index.tsx similarity index 100% rename from liquidity/components/icons/ArrowLeft/index.tsx rename to governance/components/icons/ArrowLeft/index.tsx diff --git a/liquidity/components/icons/BaseIcon/BaseIcon.tsx b/governance/components/icons/BaseIcon/BaseIcon.tsx similarity index 100% rename from liquidity/components/icons/BaseIcon/BaseIcon.tsx rename to governance/components/icons/BaseIcon/BaseIcon.tsx diff --git a/liquidity/components/icons/BaseIcon/index.ts b/governance/components/icons/BaseIcon/index.ts similarity index 100% rename from liquidity/components/icons/BaseIcon/index.ts rename to governance/components/icons/BaseIcon/index.ts diff --git a/liquidity/components/icons/BitcoinIcon/BitcoinIcon.tsx b/governance/components/icons/BitcoinIcon/BitcoinIcon.tsx similarity index 100% rename from liquidity/components/icons/BitcoinIcon/BitcoinIcon.tsx rename to governance/components/icons/BitcoinIcon/BitcoinIcon.tsx diff --git a/liquidity/components/icons/BitcoinIcon/index.tsx b/governance/components/icons/BitcoinIcon/index.tsx similarity index 100% rename from liquidity/components/icons/BitcoinIcon/index.tsx rename to governance/components/icons/BitcoinIcon/index.tsx diff --git a/liquidity/components/icons/BorrowIcon/BorrowIcon.tsx b/governance/components/icons/BorrowIcon/BorrowIcon.tsx similarity index 100% rename from liquidity/components/icons/BorrowIcon/BorrowIcon.tsx rename to governance/components/icons/BorrowIcon/BorrowIcon.tsx diff --git a/liquidity/components/icons/BorrowIcon/index.ts b/governance/components/icons/BorrowIcon/index.ts similarity index 100% rename from liquidity/components/icons/BorrowIcon/index.ts rename to governance/components/icons/BorrowIcon/index.ts diff --git a/liquidity/components/icons/CCIP/CCIP.tsx b/governance/components/icons/CCIP/CCIP.tsx similarity index 100% rename from liquidity/components/icons/CCIP/CCIP.tsx rename to governance/components/icons/CCIP/CCIP.tsx diff --git a/liquidity/components/icons/CCIP/index.ts b/governance/components/icons/CCIP/index.ts similarity index 100% rename from liquidity/components/icons/CCIP/index.ts rename to governance/components/icons/CCIP/index.ts diff --git a/liquidity/components/icons/ChevronDown/ChevronDown.tsx b/governance/components/icons/ChevronDown/ChevronDown.tsx similarity index 100% rename from liquidity/components/icons/ChevronDown/ChevronDown.tsx rename to governance/components/icons/ChevronDown/ChevronDown.tsx diff --git a/liquidity/components/icons/ChevronDown/index.ts b/governance/components/icons/ChevronDown/index.ts similarity index 100% rename from liquidity/components/icons/ChevronDown/index.ts rename to governance/components/icons/ChevronDown/index.ts diff --git a/liquidity/components/icons/ChevronUp/ChevronUp.tsx b/governance/components/icons/ChevronUp/ChevronUp.tsx similarity index 100% rename from liquidity/components/icons/ChevronUp/ChevronUp.tsx rename to governance/components/icons/ChevronUp/ChevronUp.tsx diff --git a/liquidity/components/icons/ChevronUp/index.ts b/governance/components/icons/ChevronUp/index.ts similarity index 100% rename from liquidity/components/icons/ChevronUp/index.ts rename to governance/components/icons/ChevronUp/index.ts diff --git a/liquidity/components/icons/CollateralIcon/CollateralIcon.tsx b/governance/components/icons/CollateralIcon/CollateralIcon.tsx similarity index 100% rename from liquidity/components/icons/CollateralIcon/CollateralIcon.tsx rename to governance/components/icons/CollateralIcon/CollateralIcon.tsx diff --git a/liquidity/components/icons/CollateralIcon/index.ts b/governance/components/icons/CollateralIcon/index.ts similarity index 100% rename from liquidity/components/icons/CollateralIcon/index.ts rename to governance/components/icons/CollateralIcon/index.ts diff --git a/liquidity/components/icons/DiscordIcon/DiscordIcon.tsx b/governance/components/icons/DiscordIcon/DiscordIcon.tsx similarity index 100% rename from liquidity/components/icons/DiscordIcon/DiscordIcon.tsx rename to governance/components/icons/DiscordIcon/DiscordIcon.tsx diff --git a/liquidity/components/icons/DiscordIcon/index.tsx b/governance/components/icons/DiscordIcon/index.tsx similarity index 100% rename from liquidity/components/icons/DiscordIcon/index.tsx rename to governance/components/icons/DiscordIcon/index.tsx diff --git a/liquidity/components/icons/DollarCircle/DollarCircle.tsx b/governance/components/icons/DollarCircle/DollarCircle.tsx similarity index 100% rename from liquidity/components/icons/DollarCircle/DollarCircle.tsx rename to governance/components/icons/DollarCircle/DollarCircle.tsx diff --git a/liquidity/components/icons/DollarCircle/index.ts b/governance/components/icons/DollarCircle/index.ts similarity index 100% rename from liquidity/components/icons/DollarCircle/index.ts rename to governance/components/icons/DollarCircle/index.ts diff --git a/liquidity/components/icons/EthereumIcon/EthereumIcon.tsx b/governance/components/icons/EthereumIcon/EthereumIcon.tsx similarity index 100% rename from liquidity/components/icons/EthereumIcon/EthereumIcon.tsx rename to governance/components/icons/EthereumIcon/EthereumIcon.tsx diff --git a/liquidity/components/icons/EthereumIcon/index.tsx b/governance/components/icons/EthereumIcon/index.tsx similarity index 100% rename from liquidity/components/icons/EthereumIcon/index.tsx rename to governance/components/icons/EthereumIcon/index.tsx diff --git a/liquidity/components/icons/FailedIcon/FailedIcon.tsx b/governance/components/icons/FailedIcon/FailedIcon.tsx similarity index 100% rename from liquidity/components/icons/FailedIcon/FailedIcon.tsx rename to governance/components/icons/FailedIcon/FailedIcon.tsx diff --git a/liquidity/components/icons/FailedIcon/index.ts b/governance/components/icons/FailedIcon/index.ts similarity index 100% rename from liquidity/components/icons/FailedIcon/index.ts rename to governance/components/icons/FailedIcon/index.ts diff --git a/liquidity/components/icons/GithubIcon/GithubIcon.tsx b/governance/components/icons/GithubIcon/GithubIcon.tsx similarity index 100% rename from liquidity/components/icons/GithubIcon/GithubIcon.tsx rename to governance/components/icons/GithubIcon/GithubIcon.tsx diff --git a/liquidity/components/icons/GithubIcon/index.tsx b/governance/components/icons/GithubIcon/index.tsx similarity index 100% rename from liquidity/components/icons/GithubIcon/index.tsx rename to governance/components/icons/GithubIcon/index.tsx diff --git a/liquidity/components/icons/Logo/Logo.tsx b/governance/components/icons/Logo/Logo.tsx similarity index 100% rename from liquidity/components/icons/Logo/Logo.tsx rename to governance/components/icons/Logo/Logo.tsx diff --git a/liquidity/components/icons/Logo/index.tsx b/governance/components/icons/Logo/index.tsx similarity index 100% rename from liquidity/components/icons/Logo/index.tsx rename to governance/components/icons/Logo/index.tsx diff --git a/liquidity/components/icons/LogoIcon/LogoIcon.tsx b/governance/components/icons/LogoIcon/LogoIcon.tsx similarity index 100% rename from liquidity/components/icons/LogoIcon/LogoIcon.tsx rename to governance/components/icons/LogoIcon/LogoIcon.tsx diff --git a/liquidity/components/icons/LogoIcon/index.ts b/governance/components/icons/LogoIcon/index.ts similarity index 100% rename from liquidity/components/icons/LogoIcon/index.ts rename to governance/components/icons/LogoIcon/index.ts diff --git a/liquidity/components/icons/OptimismIcon/OptimismIcon.tsx b/governance/components/icons/OptimismIcon/OptimismIcon.tsx similarity index 100% rename from liquidity/components/icons/OptimismIcon/OptimismIcon.tsx rename to governance/components/icons/OptimismIcon/OptimismIcon.tsx diff --git a/liquidity/components/icons/OptimismIcon/index.ts b/governance/components/icons/OptimismIcon/index.ts similarity index 100% rename from liquidity/components/icons/OptimismIcon/index.ts rename to governance/components/icons/OptimismIcon/index.ts diff --git a/liquidity/components/icons/SNXChainIcon/SNXChainIcon.tsx b/governance/components/icons/SNXChainIcon/SNXChainIcon.tsx similarity index 100% rename from liquidity/components/icons/SNXChainIcon/SNXChainIcon.tsx rename to governance/components/icons/SNXChainIcon/SNXChainIcon.tsx diff --git a/liquidity/components/icons/SNXChainIcon/index.tsx b/governance/components/icons/SNXChainIcon/index.tsx similarity index 100% rename from liquidity/components/icons/SNXChainIcon/index.tsx rename to governance/components/icons/SNXChainIcon/index.tsx diff --git a/liquidity/components/icons/SNXIcon/SNXIcon.tsx b/governance/components/icons/SNXIcon/SNXIcon.tsx similarity index 100% rename from liquidity/components/icons/SNXIcon/SNXIcon.tsx rename to governance/components/icons/SNXIcon/SNXIcon.tsx diff --git a/liquidity/components/icons/SNXIcon/index.tsx b/governance/components/icons/SNXIcon/index.tsx similarity index 100% rename from liquidity/components/icons/SNXIcon/index.tsx rename to governance/components/icons/SNXIcon/index.tsx diff --git a/liquidity/components/icons/SUSDCIcon/SUSDCIcon.tsx b/governance/components/icons/SUSDCIcon/SUSDCIcon.tsx similarity index 100% rename from liquidity/components/icons/SUSDCIcon/SUSDCIcon.tsx rename to governance/components/icons/SUSDCIcon/SUSDCIcon.tsx diff --git a/liquidity/components/icons/SUSDCIcon/index.tsx b/governance/components/icons/SUSDCIcon/index.tsx similarity index 100% rename from liquidity/components/icons/SUSDCIcon/index.tsx rename to governance/components/icons/SUSDCIcon/index.tsx diff --git a/liquidity/components/icons/Sparkles/Sparkles.tsx b/governance/components/icons/Sparkles/Sparkles.tsx similarity index 100% rename from liquidity/components/icons/Sparkles/Sparkles.tsx rename to governance/components/icons/Sparkles/Sparkles.tsx diff --git a/liquidity/components/icons/Sparkles/index.tsx b/governance/components/icons/Sparkles/index.tsx similarity index 100% rename from liquidity/components/icons/Sparkles/index.tsx rename to governance/components/icons/Sparkles/index.tsx diff --git a/liquidity/components/icons/WalletIcon/WalletIcon.tsx b/governance/components/icons/WalletIcon/WalletIcon.tsx similarity index 100% rename from liquidity/components/icons/WalletIcon/WalletIcon.tsx rename to governance/components/icons/WalletIcon/WalletIcon.tsx diff --git a/liquidity/components/icons/WalletIcon/index.ts b/governance/components/icons/WalletIcon/index.ts similarity index 100% rename from liquidity/components/icons/WalletIcon/index.ts rename to governance/components/icons/WalletIcon/index.ts diff --git a/liquidity/components/icons/WarpcastIcon/WarpcastIcon.tsx b/governance/components/icons/WarpcastIcon/WarpcastIcon.tsx similarity index 100% rename from liquidity/components/icons/WarpcastIcon/WarpcastIcon.tsx rename to governance/components/icons/WarpcastIcon/WarpcastIcon.tsx diff --git a/liquidity/components/icons/WarpcastIcon/index.tsx b/governance/components/icons/WarpcastIcon/index.tsx similarity index 100% rename from liquidity/components/icons/WarpcastIcon/index.tsx rename to governance/components/icons/WarpcastIcon/index.tsx diff --git a/liquidity/components/icons/XIcon/XIcon.tsx b/governance/components/icons/XIcon/XIcon.tsx similarity index 100% rename from liquidity/components/icons/XIcon/XIcon.tsx rename to governance/components/icons/XIcon/XIcon.tsx diff --git a/liquidity/components/icons/XIcon/index.tsx b/governance/components/icons/XIcon/index.tsx similarity index 100% rename from liquidity/components/icons/XIcon/index.tsx rename to governance/components/icons/XIcon/index.tsx diff --git a/liquidity/components/icons/YoutubeIcon/YoutubeIcon.tsx b/governance/components/icons/YoutubeIcon/YoutubeIcon.tsx similarity index 100% rename from liquidity/components/icons/YoutubeIcon/YoutubeIcon.tsx rename to governance/components/icons/YoutubeIcon/YoutubeIcon.tsx diff --git a/liquidity/components/icons/YoutubeIcon/index.tsx b/governance/components/icons/YoutubeIcon/index.tsx similarity index 100% rename from liquidity/components/icons/YoutubeIcon/index.tsx rename to governance/components/icons/YoutubeIcon/index.tsx diff --git a/liquidity/components/icons/index.ts b/governance/components/icons/index.ts similarity index 100% rename from liquidity/components/icons/index.ts rename to governance/components/icons/index.ts diff --git a/liquidity/components/icons/package.json b/governance/components/icons/package.json similarity index 100% rename from liquidity/components/icons/package.json rename to governance/components/icons/package.json diff --git a/governance/cypress/cypress/support/component.js b/governance/cypress/cypress/support/component.js index fb4515d97..5dcc30eb4 100644 --- a/governance/cypress/cypress/support/component.js +++ b/governance/cypress/cypress/support/component.js @@ -1,7 +1,7 @@ import { ChakraProvider } from '@chakra-ui/react'; import '@cypress/code-coverage/support'; -import { theme } from '@synthetixio/v3-theme'; +import { theme } from '@snx-v3/theme'; import { mount } from 'cypress/react18'; import { MemoryRouter } from 'react-router-dom'; diff --git a/governance/cypress/package.json b/governance/cypress/package.json index 94b198966..86866308e 100644 --- a/governance/cypress/package.json +++ b/governance/cypress/package.json @@ -11,7 +11,7 @@ "@chakra-ui/react": "^2.8.2", "@cypress/code-coverage": "^3.12.39", "@snx-cy/printBrowserLogs": "workspace:*", - "@synthetixio/v3-theme": "workspace:*", + "@snx-v3/theme": "workspace:*", "cypress": "13.11.0", "ethers": "^5.7.2", "react-router-dom": "^6.18.0", diff --git a/liquidity/lib/constants/constants.ts b/governance/lib/constants/constants.ts similarity index 100% rename from liquidity/lib/constants/constants.ts rename to governance/lib/constants/constants.ts diff --git a/liquidity/lib/constants/index.ts b/governance/lib/constants/index.ts similarity index 100% rename from liquidity/lib/constants/index.ts rename to governance/lib/constants/index.ts diff --git a/liquidity/lib/constants/package.json b/governance/lib/constants/package.json similarity index 100% rename from liquidity/lib/constants/package.json rename to governance/lib/constants/package.json diff --git a/liquidity/lib/format/currency.test.ts b/governance/lib/format/currency.test.ts similarity index 100% rename from liquidity/lib/format/currency.test.ts rename to governance/lib/format/currency.test.ts diff --git a/liquidity/lib/format/currency.ts b/governance/lib/format/currency.ts similarity index 100% rename from liquidity/lib/format/currency.ts rename to governance/lib/format/currency.ts diff --git a/liquidity/lib/format/format.test.ts b/governance/lib/format/format.test.ts similarity index 100% rename from liquidity/lib/format/format.test.ts rename to governance/lib/format/format.test.ts diff --git a/liquidity/lib/format/format.ts b/governance/lib/format/format.ts similarity index 100% rename from liquidity/lib/format/format.ts rename to governance/lib/format/format.ts diff --git a/liquidity/lib/format/index.ts b/governance/lib/format/index.ts similarity index 100% rename from liquidity/lib/format/index.ts rename to governance/lib/format/index.ts diff --git a/liquidity/lib/format/package.json b/governance/lib/format/package.json similarity index 100% rename from liquidity/lib/format/package.json rename to governance/lib/format/package.json diff --git a/liquidity/lib/formatters/date.test.ts b/governance/lib/formatters/date.test.ts similarity index 100% rename from liquidity/lib/formatters/date.test.ts rename to governance/lib/formatters/date.test.ts diff --git a/liquidity/lib/formatters/date.ts b/governance/lib/formatters/date.ts similarity index 100% rename from liquidity/lib/formatters/date.ts rename to governance/lib/formatters/date.ts diff --git a/liquidity/lib/formatters/index.ts b/governance/lib/formatters/index.ts similarity index 100% rename from liquidity/lib/formatters/index.ts rename to governance/lib/formatters/index.ts diff --git a/liquidity/lib/formatters/number.test.ts b/governance/lib/formatters/number.test.ts similarity index 100% rename from liquidity/lib/formatters/number.test.ts rename to governance/lib/formatters/number.test.ts diff --git a/liquidity/lib/formatters/number.ts b/governance/lib/formatters/number.ts similarity index 100% rename from liquidity/lib/formatters/number.ts rename to governance/lib/formatters/number.ts diff --git a/liquidity/lib/formatters/package.json b/governance/lib/formatters/package.json similarity index 100% rename from liquidity/lib/formatters/package.json rename to governance/lib/formatters/package.json diff --git a/liquidity/lib/formatters/string.test.ts b/governance/lib/formatters/string.test.ts similarity index 100% rename from liquidity/lib/formatters/string.test.ts rename to governance/lib/formatters/string.test.ts diff --git a/liquidity/lib/formatters/string.ts b/governance/lib/formatters/string.ts similarity index 100% rename from liquidity/lib/formatters/string.ts rename to governance/lib/formatters/string.ts diff --git a/theme/README.md b/governance/lib/theme/README.md similarity index 100% rename from theme/README.md rename to governance/lib/theme/README.md diff --git a/theme/src/fonts.tsx b/governance/lib/theme/fonts.tsx similarity index 100% rename from theme/src/fonts.tsx rename to governance/lib/theme/fonts.tsx diff --git a/theme/src/index.ts b/governance/lib/theme/index.ts similarity index 100% rename from theme/src/index.ts rename to governance/lib/theme/index.ts diff --git a/governance/lib/theme/package.json b/governance/lib/theme/package.json new file mode 100644 index 000000000..6a086e0c1 --- /dev/null +++ b/governance/lib/theme/package.json @@ -0,0 +1,15 @@ +{ + "name": "@snx-v3/theme", + "private": true, + "main": "index.ts", + "version": "0.0.1", + "dependencies": { + "@chakra-ui/react": "^2.8.2", + "@chakra-ui/theme-tools": "^2.1.2", + "@emotion/react": "^11.11.1", + "@emotion/styled": "^11.11.0", + "framer-motion": "^10.16.5", + "react": "^18.2.0", + "react-dom": "^18.2.0" + } +} diff --git a/theme/src/theme.ts b/governance/lib/theme/theme.ts similarity index 100% rename from theme/src/theme.ts rename to governance/lib/theme/theme.ts diff --git a/liquidity/lib/useBlockchain/SynthetixIcon.svg b/governance/lib/useBlockchain/SynthetixIcon.svg similarity index 100% rename from liquidity/lib/useBlockchain/SynthetixIcon.svg rename to governance/lib/useBlockchain/SynthetixIcon.svg diff --git a/liquidity/lib/useBlockchain/SynthetixLogo.svg b/governance/lib/useBlockchain/SynthetixLogo.svg similarity index 100% rename from liquidity/lib/useBlockchain/SynthetixLogo.svg rename to governance/lib/useBlockchain/SynthetixLogo.svg diff --git a/liquidity/lib/useBlockchain/index.ts b/governance/lib/useBlockchain/index.ts similarity index 100% rename from liquidity/lib/useBlockchain/index.ts rename to governance/lib/useBlockchain/index.ts diff --git a/liquidity/lib/useBlockchain/package.json b/governance/lib/useBlockchain/package.json similarity index 100% rename from liquidity/lib/useBlockchain/package.json rename to governance/lib/useBlockchain/package.json diff --git a/liquidity/lib/useBlockchain/useBlockchain.tsx b/governance/lib/useBlockchain/useBlockchain.tsx similarity index 100% rename from liquidity/lib/useBlockchain/useBlockchain.tsx rename to governance/lib/useBlockchain/useBlockchain.tsx diff --git a/governance/ui/babel.config.js b/governance/ui/babel.config.js index ce060d101..45897ed2d 100644 --- a/governance/ui/babel.config.js +++ b/governance/ui/babel.config.js @@ -57,7 +57,7 @@ module.exports = { cwd: path.resolve('../..'), all: true, excludeNodeModules: false, - include: ['liquidity', 'theme', 'governance'], + include: ['governance'], exclude: ['**/*.test.*', '**/*.cy.*', '**/*.e2e.*'], }, 'istanbul', diff --git a/liquidity/ui/custom.d.ts b/governance/ui/custom.d.ts similarity index 100% rename from liquidity/ui/custom.d.ts rename to governance/ui/custom.d.ts diff --git a/governance/ui/package.json b/governance/ui/package.json index 311e8eff3..54603ce56 100644 --- a/governance/ui/package.json +++ b/governance/ui/package.json @@ -18,9 +18,10 @@ "@snx-v3/format": "workspace:*", "@snx-v3/formatters": "workspace:*", "@snx-v3/icons": "workspace:*", + "@snx-v3/theme": "workspace:*", "@snx-v3/useBlockchain": "workspace:*", - "@synthetixio/v3-theme": "workspace:*", "@tanstack/react-query": "^5.8.3", + "@types/react-helmet": "^6.1.9", "@web3-onboard/coinbase": "^2.4.1", "@web3-onboard/gnosis": "^2.3.1", "@web3-onboard/injected-wallets": "^2.11.1", diff --git a/governance/ui/src/pages/index.tsx b/governance/ui/src/pages/index.tsx index 5b9b46128..803551a6a 100644 --- a/governance/ui/src/pages/index.tsx +++ b/governance/ui/src/pages/index.tsx @@ -3,7 +3,7 @@ import { createRoot } from 'react-dom/client'; import App from './App'; import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; import { ChakraProvider, extendTheme } from '@chakra-ui/react'; -import { theme, Fonts } from '@synthetixio/v3-theme'; +import { theme, Fonts } from '@snx-v3/theme'; import { RouterProvider, Navigate, createHashRouter } from 'react-router-dom'; import { RecoilRoot } from 'recoil'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; diff --git a/governance/ui/webpack.config.js b/governance/ui/webpack.config.js index e3636b5c4..216dd40fc 100644 --- a/governance/ui/webpack.config.js +++ b/governance/ui/webpack.config.js @@ -27,11 +27,10 @@ const babelRule = { include: [ // Need to list all the folders in v3 and outside (if used) /contracts/, - /theme/, - /liquidity\/lib/, - /liquidity\/components/, /governance\/cypress/, + /governance\/components/, + /governance\/lib/, /governance\/ui/, // fixes for borked 3rd party bundles @@ -145,13 +144,6 @@ module.exports = { new webpack.NormalModuleReplacementPlugin(/^bn.js$/, require.resolve('bn.js')), ]) - .concat([ - new webpack.NormalModuleReplacementPlugin( - new RegExp(`^@synthetixio/v3-theme$`), - path.resolve(path.dirname(require.resolve(`@synthetixio/v3-theme/package.json`)), 'src') - ), - ]) - .concat([ new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'], diff --git a/liquidity/components/AccountNav/AccountNav.tsx b/liquidity/components/AccountNav/AccountNav.tsx deleted file mode 100644 index 362d21664..000000000 --- a/liquidity/components/AccountNav/AccountNav.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import { ChevronLeftIcon, SettingsIcon } from '@chakra-ui/icons'; -import { Flex, Link } from '@chakra-ui/react'; -import { useParams } from '@snx-v3/useParams'; -import { generatePath, Link as RouterLink, useMatch, useLocation } from 'react-router-dom'; - -export function AccountNav() { - const params = useParams(); - const innerPage = !useMatch('/'); - const location = useLocation(); - - return ( - - {innerPage ? ( - - Account Overview - - ) : null} - - {!innerPage && params.accountId ? ( - - -   Account Settings - - ) : null} - - ); -} diff --git a/liquidity/components/AccountNav/index.ts b/liquidity/components/AccountNav/index.ts deleted file mode 100644 index 116c18f6f..000000000 --- a/liquidity/components/AccountNav/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './AccountNav'; diff --git a/liquidity/components/AccountNav/package.json b/liquidity/components/AccountNav/package.json deleted file mode 100644 index e26cacc5f..000000000 --- a/liquidity/components/AccountNav/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/AccountNav", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/icons": "^2.1.1", - "@chakra-ui/react": "^2.8.2", - "@snx-v3/useParams": "workspace:*", - "react": "^18.2.0", - "react-router-dom": "^6.18.0" - } -} diff --git a/liquidity/components/AccountsSelector/AccountsSelector.tsx b/liquidity/components/AccountsSelector/AccountsSelector.tsx deleted file mode 100644 index f49046131..000000000 --- a/liquidity/components/AccountsSelector/AccountsSelector.tsx +++ /dev/null @@ -1,167 +0,0 @@ -import { - Button, - Fade, - Menu, - MenuList, - Skeleton, - Text, - useClipboard, - MenuItem, - Flex, - MenuButton, -} from '@chakra-ui/react'; -import { - createSearchParams, - generatePath, - Link as RouterLink, - useLocation, - useNavigate, -} from 'react-router-dom'; -import { prettyString } from '@snx-v3/format'; -import { useAccounts, useCreateAccount } from '@snx-v3/useAccounts'; -import { useParams } from '@snx-v3/useParams'; -import { CheckIcon } from '@snx-v3/Multistep'; -import { useEffect } from 'react'; - -function AccountMenuItem({ accountId }: { accountId: string }) { - const params = useParams(); - - return ( - - - - {params.accountId === accountId && } - {accountId} - - - - ); -} - -interface AccountsSelectorUiProps { - isLoading: boolean; - accountId?: string; - createAccount: () => void; - accounts?: string[] | undefined; -} - -export function AccountsSelectorUi({ - accountId, - isLoading, - createAccount, - accounts, -}: AccountsSelectorUiProps) { - const { onCopy } = useClipboard(accountId || ''); - - return ( - <> - - {isLoading ? ( - - Loading... - - ) : ( - - - {`${accountId ? `Account #${prettyString(accountId, 3, 3)}` : 'Create Account'} `} - - - )} - - {!!accounts?.length && ( - - {accounts?.map((accountId) => ( - - ))} - - - - Create new account - - - - )} - - - ); -} - -export function AccountsSelector() { - const params = useParams(); - - const { - data: accounts, - isLoading: isAccountsLoading, - isFetching: isAccountsFetching, - } = useAccounts(); - - const { - mutation: { mutate: createAccount, isPending: isCreateAccountLoading, data: createAccountData }, - } = useCreateAccount(); - - const navigate = useNavigate(); - const location = useLocation(); - - const isLoading = isAccountsLoading || isAccountsFetching || isCreateAccountLoading || !accounts; - - useEffect(() => { - // If we create an account, use it - // If the account in params exists in the accounts list, use it - // If not use the first account in the list - // If there are no accounts, use undefined - const accountId = createAccountData - ? createAccountData[0] - : accounts?.includes(params?.accountId || '') - ? params.accountId - : accounts?.[0]; - - const queryParams = new URLSearchParams(location.search); - - if (accountId) { - queryParams.set('accountId', accountId); - } - - navigate( - { - pathname: location.pathname, - search: queryParams.toString(), - }, - { replace: true } - ); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [createAccountData]); - - return ( - - ); -} diff --git a/liquidity/components/Amount/Amount.tsx b/liquidity/components/Amount/Amount.tsx deleted file mode 100644 index abd0b981a..000000000 --- a/liquidity/components/Amount/Amount.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import { useMemo } from 'react'; -import { currency } from '@snx-v3/format'; -import Wei, { wei } from '@synthetixio/wei'; -import { constants } from 'ethers'; -import { Tooltip } from '@snx-v3/Tooltip'; - -export function Amount({ - value, - prefix = '', - suffix = '', - 'data-testid': testid, - showTooltip, -}: { - prefix?: string; - value?: Wei; - suffix?: string; - 'data-testid'?: string; - showTooltip?: boolean; -}) { - const { formattedValue, preciseValue, isMaxUint } = useMemo(() => { - if (!value) { - return { formattedValue: '-', preciseValue: '-' }; - } - - const formattedValue = value.eq(0) ? '0.00' : currency(value); - const cleanNumber = wei(formattedValue.replaceAll(',', '')); - - return { - isMaxUint: wei(constants.MaxInt256).lte(value), - formattedValue, - preciseValue: value.eq(cleanNumber) ? formattedValue : value.toString(), - }; - }, [value]); - - return ( - - {isMaxUint ? ( - 'You cannot borrow sUSD against this collateral' - ) : ( - <> - {prefix} - {preciseValue} - {suffix} - - )} - - } - isDisabled={formattedValue === preciseValue || !showTooltip} - > - - {prefix} - {isMaxUint ? 'Infinite' : formattedValue} - {!isMaxUint && suffix} - - - ); -} diff --git a/liquidity/components/Amount/index.ts b/liquidity/components/Amount/index.ts deleted file mode 100644 index 84dda3664..000000000 --- a/liquidity/components/Amount/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './Amount'; diff --git a/liquidity/components/Amount/package.json b/liquidity/components/Amount/package.json deleted file mode 100644 index f39b897ee..000000000 --- a/liquidity/components/Amount/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/Amount", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/Tooltip": "workspace:*", - "@snx-v3/format": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/components/Balance/Balance.tsx b/liquidity/components/Balance/Balance.tsx deleted file mode 100644 index 90bc910db..000000000 --- a/liquidity/components/Balance/Balance.tsx +++ /dev/null @@ -1,54 +0,0 @@ -import { Badge, Link, Text } from '@chakra-ui/react'; -import { useMemo } from 'react'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { Amount } from '@snx-v3/Amount'; -import Wei from '@synthetixio/wei'; - -export function Balance({ - balance, - symbol, - address, - onMax, - hideBuyButton, -}: { - balance?: Wei; - symbol: string; - address: string; - onMax?: (balance: Wei) => void; - hideBuyButton?: boolean; -}) { - const { network } = useNetwork(); - const buyAssetLink = useMemo(() => { - switch (network?.name) { - case 'goerli': - return `https://goerli.etherscan.io/address/${address}#writeContract`; - case 'sepolia': - return `https://sepolia.etherscan.io/address/${address}#writeContract`; - case 'optimism-goerli': - return `https://goerli-optimism.etherscan.io/address/${address}#writeContract`; - case 'optimism': - return `https://app.1inch.io/#/10/unified/swap/ETH/${symbol.toUpperCase()}`; - default: - return `https://app.1inch.io/#/1/unified/swap/ETH/${symbol.toUpperCase()}`; - } - }, [address, network?.name, symbol]); - - return ( - - Balance: - - {balance && balance.eq(0) && buyAssetLink && !hideBuyButton && ( - - - Buy {symbol} - - - )} - {onMax && balance?.gt(0) && ( - onMax(balance)}> - Use Max - - )} - - ); -} diff --git a/liquidity/components/Balance/index.ts b/liquidity/components/Balance/index.ts deleted file mode 100644 index de9bb0894..000000000 --- a/liquidity/components/Balance/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './Balance'; diff --git a/liquidity/components/Balance/package.json b/liquidity/components/Balance/package.json deleted file mode 100644 index cf59af174..000000000 --- a/liquidity/components/Balance/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/Balance", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/react": "^2.8.2", - "@snx-v3/Amount": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "react": "^18.2.0" - } -} diff --git a/liquidity/components/BorderBox/BorderBox.tsx b/liquidity/components/BorderBox/BorderBox.tsx deleted file mode 100644 index 6cd00ac5b..000000000 --- a/liquidity/components/BorderBox/BorderBox.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { Flex, FlexProps } from '@chakra-ui/react'; - -export const BorderBox = (props: FlexProps) => ( - -); diff --git a/liquidity/components/BorderBox/index.ts b/liquidity/components/BorderBox/index.ts deleted file mode 100644 index 3e1db6abd..000000000 --- a/liquidity/components/BorderBox/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './BorderBox'; diff --git a/liquidity/components/BorderBox/package.json b/liquidity/components/BorderBox/package.json deleted file mode 100644 index d72236c22..000000000 --- a/liquidity/components/BorderBox/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "@snx-v3/BorderBox", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/react": "^2.8.2" - } -} diff --git a/liquidity/components/BorrowModal/BorrowModal.tsx b/liquidity/components/BorrowModal/BorrowModal.tsx deleted file mode 100644 index 885f69e3c..000000000 --- a/liquidity/components/BorrowModal/BorrowModal.tsx +++ /dev/null @@ -1,199 +0,0 @@ -import { Button, Divider, Text, useToast, Link, Flex, Skeleton } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import Wei from '@synthetixio/wei'; -import { TransactionStatus } from '@snx-v3/txnReducer'; -import { Multistep } from '@snx-v3/Multistep'; -import { useCallback, useContext } from 'react'; -import { useParams } from '@snx-v3/useParams'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useContractErrorParser } from '@snx-v3/useContractErrorParser'; -import { ContractError } from '@snx-v3/ContractError'; -import { useQueryClient } from '@tanstack/react-query'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useBorrow } from '@snx-v3/useBorrow'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ArrowBackIcon } from '@chakra-ui/icons'; -import { LiquidityPositionUpdated } from '../../ui/src/components/Manage/LiquidityPositionUpdated'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { ZEROWEI } from '@snx-v3/constants'; - -export const BorrowModalUi: React.FC<{ - onClose: () => void; - debtChange: Wei; - isOpen: boolean; - txnStatus: TransactionStatus; - execBorrow: () => void; -}> = ({ onClose, isOpen, debtChange, txnStatus, execBorrow }) => { - const { network } = useNetwork(); - const isBase = isBaseAndromeda(network?.id, network?.preset); - - const { data: systemToken } = useSystemToken(); - - if (isOpen) { - if (txnStatus === 'success') { - return ( - - Your Debt has been updated, read more about it in the{' '} - - Synthetix V3 Documentation - - - } - alertText={ - <> - Debt successfully Updated - - } - /> - ); - } - - return ( -
- - - Manage Debt - - - - - - {isBase ? 'Claim' : 'Borrow'}{' '} - - - } - status={{ - failed: txnStatus === 'error', - loading: ['prompting', 'pending'].includes(txnStatus), - }} - /> - - -
- ); - } -}; - -export const BorrowModal: React.FC<{ - onClose: () => void; - isOpen: boolean; -}> = ({ onClose, isOpen }) => { - const { debtChange, setDebtChange } = useContext(ManagePositionContext); - const queryClient = useQueryClient(); - const params = useParams(); - const { data: collateralType } = useCollateralType(params.collateralSymbol); - - const { - exec: execBorrow, - txnState, - settle: settleBorrow, - } = useBorrow({ - accountId: params.accountId, - poolId: params.poolId, - collateralTypeAddress: collateralType?.tokenAddress, - debtChange, - }); - - const toast = useToast({ isClosable: true, duration: 9000 }); - const { data: CoreProxy } = useCoreProxy(); - const { network } = useNetwork(); - - const errorParserCoreProxy = useContractErrorParser(CoreProxy); - - const execBorrowWithErrorParser = useCallback(async () => { - try { - await execBorrow(); - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPosition'], - exact: false, - }); - setDebtChange(ZEROWEI); - } catch (error: any) { - const contractError = errorParserCoreProxy(error); - if (contractError) { - console.error(new Error(contractError.name), contractError); - } - toast.closeAll(); - toast({ - title: 'Borrow failed', - description: contractError ? ( - - ) : ( - 'Please try again.' - ), - status: 'error', - variant: 'left-accent', - }); - throw Error('Borrow failed', { cause: error }); - } - }, [ - execBorrow, - queryClient, - network?.id, - network?.preset, - setDebtChange, - errorParserCoreProxy, - toast, - ]); - - const { txnStatus } = txnState; - - if (!params.poolId || !params.accountId || !collateralType) - return ( - - - - - - - ); - - return ( - { - settleBorrow(); - onClose(); - }} - isOpen={isOpen} - /> - ); -}; diff --git a/liquidity/components/BorrowModal/index.ts b/liquidity/components/BorrowModal/index.ts deleted file mode 100644 index 38a7e9f90..000000000 --- a/liquidity/components/BorrowModal/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { BorrowModal } from './BorrowModal'; -export * from './BorrowModal'; -export default BorrowModal; diff --git a/liquidity/components/BorrowModal/package.json b/liquidity/components/BorrowModal/package.json deleted file mode 100644 index 4369a7b9a..000000000 --- a/liquidity/components/BorrowModal/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "@snx-v3/BorrowModal", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/icons": "^2.1.1", - "@chakra-ui/react": "^2.8.2", - "@snx-v3/Amount": "workspace:*", - "@snx-v3/ContractError": "workspace:*", - "@snx-v3/ManagePositionContext": "workspace:*", - "@snx-v3/Multistep": "workspace:*", - "@snx-v3/constants": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useBorrow": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useContractErrorParser": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useParams": "workspace:*", - "@snx-v3/useSystemToken": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/components/ClaimModal/ClaimModal.tsx b/liquidity/components/ClaimModal/ClaimModal.tsx deleted file mode 100644 index 46fabfc39..000000000 --- a/liquidity/components/ClaimModal/ClaimModal.tsx +++ /dev/null @@ -1,223 +0,0 @@ -import { Button, Divider, Text, useToast, Link, Flex, Skeleton } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import Wei, { wei } from '@synthetixio/wei'; -import { TransactionStatus } from '@snx-v3/txnReducer'; -import { Multistep } from '@snx-v3/Multistep'; -import { useCallback, useContext, useMemo } from 'react'; -import { useParams } from '@snx-v3/useParams'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useContractErrorParser } from '@snx-v3/useContractErrorParser'; -import { ContractError } from '@snx-v3/ContractError'; -import { useQueryClient } from '@tanstack/react-query'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useBorrow } from '@snx-v3/useBorrow'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ArrowBackIcon } from '@chakra-ui/icons'; -import { LiquidityPositionUpdated } from '../../ui/src/components/Manage/LiquidityPositionUpdated'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { ZEROWEI } from '@snx-v3/constants'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; - -export const ClaimModalUi: React.FC<{ - onClose: () => void; - debtChange: Wei; - isOpen: boolean; - txnStatus: TransactionStatus; - execBorrow: () => void; - symbol: string; -}> = ({ symbol, onClose, isOpen, debtChange, txnStatus, execBorrow }) => { - const { network } = useNetwork(); - const isBase = isBaseAndromeda(network?.id, network?.preset); - - if (isOpen) { - if (txnStatus === 'success') { - return ( - - Your Debt has been updated, read more about it in the{' '} - - Synthetix V3 Documentation - - - } - alertText={ - <> - Debt successfully Updated - - } - /> - ); - } - - return ( -
- - - Manage Debt - - - - - - {isBase ? 'Claim' : 'Borrow'} - - - } - status={{ - failed: txnStatus === 'error', - loading: ['prompting', 'pending'].includes(txnStatus), - }} - /> - - -
- ); - } -}; - -export const ClaimModal: React.FC<{ - onClose: () => void; - isOpen: boolean; - liquidityPosition?: LiquidityPosition; -}> = ({ onClose, isOpen, liquidityPosition }) => { - const { debtChange, setDebtChange } = useContext(ManagePositionContext); - const queryClient = useQueryClient(); - const params = useParams(); - const { network } = useNetwork(); - const isBase = isBaseAndromeda(network?.id, network?.preset); - const { data: collateralType } = useCollateralType(params.collateralSymbol); - const { data: systemToken } = useSystemToken(); - - const maxClaimble = useMemo(() => { - if (!liquidityPosition || liquidityPosition?.debt.gte(0)) { - return ZEROWEI; - } else { - return wei(liquidityPosition.debt.abs().toBN().sub(1)); - } - }, [liquidityPosition]); - const isBorrow = useMemo( - () => debtChange.gt(maxClaimble) && !isBase, - [debtChange, isBase, maxClaimble] - ); - - const { - exec: execBorrow, - txnState, - settle: settleBorrow, - } = useBorrow({ - accountId: params.accountId, - poolId: params.poolId, - collateralTypeAddress: collateralType?.tokenAddress, - debtChange, - }); - - const toast = useToast({ isClosable: true, duration: 9000 }); - const { data: CoreProxy } = useCoreProxy(); - const errorParserCoreProxy = useContractErrorParser(CoreProxy); - const execBorrowWithErrorParser = useCallback(async () => { - try { - await execBorrow(); - - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPosition'], - exact: false, - }); - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'TokenBalance'], - }); - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'AccountCollateralUnlockDate'], - }); - - setDebtChange(ZEROWEI); - } catch (error: any) { - const contractError = errorParserCoreProxy(error); - if (contractError) { - console.error(new Error(contractError.name), contractError); - } - - toast.closeAll(); - toast({ - title: isBorrow ? 'Borrow' : 'Claim' + ' failed', - description: contractError ? ( - - ) : ( - 'Please try again.' - ), - status: 'error', - variant: 'left-accent', - }); - throw Error(isBorrow ? 'Borrow' : 'Claim' + ' failed', { cause: error }); - } - }, [ - execBorrow, - queryClient, - network?.id, - network?.preset, - setDebtChange, - errorParserCoreProxy, - toast, - isBorrow, - ]); - - const { txnStatus } = txnState; - - if (!(params.poolId && params.accountId && collateralType && systemToken)) - return ( - - - - - - - ); - - return ( - { - settleBorrow(); - onClose(); - }} - isOpen={isOpen} - symbol={isBase ? collateralType.symbol : systemToken.symbol} - /> - ); -}; diff --git a/liquidity/components/ClaimModal/index.ts b/liquidity/components/ClaimModal/index.ts deleted file mode 100644 index 50b10a59a..000000000 --- a/liquidity/components/ClaimModal/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { ClaimModal } from './ClaimModal'; -export * from './ClaimModal'; -export default ClaimModal; diff --git a/liquidity/components/ClaimModal/package.json b/liquidity/components/ClaimModal/package.json deleted file mode 100644 index 20e1c6103..000000000 --- a/liquidity/components/ClaimModal/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "@snx-v3/ClaimModal", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/icons": "^2.1.1", - "@chakra-ui/react": "^2.8.2", - "@snx-v3/Amount": "workspace:*", - "@snx-v3/ContractError": "workspace:*", - "@snx-v3/ManagePositionContext": "workspace:*", - "@snx-v3/Multistep": "workspace:*", - "@snx-v3/constants": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useBorrow": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useContractErrorParser": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useLiquidityPosition": "workspace:*", - "@snx-v3/useParams": "workspace:*", - "@snx-v3/useSystemToken": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/components/CollateralTypeSelector/CollateralTypeSelector.tsx b/liquidity/components/CollateralTypeSelector/CollateralTypeSelector.tsx deleted file mode 100644 index 7f5dae283..000000000 --- a/liquidity/components/CollateralTypeSelector/CollateralTypeSelector.tsx +++ /dev/null @@ -1,84 +0,0 @@ -import { ChevronDownIcon } from '@chakra-ui/icons'; -import { Flex, Menu, MenuButton, MenuItem, MenuList, Text } from '@chakra-ui/react'; -import { CollateralType, useCollateralType, useCollateralTypes } from '@snx-v3/useCollateralTypes'; -import { CollateralIcon } from '@snx-v3/icons'; -import { FC } from 'react'; - -export const CollateralTypeSelectorUI: FC<{ - collateralTypes: CollateralType[]; - collateralType?: CollateralType; - onChange: (collateralSymbol: string) => void; -}> = ({ collateralTypes, collateralType, onChange }) => { - return ( - - - - {collateralType ? ( - <> - - - {collateralType.displaySymbol} - - - ) : null} - - - - - {collateralTypes.map((collateral) => ( - onChange(collateral.symbol)} - > - - - - {collateral?.displaySymbol} - - - - ))} - - - ); -}; - -export type CollateralTypeSelectorProps = FC<{ - collateralSymbol?: string; - onChange: (collateralSymbol: string) => void; -}>; - -export const CollateralTypeSelector: CollateralTypeSelectorProps = ({ - collateralSymbol, - onChange, -}) => { - const { data: collateralTypes = [] } = useCollateralTypes(); - const { data: collateralType } = useCollateralType(collateralSymbol); - - return ( - - ); -}; diff --git a/liquidity/components/CollateralTypeSelector/index.ts b/liquidity/components/CollateralTypeSelector/index.ts deleted file mode 100644 index 9644015ad..000000000 --- a/liquidity/components/CollateralTypeSelector/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './CollateralTypeSelector'; diff --git a/liquidity/components/CollateralTypeSelector/package.json b/liquidity/components/CollateralTypeSelector/package.json deleted file mode 100644 index e010eb75f..000000000 --- a/liquidity/components/CollateralTypeSelector/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/CollateralTypeSelector", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/icons": "^2.1.1", - "@chakra-ui/react": "^2.8.2", - "@snx-v3/icons": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "react": "^18.2.0" - } -} diff --git a/liquidity/components/ContractError/ContractError.tsx b/liquidity/components/ContractError/ContractError.tsx deleted file mode 100644 index ee4c9d4f9..000000000 --- a/liquidity/components/ContractError/ContractError.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import React from 'react'; -import { Button, Collapse, Text } from '@chakra-ui/react'; -import format from 'date-fns/format'; -import { ContractErrorType } from '@snx-v3/useContractErrorParser'; - -const defaultOpen = window?.localStorage?.CONTRACT_ERROR_OPEN === 'true'; - -export function ContractError({ contractError }: { contractError: ContractErrorType }) { - const [isOpen, setIsOpen] = React.useState(defaultOpen); - - return ( - <> - {!isOpen ? ( - - ) : null} - - - {contractError.name} - - - {Object.entries(contractError.args) - .map( - ([key, val]) => - `${key}: ${val instanceof Date ? format(val, 'yyyy-MM-dd HH:mm:ss') : val}` - ) - .join('\n')} - - - - ); -} diff --git a/liquidity/components/ContractError/index.tsx b/liquidity/components/ContractError/index.tsx deleted file mode 100644 index 309d04e7f..000000000 --- a/liquidity/components/ContractError/index.tsx +++ /dev/null @@ -1 +0,0 @@ -export * from './ContractError'; diff --git a/liquidity/components/ContractError/package.json b/liquidity/components/ContractError/package.json deleted file mode 100644 index 7e52b5f68..000000000 --- a/liquidity/components/ContractError/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@snx-v3/ContractError", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/react": "^2.8.2", - "@snx-v3/useContractErrorParser": "workspace:*", - "date-fns": "^2.30.0", - "react": "^18.2.0" - } -} diff --git a/liquidity/components/DepositModal/DepositMachine.ts b/liquidity/components/DepositModal/DepositMachine.ts deleted file mode 100644 index 3f01bcf11..000000000 --- a/liquidity/components/DepositModal/DepositMachine.ts +++ /dev/null @@ -1,195 +0,0 @@ -import { Wei, wei } from '@synthetixio/wei'; -import { createMachine, assign } from 'xstate'; - -export const Events = { - SET_REQUIRE_APPROVAL: 'SET_REQUIRE_APPROVAL', - SET_WRAP_AMOUNT: 'SET_WRAP_AMOUNT', - SET_INFINITE_APPROVAL: 'SET_INFINITE_APPROVAL', - RETRY: 'RETRY', - RUN: 'RUN', - SUCCESS: 'SUCCESS', - FAILURE: 'FAILURE', - RESET: 'RESET', -} as const; - -export const State = { - idle: 'idle', - wrap: 'wrap', - approve: 'approve', - deposit: 'deposit', - failed: 'failed', - success: 'success', -} as const; - -const FailedSteps = { - [State.approve]: State.approve, - [State.wrap]: State.wrap, - [State.deposit]: State.deposit, -} as const; - -export const ServiceNames = { - wrapEth: 'wrapEth', - approveWETH: 'approveWETH', - executeDeposit: 'executeDeposit', -} as const; - -type Context = { - error: { - error: Error; - step: keyof typeof FailedSteps; - } | null; - requireApproval: boolean; - wrapAmount: Wei; - infiniteApproval: boolean; -}; - -type EventNamesType = typeof Events; - -type DepositEvents = - | { type: EventNamesType['SET_REQUIRE_APPROVAL']; requireApproval: boolean } - | { type: EventNamesType['SET_WRAP_AMOUNT']; wrapAmount: Wei } - | { type: EventNamesType['SET_INFINITE_APPROVAL']; infiniteApproval: boolean } - | { type: EventNamesType['RETRY'] } - | { type: EventNamesType['RUN'] } - | { type: EventNamesType['SUCCESS'] } - | { type: EventNamesType['FAILURE'] } - | { type: EventNamesType['RESET'] }; - -type StateType = typeof State; -type MachineState = - | { - value: StateType['idle']; - context: Context & { error: null }; - } - | { - value: StateType['wrap']; - context: Context & { error: null }; - } - | { - value: StateType['approve']; - context: Context & { error: null }; - } - | { - value: StateType['deposit']; - context: Context & { error: null }; - } - | { - value: StateType['failed']; - context: Context & { error: { error: Error; step: keyof typeof FailedSteps } }; - } - | { - value: StateType['success']; - context: Context & { - error: null; - }; - }; - -const initialContext = { - wrapAmount: wei(0), - error: null, - requireApproval: false, - infiniteApproval: false, -}; - -export const DepositMachine = createMachine({ - id: 'DepositMachine', - initial: State.idle, - predictableActionArguments: true, - context: initialContext, - on: { - [Events.RUN]: { - target: State.deposit, - actions: assign({ - wrapAmount: (_) => initialContext.wrapAmount, - error: (_) => initialContext.error, - requireApproval: (_) => initialContext.requireApproval, - infiniteApproval: (_) => initialContext.infiniteApproval, - }), - }, - [Events.SET_REQUIRE_APPROVAL]: { - actions: assign({ requireApproval: (_context, event) => event.requireApproval }), - }, - [Events.SET_WRAP_AMOUNT]: { - actions: assign({ wrapAmount: (_context, event) => event.wrapAmount }), - }, - [Events.SET_INFINITE_APPROVAL]: { - actions: assign({ infiniteApproval: (_context, event) => event.infiniteApproval }), - }, - }, - states: { - [State.idle]: { - on: { - [Events.RUN]: [ - { target: State.wrap, cond: (context) => context.wrapAmount.gt(0) }, - { target: State.approve, cond: (context) => context.requireApproval }, - { target: State.deposit }, - ], - }, - }, - [State.wrap]: { - invoke: { - src: ServiceNames.wrapEth, - onError: { - target: State.failed, - actions: assign({ - error: (_context, event) => ({ error: event.data, step: FailedSteps.wrap }), - }), - }, - onDone: [ - { target: State.approve, cond: (context) => context.requireApproval }, - { target: State.deposit }, - ], - }, - }, - [State.approve]: { - invoke: { - src: ServiceNames.approveWETH, - onDone: { - target: State.deposit, - }, - onError: { - target: State.failed, - actions: assign({ - error: (_context, event) => ({ error: event.data, step: FailedSteps.approve }), - }), - }, - }, - }, - [State.deposit]: { - invoke: { - src: ServiceNames.executeDeposit, - onDone: { - target: State.success, - }, - onError: { - target: State.failed, - actions: assign({ - error: (_context, event) => ({ error: event.data, step: FailedSteps.deposit }), - }), - }, - }, - }, - [State.failed]: { - on: { - [Events.RETRY]: [ - { - target: State.approve, - cond: (c) => c.error?.step === FailedSteps.approve, - actions: assign({ error: (_) => null }), - }, - { - target: State.wrap, - cond: (c) => c.error?.step === FailedSteps.wrap, - actions: assign({ error: (_) => null }), - }, - { - target: State.deposit, - cond: (c) => c.error?.step === FailedSteps.deposit, - actions: assign({ error: (_) => null }), - }, - ], - }, - }, - [State.success]: {}, - }, -}); diff --git a/liquidity/components/DepositModal/DepositModal.tsx b/liquidity/components/DepositModal/DepositModal.tsx deleted file mode 100644 index f4663b028..000000000 --- a/liquidity/components/DepositModal/DepositModal.tsx +++ /dev/null @@ -1,571 +0,0 @@ -import { Button, Divider, Text, useToast, Link } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { ContractError } from '@snx-v3/ContractError'; -import { getSpotMarketId, isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { Multistep } from '@snx-v3/Multistep'; -import { useApprove } from '@snx-v3/useApprove'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { CollateralType, useCollateralType } from '@snx-v3/useCollateralTypes'; -import { useContractErrorParser } from '@snx-v3/useContractErrorParser'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useDeposit } from '@snx-v3/useDeposit'; -import { useDepositBaseAndromeda } from '@snx-v3/useDepositBaseAndromeda'; -import { useGetWrapperToken } from '@snx-v3/useGetUSDTokens'; -import { useParams } from '@snx-v3/useParams'; -import { usePool } from '@snx-v3/usePools'; -import { useSpotMarketProxy } from '@snx-v3/useSpotMarketProxy'; -import { useWrapEth } from '@snx-v3/useWrapEth'; -import { Wei, wei } from '@synthetixio/wei'; -import { useQueryClient } from '@tanstack/react-query'; -import { useMachine } from '@xstate/react'; -import { utils } from 'ethers'; -import { FC, ReactNode, useCallback, useContext, useEffect, useMemo, useState } from 'react'; -import { generatePath, useLocation, useNavigate } from 'react-router-dom'; -import type { StateFrom } from 'xstate'; -import { DepositMachine, Events, ServiceNames, State } from './DepositMachine'; -import { ArrowBackIcon } from '@chakra-ui/icons'; -import { LiquidityPositionUpdated } from '../../ui/src/components/Manage/LiquidityPositionUpdated'; -import { ZEROWEI } from '@snx-v3/constants'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { ChangeStat } from '../../ui/src/components'; -import { CRatioChangeStat } from '../../ui/src/components/CRatioBar/CRatioChangeStat'; -import { TransactionSummary } from '../../ui/src/components/TransactionSummary/TransactionSummary'; -import { currency } from '@snx-v3/format'; - -export const DepositModalUi: FC<{ - collateralChange: Wei; - isOpen: boolean; - onClose: () => void; - collateralType?: CollateralType; - state: StateFrom; - setInfiniteApproval: (x: boolean) => void; - onSubmit: () => void; - availableCollateral: Wei; - poolName: string; - title?: string; - txSummary?: ReactNode; -}> = ({ - collateralChange, - isOpen, - onClose, - collateralType, - setInfiniteApproval, - onSubmit, - state, - availableCollateral, - poolName, - title = 'Manage Collateral', - txSummary, -}) => { - const wrapAmount = state.context.wrapAmount; - const infiniteApproval = state.context.infiniteApproval; - const requireApproval = state.context.requireApproval; - const error = state.context.error; - const isProcessing = - state.matches(State.approve) || state.matches(State.deposit) || state.matches(State.wrap); - - const isWETH = collateralType?.symbol === 'WETH'; - - const stepNumbers = { - wrap: isWETH ? 1 : 0, - approve: isWETH ? 2 : 1, - deposit: isWETH ? 3 : 2, - }; - - if (isOpen) { - if (state.matches(State.success)) { - return ( - - Your Collateral has been updated, read more about it in the{' '} - - Synthetix V3 Documentation - - - } - alertText={ - <> - Collateral successfully Updated - - } - summary={txSummary} - /> - ); - } - - return ( -
- - - {title} - - - {isWETH ? ( - - from - balance will be used. - - ) : ( - - You must wrap additional before - depositing. - - ) - } - status={{ - failed: error?.step === State.wrap, - disabled: collateralType?.symbol !== 'WETH', - success: wrapAmount.eq(0) || state.matches(State.success), - loading: state.matches(State.wrap) && !error, - }} - /> - ) : null} - - setInfiniteApproval(e.target.checked), - }} - /> - - - {state.matches(State.success) ? ( - - {' '} - deposited & locked in {poolName}. - - ) : ( - <> - {availableCollateral && availableCollateral.gt(wei(0)) ? ( - <> - {availableCollateral.gte(collateralChange) ? ( - - This will deposit & lock{' '} - {' '} - in {poolName}. - - ) : ( - <> - - This will deposit & lock{' '} - {' '} - to {poolName}. - - - An additional{' '} - {' '} - will be deposited and locked from your wallet. - - - )} - - ) : ( - - This will deposit and lock{' '} - to{' '} - {poolName}. - - )} - - )} - - } - status={{ - failed: error?.step === State.deposit, - disabled: state.matches(State.success) && requireApproval, - success: state.matches(State.success), - loading: state.matches(State.deposit) && !error, - }} - /> - -
- ); - } -}; - -export type DepositModalProps = FC<{ - isOpen: boolean; - onClose: () => void; - title?: string; - liquidityPosition?: LiquidityPosition; -}>; - -export const DepositModal: DepositModalProps = ({ onClose, isOpen, title, liquidityPosition }) => { - const { collateralChange, setCollateralChange } = useContext(ManagePositionContext); - const currentCollateral = liquidityPosition?.collateralAmount ?? ZEROWEI; - const availableCollateral = liquidityPosition?.accountCollateral.availableCollateral ?? ZEROWEI; - - const [txSummary, setTxSummary] = useState({ - currentCollateral: ZEROWEI, - collateralChange: ZEROWEI, - currentDebt: ZEROWEI, - }); - - const navigate = useNavigate(); - const { collateralSymbol, poolId, accountId } = useParams(); - const queryClient = useQueryClient(); - const { network } = useNetwork(); - - const { data: CoreProxy } = useCoreProxy(); - const { data: SpotProxy } = useSpotMarketProxy(); - const { data: collateralType } = useCollateralType(collateralSymbol); - - const isBase = isBaseAndromeda(network?.id, network?.preset); - const { data: wrapperToken } = useGetWrapperToken(getSpotMarketId(collateralSymbol)); - - const collateralAddress = isBaseAndromeda(network?.id, network?.preset) - ? wrapperToken - : collateralType?.tokenAddress; - - const collateralNeeded = collateralChange.sub(availableCollateral); - - const { approve, requireApproval } = useApprove({ - contractAddress: collateralAddress, - amount: collateralNeeded.gt(0) - ? isBase - ? // Base USDC and Base stataUSDC are 6 decimals - utils.parseUnits(collateralNeeded.toString(), 6) - : utils.parseUnits(collateralNeeded.toString(), collateralType?.decimals) - : 0, - spender: isBase ? SpotProxy?.address : CoreProxy?.address, - }); - - const toast = useToast({ isClosable: true, duration: 9000 }); - - // TODO: Update logic on new account id - const newAccountId = useMemo(() => `${Math.floor(Math.random() * 1000000000000)}`, []); - - const { exec: wrapEth, wethBalance } = useWrapEth(); - - const wrapAmount = - collateralType?.symbol === 'WETH' && collateralNeeded.gt(wethBalance || 0) - ? collateralNeeded.sub(wethBalance || 0) - : wei(0); - - const { data: pool } = usePool(poolId); - - const { exec: execDeposit } = useDeposit({ - accountId: accountId, - newAccountId, - poolId: poolId, - collateralTypeAddress: collateralAddress, - collateralChange, - currentCollateral, - availableCollateral: availableCollateral || wei(0), - decimals: Number(collateralType?.decimals) || 18, - }); - - const { exec: depositBaseAndromeda } = useDepositBaseAndromeda({ - accountId, - newAccountId, - poolId, - collateralTypeAddress: collateralAddress, - collateralChange, - currentCollateral, - availableCollateral: availableCollateral || wei(0), - collateralSymbol, - }); - - const errorParserCoreProxy = useContractErrorParser(CoreProxy); - - const [state, send] = useMachine(DepositMachine, { - services: { - [ServiceNames.wrapEth]: async () => { - try { - await wrapEth(state.context.wrapAmount); - } catch (error: any) { - const contractError = errorParserCoreProxy(error); - if (contractError) { - console.error(new Error(contractError.name), contractError); - } - - toast.closeAll(); - toast({ - title: 'Wrapping ETH failed', - description: contractError ? ( - - ) : ( - error.message || 'Please try again.' - ), - status: 'error', - variant: 'left-accent', - }); - throw Error('Wrapping failed', { cause: error }); - } - }, - [ServiceNames.approveWETH]: async () => { - try { - toast({ - title: 'Approve collateral for transfer', - description: accountId - ? 'The next transaction will lock this collateral.' - : 'The next transaction will create your account and and lock this collateral', - status: 'info', - variant: 'left-accent', - }); - - await approve(Boolean(state.context.infiniteApproval)); - } catch (error: any) { - const contractError = errorParserCoreProxy(error); - if (contractError) { - console.error(new Error(contractError.name), contractError); - } - toast.closeAll(); - toast({ - title: 'Approval failed', - description: contractError ? ( - - ) : ( - 'Please try again.' - ), - status: 'error', - variant: 'left-accent', - }); - throw Error('Approve failed', { cause: error }); - } - }, - [ServiceNames.executeDeposit]: async () => { - try { - toast.closeAll(); - toast({ - title: Boolean(accountId) - ? 'Locking your collateral' - : 'Creating your account and locking your collateral', - description: '', - variant: 'left-accent', - }); - - setTxSummary({ - currentCollateral, - currentDebt: liquidityPosition?.debt || ZEROWEI, - collateralChange, - }); - - if (isBase) { - await depositBaseAndromeda(); - } else { - await execDeposit(); - } - - await Promise.all([ - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'EthBalance'], - }), - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPosition'], - }), - collateralType?.symbol === 'SNX' - ? queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'TransferableSynthetix'], - }) - : Promise.resolve(), - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'Allowance'], - }), - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPositions'], - }), - !accountId - ? queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'Accounts'], - }) - : Promise.resolve(), - ]); - - setCollateralChange(ZEROWEI); - - toast.closeAll(); - toast({ - title: 'Success', - description: 'Your locked collateral amount has been updated.', - status: 'success', - duration: 5000, - variant: 'left-accent', - }); - } catch (error: any) { - const contractError = errorParserCoreProxy(error); - if (contractError) { - console.error(new Error(contractError.name), contractError); - } - - toast.closeAll(); - toast({ - title: 'Could not complete locking collateral', - description: contractError ? ( - - ) : ( - 'Please try again.' - ), - status: 'error', - variant: 'left-accent', - }); - throw Error('Lock collateral failed', { cause: error }); - } - }, - }, - }); - - const wrapAmountString = wrapAmount.toString(); - const isSuccessOrDeposit = state.matches(State.success) || state.matches(State.deposit); - - useEffect(() => { - if (isSuccessOrDeposit) { - // We do this to ensure the success state displays the wrap amount used before deposit - return; - } - send(Events.SET_WRAP_AMOUNT, { wrapAmount: wei(wrapAmountString) }); - }, [wrapAmountString, send, isSuccessOrDeposit]); - - useEffect(() => { - send(Events.SET_REQUIRE_APPROVAL, { requireApproval }); - }, [requireApproval, send]); - - const location = useLocation(); - - const handleClose = useCallback(() => { - const isSuccess = state.matches(State.success); - - if (isSuccess && poolId && collateralType?.symbol) { - send(Events.RESET); - onClose(); - navigate({ - pathname: generatePath('/positions/:collateralType/:poolId', { - collateralType: collateralType.symbol, - poolId, - }), - search: location.search, - }); - } - send(Events.RESET); - onClose(); - }, [location.search, send, onClose, state, poolId, collateralType?.symbol, navigate]); - - const onSubmit = useCallback(async () => { - if (state.matches(State.success)) { - handleClose(); - return; - } - if (state.context.error) { - send(Events.RETRY); - return; - } - send(Events.RUN); - }, [handleClose, send, state]); - - const txSummaryItems = useMemo(() => { - const items = [ - { - label: 'Locked ' + collateralType?.symbol, - value: ( - currency(val)} - hasChanges={txSummary.collateralChange.abs().gt(0)} - size="sm" - /> - ), - }, - ]; - - if (isBase) { - return items; - } - - return [ - ...items, - { - label: 'C-ratio', - value: ( - - ), - }, - ]; - }, [ - collateralType?.symbol, - isBase, - liquidityPosition?.collateralPrice, - txSummary.collateralChange, - txSummary.currentCollateral, - txSummary.currentDebt, - ]); - - return ( - { - send(Events.SET_INFINITE_APPROVAL, { infiniteApproval }); - }} - onSubmit={onSubmit} - poolName={pool?.name || ''} - availableCollateral={availableCollateral || wei(0)} - title={title} - txSummary={} - /> - ); -}; diff --git a/liquidity/components/DepositModal/index.ts b/liquidity/components/DepositModal/index.ts deleted file mode 100644 index cd45c6766..000000000 --- a/liquidity/components/DepositModal/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { DepositModal } from './DepositModal'; -export * from './DepositModal'; -export default DepositModal; diff --git a/liquidity/components/DepositModal/package.json b/liquidity/components/DepositModal/package.json deleted file mode 100644 index defbd0d70..000000000 --- a/liquidity/components/DepositModal/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "@snx-v3/DepositModal", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/icons": "^2.1.1", - "@chakra-ui/react": "^2.8.2", - "@snx-v3/Amount": "workspace:*", - "@snx-v3/ContractError": "workspace:*", - "@snx-v3/ManagePositionContext": "workspace:*", - "@snx-v3/Multistep": "workspace:*", - "@snx-v3/constants": "workspace:*", - "@snx-v3/format": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/useApprove": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useContractErrorParser": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useDeposit": "workspace:*", - "@snx-v3/useDepositBaseAndromeda": "workspace:*", - "@snx-v3/useGetUSDTokens": "workspace:*", - "@snx-v3/useLiquidityPosition": "workspace:*", - "@snx-v3/useParams": "workspace:*", - "@snx-v3/usePools": "workspace:*", - "@snx-v3/useSpotMarketProxy": "workspace:*", - "@snx-v3/useWrapEth": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "@xstate/react": "^3.2.2", - "ethers": "^5.7.2", - "react": "^18.2.0", - "react-router-dom": "^6.18.0", - "xstate": "^4.38.3" - } -} diff --git a/liquidity/components/HomeLink/HomeLink.tsx b/liquidity/components/HomeLink/HomeLink.tsx deleted file mode 100644 index de4e81840..000000000 --- a/liquidity/components/HomeLink/HomeLink.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import { Link as ReactRouterLink, useLocation } from 'react-router-dom'; -import { Link, LinkProps } from '@chakra-ui/react'; -import { ArrowBackIcon } from '@chakra-ui/icons'; - -export const HomeLink = ({ ...props }: LinkProps) => { - const location = useLocation(); - - return ( - - All Pools - - ); -}; diff --git a/liquidity/components/HomeLink/index.tsx b/liquidity/components/HomeLink/index.tsx deleted file mode 100644 index 99d110cba..000000000 --- a/liquidity/components/HomeLink/index.tsx +++ /dev/null @@ -1 +0,0 @@ -export * from './HomeLink'; diff --git a/liquidity/components/HomeLink/package.json b/liquidity/components/HomeLink/package.json deleted file mode 100644 index ccd6ba071..000000000 --- a/liquidity/components/HomeLink/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@snx-v3/HomeLink", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/icons": "^2.1.1", - "@chakra-ui/react": "^2.8.2", - "react": "^18.2.0", - "react-router-dom": "^6.18.0" - } -} diff --git a/liquidity/components/Multistep/Multistep.tsx b/liquidity/components/Multistep/Multistep.tsx deleted file mode 100644 index 506ee91d0..000000000 --- a/liquidity/components/Multistep/Multistep.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { PropsWithChildren, ReactNode } from 'react'; -import { Box, Checkbox, CheckboxProps, Flex, FlexProps, Text } from '@chakra-ui/react'; -import { Step } from './Step'; -import { statusColor } from './statusColor'; -import { MultistepStatus } from './MultistepStatus'; - -function StepCheckbox({ children, ...props }: PropsWithChildren) { - return ( - - - - {children} - - - - ); -} -interface Props extends Omit { - step: number; - title: string | ReactNode; - subtitle?: string | ReactNode; - checkboxLabel?: string; - checkboxProps?: CheckboxProps; - status: MultistepStatus; - children?: ReactNode | undefined; -} - -export function Multistep({ - step, - title, - subtitle, - checkboxLabel, - checkboxProps, - status, - children, - ...props -}: Props) { - return ( - - {step} - - {title} - {subtitle ? ( - - {subtitle} - - ) : null} - {checkboxLabel ? {checkboxLabel} : null} - {children} - - - ); -} diff --git a/liquidity/components/Multistep/MultistepStatus.ts b/liquidity/components/Multistep/MultistepStatus.ts deleted file mode 100644 index 1cd7fe761..000000000 --- a/liquidity/components/Multistep/MultistepStatus.ts +++ /dev/null @@ -1,6 +0,0 @@ -export type MultistepStatus = { - failed?: boolean; - disabled?: boolean; - loading?: boolean; - success?: boolean; -}; diff --git a/liquidity/components/Multistep/Step.tsx b/liquidity/components/Multistep/Step.tsx deleted file mode 100644 index 8b60462fc..000000000 --- a/liquidity/components/Multistep/Step.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { Flex } from '@chakra-ui/react'; -import { PropsWithChildren } from 'react'; -import { MultistepStatus } from './MultistepStatus'; -import { StepIcon } from './StepIcon'; -import { statusColor } from './statusColor'; - -export function Step({ status, children }: PropsWithChildren<{ status: MultistepStatus }>) { - return ( - - {children} - - ); -} diff --git a/liquidity/components/Multistep/StepIcon.tsx b/liquidity/components/Multistep/StepIcon.tsx deleted file mode 100644 index 8c7f6f554..000000000 --- a/liquidity/components/Multistep/StepIcon.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import { Box, Spinner } from '@chakra-ui/react'; -import { PropsWithChildren } from 'react'; -import { MultistepStatus } from './MultistepStatus'; - -import { createIcon } from '@chakra-ui/icon'; - -export const CheckIcon = createIcon({ - viewBox: '0 0 14 14', - path: ( - - - - ), -}); - -export const CloseIcon = createIcon({ - d: 'M.439,21.44a1.5,1.5,0,0,0,2.122,2.121L11.823,14.3a.25.25,0,0,1,.354,0l9.262,9.263a1.5,1.5,0,1,0,2.122-2.121L14.3,12.177a.25.25,0,0,1,0-.354l9.263-9.262A1.5,1.5,0,0,0,21.439.44L12.177,9.7a.25.25,0,0,1-.354,0L2.561.44A1.5,1.5,0,0,0,.439,2.561L9.7,11.823a.25.25,0,0,1,0,.354Z', -}); - -export function StepIcon({ status, children }: PropsWithChildren<{ status: MultistepStatus }>) { - switch (true) { - case status.failed: - return ; - case status.success: - return ; - case status.loading: - return ; - case status.disabled: - default: - return ( - - {children} - - ); - } -} diff --git a/liquidity/components/Multistep/index.ts b/liquidity/components/Multistep/index.ts deleted file mode 100644 index d65efcc61..000000000 --- a/liquidity/components/Multistep/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export * from './statusColor'; -export * from './Step'; -export * from './StepIcon'; -export * from './Multistep'; -export * from './MultistepStatus'; diff --git a/liquidity/components/Multistep/package.json b/liquidity/components/Multistep/package.json deleted file mode 100644 index 7a0cf8542..000000000 --- a/liquidity/components/Multistep/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@snx-v3/Multistep", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/icon": "^3.2.0", - "@chakra-ui/react": "^2.8.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/components/Multistep/statusColor.ts b/liquidity/components/Multistep/statusColor.ts deleted file mode 100644 index 2d316a35c..000000000 --- a/liquidity/components/Multistep/statusColor.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { MultistepStatus } from './MultistepStatus'; - -export function statusColor(status: MultistepStatus): string { - switch (true) { - // order matters - case status.failed: - return 'red.700'; - case status.disabled: - return 'gray.900'; - case status.loading: - return 'gray.900'; - case status.success: - return 'green.700'; - default: - return 'gray.900'; - } -} diff --git a/liquidity/components/NumberInput/NumberInput.tsx b/liquidity/components/NumberInput/NumberInput.tsx deleted file mode 100644 index 34388c2ab..000000000 --- a/liquidity/components/NumberInput/NumberInput.tsx +++ /dev/null @@ -1,136 +0,0 @@ -import { Input, InputProps } from '@chakra-ui/react'; -import { ChangeEvent, useCallback, useEffect, useRef, useState } from 'react'; -import { Wei, wei } from '@synthetixio/wei'; - -export interface NumberInputProps extends InputProps { - 'data-testid'?: string; - 'data-max'?: string; -} - -export const NUMBER_REGEX = /^([0-9]*[.])?[0-9]{0,18}$/; - -function cleanupNumber(value: Wei) { - // Cleanup trailing precision zeroes - const float = parseFloat(value.toString()); - if (float === value.toNumber()) { - return `${float}`; - } - return value.toString(); -} - -export function NumberInput({ - value, - onChange, - min, - max, - InputProps, - dataTestId, - disabled, -}: { - onChange?: (value: Wei) => void; - value: Wei; - min?: Wei; - max?: Wei; - InputProps?: NumberInputProps; - dataTestId?: string; - disabled?: boolean; -}) { - const [inputValue, setInputValue] = useState(value.gt(0) ? value.toString() : ''); - - const onInputChange = useCallback( - (e: ChangeEvent) => { - // Define max length here - if (e.target.value.length > 24) return; - - let _value = e.target.value; - - if (!isNaN(Number(e.target.value))) { - if (!!min && min.gt(Number(e.target.value))) { - _value = min.toNumber().toString(); - } - } - - setInputValue(_value); - if (!onChange) { - // Could be a read-only input - return; - } - if (!NUMBER_REGEX.test(`${_value}`)) { - return; - } - let nextValue = value; - try { - nextValue = wei(_value || 0); - } catch (_err) { - // whatever - } - if (!value.eq(nextValue)) { - onChange(nextValue); - } - }, - [min, onChange, value] - ); - - const ref = useRef(null); - - useEffect(() => { - if (!ref.current) { - return; - } - if (!NUMBER_REGEX.test(`${inputValue}`)) { - ref.current.setCustomValidity('Invalid number'); - return; - } - if (value && value.eq(0)) { - ref.current.setCustomValidity('Value required'); - return; - } - if (min && min.gte(0) && value && value.lt(min)) { - ref.current.setCustomValidity(`Value smaller than minimum of ${cleanupNumber(min)}`); - return; - } - if (max && max.gte(0) && value && value.gt(max)) { - ref.current.setCustomValidity(`Value greater than maximum of ${cleanupNumber(max)}`); - return; - } - ref.current.setCustomValidity(''); - }, [inputValue, min, max, value]); - - useEffect(() => { - if (value.eq(0)) { - return setInputValue(''); - } - return setInputValue(cleanupNumber(value)); - }, [value]); - - return ( - - ); -} diff --git a/liquidity/components/NumberInput/index.ts b/liquidity/components/NumberInput/index.ts deleted file mode 100644 index 6433506aa..000000000 --- a/liquidity/components/NumberInput/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './NumberInput'; diff --git a/liquidity/components/NumberInput/package.json b/liquidity/components/NumberInput/package.json deleted file mode 100644 index b4cb09a9b..000000000 --- a/liquidity/components/NumberInput/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@snx-v3/NumberInput", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/react": "^2.8.2", - "@synthetixio/wei": "^2.74.4", - "react": "^18.2.0" - } -} diff --git a/liquidity/components/PercentBadges/PercentBadges.tsx b/liquidity/components/PercentBadges/PercentBadges.tsx deleted file mode 100644 index 19c1f446c..000000000 --- a/liquidity/components/PercentBadges/PercentBadges.tsx +++ /dev/null @@ -1,104 +0,0 @@ -import { FC } from 'react'; -import { Flex, Button } from '@chakra-ui/react'; -export const PercentBadges: FC<{ - disabled: boolean; - onBadgePress: (num: number) => void; - activeBadge: number; -}> = ({ onBadgePress, activeBadge, disabled }) => { - return ( - - - - - - - ); -}; diff --git a/liquidity/components/PercentBadges/index.ts b/liquidity/components/PercentBadges/index.ts deleted file mode 100644 index c4acc6957..000000000 --- a/liquidity/components/PercentBadges/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './PercentBadges'; diff --git a/liquidity/components/PercentBadges/package.json b/liquidity/components/PercentBadges/package.json deleted file mode 100644 index b0d96d4c9..000000000 --- a/liquidity/components/PercentBadges/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@snx-v3/PercentBadges", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/react": "^2.8.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/components/PoolBox/PoolBox.tsx b/liquidity/components/PoolBox/PoolBox.tsx deleted file mode 100644 index 25d314609..000000000 --- a/liquidity/components/PoolBox/PoolBox.tsx +++ /dev/null @@ -1,71 +0,0 @@ -import { Box, Button, Flex, Heading, Skeleton, Text } from '@chakra-ui/react'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { FC } from 'react'; -import { usePoolData } from '@snx-v3/usePoolData'; -import { calculatePoolPerformanceSevenDays } from '@snx-v3/calculations'; -import { generatePath, Link, useLocation } from 'react-router-dom'; -import { Wei } from '@synthetixio/wei'; -import { useParams } from '@snx-v3/useParams'; -import { usePool } from '@snx-v3/usePools'; - -const PoolBoxUi: FC<{ - poolName?: string; - poolId?: string; - sevenDaysPoolPerformanceGrowth?: Wei; -}> = ({ poolName, poolId }) => { - const location = useLocation(); - return ( - - {poolId ? ( - - - {poolName} - - Pool #{poolId} - - - - ) : ( - - - - - - - - )} - {poolId && ( - - )} - - ); -}; - -export const PoolBox = () => { - const { poolId } = useParams(); - - const { data: poolData } = usePoolData(poolId); - - const sevenDaysPoolPerformance = calculatePoolPerformanceSevenDays(poolData); - - const { data: pool } = usePool(poolId); - - return ( - - ); -}; diff --git a/liquidity/components/PoolBox/index.ts b/liquidity/components/PoolBox/index.ts deleted file mode 100644 index 26b80c37c..000000000 --- a/liquidity/components/PoolBox/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './PoolBox'; diff --git a/liquidity/components/PoolBox/package.json b/liquidity/components/PoolBox/package.json deleted file mode 100644 index d0feaa513..000000000 --- a/liquidity/components/PoolBox/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "@snx-v3/PoolBox", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/react": "^2.8.2", - "@snx-v3/BorderBox": "workspace:*", - "@snx-v3/calculations": "workspace:*", - "@snx-v3/useParams": "workspace:*", - "@snx-v3/usePoolData": "workspace:*", - "@snx-v3/usePools": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "react": "^18.2.0", - "react-router-dom": "^6.18.0" - } -} diff --git a/liquidity/components/PoolSelector/PoolItem.tsx b/liquidity/components/PoolSelector/PoolItem.tsx deleted file mode 100644 index 5e1abdaf3..000000000 --- a/liquidity/components/PoolSelector/PoolItem.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import { ExternalLinkIcon, InfoIcon } from '@chakra-ui/icons'; -import { Box, Flex, Heading, Link, Radio, Text } from '@chakra-ui/react'; -import { generatePath, Link as NavLink } from 'react-router-dom'; -import { Tooltip } from '@snx-v3/Tooltip'; -import { useSystemToken } from '@snx-v3/useSystemToken'; - -export function PoolItem({ name, value }: { name: string; value: string }) { - const { data: systemToken } = useSystemToken(); - return ( - - - - - - - {name} - - - Pool #{value}{' '} - {value == '0' ? ( - - - - ) : ( - - - - )} - - - - ); -} diff --git a/liquidity/components/PoolSelector/PoolSelector.tsx b/liquidity/components/PoolSelector/PoolSelector.tsx deleted file mode 100644 index 63630f776..000000000 --- a/liquidity/components/PoolSelector/PoolSelector.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { Box, Button, RadioGroup } from '@chakra-ui/react'; -import { usePools } from '@snx-v3/usePools'; -import { PoolItem } from './PoolItem'; -import { useState, useEffect } from 'react'; - -export function PoolSelector({ - poolId, - setPoolId, -}: { - poolId: string; - setPoolId: (poolId: string) => void; -}) { - const { data: pools = [] } = usePools(); - const [value, setValue] = useState(poolId); - useEffect(() => { - setValue(poolId); - }, [poolId]); - return ( - <> - - - - {pools.map(({ id, name }) => ( - - ))} - - - - - ); -} diff --git a/liquidity/components/PoolSelector/index.ts b/liquidity/components/PoolSelector/index.ts deleted file mode 100644 index 9d47e443b..000000000 --- a/liquidity/components/PoolSelector/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './PoolSelector'; -export * from './PoolItem'; diff --git a/liquidity/components/PoolSelector/package.json b/liquidity/components/PoolSelector/package.json deleted file mode 100644 index ac3a40047..000000000 --- a/liquidity/components/PoolSelector/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "@snx-v3/PoolSelector", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/icons": "^2.1.1", - "@chakra-ui/react": "^2.8.2", - "@snx-v3/Tooltip": "workspace:*", - "@snx-v3/usePools": "workspace:*", - "@snx-v3/useSystemToken": "workspace:*", - "react": "^18.2.0", - "react-router-dom": "^6.18.0" - } -} diff --git a/liquidity/components/RepayModal/RepayMachine.ts b/liquidity/components/RepayModal/RepayMachine.ts deleted file mode 100644 index 701b162fc..000000000 --- a/liquidity/components/RepayModal/RepayMachine.ts +++ /dev/null @@ -1,160 +0,0 @@ -import { createMachine, assign } from 'xstate'; - -export const Events = { - SET_REQUIRE_APPROVAL: 'SET_REQUIRE_APPROVAL', - SET_INFINITE_APPROVAL: 'SET_INFINITE_APPROVAL', - RETRY: 'RETRY', - RUN: 'RUN', - SUCCESS: 'SUCCESS', - FAILURE: 'FAILURE', - RESET: 'RESET', -} as const; - -export const State = { - idle: 'idle', - approve: 'approve', - repay: 'repay', - failed: 'failed', - success: 'success', -} as const; - -const FailedSteps = { - [State.approve]: State.approve, - [State.repay]: State.repay, -} as const; - -export const ServiceNames = { - approveSUSD: 'approveSUSD', - executeRepay: 'executeRepay', -} as const; - -type Context = { - error: { - error: Error; - step: keyof typeof FailedSteps; - } | null; - requireApproval: boolean; - infiniteApproval: boolean; -}; - -type EventNamesType = typeof Events; -type RepayEvents = - | { type: EventNamesType['SET_REQUIRE_APPROVAL']; requireApproval: boolean } - | { type: EventNamesType['SET_INFINITE_APPROVAL']; infiniteApproval: boolean } - | { type: EventNamesType['RETRY'] } - | { type: EventNamesType['RUN'] } - | { type: EventNamesType['SUCCESS'] } - | { type: EventNamesType['FAILURE'] } - | { type: EventNamesType['RESET'] }; - -type StateType = typeof State; -type MachineState = - | { - value: StateType['idle']; - context: Context & { error: null }; - } - | { - value: StateType['approve']; - context: Context & { error: null }; - } - | { - value: StateType['repay']; - context: Context & { error: null }; - } - | { - value: StateType['failed']; - context: Context & { error: { error: Error; step: keyof typeof FailedSteps } }; - } - | { - value: StateType['success']; - context: Context & { - error: null; - }; - }; - -const initialContext = { - error: null, - requireApproval: false, - infiniteApproval: false, -}; - -export const RepayMachine = createMachine({ - id: 'RepayMachine', - initial: State.idle, - predictableActionArguments: true, - context: initialContext, - on: { - [Events.RUN]: { - target: State.repay, - actions: assign({ - error: (_) => initialContext.error, - requireApproval: (_) => initialContext.requireApproval, - infiniteApproval: (_) => initialContext.infiniteApproval, - }), - }, - [Events.SET_REQUIRE_APPROVAL]: { - actions: assign({ requireApproval: (_context, event) => event.requireApproval }), - }, - - [Events.SET_INFINITE_APPROVAL]: { - actions: assign({ infiniteApproval: (_context, event) => event.infiniteApproval }), - }, - }, - states: { - [State.idle]: { - on: { - [Events.RUN]: [ - { target: State.approve, cond: (context) => context.requireApproval }, - { target: State.repay }, - ], - }, - }, - - [State.approve]: { - invoke: { - src: ServiceNames.approveSUSD, - onDone: { - target: State.repay, - }, - onError: { - target: State.failed, - actions: assign({ - error: (_context, event) => ({ error: event.data, step: FailedSteps.approve }), - }), - }, - }, - }, - [State.repay]: { - invoke: { - src: ServiceNames.executeRepay, - onDone: { - target: State.success, - }, - onError: { - target: State.failed, - actions: assign({ - error: (_context, event) => ({ error: event.data, step: FailedSteps.repay }), - }), - }, - }, - }, - [State.failed]: { - on: { - [Events.RETRY]: [ - { - target: State.approve, - cond: (c) => c.error?.step === FailedSteps.approve, - actions: assign({ error: (_) => null }), - }, - - { - target: State.repay, - cond: (c) => c.error?.step === FailedSteps.repay, - actions: assign({ error: (_) => null }), - }, - ], - }, - }, - [State.success]: {}, - }, -}); diff --git a/liquidity/components/RepayModal/RepayModal.tsx b/liquidity/components/RepayModal/RepayModal.tsx deleted file mode 100644 index 11bcbec0e..000000000 --- a/liquidity/components/RepayModal/RepayModal.tsx +++ /dev/null @@ -1,317 +0,0 @@ -import { Button, Divider, Text, useToast, Link, Flex, Skeleton } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { ContractError } from '@snx-v3/ContractError'; -import { parseUnits } from '@snx-v3/format'; -import { getSpotMarketId, isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { Multistep } from '@snx-v3/Multistep'; -import { useApprove } from '@snx-v3/useApprove'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { useContractErrorParser } from '@snx-v3/useContractErrorParser'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useGetWrapperToken } from '@snx-v3/useGetUSDTokens'; -import { useParams } from '@snx-v3/useParams'; -import { useRepay } from '@snx-v3/useRepay'; -import { useRepayBaseAndromeda } from '@snx-v3/useRepayBaseAndromeda'; -import { useSpotMarketProxy } from '@snx-v3/useSpotMarketProxy'; -import { useTokenBalance } from '@snx-v3/useTokenBalance'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import Wei from '@synthetixio/wei'; -import { useQueryClient } from '@tanstack/react-query'; -import { useMachine } from '@xstate/react'; -import { useCallback, useContext, useEffect } from 'react'; -import type { StateFrom } from 'xstate'; -import { Events, RepayMachine, ServiceNames, State } from './RepayMachine'; -import { ArrowBackIcon } from '@chakra-ui/icons'; -import { LiquidityPositionUpdated } from '../../ui/src/components/Manage/LiquidityPositionUpdated'; -import { ZEROWEI } from '@snx-v3/constants'; - -export const RepayModalUi: React.FC<{ - onClose: () => void; - debtChange: Wei; - isOpen: boolean; - onSubmit: () => void; - state: StateFrom; - setInfiniteApproval: (x: boolean) => void; - symbol: string; -}> = ({ symbol, onClose, isOpen, debtChange, state, onSubmit, setInfiniteApproval }) => { - const isProcessing = state.matches(State.approve) || state.matches(State.repay); - const { infiniteApproval, requireApproval, error } = state.context; - - if (isOpen) { - if (state.matches(State.success)) { - return ( - - Your Debt has been updated, read more about it in the{' '} - - Synthetix V3 Documentation - - - } - alertText={ - <> - Debt successfully Updated - - } - /> - ); - } - - return ( -
- - - Manage Debt - - - setInfiniteApproval(e.target.checked), - }} - /> - - Repay - - } - status={{ - failed: error?.step === State.repay, - success: state.matches(State.success), - loading: state.matches(State.repay) && !error, - }} - /> - - -
- ); - } -}; - -export const RepayModal: React.FC<{ - onClose: () => void; - isOpen: boolean; - availableCollateral?: Wei; -}> = ({ onClose, isOpen, availableCollateral }) => { - const { debtChange, setDebtChange } = useContext(ManagePositionContext); - const params = useParams(); - - const { network } = useNetwork(); - const queryClient = useQueryClient(); - - const { data: collateralType } = useCollateralType(params.collateralSymbol); - const { data: systemToken } = useSystemToken(); - const { data: balance } = useTokenBalance(systemToken?.address); - - const { exec: execRepay, settle: settleRepay } = useRepay({ - accountId: params.accountId, - poolId: params.poolId, - collateralTypeAddress: collateralType?.tokenAddress, - debtChange, - availableUSDCollateral: availableCollateral, - balance, - }); - - const { exec: execRepayBaseAndromeda, settle: settleRepayBaseAndromeda } = useRepayBaseAndromeda({ - accountId: params.accountId, - poolId: params.poolId, - collateralTypeAddress: collateralType?.tokenAddress, - debtChange, - availableUSDCollateral: availableCollateral, - }); - - const toast = useToast({ isClosable: true, duration: 9000 }); - - const { data: CoreProxy } = useCoreProxy(); - const { data: SpotProxy } = useSpotMarketProxy(); - - const errorParserCoreProxy = useContractErrorParser(CoreProxy); - const amountToDeposit = debtChange.abs().sub(availableCollateral || 0); - - const { data: wrapperToken } = useGetWrapperToken(getSpotMarketId(params.collateralSymbol)); - - const isBase = isBaseAndromeda(network?.id, network?.preset); - const collateralAddress = isBase ? wrapperToken : systemToken?.address; - - const { approve, requireApproval } = useApprove({ - contractAddress: collateralAddress, - amount: isBase - ? //Base USDC is 6 decimals - parseUnits(amountToDeposit.toString(), 6) - : amountToDeposit.toBN(), - spender: isBase ? SpotProxy?.address : CoreProxy?.address, - }); - - const [state, send] = useMachine(RepayMachine, { - services: { - [ServiceNames.approveSUSD]: async () => { - try { - toast({ - title: `Approve ${systemToken?.symbol} for transfer`, - description: 'The next transaction will repay your debt.', - status: 'info', - variant: 'left-accent', - }); - - await approve(Boolean(state.context.infiniteApproval)); - } catch (error: any) { - const contractError = errorParserCoreProxy(error); - if (contractError) { - console.error(new Error(contractError.name), contractError); - } - toast.closeAll(); - toast({ - title: 'Approval failed', - description: contractError ? ( - - ) : ( - 'Please try again.' - ), - status: 'error', - variant: 'left-accent', - }); - throw Error('Approve failed', { cause: error }); - } - }, - - [ServiceNames.executeRepay]: async () => { - try { - toast.closeAll(); - toast({ title: 'Repaying...', variant: 'left-accent' }); - - if (isBaseAndromeda(network?.id, network?.preset)) { - await execRepayBaseAndromeda(); - } else { - await execRepay(); - } - - await Promise.all([ - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'TokenBalance'], - }), - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'Allowance'], - }), - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPosition'], - }), - ]); - - setDebtChange(ZEROWEI); - - toast.closeAll(); - toast({ - title: 'Success', - description: 'Your debt has been repaid.', - status: 'success', - duration: 5000, - variant: 'left-accent', - }); - } catch (error: any) { - const contractError = errorParserCoreProxy(error); - if (contractError) { - console.error(new Error(contractError.name), contractError); - } - toast({ - title: 'Could not complete repaying', - description: contractError ? ( - - ) : ( - 'Please try again.' - ), - status: 'error', - variant: 'left-accent', - }); - throw Error('Repay failed', { cause: error }); - } - }, - }, - }); - const needToDeposit = amountToDeposit.gt(0); - - useEffect(() => { - send(Events.SET_REQUIRE_APPROVAL, { requireApproval: requireApproval && needToDeposit }); - }, [needToDeposit, requireApproval, send]); - - const onSubmit = useCallback(async () => { - if (state.matches(State.success)) { - send(Events.RESET); - onClose(); - return; - } - if (state.context.error) { - send(Events.RETRY); - return; - } - send(Events.RUN); - }, [onClose, send, state]); - - if (!(params.poolId && params.accountId && collateralType && systemToken)) - return ( - - - - - - - ); - - return ( - { - send(Events.SET_INFINITE_APPROVAL, { infiniteApproval }); - }} - onClose={() => { - settleRepay(); - settleRepayBaseAndromeda(); - onClose(); - }} - isOpen={isOpen} - symbol={isBase ? collateralType.symbol : systemToken?.symbol} - /> - ); -}; diff --git a/liquidity/components/RepayModal/index.ts b/liquidity/components/RepayModal/index.ts deleted file mode 100644 index 9b83f002b..000000000 --- a/liquidity/components/RepayModal/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { RepayModal } from './RepayModal'; -export * from './RepayModal'; -export default RepayModal; diff --git a/liquidity/components/RepayModal/package.json b/liquidity/components/RepayModal/package.json deleted file mode 100644 index 730faba1d..000000000 --- a/liquidity/components/RepayModal/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "@snx-v3/RepayModal", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/icons": "^2.1.1", - "@chakra-ui/react": "^2.8.2", - "@snx-v3/Amount": "workspace:*", - "@snx-v3/ContractError": "workspace:*", - "@snx-v3/ManagePositionContext": "workspace:*", - "@snx-v3/Multistep": "workspace:*", - "@snx-v3/constants": "workspace:*", - "@snx-v3/format": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/useApprove": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useContractErrorParser": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGetUSDTokens": "workspace:*", - "@snx-v3/useParams": "workspace:*", - "@snx-v3/useRepay": "workspace:*", - "@snx-v3/useRepayBaseAndromeda": "workspace:*", - "@snx-v3/useSpotMarketProxy": "workspace:*", - "@snx-v3/useSystemToken": "workspace:*", - "@snx-v3/useTokenBalance": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "@xstate/react": "^3.2.2", - "react": "^18.2.0", - "xstate": "^4.38.3" - } -} diff --git a/liquidity/components/TermsModal/TermsModal.tsx b/liquidity/components/TermsModal/TermsModal.tsx deleted file mode 100644 index 8fc7b774b..000000000 --- a/liquidity/components/TermsModal/TermsModal.tsx +++ /dev/null @@ -1,198 +0,0 @@ -import { useState } from 'react'; -import { - Modal, - ModalOverlay, - ModalContent, - ModalHeader, - ModalBody, - Text, - Button, - Box, - Link, - ListItem, - UnorderedList, -} from '@chakra-ui/react'; -import { Link as ReactRouterLink } from 'react-router-dom'; -import { theme } from '@synthetixio/v3-theme'; -import { SESSION_STORAGE_KEYS } from '@snx-v3/constants'; - -interface TermsModalProps { - defaultOpen: boolean; -} - -export const TermsModal = ({ defaultOpen = true }: TermsModalProps) => { - const [isOpen, setOpen] = useState(defaultOpen); - const [enabled, setEnabled] = useState(false); - - const onSubmit = () => { - if (enabled) { - localStorage.setItem(SESSION_STORAGE_KEYS.TERMS_CONDITIONS_ACCEPTED, JSON.stringify(true)); - setOpen(false); - } - }; - - return ( - // eslint-disable-next-line @typescript-eslint/no-empty-function - {}}> - - - - Synthetix Terms of Service - - - - By clicking “I Agree” below, you agree to be bound by the terms of this Agreement. As - such, you fully understand that: - - { - const div = e.currentTarget; - const scrollTopWithTolerance = div.scrollTop + 10; - if (scrollTopWithTolerance >= div.scrollHeight - div.offsetHeight) { - setEnabled(true); - } else { - setEnabled(false); - } - }} - as="div" - my={2} - py={3} - height="350px" - overflow="auto" - overflowX="scroll" - sx={{ - '::-webkit-scrollbar': { - display: 'block', - }, - '::-webkit-scrollbar-track': { - backgroundColor: 'transparent', - }, - '::-webkit-scrollbar-track-piece': { - backgroundColor: 'transparent', - }, - '::-webkit-scrollbar-corner': { - backgroundColor: 'transparent', - }, - }} - > - - - - - Synthetix{' '} - - is a blockchain-based decentralized finance project. You are participating at your - own risk. - - - Synthetix is offered for use “as is” and without any guarantees regarding - security. The protocol is made up of immutable code and can be accessed through a - variety of user interfaces. - - - No central entity operates the Synthetix protocol. Decisions related to the - protocol are governed by a dispersed group of participants who collectively govern - and maintain the protocol. - - - Synthetix DAO does not unilaterally offer, maintain, operate, administer, or - control any trading interfaces. The only user interfaces maintained by Synthetix - DAO are the governance and liquidity interfaces herein. - - - You can participate in the governance process by staking SNX tokens in accordance - with the rules and parameters summarized{' '} - - here - - , and/or joining the{' '} - - Synthetix Discord - {' '} - and contributing to the conversation. - - - The rules and parameters associated with the Synthetix protocol and Synthetix DAO - governance are subject to change at any time. - - - Your use of Synthetix is conditioned upon your acceptance to be bound by the - Synthetix Term of Use, which can be found{' '} - - here - - . - - - The laws that apply to your use of Synthetix may vary based upon the jurisdiction - in which you are located. We strongly encourage you to speak with legal counsel in - your jurisdiction if you have any questions regarding your use of Synthetix. - - - By entering into this agreement, you are not agreeing to enter into a partnership. - You understand that Synthetix is a decentralized protocol provided on an “as is” - basis. - - - You hereby release all present and future claims against Synthetix DAO related to - your use of the protocol, the SNX token, SNX DAO governance, and any other facet - of the protocol. - - - You agree to indemnify and hold harmless SNX DAO and its affiliates for any costs - arising out of or relating to your use of the Synthetix protocol. - - - You are not accessing the protocol from Burma (Myanmar), Cuba, Iran, Sudan, Syria, - the Western Balkans, Belarus, Côte d’Ivoire, Democratic Republic of the Congo, - Iraq, Lebanon, Liberia, Libya, North Korea, Russia, certain sanctioned areas of - Ukraine, Somalia, Venezuela, Yemen, or Zimbabwe (collectively, “Prohibited - Jurisdictions”), or any other jurisdiction listed as a Specially Designated - National by the United States Office of Foreign Asset Control (“OFAC”). - - - - - - - - - ); -}; diff --git a/liquidity/components/TermsModal/index.ts b/liquidity/components/TermsModal/index.ts deleted file mode 100644 index 784a2ba38..000000000 --- a/liquidity/components/TermsModal/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './TermsModal'; diff --git a/liquidity/components/TermsModal/package.json b/liquidity/components/TermsModal/package.json deleted file mode 100644 index c05b43f0e..000000000 --- a/liquidity/components/TermsModal/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/TermsModal", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/react": "^2.8.2", - "@snx-v3/constants": "workspace:*", - "@synthetixio/v3-theme": "workspace:*", - "react": "^18.2.0", - "react-router-dom": "^6.18.0" - } -} diff --git a/liquidity/components/TrendText/TrendText.tsx b/liquidity/components/TrendText/TrendText.tsx deleted file mode 100644 index 4b6ebdbb4..000000000 --- a/liquidity/components/TrendText/TrendText.tsx +++ /dev/null @@ -1,6 +0,0 @@ -import { Text, TextProps } from '@chakra-ui/react'; -import Wei, { wei } from '@synthetixio/wei'; - -export const TrendText = (props: TextProps & { value: Wei | number }) => ( - -); diff --git a/liquidity/components/TrendText/index.ts b/liquidity/components/TrendText/index.ts deleted file mode 100644 index b3468fafa..000000000 --- a/liquidity/components/TrendText/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './TrendText'; diff --git a/liquidity/components/TrendText/package.json b/liquidity/components/TrendText/package.json deleted file mode 100644 index 5aa55fe6e..000000000 --- a/liquidity/components/TrendText/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@snx-v3/TrendText", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/react": "^2.8.2", - "@synthetixio/wei": "^2.74.4" - } -} diff --git a/liquidity/components/UndelegateModal/UndelegateMachine.ts b/liquidity/components/UndelegateModal/UndelegateMachine.ts deleted file mode 100644 index d725fda10..000000000 --- a/liquidity/components/UndelegateModal/UndelegateMachine.ts +++ /dev/null @@ -1,125 +0,0 @@ -import Wei, { wei } from '@synthetixio/wei'; -import { createMachine, assign } from 'xstate'; - -export const Events = { - SET_AMOUNT: 'SET_AMOUNT', - SET_COLLATERAL_SYMBOL: 'SET_COLLATERAL_SYMBOL', - RETRY: 'RETRY', - RUN: 'RUN', - SUCCESS: 'SUCCESS', - FAILURE: 'FAILURE', - RESET: 'RESET', -} as const; - -export const State = { - idle: 'idle', - undelegate: 'undelegate', - failed: 'failed', - success: 'success', -} as const; - -export const FailedSteps = { - [State.undelegate]: State.undelegate, -} as const; - -export const ServiceNames = { - undelegate: 'undelegate', -} as const; - -type Context = { - error: { error: Error; step: keyof typeof FailedSteps } | null; - amount: Wei; - collateralSymbol?: string; -}; - -type EventType = typeof Events; -type UndelegateEvents = - | { type: EventType['SET_AMOUNT']; amount: Wei } - | { type: EventType['SET_COLLATERAL_SYMBOL']; symbol: string } - | { type: EventType['RETRY'] } - | { type: EventType['RUN'] } - | { type: EventType['SUCCESS'] } - | { type: EventType['FAILURE'] } - | { type: EventType['RESET'] }; - -type StateType = typeof State; -export type MachineState = - | { - value: StateType['idle']; - context: Context & { error: null }; - } - | { - value: StateType['undelegate']; - context: Context & { error: null }; - } - | { - value: StateType['failed']; - context: Context & { error: { error: Error; step: keyof typeof FailedSteps } }; - } - | { - value: StateType['success']; - context: Context & { - error: null; - }; - }; - -const initialContext = { - amount: wei(0), - error: null, - collateralSymbol: undefined, -}; -export const UndelegateMachine = createMachine({ - id: 'UndelegateMachine', - initial: State.idle, - predictableActionArguments: true, - context: initialContext, - on: { - [Events.RESET]: { - target: State.idle, - actions: assign({ - amount: (_) => initialContext.amount, - error: (_) => initialContext.error, - collateralSymbol: (_) => initialContext.collateralSymbol, - }), - }, - [Events.SET_AMOUNT]: { - actions: assign({ amount: (_context, event) => event.amount }), - }, - [Events.SET_COLLATERAL_SYMBOL]: { - actions: assign({ collateralSymbol: (_context, event) => event.symbol }), - }, - }, - states: { - [State.idle]: { - on: { - [Events.RUN]: [{ target: State.undelegate, cond: (context) => context.amount.gt(0) }], - }, - }, - - [State.undelegate]: { - invoke: { - src: ServiceNames.undelegate, - onError: { - target: State.failed, - actions: assign({ - error: (_context, event) => ({ error: event.data, step: FailedSteps.undelegate }), - }), - }, - onDone: [{ target: State.success }], - }, - }, - - [State.failed]: { - on: { - [Events.RETRY]: [ - { - target: State.undelegate, - cond: (c) => c.error?.step === FailedSteps.undelegate, - actions: assign({ error: (_) => null }), - }, - ], - }, - }, - [State.success]: {}, - }, -}); diff --git a/liquidity/components/UndelegateModal/UndelegateModal.tsx b/liquidity/components/UndelegateModal/UndelegateModal.tsx deleted file mode 100644 index 4e0965b36..000000000 --- a/liquidity/components/UndelegateModal/UndelegateModal.tsx +++ /dev/null @@ -1,297 +0,0 @@ -import { Button, Divider, Text, useToast, Link } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { ContractError } from '@snx-v3/ContractError'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { Multistep } from '@snx-v3/Multistep'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { CollateralType, useCollateralType } from '@snx-v3/useCollateralTypes'; -import { useContractErrorParser } from '@snx-v3/useContractErrorParser'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { useParams } from '@snx-v3/useParams'; -import { useUndelegate } from '@snx-v3/useUndelegate'; -import { useUndelegateBaseAndromeda } from '@snx-v3/useUndelegateBaseAndromeda'; -import { Wei, wei } from '@synthetixio/wei'; -import { useQueryClient } from '@tanstack/react-query'; -import { useMachine } from '@xstate/react'; -import { FC, ReactNode, useCallback, useContext, useEffect, useMemo, useState } from 'react'; -import type { StateFrom } from 'xstate'; -import { Events, ServiceNames, State, UndelegateMachine } from './UndelegateMachine'; -import { ArrowBackIcon } from '@chakra-ui/icons'; -import { LiquidityPositionUpdated } from '../../ui/src/components/Manage/LiquidityPositionUpdated'; -import { ZEROWEI } from '@snx-v3/constants'; -import { ChangeStat } from '../../ui/src/components'; -import { currency } from '@snx-v3/format'; -import { CRatioChangeStat } from '../../ui/src/components/CRatioBar/CRatioChangeStat'; -import { TransactionSummary } from '../../ui/src/components/TransactionSummary/TransactionSummary'; - -export const UndelegateModalUi: FC<{ - amount: Wei; - isOpen: boolean; - onClose: () => void; - collateralType?: CollateralType; - state: StateFrom; - error: { error: Error; step: string } | null; - onSubmit: () => void; - txSummary?: ReactNode; -}> = ({ txSummary, amount, isOpen, onClose, collateralType, onSubmit, state, error }) => { - const isProcessing = state.matches(State.undelegate); - if (isOpen) { - if (state.matches(State.success)) { - return ( - - Your Collateral has been updated, read more about it in the{' '} - - Synthetix V3 Documentation - - - } - alertText={ - <> - Collateral successfully Updated - - } - summary={txSummary} - /> - ); - } - - return ( -
- - - Manage Collateral - - - - will be - unlocked from the pool. - - } - status={{ - failed: Boolean(error?.step === State.undelegate), - disabled: amount.eq(0), - success: state.matches(State.success), - loading: state.matches(State.undelegate) && !error, - }} - /> - - -
- ); - } -}; -export type UndelegateModalProps = FC<{ - isOpen: boolean; - onClose: () => void; - liquidityPosition?: LiquidityPosition; -}>; -export const UndelegateModal: UndelegateModalProps = ({ onClose, isOpen, liquidityPosition }) => { - const params = useParams(); - const { collateralChange, setCollateralChange } = useContext(ManagePositionContext); - const { network } = useNetwork(); - - const queryClient = useQueryClient(); - - const { data: collateralType } = useCollateralType(params.collateralSymbol); - - const toast = useToast({ isClosable: true, duration: 9000 }); - - const [txSummary, setTxSummary] = useState({ - currentCollateral: ZEROWEI, - collateralChange: ZEROWEI, - currentDebt: ZEROWEI, - }); - - const currentCollateral = liquidityPosition?.collateralAmount || wei(0); - - const { exec: execUndelegate } = useUndelegate({ - accountId: params.accountId, - poolId: params.poolId, - collateralTypeAddress: liquidityPosition?.tokenAddress, - collateralChange, - currentCollateral: currentCollateral, - }); - const { exec: undelegateBaseAndromeda } = useUndelegateBaseAndromeda({ - accountId: params.accountId, - poolId: params.poolId, - collateralTypeAddress: liquidityPosition?.tokenAddress, - collateralChange, - currentCollateral: currentCollateral, - liquidityPosition, - }); - - const { data: CoreProxy } = useCoreProxy(); - const errorParserCoreProxy = useContractErrorParser(CoreProxy); - - const isBase = isBaseAndromeda(network?.id, network?.preset); - const [state, send] = useMachine(UndelegateMachine, { - context: { - amount: collateralChange.abs(), - }, - services: { - [ServiceNames.undelegate]: async () => { - try { - setTxSummary({ - currentCollateral, - currentDebt: liquidityPosition?.debt || ZEROWEI, - collateralChange, - }); - - if (isBase) { - await undelegateBaseAndromeda(); - } else { - await execUndelegate(); - } - - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPosition'], - exact: false, - }); - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPositions'], - }); - queryClient.invalidateQueries({ - queryKey: [ - `${network?.id}-${network?.preset}`, - 'AccountCollateralUnlockDate', - { accountId: params.accountId }, - ], - }); - - setCollateralChange(ZEROWEI); - } catch (error: any) { - const contractError = errorParserCoreProxy(error); - if (contractError) { - console.error(new Error(contractError.name), contractError); - } - toast.closeAll(); - toast({ - title: 'Unlock collateral failed', - description: contractError ? ( - - ) : ( - 'Please try again.' - ), - status: 'error', - variant: 'left-accent', - }); - throw Error('Unlock collateral failed', { cause: error }); - } - }, - }, - }); - - const collateralChangeString = collateralChange.toString(); - - useEffect(() => { - send(Events.SET_AMOUNT, { amount: wei(collateralChangeString).abs() }); - }, [collateralChangeString, send]); - - useEffect(() => { - send(Events.SET_COLLATERAL_SYMBOL, { symbol: wei(collateralChangeString).abs() }); - }, [collateralChangeString, send]); - - const onSubmit = useCallback(async () => { - if (state.matches(State.success)) { - send(Events.RESET); - onClose(); - return; - } - if (state.context.error) { - send(Events.RETRY); - return; - } - send(Events.RUN); - }, [onClose, send, state]); - - const txSummaryItems = useMemo(() => { - const items = [ - { - label: 'Locked ' + collateralType?.displaySymbol, - value: ( - currency(val)} - hasChanges={txSummary.collateralChange.abs().gt(0)} - size="sm" - /> - ), - }, - ]; - - if (isBase) { - return items; - } - - return [ - ...items, - { - label: 'C-ratio', - value: ( - - ), - }, - ]; - }, [ - collateralType?.displaySymbol, - isBase, - liquidityPosition?.collateralPrice, - txSummary.collateralChange, - txSummary.currentCollateral, - txSummary.currentDebt, - ]); - - return ( - } - /> - ); -}; diff --git a/liquidity/components/UndelegateModal/index.ts b/liquidity/components/UndelegateModal/index.ts deleted file mode 100644 index 65f47390f..000000000 --- a/liquidity/components/UndelegateModal/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { UndelegateModal } from './UndelegateModal'; -export * from './UndelegateModal'; -export default UndelegateModal; diff --git a/liquidity/components/UndelegateModal/package.json b/liquidity/components/UndelegateModal/package.json deleted file mode 100644 index 6f869b8a0..000000000 --- a/liquidity/components/UndelegateModal/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "@snx-v3/UndelegateModal", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/icons": "^2.1.1", - "@chakra-ui/react": "^2.8.2", - "@snx-v3/Amount": "workspace:*", - "@snx-v3/ContractError": "workspace:*", - "@snx-v3/ManagePositionContext": "workspace:*", - "@snx-v3/Multistep": "workspace:*", - "@snx-v3/constants": "workspace:*", - "@snx-v3/format": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useContractErrorParser": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useLiquidityPosition": "workspace:*", - "@snx-v3/useParams": "workspace:*", - "@snx-v3/useUndelegate": "workspace:*", - "@snx-v3/useUndelegateBaseAndromeda": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "@xstate/react": "^3.2.2", - "react": "^18.2.0", - "xstate": "^4.38.3" - } -} diff --git a/liquidity/components/WithdrawIncrease/WithdrawIncrease.tsx b/liquidity/components/WithdrawIncrease/WithdrawIncrease.tsx deleted file mode 100644 index 5ac0ab1a8..000000000 --- a/liquidity/components/WithdrawIncrease/WithdrawIncrease.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { Alert, AlertIcon, Text } from '@chakra-ui/react'; - -export function WithdrawIncrease() { - return ( - - - This action will reset the withdrawal waiting period to 24 hours - - ); -} diff --git a/liquidity/components/WithdrawIncrease/index.ts b/liquidity/components/WithdrawIncrease/index.ts deleted file mode 100644 index 3ff857b97..000000000 --- a/liquidity/components/WithdrawIncrease/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './WithdrawIncrease'; diff --git a/liquidity/components/WithdrawIncrease/package.json b/liquidity/components/WithdrawIncrease/package.json deleted file mode 100644 index d878e0bb4..000000000 --- a/liquidity/components/WithdrawIncrease/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@snx-v3/WithdrawIncrease", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/react": "^2.8.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/components/WithdrawModal/WithdrawModal.tsx b/liquidity/components/WithdrawModal/WithdrawModal.tsx deleted file mode 100644 index 719fc2f14..000000000 --- a/liquidity/components/WithdrawModal/WithdrawModal.tsx +++ /dev/null @@ -1,255 +0,0 @@ -import { Button, Divider, Text, useToast, Link } from '@chakra-ui/react'; -import React, { FC, useCallback, useContext, useState } from 'react'; -import { Multistep } from '@snx-v3/Multistep'; -import { Wei } from '@synthetixio/wei'; -import { useWithdraw } from '@snx-v3/useWithdraw'; -import { useAccountSpecificCollateral } from '@snx-v3/useAccountCollateral'; -import { useContractErrorParser } from '@snx-v3/useContractErrorParser'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { ContractError } from '@snx-v3/ContractError'; -import { useQueryClient } from '@tanstack/react-query'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { ArrowBackIcon } from '@chakra-ui/icons'; -import { LiquidityPositionUpdated } from '../../ui/src/components/Manage/LiquidityPositionUpdated'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ZEROWEI } from '@snx-v3/constants'; -import { useWithdrawBaseAndromeda } from '@snx-v3/useWithdrawBaseAndromeda'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { useParams } from '@snx-v3/useParams'; -import { Amount } from '@snx-v3/Amount'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; - -export const WithdrawModalUi: FC<{ - amount: Wei; - isOpen: boolean; - onClose: () => void; - symbol?: string; - state: { - step: number; - status: string; - }; - onSubmit: () => void; - isDebtWithdrawal: boolean; -}> = ({ isDebtWithdrawal, amount, isOpen, onClose, onSubmit, state, symbol }) => { - if (isOpen) { - if (state.step > 1) { - return ( - - Your {isDebtWithdrawal ? 'Debt' : 'Collateral'} has been withdrawn, read more - about it in the{' '} - - Synthetix V3 Documentation - - - } - alertText={(isDebtWithdrawal ? 'Debt' : 'Collateral') + ' successfully Withdrawn'} - /> - ); - } - - return ( -
- - - Manage {isDebtWithdrawal ? 'Debt' : 'Collateral'} - - - - - -  {symbol} will be withdrawn - - } - status={{ - failed: state.step === 1 && state.status === 'error', - success: state.step > 1, - loading: state.step === 1 && state.status === 'pending', - }} - /> - - -
- ); - } -}; - -export function WithdrawModal({ - liquidityPosition, - onClose, - isOpen, - isDebtWithdrawal = false, -}: { - liquidityPosition?: LiquidityPosition; - isOpen: boolean; - onClose: () => void; - isDebtWithdrawal?: boolean; -}) { - const [txState, setTxState] = useState({ - step: 1, - status: 'idle', - }); - - const params = useParams(); - const toast = useToast({ isClosable: true, duration: 9000 }); - const { network } = useNetwork(); - const queryClient = useQueryClient(); - - const { withdrawAmount, setWithdrawAmount } = useContext(ManagePositionContext); - - const { data: collateralType } = useCollateralType(params.collateralSymbol); - const { data: CoreProxy } = useCoreProxy(); - const errorParserCoreProxy = useContractErrorParser(CoreProxy); - const accountId = liquidityPosition?.accountId; - - const { data: systemToken } = useSystemToken(); - const { data: systemTokenBalance } = useAccountSpecificCollateral( - accountId, - systemToken?.address - ); - - const { mutation: withdrawMain } = useWithdraw({ - amount: withdrawAmount, - accountId, - collateralTypeAddress: isDebtWithdrawal - ? systemToken?.address - : liquidityPosition?.accountCollateral?.tokenAddress, - }); - - const { mutation: withdrawAndromeda } = useWithdrawBaseAndromeda({ - accountId, - availableCollateral: liquidityPosition?.accountCollateral.availableCollateral || ZEROWEI, - snxUSDCollateral: systemTokenBalance?.availableCollateral || ZEROWEI, - amountToWithdraw: withdrawAmount, - accountCollateral: liquidityPosition?.accountCollateral, - collateralSymbol: params.collateralSymbol, - }); - - const onSubmit = useCallback(async () => { - try { - if (txState.step === 1) { - setTxState({ - step: 1, - status: 'pending', - }); - - if (!isBaseAndromeda(network?.id, network?.preset)) { - await withdrawMain.mutateAsync(); - } else { - await withdrawAndromeda.mutateAsync(); - } - - setTxState({ - step: 2, - status: 'success', - }); - - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPosition', { accountId }], - }); - queryClient.invalidateQueries({ - queryKey: [ - `${network?.id}-${network?.preset}`, - 'AccountSpecificCollateral', - { accountId }, - ], - }); - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPositions', { accountId }], - }); - queryClient.invalidateQueries({ - queryKey: [ - `${network?.id}-${network?.preset}`, - 'AccountCollateralUnlockDate', - { accountId }, - ], - }); - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'TokenBalance'], - }); - - setWithdrawAmount(ZEROWEI); - } else { - onClose(); - } - } catch (error) { - setTxState((state) => ({ - ...state, - status: 'error', - })); - - const contractError = errorParserCoreProxy(error); - if (contractError) { - console.error(new Error(contractError.name), contractError); - } - toast.closeAll(); - toast({ - title: 'Withdraw failed', - description: contractError ? ( - - ) : ( - 'Please try again.' - ), - status: 'error', - variant: 'left-accent', - }); - throw Error('Withdraw failed', { cause: error }); - } - }, [ - accountId, - errorParserCoreProxy, - network?.id, - network?.preset, - onClose, - queryClient, - setWithdrawAmount, - toast, - txState.step, - withdrawAndromeda, - withdrawMain, - ]); - - return ( - - ); -} diff --git a/liquidity/components/WithdrawModal/index.ts b/liquidity/components/WithdrawModal/index.ts deleted file mode 100644 index b6cfa05fc..000000000 --- a/liquidity/components/WithdrawModal/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { WithdrawModal } from './WithdrawModal'; -export * from './WithdrawModal'; -export default WithdrawModal; diff --git a/liquidity/components/WithdrawModal/package.json b/liquidity/components/WithdrawModal/package.json deleted file mode 100644 index a9dc0c179..000000000 --- a/liquidity/components/WithdrawModal/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "@snx-v3/WithdrawModal", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@chakra-ui/icons": "^2.1.1", - "@chakra-ui/react": "^2.8.2", - "@snx-v3/Amount": "workspace:*", - "@snx-v3/ContractError": "workspace:*", - "@snx-v3/ManagePositionContext": "workspace:*", - "@snx-v3/Multistep": "workspace:*", - "@snx-v3/constants": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/useAccountCollateral": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useContractErrorParser": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useLiquidityPosition": "workspace:*", - "@snx-v3/useParams": "workspace:*", - "@snx-v3/useSystemToken": "workspace:*", - "@snx-v3/useWithdraw": "workspace:*", - "@snx-v3/useWithdrawBaseAndromeda": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/cypress/.eslintrc b/liquidity/cypress/.eslintrc deleted file mode 100644 index d5ba8f9d9..000000000 --- a/liquidity/cypress/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "rules": { - "no-console": "off" - } -} diff --git a/liquidity/cypress/.gitignore b/liquidity/cypress/.gitignore deleted file mode 100644 index 11ee75815..000000000 --- a/liquidity/cypress/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.env.local diff --git a/liquidity/cypress/bin/approveCollateral.ts b/liquidity/cypress/bin/approveCollateral.ts deleted file mode 100755 index bf222e64e..000000000 --- a/liquidity/cypress/bin/approveCollateral.ts +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env ts-node - -// @ts-ignore -import { approveCollateral } from '../cypress/tasks/approveCollateral'; -const [privateKey, symbol] = process.argv.slice(2); -if (!privateKey || !symbol) { - throw new Error('Usage: ./approveCollateral.ts '); -} -approveCollateral({ privateKey, symbol }); diff --git a/liquidity/cypress/bin/createAccount.ts b/liquidity/cypress/bin/createAccount.ts deleted file mode 100755 index eec637e82..000000000 --- a/liquidity/cypress/bin/createAccount.ts +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env ts-node - -// @ts-ignore -import { createAccount } from '../cypress/tasks/createAccount'; -const [privateKey] = process.argv.slice(2); -if (!privateKey) { - throw new Error('Usage: ./approveCollateral.ts '); -} -createAccount({ privateKey }); diff --git a/liquidity/cypress/bin/getSnx.ts b/liquidity/cypress/bin/getSnx.ts deleted file mode 100755 index 7c25eca88..000000000 --- a/liquidity/cypress/bin/getSnx.ts +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env ts-node - -// @ts-ignore -import { getSnx } from '../cypress/tasks/getSnx'; -const [address, amount] = process.argv.slice(2); -if (!address || !amount) { - throw new Error('Usage: ./getSnx.ts
'); -} -getSnx({ address, amount: parseFloat(amount) }); diff --git a/liquidity/cypress/bin/setEthBalance.ts b/liquidity/cypress/bin/setEthBalance.ts deleted file mode 100755 index 643e5c0df..000000000 --- a/liquidity/cypress/bin/setEthBalance.ts +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env ts-node - -// @ts-ignore -import { setEthBalance } from '../cypress/tasks/setEthBalance'; -const [address, balance] = process.argv.slice(2); -if (!address || !balance) { - throw new Error('Usage: ./setEthBalance.ts
'); -} -setEthBalance({ address, balance }); diff --git a/liquidity/cypress/cypress.config.js b/liquidity/cypress/cypress.config.js deleted file mode 100644 index 263833e13..000000000 --- a/liquidity/cypress/cypress.config.js +++ /dev/null @@ -1,62 +0,0 @@ -const { defineConfig } = require('cypress'); - -module.exports = defineConfig({ - reporter: 'junit', - reporterOptions: { - mochaFile: './cypress/reports/junit-results.[hash].xml', - toConsole: false, - }, - - component: { - watchForFileChanges: false, - specPattern: ['../**/*.cy.{js,jsx,ts,tsx}'], - devServer: { - framework: 'react', - bundler: 'webpack', - webpackConfig: require('@snx-v3/liquidity/webpack.config'), - }, - setupNodeEvents(on, config) { - require('@cypress/code-coverage/task')(on, config); - return config; - }, - }, - - e2e: { - watchForFileChanges: false, - specPattern: ['../**/*.e2e.{js,jsx,ts,tsx}'], - baseUrl: 'http://localhost:3000', - setupNodeEvents(on, config) { - if (process.env.CI) { - on('before:browser:launch', require('@snx-cy/printBrowserLogs').printBrowserLogs); - require('@cypress/code-coverage/task')(on, config); - } - on('task', { - ...require('./cypress/tasks/automineBlocks'), - ...require('./cypress/tasks/mineBlock'), - ...require('./cypress/tasks/setEthBalance'), - ...require('./cypress/tasks/wrapEth'), - ...require('./cypress/tasks/getCollateralConfig'), - ...require('./cypress/tasks/getSnx'), - ...require('./cypress/tasks/createAccount'), - ...require('./cypress/tasks/approveCollateral'), - ...require('./cypress/tasks/depositCollateral'), - ...require('./cypress/tasks/delegateCollateral'), - ...require('./cypress/tasks/borrowUsd'), - ...require('./cypress/tasks/setConfig'), - ...require('./cypress/tasks/getSUSDC'), - ...require('./cypress/tasks/getUSDC'), - ...require('./cypress/tasks/isBase'), - }); - - return config; - }, - - retries: { - runMode: 1, - openMode: 0, - }, - defaultCommandTimeout: 90_000, - execTimeout: 120_000, - taskTimeout: 300_000, // sometimes Anvil needs quite a bit of time to complete impersonating tx - }, -}); diff --git a/liquidity/cypress/cypress.d.ts b/liquidity/cypress/cypress.d.ts deleted file mode 100644 index b4d2b6c45..000000000 --- a/liquidity/cypress/cypress.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { mount } from 'cypress/react'; -import { ethers } from 'ethers'; - -// Augment the Cypress namespace to include type definitions for -// your custom command. -// Alternatively, can be defined in cypress/support/component.d.ts -// with a at the top of your spec. -declare global { - namespace Cypress { - interface Chainable { - mount: typeof mount; - connectWallet: (namespace?: string) => Promise; - } - } -} diff --git a/liquidity/cypress/cypress/.gitignore b/liquidity/cypress/cypress/.gitignore deleted file mode 100644 index 74798a0ca..000000000 --- a/liquidity/cypress/cypress/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -# cypress ignores -videos -screenshots -reports -forks diff --git a/liquidity/cypress/cypress/e2e/Create Account.e2e.js b/liquidity/cypress/cypress/e2e/Create Account.e2e.js deleted file mode 100644 index 7ab241f23..000000000 --- a/liquidity/cypress/cypress/e2e/Create Account.e2e.js +++ /dev/null @@ -1,24 +0,0 @@ -it('Create Account', () => { - cy.connectWallet().then((wallet) => { - cy.task('setEthBalance', { address: wallet.address, balance: 2 }); - }); - - cy.viewport(1200, 900); - cy.visit('/'); - - cy.get('[data-cy="account-menu-button"]').click(); - cy.contains('[data-cy="create-new-account-menu-item"]', 'Create Account').should('exist'); - - // Create account - cy.get('[data-cy="header-wallet-address-button"]').click(); - cy.get('[data-cy="create-new-account-menu-item"]').click(); - cy.get('[data-cy="header-account-list"]').children().should('have.length', 1); - - // The account id in the url should be the same as in the header - cy.url().then((url) => { - const [baseUrl, fragment] = url.split('/#/'); - const params = new URL(`${baseUrl}${fragment}`).searchParams; - const accountId = params.get('accountId'); - cy.get(`[data-cy="account-${accountId}"]`).should('exist'); - }); -}); diff --git a/liquidity/cypress/cypress/e2e/Home - Connected.e2e.js b/liquidity/cypress/cypress/e2e/Home - Connected.e2e.js deleted file mode 100644 index 8956a4972..000000000 --- a/liquidity/cypress/cypress/e2e/Home - Connected.e2e.js +++ /dev/null @@ -1,46 +0,0 @@ -it('Home Connected', () => { - cy.connectWallet().then((wallet) => { - cy.task('setEthBalance', { address: wallet.address, balance: 2 }); - - cy.viewport(1200, 900); - cy.visit('/'); - - cy.get('[data-cy="liquidity-home"]').contains('The Liquidity Layer of DeFi'); - cy.get('[data-cy="account-menu-button"]').click(); - cy.get('[data-cy="create-new-account-menu-item"]').contains('Create Account'); - - // Create account - cy.task('setEthBalance', { address: wallet.address, balance: 2 }); - cy.get('[data-cy="header-wallet-address-button"]').click(); - cy.get('[data-cy="create-new-account-menu-item"]').click(); - cy.get('[data-cy="header-account-list"]').children().should('have.length', 1); - - // The account id in the url should be the same as in the header - cy.url().then((url) => { - const [baseUrl, fragment] = url.split('/#/'); - const params = new URL(`${baseUrl}${fragment}`).searchParams; - - const accountId = params.get('accountId'); - - cy.get(`[data-cy="account-${accountId}"]`).should('exist'); - }); - - cy.get('@wallet').then((wallet) => { - cy.get('[data-cy="header-wallet-address-display"]').contains( - `${wallet.address.substring(0, 6)}...${wallet.address.substring(wallet.address.length - 4)}` - ); - }); - - // Check the dashboard - cy.visit('/#/dashboard'); - cy.get('[data-cy="liquidity-dashboard"]').contains('Dashboard'); - // Assets are temporarily disabled - // cy.get('[data-cy="asset-list-wallet-balance"]').contains('$0.00'); - // cy.get('[data-cy="asset-list-account-balance"]').contains('$0.00'); - // cy.get('[data-cy="asset-list-locked-balance"]').contains('$0.00'); - // cy.get('[data-cy="assets-deposit-button"]').contains('Deposit'); - // cy.get('[data-cy="Total Unlocked-stats-box"]').contains('$0.00'); - cy.get('[data-cy="Total Locked-stats-box"]').contains('$0.00'); - // cy.get('[data-cy="Total Debt-stats-box"]').contains('$0.00'); - }); -}); diff --git a/liquidity/cypress/cypress/e2e/Home - Not Connected.e2e.js b/liquidity/cypress/cypress/e2e/Home - Not Connected.e2e.js deleted file mode 100644 index 7392bbc82..000000000 --- a/liquidity/cypress/cypress/e2e/Home - Not Connected.e2e.js +++ /dev/null @@ -1,16 +0,0 @@ -it('Home Not Connected', () => { - cy.viewport(1200, 900); - cy.visit('/'); - cy.get('[data-cy="header-connect-wallet"]').contains('Connect Wallet'); - cy.get('[data-cy="liquidity-home"]').contains('The Liquidity Layer of DeFi'); - - cy.visit('/#/dashboard'); - - cy.get('[data-cy="liquidity-dashboard"]').contains('Dashboard'); - // Assets are temporarily disabled - // cy.get('[data-cy="connect-button-asset-table"]').contains('Connect Wallet'); - cy.get('[data-cy="connect-button-position-table"]').contains('Connect Wallet'); - cy.get('[data-cy="Total Locked-stats-box"]').contains('$0.00'); - // cy.get('[data-cy="Total Unlocked-stats-box"]').contains('$0.00'); - // cy.get('[data-cy="Total Debt-stats-box"]').contains('$0.00'); -}); diff --git a/liquidity/cypress/cypress/e2e/Manage Position - Andromeda USDC Deposit.e2e.js b/liquidity/cypress/cypress/e2e/Manage Position - Andromeda USDC Deposit.e2e.js deleted file mode 100644 index 228b4c2ed..000000000 --- a/liquidity/cypress/cypress/e2e/Manage Position - Andromeda USDC Deposit.e2e.js +++ /dev/null @@ -1,69 +0,0 @@ -import { generatePath } from 'react-router-dom'; - -it.skip('should deposit additional USDC collateral', () => { - cy.task('isBase').then((isBase) => { - if (!isBase) { - return; - } - - cy.connectWallet().then(({ address, privateKey }) => { - cy.task('setEthBalance', { address, balance: 100 }); - cy.task('getUSDC', { address: address, amount: 500 }); - cy.task('createAccount', { privateKey }).then((accountId) => { - cy.wrap(accountId).as('accountId'); - }); - }); - - cy.get('@accountId').then(async (accountId) => { - const path = generatePath('/positions/:collateralSymbol/:poolId', { - collateralSymbol: 'USDC', - poolId: 1, - }); - cy.visit(`/#${path}?manageAction=deposit&accountId=${accountId}`); - cy.wait(1000); - }); - - cy.task('mineBlock'); - - cy.get('[data-cy="manage-action-deposit"]').click(); - cy.get('[data-testid="deposit amount input"]').type('101'); - cy.get('[data-testid="deposit submit"]').should('be.enabled').click(); - - cy.get('[data-cy="deposit-modal"]').should('exist').and('include.text', 'Complete this action'); - - cy.get('[data-cy="deposit-modal"]') - .should('include.text', 'Approve USDC transfer') - .and('include.text', 'Delegate USDC') - .and('include.text', 'This will deposit and delegate 101 USDC to Spartan Council Pool'); - - cy.get('[data-cy="deposit-confirm-button"]').should('include.text', 'Start').click(); - - cy.get('[data-cy="deposit-confirm-button"]') - .should('include.text', 'Done') - .and('be.enabled') - .click(); - - cy.get('[data-cy="manage stats collateral"]').should('include.text', '101 USDC'); - cy.get('[data-testid="deposit amount input"]').type('101'); - - cy.get('[data-testid="deposit submit"]').should('be.enabled').click(); - - cy.get('[data-cy="deposit-modal"]').should('exist').and('include.text', 'Complete this action'); - - cy.get('[data-cy="deposit-modal"]') - .should('include.text', 'Approve USDC transfer') - .and('include.text', 'Delegate USDC') - .and('include.text', 'This will deposit and delegate 101 USDC to Spartan Council Pool'); - - cy.get('[data-cy="deposit-confirm-button"]').should('include.text', 'Start').click(); - - cy.get('[data-cy="deposit-confirm-button"]') - .should('include.text', 'Done') - .and('be.enabled') - .click(); - - cy.get('[data-cy="deposit-modal"]').should('not.exist'); - - cy.get('[data-cy="manage stats collateral"]').should('include.text', '202 USDC'); - }); -}); diff --git a/liquidity/cypress/cypress/e2e/Manage Position - Deposit.e2e.js b/liquidity/cypress/cypress/e2e/Manage Position - Deposit.e2e.js deleted file mode 100644 index 1c34f21ba..000000000 --- a/liquidity/cypress/cypress/e2e/Manage Position - Deposit.e2e.js +++ /dev/null @@ -1,130 +0,0 @@ -import { generatePath } from 'react-router-dom'; - -it('should deposit additional WETH collateral', () => { - cy.task('isBase').then((isBase) => { - if (isBase) { - return; - } - cy.connectWallet().then(({ address, privateKey }) => { - cy.task('setEthBalance', { address, balance: 100 }); - cy.task('wrapEth', { privateKey: privateKey, amount: 50 }); - cy.task('approveCollateral', { privateKey: privateKey, symbol: 'WETH' }); - cy.task('createAccount', { privateKey }).then((accountId) => { - cy.wrap(accountId).as('accountId'); - }); - - cy.get('@accountId').then(async (accountId) => { - const path = generatePath('/positions/:collateralSymbol/:poolId', { - collateralSymbol: 'WETH', - poolId: 1, - }); - cy.visit(`/#${path}?manageAction=deposit&accountId=${accountId}`); - cy.wait(1000); - }); - cy.task('mineBlock'); - cy.get('[data-cy="manage-action-deposit"]').click(); - - cy.wait(5000); - - cy.get('[data-testid="deposit amount input"]').type(isBase ? '101' : '10'); - - cy.get('[data-testid="deposit submit"]').should('be.enabled').click(); - - cy.get('[data-cy="deposit-modal"]') - .should('exist') - .and('include.text', 'Complete this action'); - - cy.get('[data-cy="deposit-modal"]') - .should('include.text', 'Approve WETH transfer') - .and('include.text', 'Delegate WETH') - .and('include.text', 'This will deposit and delegate 10 WETH to Spartan Council Pool.'); - - cy.get('[data-cy="deposit-confirm-button"]').should('include.text', 'Start').click(); - - cy.get('[data-cy="deposit-confirm-button"]') - .should('include.text', 'Done') - .and('be.enabled') - .click(); - - cy.get('[data-cy="manage stats collateral"]').should('include.text', '10 WETH'); - - cy.get('[data-testid="deposit amount input"]').type('10'); - - cy.get('[data-testid="deposit submit"]').should('be.enabled').click(); - - cy.get('[data-cy="deposit-modal"]') - .should('exist') - .and('include.text', 'Complete this action'); - - cy.get('[data-cy="deposit-modal"]') - .should('include.text', 'Approve WETH transfer') - .and('include.text', 'Delegate WETH') - .and('include.text', 'This will deposit and delegate 10 WETH to Spartan Council Pool.'); - - cy.get('[data-cy="deposit-confirm-button"]').should('include.text', 'Start').click(); - - cy.get('[data-cy="deposit-confirm-button"]') - .should('include.text', 'Done') - .and('be.enabled') - .click(); - - cy.get('[data-cy="deposit-modal"]').should('not.exist'); - - cy.get('[data-cy="manage stats collateral"]').should('include.text', '20 WETH'); - }); - - cy.get('@accountId').then(async (accountId) => { - const path = generatePath('/positions/:collateralSymbol/:poolId', { - collateralSymbol: 'WETH', - poolId: 1, - }); - cy.visit(`/#${path}?manageAction=deposit&accountId=${accountId}`); - cy.wait(1000); - }); - - cy.task('mineBlock'); - cy.get('[data-cy="manage-action-deposit"]').click(); - - cy.get('[data-testid="deposit amount input"]').type('10'); - - cy.get('[data-testid="deposit submit"]').should('be.enabled').click(); - - cy.get('[data-cy="deposit-modal"]').should('exist').and('include.text', 'Complete this action'); - - cy.get('[data-cy="deposit-modal"]') - .should('include.text', 'Approve WETH transfer') - .and('include.text', 'Delegate WETH') - .and('include.text', 'This will deposit and delegate 10 WETH to Spartan Council Pool.'); - - cy.get('[data-cy="deposit-confirm-button"]').should('include.text', 'Start').click(); - - cy.get('[data-cy="deposit-confirm-button"]') - .should('include.text', 'Done') - .and('be.enabled') - .click(); - - cy.get('[data-cy="manage stats collateral"]').should('include.text', '30 WETH'); - - cy.get('[data-testid="deposit amount input"]').type('10'); - - cy.get('[data-testid="deposit submit"]').should('be.enabled').click(); - - cy.get('[data-cy="deposit-modal"]').should('exist').and('include.text', 'Complete this action'); - - cy.get('[data-cy="deposit-modal"]') - .should('include.text', 'Approve WETH transfer') - .and('include.text', 'Delegate WETH') - .and('include.text', 'This will deposit and delegate 10 WETH to Spartan Council Pool.'); - - cy.get('[data-cy="deposit-confirm-button"]').should('include.text', 'Start').click(); - - cy.get('[data-cy="deposit-confirm-button"]') - .should('include.text', 'Done') - .and('be.enabled') - .click(); - - cy.get('[data-cy="deposit-modal"]').should('not.exist'); - - cy.get('[data-cy="manage stats collateral"]').should('include.text', '40 WETH'); - }); -}); diff --git a/liquidity/cypress/cypress/e2e/Manage Position - Repay.e2e.js b/liquidity/cypress/cypress/e2e/Manage Position - Repay.e2e.js deleted file mode 100644 index 59aaf042c..000000000 --- a/liquidity/cypress/cypress/e2e/Manage Position - Repay.e2e.js +++ /dev/null @@ -1,89 +0,0 @@ -import { generatePath } from 'react-router-dom'; - -it('should repay borrowed snxUSD and get back WETH collateral', () => { - cy.task('isBase').then((isBase) => { - if (isBase) { - return; - } - - cy.connectWallet().then(({ address, privateKey }) => { - cy.task('setEthBalance', { address, balance: 105 }); - - cy.task('approveCollateral', { privateKey: privateKey, symbol: 'WETH' }); - cy.task('wrapEth', { privateKey: privateKey, amount: 20 }); - - cy.task('createAccount', { privateKey }).then((accountId) => { - cy.wrap(accountId).as('accountId'); - cy.task('depositCollateral', { - privateKey, - symbol: 'WETH', - accountId, - amount: 10, - }); - cy.task('delegateCollateral', { - privateKey, - symbol: 'WETH', - accountId, - amount: 10, - poolId: 1, - }); - cy.task('borrowUsd', { - privateKey, - symbol: 'WETH', - accountId, - amount: 10, - poolId: 1, - }).then((debt) => cy.wrap(debt).as('debt')); - }); - }); - - cy.viewport(1000, 800); - - cy.get('@accountId').then((accountId) => { - const path = generatePath('/positions/:collateralSymbol/:poolId', { - collateralSymbol: 'WETH', - poolId: 1, - }); - cy.visit(`/#${path}?manageAction=repay&accountId=${accountId}`); - }); - cy.wait(7000); - cy.get('[data-cy="manage-action-repay"]').click(); - - // Need to wait for max repay amount to be fetched - cy.get('[data-testid="repay amount input"]') - .should('have.attr', 'data-max') - .and('not.match', /^0\.00/); // .and ensures both assertions are waiting for resolution - - cy.get('@debt').then((debt) => { - cy.get('[data-testid="repay amount input"]').type(`${debt}`); - }); - - cy.get('[data-testid="repay submit"]').should('be.enabled').click(); - - cy.get('[data-testid="repay modal"]') - .should('exist') - .and('include.text', 'Complete this action'); - cy.get('[data-testid="repay modal"]') - .should('exist') - .and('include.text', 'Approve sUSD transfer'); - - cy.get('@debt').then((debt) => { - cy.get('[data-testid="repay modal"]').should('include.text', `Repay ${debt} sUSD`); - }); - - // Repay - cy.get('[data-testid="repay confirm button"]').should('include.text', 'Start').click(); - cy.get('[data-testid="repay confirm button"]') - .should('include.text', 'Processing...') - .and('be.disabled'); - - cy.get('[data-testid="repay confirm button"]') - .should('include.text', 'Done') - .and('be.enabled') - .click(); - - cy.get('[data-testid="repay modal"]').should('not.exist'); - - cy.get('[data-cy="manage-stats-debt-value"]').should('have.text', `$0`); - }); -}); diff --git a/liquidity/cypress/cypress/lib/metamask.js b/liquidity/cypress/cypress/lib/metamask.js deleted file mode 100644 index 3f9eb91ef..000000000 --- a/liquidity/cypress/cypress/lib/metamask.js +++ /dev/null @@ -1,38 +0,0 @@ -import { ethers } from 'ethers'; - -export function metamask({ pk, address }) { - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - return new Proxy(provider, { - get(target, prop) { - switch (prop) { - case 'chainId': - return `0x${Number(provider._network.chainId).toString(16)}`; - case 'isMetaMask': - return true; - case 'getSigner': - return () => { - const wallet = new ethers.Wallet(pk); - return wallet.connect(provider); - }; - case 'request': - return async ({ method, params }) => { - switch (method) { - case 'eth_accounts': - case 'eth_requestAccounts': - return [address]; - case 'eth_sendTransaction': - await provider.send('anvil_impersonateAccount', [address]); - const result = await provider.send(method, params); - await provider.send('anvil_stopImpersonatingAccount', [address]); - return result; - default: { - return await provider.send(method, params); - } - } - }; - default: - return target[prop]; - } - }, - }); -} diff --git a/liquidity/cypress/cypress/lib/subgraph.js b/liquidity/cypress/cypress/lib/subgraph.js deleted file mode 100644 index 8b6fe81bc..000000000 --- a/liquidity/cypress/cypress/lib/subgraph.js +++ /dev/null @@ -1,17 +0,0 @@ -export function subgraph(req) { - const body = JSON.parse(req.body); - if (body.query.trim().startsWith('query pool($id: String)')) { - return req.reply({ - data: { - pool: { - id: body.variables.id, - name: 'TEST_POOL', - total_weight: (1e18).toString(), - configurations: [], - }, - }, - }); - } - - return req.reply({ data: null }); -} diff --git a/liquidity/cypress/cypress/lib/testname.js b/liquidity/cypress/cypress/lib/testname.js deleted file mode 100644 index 8408c713f..000000000 --- a/liquidity/cypress/cypress/lib/testname.js +++ /dev/null @@ -1,3 +0,0 @@ -export function testname() { - return Cypress.currentTest.titlePath.join('--').replace(/[^\w-]+/gi, '-'); -} diff --git a/liquidity/cypress/cypress/support/component-index.html b/liquidity/cypress/cypress/support/component-index.html deleted file mode 100644 index 5aaab9c5f..000000000 --- a/liquidity/cypress/cypress/support/component-index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - Components App - - -
- - diff --git a/liquidity/cypress/cypress/support/component.js b/liquidity/cypress/cypress/support/component.js deleted file mode 100644 index fb4515d97..000000000 --- a/liquidity/cypress/cypress/support/component.js +++ /dev/null @@ -1,18 +0,0 @@ -import { ChakraProvider } from '@chakra-ui/react'; -import '@cypress/code-coverage/support'; - -import { theme } from '@synthetixio/v3-theme'; -import { mount } from 'cypress/react18'; -import { MemoryRouter } from 'react-router-dom'; - -function Container(props) { - return ( - - -
- - - ); -} - -Cypress.Commands.add('mount', (el) => mount({el})); diff --git a/liquidity/cypress/cypress/support/e2e.js b/liquidity/cypress/cypress/support/e2e.js deleted file mode 100644 index 009d983f5..000000000 --- a/liquidity/cypress/cypress/support/e2e.js +++ /dev/null @@ -1,57 +0,0 @@ -import '@cypress/code-coverage/support'; -import { onLogAdded } from '@snx-cy/onLogAdded'; -import { ethers } from 'ethers'; -import { metamask } from '../lib/metamask'; -import { subgraph } from '../lib/subgraph'; - -beforeEach(() => { - cy.on('log:added', onLogAdded); - - cy.intercept('https://analytics.synthetix.io/matomo.js', { statusCode: 204 }).as('matomo'); - - // Because we are working with local fork, subgraph becomes irrelevant - cy.intercept('https://api.thegraph.com/**', (req) => { - return subgraph(req); - }).as('subgraph'); - - cy.intercept('https://subgraph.satsuma-prod.com/**', (req) => { - return subgraph(req); - }).as('subgraph'); - - [ - 'mainnet', - 'optimism-mainnet', - 'base-mainnet', - 'sepolia', - 'base-sepolia', - 'arbitrum-mainnet', - 'arbitrum-sepolia', - ].forEach((networkName) => { - cy.intercept(`https://${networkName}.infura.io/v3/**`, (req) => { - req.url = 'http://127.0.0.1:8545'; - req.continue(); - }).as(networkName); - }); - - cy.on('window:before:load', (win) => { - win.sessionStorage.setItem('TERMS_CONDITIONS_ACCEPTED', 'true'); - win.localStorage.setItem( - 'DEFAULT_NETWORK', - `${Cypress.env('CHAIN_ID')}-${Cypress.env('PRESET')}` - ); - win.localStorage.setItem('UNSAFE_IMPORT', 'true'); - win.localStorage.setItem('connectedWallets', '"MetaMask"'); - win.localStorage.setItem('CONTRACT_ERROR_OPEN', 'true'); - }); -}); - -Cypress.Commands.add('connectWallet', (namespace = 'wallet') => { - const wallet = ethers.Wallet.createRandom(); - const privateKey = wallet.privateKey; - const address = wallet.address; - cy.on('window:before:load', (win) => { - win.ethereum = metamask({ privateKey, address }); - }); - - return cy.wrap(wallet).as(namespace); -}); diff --git a/liquidity/cypress/cypress/tasks/approveCollateral.js b/liquidity/cypress/cypress/tasks/approveCollateral.js deleted file mode 100644 index 14ded41e6..000000000 --- a/liquidity/cypress/cypress/tasks/approveCollateral.js +++ /dev/null @@ -1,21 +0,0 @@ -import { ethers } from 'ethers'; -import { importCoreProxy } from './importCoreProxy'; -import { getCollateralConfig } from './getCollateralConfig'; - -export async function approveCollateral({ privateKey, symbol }) { - const CoreProxy = await importCoreProxy(); - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - const wallet = new ethers.Wallet(privateKey, provider); - const config = await getCollateralConfig(symbol); - console.log('approveCollateral', { wallet: wallet.address, symbol }); - - const contract = new ethers.Contract( - config.tokenAddress, - ['function approve(address spender, uint256 amount) returns (bool)'], - wallet - ); - - const tx = await contract.approve(CoreProxy.address, ethers.constants.MaxUint256); - await tx.wait(); - return null; -} diff --git a/liquidity/cypress/cypress/tasks/automineBlocks.js b/liquidity/cypress/cypress/tasks/automineBlocks.js deleted file mode 100644 index 06170ce5c..000000000 --- a/liquidity/cypress/cypress/tasks/automineBlocks.js +++ /dev/null @@ -1,9 +0,0 @@ -import { ethers } from 'ethers'; - -export async function automineBlocks({ enabled }) { - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - console.log('automineBlocks', { oldAutomine: await provider.send('anvil_getAutomine', []) }); - await provider.send('evm_setAutomine', [enabled]); - console.log('automineBlocks', { newAutomine: await provider.send('anvil_getAutomine', []) }); - return null; -} diff --git a/liquidity/cypress/cypress/tasks/borrowUsd.js b/liquidity/cypress/cypress/tasks/borrowUsd.js deleted file mode 100644 index 66b090729..000000000 --- a/liquidity/cypress/cypress/tasks/borrowUsd.js +++ /dev/null @@ -1,23 +0,0 @@ -import { ethers } from 'ethers'; -import { importCoreProxy } from './importCoreProxy'; -import { getCollateralConfig } from './getCollateralConfig'; - -export async function borrowUsd({ privateKey, accountId, symbol, amount, poolId }) { - const CoreProxy = await importCoreProxy(); - const config = await getCollateralConfig(symbol); - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - const wallet = new ethers.Wallet(privateKey, provider); - console.log('borrowUsd', { address: wallet.address, accountId, symbol, amount, poolId }); - - const coreProxy = new ethers.Contract(CoreProxy.address, CoreProxy.abi, wallet); - - const tx = await coreProxy.mintUsd( - ethers.BigNumber.from(accountId), - ethers.BigNumber.from(poolId), - config.tokenAddress, - ethers.utils.parseEther(`${amount}`), - { gasLimit: 10_000_000 } - ); - await tx.wait(); - return amount; -} diff --git a/liquidity/cypress/cypress/tasks/createAccount.js b/liquidity/cypress/cypress/tasks/createAccount.js deleted file mode 100644 index c1b0d5f5a..000000000 --- a/liquidity/cypress/cypress/tasks/createAccount.js +++ /dev/null @@ -1,25 +0,0 @@ -import { ethers } from 'ethers'; -import crypto from 'crypto'; -import { importCoreProxy } from './importCoreProxy'; - -export async function createAccount({ privateKey }) { - const CoreProxy = await importCoreProxy(); - - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - const wallet = new ethers.Wallet(privateKey, provider); - - const coreProxy = new ethers.Contract(CoreProxy.address, CoreProxy.abi, wallet); - - const accountId = parseInt(`1337${crypto.randomInt(1000)}`); - - const currentAccountOwner = await coreProxy.getAccountOwner(accountId); - console.log('createAccount', { accountId, currentAccountOwner }); - - const tx = await coreProxy['createAccount(uint128)'](accountId, { gasLimit: 10_000_000 }); - await tx.wait(); - - const newAccountOwner = await coreProxy.getAccountOwner(accountId); - console.log('createAccount', { accountId, newAccountOwner }); - - return accountId; -} diff --git a/liquidity/cypress/cypress/tasks/delegateCollateral.js b/liquidity/cypress/cypress/tasks/delegateCollateral.js deleted file mode 100644 index 386b94fab..000000000 --- a/liquidity/cypress/cypress/tasks/delegateCollateral.js +++ /dev/null @@ -1,28 +0,0 @@ -import { ethers } from 'ethers'; -import { getCollateralConfig } from './getCollateralConfig'; -import { importCoreProxy } from './importCoreProxy'; - -export async function delegateCollateral({ privateKey, accountId, symbol, amount, poolId }) { - const CoreProxy = await importCoreProxy(); - const config = await getCollateralConfig(symbol); - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - const wallet = new ethers.Wallet(privateKey, provider); - console.log('delegateCollateral', { address: wallet.address, accountId, symbol, amount, poolId }); - - const coreProxy = new ethers.Contract(CoreProxy.address, CoreProxy.abi, wallet); - try { - const tx = await coreProxy.delegateCollateral( - ethers.BigNumber.from(accountId), - ethers.BigNumber.from(poolId), - config.tokenAddress, - ethers.utils.parseEther(`${amount}`), - ethers.utils.parseEther(`1`), - { gasLimit: 10_000_000 } - ); - await tx.wait(); - return accountId; - } catch (error) { - console.log('error: ', error); - return false; - } -} diff --git a/liquidity/cypress/cypress/tasks/depositCollateral.js b/liquidity/cypress/cypress/tasks/depositCollateral.js deleted file mode 100644 index a758c465a..000000000 --- a/liquidity/cypress/cypress/tasks/depositCollateral.js +++ /dev/null @@ -1,23 +0,0 @@ -import { ethers } from 'ethers'; -import { getCollateralConfig } from './getCollateralConfig'; -import { importCoreProxy } from './importCoreProxy'; - -export async function depositCollateral({ privateKey, accountId, symbol, amount }) { - const CoreProxy = await importCoreProxy(); - const config = await getCollateralConfig(symbol); - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - const wallet = new ethers.Wallet(privateKey, provider); - console.log('depositCollateral', { address: wallet.address, accountId, symbol, amount }); - - const coreProxy = new ethers.Contract(CoreProxy.address, CoreProxy.abi, wallet); - - const tx = await coreProxy.deposit( - ethers.BigNumber.from(accountId), - config.tokenAddress, - ethers.utils.parseEther(`${amount}`), - { gasLimit: 10_000_000 } - ); - await tx.wait(); - - return accountId; -} diff --git a/liquidity/cypress/cypress/tasks/getCollateralConfig.js b/liquidity/cypress/cypress/tasks/getCollateralConfig.js deleted file mode 100644 index f4c503f6f..000000000 --- a/liquidity/cypress/cypress/tasks/getCollateralConfig.js +++ /dev/null @@ -1,15 +0,0 @@ -import { importCollateralTokens } from './importCollateralTokens'; - -export async function getCollateralConfig(symbol) { - const collateralConfigs = await importCollateralTokens(); - for (const config of collateralConfigs) { - try { - if (config.symbol === symbol && config.depositingEnabled) { - return config; - } - } catch (e) { - // nevermind - } - } - throw new Error(`Collateral config for "${symbol}" does not exist`); -} diff --git a/liquidity/cypress/cypress/tasks/getSUSDC.js b/liquidity/cypress/cypress/tasks/getSUSDC.js deleted file mode 100644 index 5c1669980..000000000 --- a/liquidity/cypress/cypress/tasks/getSUSDC.js +++ /dev/null @@ -1,63 +0,0 @@ -import { ethers } from 'ethers'; -import { getCollateralConfig } from './getCollateralConfig'; -import { setEthBalance } from './setEthBalance'; -import { importCoreProxy } from './importCoreProxy'; - -export async function getSUSDC({ address, amount }) { - const config = await getCollateralConfig('sUSDC'); - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - - const CoreProxy = await importCoreProxy(); - const coreProxy = new ethers.Contract(CoreProxy.address, CoreProxy.abi, provider); - const owner = await coreProxy.owner(); - - await setEthBalance({ address: owner, balance: 1000 }); - await setEthBalance({ address: CoreProxy.address, balance: 1000 }); - - console.log({ - tokenAddress: config.tokenAddress, - }); - - const erc20 = new ethers.Contract( - config.tokenAddress, - [ - 'function balanceOf(address account) view returns (uint256)', - 'function transfer(address to, uint256 value) returns (bool)', - ], - provider - ); - - const oldBalance = parseFloat(ethers.utils.formatUnits(await erc20.balanceOf(address))); - - console.log('getSUSD', { - address, - oldBalance, - }); - - if (oldBalance > amount) { - console.log('getSUSD', { result: 'SKIP' }); - return; - } - - const ownerBalance = parseFloat( - ethers.utils.formatUnits(await erc20.balanceOf(CoreProxy.address)) - ); - console.log('getSUSD', { CoreProxy: CoreProxy.address, balance: ownerBalance }); - - console.log({ - amount: ethers.utils.parseEther(`${amount}`).toString(), - }); - await provider.send('anvil_impersonateAccount', [CoreProxy.address]); - const signer = provider.getSigner(CoreProxy.address); - - const transferTx = await erc20 - .connect(signer) - .transfer(address, ethers.utils.parseEther(`${amount}`)); - await transferTx.wait(); - await provider.send('anvil_stopImpersonatingAccount', [CoreProxy.address]); - - const newBalance = parseFloat(ethers.utils.formatUnits(await erc20.balanceOf(CoreProxy.address))); - console.log('getSUSD', { address, newBalance }); - - return null; -} diff --git a/liquidity/cypress/cypress/tasks/getSnx.js b/liquidity/cypress/cypress/tasks/getSnx.js deleted file mode 100644 index 257ad65c8..000000000 --- a/liquidity/cypress/cypress/tasks/getSnx.js +++ /dev/null @@ -1,75 +0,0 @@ -import { ethers } from 'ethers'; -import { getCollateralConfig } from './getCollateralConfig'; -import { setEthBalance } from './setEthBalance'; - -async function getOwner() { - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - const network = await provider.getNetwork(); - - switch (network.chainId) { - case 1: - return '0xAc86855865CbF31c8f9FBB68C749AD5Bd72802e3'; // RewardEscrowV2 - case 5: - return '0x48914229dedd5a9922f44441ffccfc2cb7856ee9'; - case 10: - return '0x5Fc9B8d2B7766f061bD84a41255fD1A76Fd1FAa2'; // ImportableRewardEscrowV2 - case 420: - return '0x48914229dedd5a9922f44441ffccfc2cb7856ee9'; - default: - throw new Error(`Unsupported chain ${network.chainId}`); - } -} - -export async function getSnx({ address, amount }) { - const config = await getCollateralConfig('SNX'); - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - - const owner = await getOwner(); - - // const coreProxy = new ethers.Contract(CoreProxy.address, CoreProxy.abi, provider); - // const owner = await coreProxy.owner(); - // console.log('getSnx', { owner }); - await setEthBalance({ address: owner, balance: 1000 }); - - console.log({ - tokenAddress: config.tokenAddress, - }); - const erc20 = new ethers.Contract( - config.tokenAddress, - [ - 'function balanceOf(address account) view returns (uint256)', - 'function transfer(address to, uint256 value) returns (bool)', - ], - provider - ); - - const oldBalance = parseFloat(ethers.utils.formatUnits(await erc20.balanceOf(address))); - console.log('getSnx', { - address, - oldBalance, - }); - - if (oldBalance > amount) { - console.log('getSnx', { result: 'SKIP' }); - return; - } - - const ownerBalance = parseFloat(ethers.utils.formatUnits(await erc20.balanceOf(owner))); - console.log('getSnx', { owner, ownerBalance }); - - console.log({ - amount: ethers.utils.parseEther(`${amount}`).toString(), - }); - await provider.send('anvil_impersonateAccount', [owner]); - const signer = provider.getSigner(owner); - const transferTx = await erc20 - .connect(signer) - .transfer(address, ethers.utils.parseEther(`${amount}`)); - await transferTx.wait(); - await provider.send('anvil_stopImpersonatingAccount', [owner]); - - const newBalance = parseFloat(ethers.utils.formatUnits(await erc20.balanceOf(address))); - console.log('getSnx', { address, newBalance }); - - return null; -} diff --git a/liquidity/cypress/cypress/tasks/getUSDC.js b/liquidity/cypress/cypress/tasks/getUSDC.js deleted file mode 100644 index b0d579dc2..000000000 --- a/liquidity/cypress/cypress/tasks/getUSDC.js +++ /dev/null @@ -1,56 +0,0 @@ -import { ethers } from 'ethers'; - -const usdcAddressBase = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; -const circleAddressBase = '0xd34ea7278e6bd48defe656bbe263aef11101469c'; - -export async function getUSDC({ address, amount }) { - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - - const erc20 = new ethers.Contract( - usdcAddressBase, - [ - 'function balanceOf(address account) view returns (uint256)', - 'function transfer(address to, uint256 value) returns (bool)', - ], - provider - ); - - const oldBalance = parseFloat(ethers.utils.formatUnits(await erc20.balanceOf(address))); - - console.log('getUSDC', { - address, - oldBalance, - }); - - if (oldBalance > amount) { - console.log('getUSDC', { result: 'SKIP' }); - return; - } - - const circleBalance = parseFloat( - ethers.utils.formatUnits(await erc20.balanceOf(circleAddressBase), 6) - ); - - console.log('getSUSD', { circleAddressBase, circleBalance }); - - const transferAmount = ethers.utils.parseUnits(`${amount}`, 6).toString(); - - console.log({ - amount: transferAmount, - }); - - await provider.send('anvil_impersonateAccount', [circleAddressBase]); - - const signer = provider.getSigner(circleAddressBase); - - const transferTx = await erc20.connect(signer).transfer(address, transferAmount); - - await transferTx.wait(); - - await provider.send('anvil_stopImpersonatingAccount', [circleAddressBase]); - - const newBalance = parseFloat(ethers.utils.formatUnits(await erc20.balanceOf(address))); - console.log('getUSDC', { address, newBalance }); - - return newBalance; -} diff --git a/liquidity/cypress/cypress/tasks/importCollateralTokens.js b/liquidity/cypress/cypress/tasks/importCollateralTokens.js deleted file mode 100644 index b4a8df3cb..000000000 --- a/liquidity/cypress/cypress/tasks/importCollateralTokens.js +++ /dev/null @@ -1,5 +0,0 @@ -import { importCollateralTokens as importer } from '@snx-v3/contracts'; - -export async function importCollateralTokens() { - return importer(process.env.CYPRESS_CHAIN_ID, process.env.CYPRESS_PRESET); -} diff --git a/liquidity/cypress/cypress/tasks/importCoreProxy.js b/liquidity/cypress/cypress/tasks/importCoreProxy.js deleted file mode 100644 index 754a335f4..000000000 --- a/liquidity/cypress/cypress/tasks/importCoreProxy.js +++ /dev/null @@ -1,5 +0,0 @@ -import { importCoreProxy as importer } from '@snx-v3/contracts'; - -export async function importCoreProxy() { - return importer(process.env.CYPRESS_CHAIN_ID, process.env.CYPRESS_PRESET); -} diff --git a/liquidity/cypress/cypress/tasks/isBase.js b/liquidity/cypress/cypress/tasks/isBase.js deleted file mode 100644 index cb80fad31..000000000 --- a/liquidity/cypress/cypress/tasks/isBase.js +++ /dev/null @@ -1,7 +0,0 @@ -import { ethers } from 'ethers'; - -export async function isBase() { - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - const network = await provider.getNetwork(); - return network.chainId === 8453 || network.chainId === 84532; -} diff --git a/liquidity/cypress/cypress/tasks/mineBlock.js b/liquidity/cypress/cypress/tasks/mineBlock.js deleted file mode 100644 index 872123221..000000000 --- a/liquidity/cypress/cypress/tasks/mineBlock.js +++ /dev/null @@ -1,15 +0,0 @@ -import { ethers } from 'ethers'; - -export async function mineBlock() { - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - console.log('mineBlock', { - oldBlockNumber: await provider.getBlockNumber(), - oldTimestamp: new Date((await provider.getBlock()).timestamp * 1000), - }); - await provider.send('evm_mine', []); - console.log('mineBlock', { - newBlockNumber: await provider.getBlockNumber(), - newTimestamp: new Date((await provider.getBlock()).timestamp * 1000), - }); - return null; -} diff --git a/liquidity/cypress/cypress/tasks/setConfig.js b/liquidity/cypress/cypress/tasks/setConfig.js deleted file mode 100644 index d3ba78970..000000000 --- a/liquidity/cypress/cypress/tasks/setConfig.js +++ /dev/null @@ -1,46 +0,0 @@ -import { ethers } from 'ethers'; -import { importCoreProxy } from './importCoreProxy'; -import { setEthBalance } from './setEthBalance'; - -export async function setConfig({ key, value }) { - const CoreProxy = await importCoreProxy(); - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - - const coreProxy = new ethers.Contract(CoreProxy.address, CoreProxy.abi, provider); - - const owner = await coreProxy.owner(); - - const signer = provider.getSigner(owner); - console.log('setConfig', { owner }); - - await setEthBalance({ address: owner, balance: 1000 }); - - await provider.send('anvil_impersonateAccount', [owner]); - console.log( - `await coreProxy.connect(signer).getConfig(ethers.utils.formatBytes32String(key))`, - await coreProxy.connect(signer).getConfig(ethers.utils.formatBytes32String(key)) - ); - const oldValue = parseInt( - await coreProxy.connect(signer).getConfig(ethers.utils.formatBytes32String(key)), - 16 - ); - console.log('setConfig', { key, oldValue }); - - const tx = await coreProxy - .connect(signer) - .setConfig( - ethers.utils.formatBytes32String(key), - ethers.utils.formatBytes32String(`${value}`), - { gasLimit: 10_000_000 } - ); - await tx.wait(); - - const newValue = parseInt( - await coreProxy.connect(signer).getConfig(ethers.utils.formatBytes32String(key)), - 16 - ); - console.log('setConfig', { key, newValue }); - await provider.send('anvil_stopImpersonatingAccount', [owner]); - - return null; -} diff --git a/liquidity/cypress/cypress/tasks/setEthBalance.js b/liquidity/cypress/cypress/tasks/setEthBalance.js deleted file mode 100644 index b6241ea2f..000000000 --- a/liquidity/cypress/cypress/tasks/setEthBalance.js +++ /dev/null @@ -1,14 +0,0 @@ -import { ethers } from 'ethers'; - -export async function setEthBalance({ address, balance }) { - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - const oldBalance = parseFloat(ethers.utils.formatUnits(await provider.getBalance(address))); - console.log('setEthBalance', { address, oldBalance }); - await provider.send('anvil_setBalance', [ - address, - ethers.utils.parseEther(`${balance}`).toHexString(), - ]); - const newBalance = parseFloat(ethers.utils.formatUnits(await provider.getBalance(address))); - console.log('setEthBalance', { address, newBalance }); - return newBalance; -} diff --git a/liquidity/cypress/cypress/tasks/wrapEth.js b/liquidity/cypress/cypress/tasks/wrapEth.js deleted file mode 100644 index c06d4cdd1..000000000 --- a/liquidity/cypress/cypress/tasks/wrapEth.js +++ /dev/null @@ -1,36 +0,0 @@ -import { ethers } from 'ethers'; -import { getCollateralConfig } from './getCollateralConfig'; - -const erc20Abi = [ - 'function symbol() view returns (string)', - 'function balanceOf(address) view returns (uint256)', - 'function deposit() payable', -]; - -export async function wrapEth({ privateKey, amount }) { - const provider = new ethers.providers.JsonRpcProvider('http://127.0.0.1:8545'); - const wallet = new ethers.Wallet(privateKey, provider); - - const WETH = await getCollateralConfig('WETH'); - const WETHContract = new ethers.Contract(WETH.tokenAddress, erc20Abi, wallet); - const balance = parseFloat( - ethers.utils.formatUnits(await WETHContract.balanceOf(wallet.address)) - ); - - if (balance >= amount) { - console.log('wrapEth', { balance }); - console.log('wrapEth', { result: 'SKIP' }); - return balance; - } - - const wrapTx = await WETHContract.deposit({ - value: ethers.utils.hexValue(ethers.utils.parseEther(`${amount}`).toHexString()), - }); - await wrapTx.wait(); - const newBalance = parseFloat( - ethers.utils.formatUnits(await WETHContract.balanceOf(wallet.address)) - ); - console.log('wrapEth', { balance: newBalance }); - console.log('wrapEth', { result: 'OK' }); - return newBalance; -} diff --git a/liquidity/cypress/package.json b/liquidity/cypress/package.json deleted file mode 100644 index 756dd72dd..000000000 --- a/liquidity/cypress/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@snx-v3/liquidity-cypress", - "private": true, - "main": "index.ts", - "version": "0.0.9", - "scripts": { - "anvil:sepolia": "anvil --fork-url https://sepolia.infura.io/v3/$INFURA_KEY", - "anvil:base": "anvil --fork-url https://base-mainnet.infura.io/v3/$INFURA_KEY", - "cy": "NODE_ENV=test cypress open --component --browser chrome", - "e2e:sepolia": "NODE_ENV=test CYPRESS_CHAIN_ID=11155111 CYPRESS_PRESET=main cypress open --e2e --browser chrome", - "e2e:base": "NODE_ENV=test CYPRESS_CHAIN_ID=8453 CYPRESS_PRESET=andromeda cypress open --e2e --browser chrome" - }, - "devDependencies": { - "@chakra-ui/react": "^2.8.2", - "@cypress/code-coverage": "^3.12.39", - "@snx-cy/onLogAdded": "workspace:*", - "@snx-cy/printBrowserLogs": "workspace:*", - "@snx-v3/contracts": "workspace:*", - "@snx-v3/liquidity": "workspace:*", - "@synthetixio/v3-theme": "workspace:*", - "cypress": "13.11.0", - "ethers": "^5.7.2", - "react-router-dom": "^6.18.0", - "ts-node": "^10.9.1" - }, - "depcheck": { - "ignoreMatches": [ - "ts-node" - ] - } -} diff --git a/liquidity/lib/ManagePositionContext/ManagePositionContext.tsx b/liquidity/lib/ManagePositionContext/ManagePositionContext.tsx deleted file mode 100644 index b3f2008be..000000000 --- a/liquidity/lib/ManagePositionContext/ManagePositionContext.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import Wei, { wei } from '@synthetixio/wei'; -import React, { createContext, useState, PropsWithChildren, Dispatch, SetStateAction } from 'react'; - -export const ManagePositionContext = createContext<{ - collateralChange: Wei; - debtChange: Wei; - withdrawAmount: Wei; - setDebtChange: Dispatch>; - setCollateralChange: Dispatch>; - setWithdrawAmount: Dispatch>; -}>({ - collateralChange: wei(0), - debtChange: wei(0), - withdrawAmount: wei(0), - // eslint-disable-next-line @typescript-eslint/no-empty-function - setDebtChange: () => {}, - // eslint-disable-next-line @typescript-eslint/no-empty-function - setCollateralChange: () => {}, - setWithdrawAmount: () => {}, -}); - -export const ManagePositionProvider: React.FC = ({ children }) => { - const [debtChange, setDebtChange] = useState(wei(0)); - const [collateralChange, setCollateralChange] = useState(wei(0)); - const [withdrawAmount, setWithdrawAmount] = useState(wei(0)); - - return ( - - {children} - - ); -}; diff --git a/liquidity/lib/ManagePositionContext/index.ts b/liquidity/lib/ManagePositionContext/index.ts deleted file mode 100644 index cd34b25a8..000000000 --- a/liquidity/lib/ManagePositionContext/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './ManagePositionContext'; diff --git a/liquidity/lib/ManagePositionContext/package.json b/liquidity/lib/ManagePositionContext/package.json deleted file mode 100644 index 803802f1f..000000000 --- a/liquidity/lib/ManagePositionContext/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@snx-v3/ManagePositionContext", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@synthetixio/wei": "^2.74.4", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/assertAddressType/assertAddressType.ts b/liquidity/lib/assertAddressType/assertAddressType.ts deleted file mode 100644 index a119ad23e..000000000 --- a/liquidity/lib/assertAddressType/assertAddressType.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function assertAddressType(tokenAddress?: string): tokenAddress is `0x${string}` { - return tokenAddress ? tokenAddress.startsWith('0x') : false; -} diff --git a/liquidity/lib/assertAddressType/index.ts b/liquidity/lib/assertAddressType/index.ts deleted file mode 100644 index 0cb5e2bf7..000000000 --- a/liquidity/lib/assertAddressType/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './assertAddressType'; diff --git a/liquidity/lib/assertAddressType/package.json b/liquidity/lib/assertAddressType/package.json deleted file mode 100644 index 700b66f21..000000000 --- a/liquidity/lib/assertAddressType/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "@snx-v3/assertAddressType", - "private": true, - "main": "index.ts", - "version": "0.0.1" -} diff --git a/liquidity/lib/calculations/calculations.test.ts b/liquidity/lib/calculations/calculations.test.ts deleted file mode 100644 index f29dd127b..000000000 --- a/liquidity/lib/calculations/calculations.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { wei } from '@synthetixio/wei'; -import { - calculateSevenDaysPnlGrowth, - calculatePoolPerformanceLifetime, - calculatePoolPerformanceSevenDays, -} from './calculations'; - -describe('calculateSevenDaysPnlGrowth', () => { - test('returns undefined when no previous snapshot missing or 0', () => { - expect(calculateSevenDaysPnlGrowth()).toBe(undefined); - expect(calculateSevenDaysPnlGrowth([])).toBe(undefined); - }); - test('return undefined for percentage when the pnl 7days ago is missing or 0', () => { - expect(calculateSevenDaysPnlGrowth([{ pnl: wei(100) }] as any)).toEqual({ - value: wei(100), - percentage: undefined, - }); - - expect(calculateSevenDaysPnlGrowth([{ pnl: wei(100) }, { pnl: wei(0) }] as any)).toEqual({ - value: wei(100), - percentage: undefined, - }); - }); - test('calculate positive growth', () => { - expect(calculateSevenDaysPnlGrowth([{ pnl: wei(100) }, { pnl: wei(50) }] as any)).toEqual({ - value: wei(50), - percentage: wei(1), - }); - }); - test('calculate negative growth', () => { - expect(calculateSevenDaysPnlGrowth([{ pnl: wei(50) }, { pnl: wei(100) }] as any)).toEqual({ - value: wei(-50), - percentage: wei(-0.5), - }); - }); - test('last week negative this week more negative', () => { - expect( - calculateSevenDaysPnlGrowth([{ pnl: wei(-5008.54) }, { pnl: wei(-569.21) }] as any) - ).toEqual({ - value: wei('-4439.330000000000000000'), - percentage: wei('-7.799107535004655575'), - }); - }); -}); - -describe('calculatePoolPerformanceLifetime', () => { - test('returns 0 when there is no configurations', () => { - expect(calculatePoolPerformanceLifetime({ configurations: [] } as any)).toEqual(wei(0)); - }); - test('returns lifetime performance', () => { - expect( - calculatePoolPerformanceLifetime({ - configurations: [{ market: { pnl: wei(60) } }, { market: { pnl: wei(40) } }], - } as any) - ).toEqual(wei(100)); - }); -}); -describe('calculatePoolPerformanceSevenDays', () => { - test('returns 0 when there is no configurations', () => { - expect(calculatePoolPerformanceSevenDays({ configurations: [] } as any)).toEqual({ - value: wei(0), - growthPercentage: undefined, - }); - }); - test('handles market_snapshots_by_week[1] (last week) missing ', () => { - expect( - calculatePoolPerformanceSevenDays({ - configurations: [ - { market: { pnl: wei(100), market_snapshots_by_week: [{ pnl: wei(100) }] } }, - ], - } as any) - ).toEqual({ - value: wei(100), - growthPercentage: undefined, - }); - }); - test('handles market_snapshots_by_week[1] (last week) having 0 pnl', () => { - expect( - calculatePoolPerformanceSevenDays({ - configurations: [ - { - market: { - pnl: wei(100), - market_snapshots_by_week: [{ pnl: wei(100) }, { pnl: wei(0) }], - }, - }, - ], - } as any) - ).toEqual({ - value: wei(100), - growthPercentage: undefined, - }); - }); - test('calculates 7days positive growth', () => { - expect( - calculatePoolPerformanceSevenDays({ - configurations: [ - { - market: { - pnl: wei(100), - market_snapshots_by_week: [{ pnl: wei(100) }, { pnl: wei(50) }], - }, - }, - ], - } as any) - ).toEqual({ - value: wei(50), - growthPercentage: wei(1), - }); - }); - test('calculates 7days negative growth', () => { - expect( - calculatePoolPerformanceSevenDays({ - configurations: [ - { - market: { - pnl: wei(50), - market_snapshots_by_week: [{ pnl: wei(50) }, { pnl: wei(100) }], - }, - }, - ], - } as any) - ).toEqual({ - value: wei(-50), - growthPercentage: wei(-0.5), - }); - }); - test('handles improving pnl that still is negative', () => { - expect( - calculatePoolPerformanceSevenDays({ - configurations: [ - { - market: { - pnl: wei(-50), - market_snapshots_by_week: [{ pnl: wei(-50) }, { pnl: wei(-100) }], - }, - }, - ], - } as any) - ).toEqual({ - value: wei(50), - growthPercentage: wei(0.5), - }); - }); - test('handles 0 growth', () => { - expect( - calculatePoolPerformanceSevenDays({ - configurations: [ - { - market: { - pnl: wei(100), - market_snapshots_by_week: [{ pnl: wei(100) }, { pnl: wei(100) }], - }, - }, - ], - } as any) - ).toEqual({ - value: wei(0), - growthPercentage: wei(0), - }); - }); -}); diff --git a/liquidity/lib/calculations/calculations.ts b/liquidity/lib/calculations/calculations.ts deleted file mode 100644 index d2ba938cf..000000000 --- a/liquidity/lib/calculations/calculations.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type { MarketSnapshotByWeekSchema, PoolType } from '@snx-v3/usePoolData'; -import { z } from 'zod'; -import { wei, Wei } from '@synthetixio/wei'; -import { ZEROWEI } from '@snx-v3/constants'; - -type MarketSnapshotByWeek = z.infer; - -export const calculateSevenDaysPnlGrowth = (marketSnapshots?: MarketSnapshotByWeek[]) => { - if (!marketSnapshots || marketSnapshots.length === 0) return undefined; - const end = marketSnapshots[0].pnl; - const start = marketSnapshots[1]?.pnl || wei(0); - - return { - value: end.sub(start), - percentage: start.eq(0) ? undefined : end.sub(start).div(start.abs()), - }; -}; - -export const calculatePoolPerformanceLifetime = (poolData?: PoolType) => { - return poolData?.configurations.reduce((acc, { market }) => { - return acc.add(market.pnl); - }, wei(0)); -}; - -export const calculatePoolPerformanceSevenDays = (poolData?: PoolType) => { - const total = calculatePoolPerformanceLifetime(poolData); - - const totalSevenDaysAgo = poolData?.configurations.reduce((acc, { market }) => { - return acc.add(market.market_snapshots_by_week[1]?.pnl || wei(0)); - }, wei(0)); - - if (!total || !totalSevenDaysAgo) { - return undefined; - } - - return { - value: total.sub(totalSevenDaysAgo), // Not that this value does not take into account that other pools might have exposure to markets - growthPercentage: totalSevenDaysAgo.eq(0) - ? undefined - : total.sub(totalSevenDaysAgo).div(totalSevenDaysAgo.abs()), - }; -}; - -export const calculateCRatio = (debt: Wei, collateralValue: Wei) => - debt.eq(0) || collateralValue.eq(0) ? ZEROWEI : collateralValue.div(debt); diff --git a/liquidity/lib/calculations/index.ts b/liquidity/lib/calculations/index.ts deleted file mode 100644 index d79c3a641..000000000 --- a/liquidity/lib/calculations/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './calculations'; diff --git a/liquidity/lib/calculations/package.json b/liquidity/lib/calculations/package.json deleted file mode 100644 index 64ed8a1b5..000000000 --- a/liquidity/lib/calculations/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@snx-v3/calculations", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/usePoolData": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "zod": "^3.22.4" - } -} diff --git a/liquidity/lib/etherscanLink/etherscanLink.ts b/liquidity/lib/etherscanLink/etherscanLink.ts deleted file mode 100644 index c0595bee9..000000000 --- a/liquidity/lib/etherscanLink/etherscanLink.ts +++ /dev/null @@ -1,25 +0,0 @@ -export function etherscanLink({ - chain, - address, - isTx = false, -}: { - chain: string; - address: string; - isTx?: boolean; -}): string { - switch (chain) { - case 'sepolia': - return `https://sepolia.etherscan.io/${isTx ? 'tx' : 'address'}/${address}`; - case 'arbitrum': - return `https://arbiscan.io/${isTx ? 'tx' : 'address'}/${address}`; - case 'optimism': - return `https://optimistic.etherscan.io/${isTx ? 'tx' : 'address'}/${address}`; - case 'base': - return `https://basescan.org/${isTx ? 'tx' : 'address'}/${address}`; - case 'base-sepolia': - return `https://sepolia.basescan.org/${isTx ? 'tx' : 'address'}/${address}`; - case 'mainnet': - default: - return `https://etherscan.io/${isTx ? 'tx' : 'address'}/${address}`; - } -} diff --git a/liquidity/lib/etherscanLink/index.ts b/liquidity/lib/etherscanLink/index.ts deleted file mode 100644 index f1d6d20e4..000000000 --- a/liquidity/lib/etherscanLink/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './etherscanLink'; diff --git a/liquidity/lib/etherscanLink/package.json b/liquidity/lib/etherscanLink/package.json deleted file mode 100644 index daf675b5e..000000000 --- a/liquidity/lib/etherscanLink/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "@snx-v3/etherscanLink", - "private": true, - "main": "index.ts", - "version": "0.0.1" -} diff --git a/liquidity/lib/feeSuggestion/feeSuggestion.ts b/liquidity/lib/feeSuggestion/feeSuggestion.ts deleted file mode 100644 index 829404b55..000000000 --- a/liquidity/lib/feeSuggestion/feeSuggestion.ts +++ /dev/null @@ -1,122 +0,0 @@ -/** - * This module is heavily inspired by https://github.com/rainbow-me/fee-suggestions - * That library have some hardcoded min and max that doesn't make sense for optimism. See: https://github.com/rainbow-me/fee-suggestions/blob/main/src/index.ts#L165 - * - * So I changed min max a bit - * - * That library is also a bit overkill in how it calculates maxFeePerGas per gas. It's using linear regression and sampling curves. - * Instead of doing that, this module calculates max by taking (previous baseFeePerGas * 2) + maxPriorityFeePerGas. - * - * The calculation for maxPriorityFeePerGas I kept quite complex since that will affect what the user actually pay.. - * It's calculated based on the Exponential Moving Average (EMA) of the block rewards at the 15th, 30th, and 45th percentiles, after removing the outliers. - * - * The other differences is that I also rely on our Wei library. - * - */ -import { ethers } from 'ethers'; -import { ema } from './math'; -import { getOutlierBlocksToRemove, rewardsFilterOutliers } from './utils'; -import { wei, Wei } from '@synthetixio/wei'; -import { GWEI_DECIMALS } from '@snx-v3/constants'; - -type Reward = string[]; -type GasUsedRatio = number[]; -interface FeeHistoryResponse { - baseFeePerGas: string[]; - gasUsedRatio: GasUsedRatio; - oldestBlock: number; - reward: Reward[]; -} - -const defaultForLocalProvider = () => { - const baseFeePerGas = wei(1, 9).toBN(); - const maxFeePerGas = wei(5, 9).toBN(); - const maxPriorityFeePerGas = wei(1, 9).toBN(); - return { - average: { - maxPriorityFeePerGas, - maxFeePerGas, - baseFeePerGas, - }, - fast: { - maxPriorityFeePerGas, - maxFeePerGas, - baseFeePerGas, - }, - fastest: { - maxPriorityFeePerGas, - maxFeePerGas, - baseFeePerGas, - }, - }; -}; -export const feeSuggestion = async ( - provider: ethers.providers.JsonRpcProvider, - fromBlock = 'latest' -) => { - // If local or base-goerli, use defaults - // Base goerli sometimes doesn't have enough tx we can use to estimate the priority fee, when this happens the tx will get "tx underprices" - if (provider.network.chainId === 13370 || provider.network.chainId === 84531) { - return defaultForLocalProvider(); - } - const feeHistory = await provider - .send('eth_feeHistory', [ - ethers.utils.hexStripZeros(ethers.utils.hexlify(10)), - fromBlock, - [15, 30, 45], - ]) - .then((feeHistoryResponse: FeeHistoryResponse) => { - return { - baseFeePerGas: feeHistoryResponse.baseFeePerGas.map((x) => wei(x, GWEI_DECIMALS, true)), - reward: feeHistoryResponse.reward.map((x) => x.map((num) => wei(num, GWEI_DECIMALS, true))), - }; - }); - const blocksRewards = feeHistory.reward; - const baseFeePerGas = feeHistory.baseFeePerGas.at(-1); - - if (!blocksRewards.length) throw new Error('Error: block reward was empty'); - if (!baseFeePerGas) throw new Error('Error: currentBaseFee was empty'); - - const outlierBlocks = getOutlierBlocksToRemove(blocksRewards, 0); - - const blocksRewardsPerc15 = rewardsFilterOutliers(blocksRewards, outlierBlocks, 0); - const blocksRewardsPerc30 = rewardsFilterOutliers(blocksRewards, outlierBlocks, 1); - const blocksRewardsPerc45 = rewardsFilterOutliers(blocksRewards, outlierBlocks, 2); - - const emaPerc15 = ema(blocksRewardsPerc15, blocksRewardsPerc15.length)[ - blocksRewardsPerc15.length - 1 - ]; - const emaPerc30 = ema(blocksRewardsPerc30, blocksRewardsPerc30.length)[ - blocksRewardsPerc30.length - 1 - ]; - const emaPerc45 = ema(blocksRewardsPerc45, blocksRewardsPerc45.length)[ - blocksRewardsPerc45.length - 1 - ]; - - if (emaPerc15 === undefined || emaPerc30 === undefined || emaPerc45 === undefined) { - throw new Error('Error: ema was undefined'); - } - - const averageMaxPriorityFee = wei(Math.min(emaPerc15, 1), GWEI_DECIMALS); - const fastMaxPriorityFee = wei(Math.min(emaPerc30, 2), GWEI_DECIMALS); - const fastestMaxPriorityFee = wei(Math.min(emaPerc45, 4), GWEI_DECIMALS); - - const baseFeeToMax = (base: Wei, prio: Wei) => base.mul(wei(2, GWEI_DECIMALS)).add(prio); - return { - average: { - maxPriorityFeePerGas: averageMaxPriorityFee.toBN(), - maxFeePerGas: baseFeeToMax(baseFeePerGas, averageMaxPriorityFee).toBN(), - baseFeePerGas: baseFeePerGas.toBN(), - }, - fast: { - maxPriorityFeePerGas: fastMaxPriorityFee.toBN(), - maxFeePerGas: baseFeeToMax(baseFeePerGas, fastMaxPriorityFee).toBN(), - baseFeePerGas: baseFeePerGas.toBN(), - }, - fastest: { - maxPriorityFeePerGas: fastestMaxPriorityFee.toBN(), - maxFeePerGas: baseFeeToMax(baseFeePerGas, fastestMaxPriorityFee).toBN(), - baseFeePerGas: baseFeePerGas.toBN(), - }, - }; -}; diff --git a/liquidity/lib/feeSuggestion/index.ts b/liquidity/lib/feeSuggestion/index.ts deleted file mode 100644 index 769f31a17..000000000 --- a/liquidity/lib/feeSuggestion/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './feeSuggestion'; diff --git a/liquidity/lib/feeSuggestion/math.ts b/liquidity/lib/feeSuggestion/math.ts deleted file mode 100644 index 05689a32e..000000000 --- a/liquidity/lib/feeSuggestion/math.ts +++ /dev/null @@ -1,72 +0,0 @@ -// copied from npm package: moving-averages -// Only grabbed what we needed and added types -export const isNumber = (subject: unknown) => - typeof subject === 'number' && - // is not NaN: `NaN === NaN` => `false` - subject === subject; - -export const dma = (data: number[], alpha: number, noHead?: boolean): number[] => { - const length = data.length; - - if (alpha > 1) { - return Array(length); - } - - if (alpha === 1) { - return data.slice(); - } - - const noArrayWeight = !Array.isArray(alpha); - const ret = []; - - let datum; - - // period `i` - let i = 0; - - // `s` is the value of the DWMA at any time period `i` - let s = 0; - - // Handles head - for (; i < length; i++) { - datum = data[i]; - - if (isNumber(datum) && (noArrayWeight || isNumber(datum))) { - ret[i] = noHead ? 0 : datum; - - s = datum; - i++; - - break; - } - } - - // Dynamic weights: an array of weights - // Ref: - // https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average - // with a dynamic alpha - if (!noArrayWeight) { - for (; i < length; i++) { - datum = data[i]; - - isNumber(datum) && isNumber(alpha[i]) - ? (s = ret[i] = alpha[i] * datum + (1 - alpha[i]) * s) - : (ret[i] = ret[i - 1]); - } - - return ret; - } - - const o = 1 - alpha; - - // Fixed alpha - for (; i < length; i++) { - datum = data[i]; - - isNumber(datum) ? (s = ret[i] = alpha * datum + o * s) : (ret[i] = ret[i - 1]); - } - - return ret; -}; - -export const ema = (data: number[], size: number) => dma(data, 2 / (size + 1)); diff --git a/liquidity/lib/feeSuggestion/package.json b/liquidity/lib/feeSuggestion/package.json deleted file mode 100644 index 578942006..000000000 --- a/liquidity/lib/feeSuggestion/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@snx-v3/feeSuggestion", - "private": true, - "main": "index.ts", - "version": "0.0.0", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "ethers": "^5.7.2" - } -} diff --git a/liquidity/lib/feeSuggestion/utils.ts b/liquidity/lib/feeSuggestion/utils.ts deleted file mode 100644 index ea89d383e..000000000 --- a/liquidity/lib/feeSuggestion/utils.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Wei } from '@synthetixio/wei'; - -export const rewardsFilterOutliers = ( - blocksRewards: Wei[][], - outlierBlocks: number[], - rewardIndex: number -) => - blocksRewards - .filter((_, index) => !outlierBlocks.includes(index)) - .map((reward) => reward[rewardIndex].toNumber()); - -export const getOutlierBlocksToRemove = (blocksRewards: Wei[][], index: number) => { - const blocks: number[] = []; - blocksRewards - .map((reward) => reward[index]) - .forEach((gweiReward, i) => { - if (gweiReward.gt(5)) { - blocks.push(i); - } - }); - return blocks; -}; diff --git a/liquidity/lib/fetchPythPrices/fetchPythPrices.ts b/liquidity/lib/fetchPythPrices/fetchPythPrices.ts deleted file mode 100644 index 6ebcc5f85..000000000 --- a/liquidity/lib/fetchPythPrices/fetchPythPrices.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { offchainMainnetEndpoint, offchainTestnetEndpoint } from '@snx-v3/constants'; -import { EvmPriceServiceConnection } from '@pythnetwork/pyth-evm-js'; -import { ethers, PopulatedTransaction, BigNumber } from 'ethers'; -import { Wei } from '@synthetixio/wei'; - -export const fetchPriceUpdates = async ( - requestedPriceUpdates: { priceFeedId: string; stalenessTolerance: Wei }[], - isTestnet: boolean -) => { - if (requestedPriceUpdates.length === 0) return []; - const priceService = new EvmPriceServiceConnection( - isTestnet ? offchainTestnetEndpoint : offchainMainnetEndpoint - ); - const signedPricesData = await priceService.getPriceFeedsUpdateData( - requestedPriceUpdates.map(({ priceFeedId }) => priceFeedId) - ); - - return signedPricesData.map((signedOffchainData, i) => { - const updateType = 1; // todo can I fetch this? - - const { priceFeedId, stalenessTolerance } = requestedPriceUpdates[i]; - return ethers.utils.defaultAbiCoder.encode( - ['uint8', 'uint64', 'bytes32[]', 'bytes[]'], - [updateType, stalenessTolerance.toBN(), [priceFeedId], [signedOffchainData]] - ); - }); -}; - -export const priceUpdatesToPopulatedTx = ( - from: string, - oracleAddresses: { address: string }[], - signedOffchainData: string[] -) => { - if (oracleAddresses.length !== signedOffchainData.length) { - throw new Error('oracleAddresses and signedOffchainData must be the same length'); - } - return signedOffchainData.map((signedOffchainDatum, i) => { - const tx: PopulatedTransaction = { - to: oracleAddresses[i].address, - from: from, - data: new ethers.utils.Interface([ - 'function fulfillOracleQuery(bytes calldata signedOffchainData) payable external', - ]).encodeFunctionData('fulfillOracleQuery', [signedOffchainDatum]), - // We set the value to 1 wei to avoid FeeRequired error from pyth, it's quite nice that their fee seems to be the lowest denominator on every network. - // If this ever changes, things wont break, but become slower. - value: BigNumber.from(1), - }; - return tx; - }); -}; diff --git a/liquidity/lib/fetchPythPrices/index.ts b/liquidity/lib/fetchPythPrices/index.ts deleted file mode 100644 index 1d1b66133..000000000 --- a/liquidity/lib/fetchPythPrices/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './fetchPythPrices'; diff --git a/liquidity/lib/fetchPythPrices/package.json b/liquidity/lib/fetchPythPrices/package.json deleted file mode 100644 index 6b8965a24..000000000 --- a/liquidity/lib/fetchPythPrices/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@snx-v3/fetchPythPrices", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@pythnetwork/pyth-evm-js": "^1.42.0", - "@snx-v3/constants": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "ethers": "^5.7.2" - } -} diff --git a/liquidity/lib/isBaseAndromeda/index.ts b/liquidity/lib/isBaseAndromeda/index.ts deleted file mode 100644 index eaf982470..000000000 --- a/liquidity/lib/isBaseAndromeda/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './isBaseAndromeda'; diff --git a/liquidity/lib/isBaseAndromeda/isBaseAndromeda.ts b/liquidity/lib/isBaseAndromeda/isBaseAndromeda.ts deleted file mode 100644 index 3e8bb8cba..000000000 --- a/liquidity/lib/isBaseAndromeda/isBaseAndromeda.ts +++ /dev/null @@ -1,31 +0,0 @@ -export const isBaseAndromeda = (id?: number | string, preset?: string) => - (id?.toString() === '8453' || '84532') && preset === 'andromeda'; - -export function getRepayerContract(id?: number) { - switch (id) { - case 8453: - return '0xBD8004ea5c73E33d405d35d594221Efc733F7E37'; - case 84532: - return '0xD00a601eafC2C131F46105827AFB02b925Adf62A'; - default: - return ''; - } -} - -export function getSpotMarketId(collateralSymbol?: string) { - switch (collateralSymbol?.toLowerCase()) { - case 'usdc': - case 'susdc': - return USDC_BASE_MARKET; - - case 'statausdc': - case 'sstatausdc': - return STATA_BASE_MARKET; - - default: - return USDC_BASE_MARKET; - } -} - -export const USDC_BASE_MARKET = '1'; -export const STATA_BASE_MARKET = '3'; diff --git a/liquidity/lib/isBaseAndromeda/package.json b/liquidity/lib/isBaseAndromeda/package.json deleted file mode 100644 index 13d7d5bd1..000000000 --- a/liquidity/lib/isBaseAndromeda/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "@snx-v3/isBaseAndromeda", - "private": true, - "main": "index.ts", - "version": "0.0.1" -} diff --git a/liquidity/lib/parser/index.ts b/liquidity/lib/parser/index.ts deleted file mode 100644 index 6d11f45f0..000000000 --- a/liquidity/lib/parser/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './parseTxError'; diff --git a/liquidity/lib/parser/package.json b/liquidity/lib/parser/package.json deleted file mode 100644 index a414c6068..000000000 --- a/liquidity/lib/parser/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "@snx-v3/parser", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "viem": "^2.13.5" - } -} diff --git a/liquidity/lib/parser/parseTxError.test.ts b/liquidity/lib/parser/parseTxError.test.ts deleted file mode 100644 index cc2f6fe13..000000000 --- a/liquidity/lib/parser/parseTxError.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { parseTxError } from './parseTxError'; - -describe('parseTxError', () => { - it('should return erorr data', () => { - const error = { - cause: { - data: 'error', - }, - }; - expect(parseTxError(error)).toBe(error.cause.data); - }); -}); diff --git a/liquidity/lib/parser/parseTxError.ts b/liquidity/lib/parser/parseTxError.ts deleted file mode 100644 index f97e6d274..000000000 --- a/liquidity/lib/parser/parseTxError.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Hex } from 'viem'; - -export function parseTxError(error: any): Hex | undefined { - try { - if (error.cause?.data) { - return error.cause?.data; - } - if (error.cause?.cause?.data) { - return error.cause?.cause?.data; - } - if (error.cause?.cause?.cause?.data) { - return error.cause?.cause?.cause?.data; - } - if (error.cause?.cause?.error?.data) { - return error.cause?.cause?.error?.data; - } - if (error.cause?.cause?.cause?.error?.data) { - return error.cause?.cause?.cause?.error?.data; - } - if (error?.error?.error?.data) { - return error?.error?.error?.data; - } - } catch (err) { - console.error('exception error parser:', err); - } -} diff --git a/liquidity/lib/tsHelpers/index.ts b/liquidity/lib/tsHelpers/index.ts deleted file mode 100644 index 4f545e7b5..000000000 --- a/liquidity/lib/tsHelpers/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from './typeModifiers'; -export * from './notNill'; -export * from './keyBy'; -export * from './stringToHash'; diff --git a/liquidity/lib/tsHelpers/keyBy.ts b/liquidity/lib/tsHelpers/keyBy.ts deleted file mode 100644 index e13a89fa0..000000000 --- a/liquidity/lib/tsHelpers/keyBy.ts +++ /dev/null @@ -1,10 +0,0 @@ -export function keyBy, K extends keyof T>(key: K, array: T[]) { - return array.reduce( - (acc, item) => { - const keyValue = item[key]; - acc[keyValue] = item; - return acc; - }, - {} as Record - ); -} diff --git a/liquidity/lib/tsHelpers/notNill.ts b/liquidity/lib/tsHelpers/notNill.ts deleted file mode 100644 index 1397d4181..000000000 --- a/liquidity/lib/tsHelpers/notNill.ts +++ /dev/null @@ -1,3 +0,0 @@ -// This is a type guard function that checks if a value is not null and not undefined. -// This is useful when filtering an array that might have null or undefined values. -export const notNil = (x: T | null | undefined): x is T => x !== null && x !== undefined; diff --git a/liquidity/lib/tsHelpers/package.json b/liquidity/lib/tsHelpers/package.json deleted file mode 100644 index d91236cab..000000000 --- a/liquidity/lib/tsHelpers/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "@snx-v3/tsHelpers", - "private": true, - "main": "index.ts", - "version": "0.0.1" -} diff --git a/liquidity/lib/tsHelpers/stringToHash.ts b/liquidity/lib/tsHelpers/stringToHash.ts deleted file mode 100644 index 1a7cca1c5..000000000 --- a/liquidity/lib/tsHelpers/stringToHash.ts +++ /dev/null @@ -1,6 +0,0 @@ -export function stringToHash(s: string | undefined) { - return (s || '').split('').reduce(function (a, b) { - a = (a << 5) - a + b.charCodeAt(0); - return a & a; - }, 0); -} diff --git a/liquidity/lib/tsHelpers/typeModifiers.ts b/liquidity/lib/tsHelpers/typeModifiers.ts deleted file mode 100644 index bff79f1e1..000000000 --- a/liquidity/lib/tsHelpers/typeModifiers.ts +++ /dev/null @@ -1,2 +0,0 @@ -export type MakeRequired = Required> & Omit; -export type Modify = Omit & R; diff --git a/liquidity/lib/txnReducer/index.ts b/liquidity/lib/txnReducer/index.ts deleted file mode 100644 index 8490bf3d9..000000000 --- a/liquidity/lib/txnReducer/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './txnReducer'; diff --git a/liquidity/lib/txnReducer/package.json b/liquidity/lib/txnReducer/package.json deleted file mode 100644 index d113b27b2..000000000 --- a/liquidity/lib/txnReducer/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "@snx-v3/txnReducer", - "private": true, - "main": "index.ts", - "version": "0.0.1" -} diff --git a/liquidity/lib/txnReducer/txnReducer.ts b/liquidity/lib/txnReducer/txnReducer.ts deleted file mode 100644 index 54d6d7439..000000000 --- a/liquidity/lib/txnReducer/txnReducer.ts +++ /dev/null @@ -1,66 +0,0 @@ -export type TransactionStatus = 'unsent' | 'prompting' | 'pending' | 'success' | 'error'; - -type TxnState = { - error: Error | null; - modalOpen: boolean; - txnStatus: TransactionStatus; - txnHash: string | null; -}; - -export const initialState: TxnState = { - error: null, - modalOpen: false, - txnStatus: 'unsent', - txnHash: null, -}; - -export type Actions = - | { type: 'prompting' } - | { type: 'pending'; payload: { txnHash: string } } - | { type: 'success' } - | { type: 'error'; payload: { error: Error } } - | { type: 'settled' }; - -export function reducer(state: TxnState, action: Actions): TxnState { - switch (action.type) { - case 'prompting': - return { - ...state, - txnStatus: 'prompting', - modalOpen: true, - error: null, - }; - - case 'pending': - return { - ...state, - txnStatus: 'pending', - txnHash: action.payload.txnHash, - }; - - case 'success': - return { - ...state, - txnStatus: 'success', - }; - - case 'error': - return { - ...state, - txnStatus: 'error', - error: action.payload.error, - }; - - case 'settled': - return { - ...state, - modalOpen: false, - txnStatus: 'unsent', - error: null, - txnHash: null, - }; - - default: - return state; - } -} diff --git a/liquidity/lib/useAccountCollateral/index.ts b/liquidity/lib/useAccountCollateral/index.ts deleted file mode 100644 index 2864a95ea..000000000 --- a/liquidity/lib/useAccountCollateral/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useAccountCollateral'; diff --git a/liquidity/lib/useAccountCollateral/package.json b/liquidity/lib/useAccountCollateral/package.json deleted file mode 100644 index 500ac9599..000000000 --- a/liquidity/lib/useAccountCollateral/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "@snx-v3/useAccountCollateral", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useSystemToken": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useAccountCollateral/useAccountCollateral.ts b/liquidity/lib/useAccountCollateral/useAccountCollateral.ts deleted file mode 100644 index e08b9c7d4..000000000 --- a/liquidity/lib/useAccountCollateral/useAccountCollateral.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { stringToHash } from '@snx-v3/tsHelpers'; -import { useDefaultProvider, useNetwork } from '@snx-v3/useBlockchain'; -import { useCollateralTypes } from '@snx-v3/useCollateralTypes'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { erc7412Call } from '@snx-v3/withERC7412'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { Wei, wei } from '@synthetixio/wei'; -import { useQuery } from '@tanstack/react-query'; -import { ethers } from 'ethers'; -import { useAllCollateralPriceUpdates } from '@snx-v3/useCollateralPriceUpdates'; - -export type AccountCollateralType = { - tokenAddress: string; - availableCollateral: Wei; - totalAssigned: Wei; - totalDeposited: Wei; - totalLocked: Wei; - symbol: string; - displaySymbol: string; -}; - -export const loadAccountCollateral = async ({ - accountId, - tokenAddresses, - CoreProxy, -}: { - accountId: string; - tokenAddresses: string[]; - CoreProxy: ethers.Contract; -}) => { - const callsP = tokenAddresses.flatMap((tokenAddress) => [ - CoreProxy.populateTransaction.getAccountAvailableCollateral(accountId, tokenAddress), - CoreProxy.populateTransaction.getAccountCollateral(accountId, tokenAddress), - ]); - const calls = await Promise.all(callsP); - const decoder = (multicallEncoded: string | string[]) => { - if (!Array.isArray(multicallEncoded)) throw Error('Expected array'); - return tokenAddresses.map((tokenAddress, i) => { - const [availableCollateral] = CoreProxy.interface.decodeFunctionResult( - 'getAccountAvailableCollateral', - multicallEncoded[i * 2] - ); - const { totalAssigned, totalDeposited, totalLocked } = - CoreProxy.interface.decodeFunctionResult( - 'getAccountCollateral', - multicallEncoded[i * 2 + 1] - ); - - return { - tokenAddress, - availableCollateral: wei(availableCollateral), - totalAssigned: wei(totalAssigned), - totalDeposited: wei(totalDeposited), - totalLocked: wei(totalLocked), - symbol: '', - displaySymbol: '', - decimals: '', - }; - }); - }; - return { decoder, calls }; -}; - -export type AccountCollateralWithSymbol = AccountCollateralType & { symbol: string }; - -export function useAccountCollateral({ - accountId, - includeDelegationOff, -}: { - accountId?: string; - includeDelegationOff?: boolean; -}) { - const { data: CoreProxy } = useCoreProxy(); - const { network } = useNetwork(); - const { data: collateralTypes } = useCollateralTypes(includeDelegationOff); - - const provider = useDefaultProvider(); - const { data: priceUpdateTx } = useAllCollateralPriceUpdates(); - - const { data: systemToken } = useSystemToken(); - - return useQuery({ - queryKey: [ - `${network?.id}-${network?.preset}`, - 'AccountCollateral', - { accountId }, - { systemToken: systemToken?.address }, - { priceUpdateTx: stringToHash(priceUpdateTx?.data) }, - ], - enabled: Boolean( - network && - provider && - CoreProxy && - accountId && - collateralTypes && - collateralTypes.length > 0 && - systemToken - ), - staleTime: 60000 * 5, - queryFn: async function () { - if ( - !( - network && - provider && - CoreProxy && - accountId && - collateralTypes && - collateralTypes.length > 0 && - systemToken - ) - ) { - throw new Error('OMG'); - } - - const tokenAddresses = collateralTypes - .map((c) => c.tokenAddress) - .concat([systemToken.address]); - - const { calls, decoder } = await loadAccountCollateral({ - accountId, - tokenAddresses, - CoreProxy, - }); - const allCalls = [...calls]; - if (priceUpdateTx) { - allCalls.unshift(priceUpdateTx as any); - } - const data = await erc7412Call(network, provider, allCalls, decoder, 'useAccountCollateral'); - - return data.map((x) => { - if (`${systemToken.address}`.toLowerCase() === `${x.tokenAddress}`.toLowerCase()) { - return Object.assign(x, { - symbol: systemToken.symbol, - displaySymbol: systemToken.name, - decimals: systemToken.decimals, - }); - } - const collateralType = collateralTypes.find( - (c) => `${c.tokenAddress}`.toLowerCase() === `${x.tokenAddress}`.toLowerCase() - ); - return Object.assign(x, { - symbol: collateralType?.symbol ?? '', - displaySymbol: collateralType?.displaySymbol ?? '', - decimals: collateralType?.decimals ?? '18', - }); - }); - }, - }); -} - -export function useAccountSpecificCollateral(accountId?: string, collateralAddress?: string) { - const { data: CoreProxy } = useCoreProxy(); - const { network } = useNetwork(); - const provider = useDefaultProvider(); - const { data: priceUpdateTx } = useAllCollateralPriceUpdates(); - - return useQuery({ - queryKey: [ - `${network?.id}-${network?.preset}`, - 'AccountSpecificCollateral', - { accountId }, - { token: collateralAddress, priceUpdateTx: stringToHash(priceUpdateTx?.data) }, - ], - enabled: Boolean(CoreProxy && accountId && collateralAddress), - queryFn: async function () { - if (!CoreProxy || !accountId || !collateralAddress || !network || !provider) { - throw 'useAccountSpecificCollateral should not be enabled'; - } - const { calls, decoder } = await loadAccountCollateral({ - accountId, - tokenAddresses: [collateralAddress], - CoreProxy, - }); - const allCalls = [...calls]; - if (priceUpdateTx) { - allCalls.unshift(priceUpdateTx as any); - } - - const data = await erc7412Call( - network, - provider, - calls, - decoder, - 'useAccountSpecificCollateral' - ); - - return data.at(0); - }, - }); -} diff --git a/liquidity/lib/useAccountCollateralUnlockDate/index.ts b/liquidity/lib/useAccountCollateralUnlockDate/index.ts deleted file mode 100644 index 3f2754453..000000000 --- a/liquidity/lib/useAccountCollateralUnlockDate/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useAccountCollateralUnlockDate'; diff --git a/liquidity/lib/useAccountCollateralUnlockDate/package.json b/liquidity/lib/useAccountCollateralUnlockDate/package.json deleted file mode 100644 index 3f2b8cf30..000000000 --- a/liquidity/lib/useAccountCollateralUnlockDate/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useAccountCollateralUnlockDate", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useAccountCollateralUnlockDate/useAccountCollateralUnlockDate.ts b/liquidity/lib/useAccountCollateralUnlockDate/useAccountCollateralUnlockDate.ts deleted file mode 100644 index 5ee33b63c..000000000 --- a/liquidity/lib/useAccountCollateralUnlockDate/useAccountCollateralUnlockDate.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { ethers } from 'ethers'; -import { useQuery } from '@tanstack/react-query'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useNetwork } from '@snx-v3/useBlockchain'; - -export function useAccountCollateralUnlockDate({ accountId }: { accountId?: string }) { - const { data: CoreProxy } = useCoreProxy(); - const { network } = useNetwork(); - - return useQuery({ - queryKey: [`${network?.id}-${network?.preset}`, 'AccountCollateralUnlockDate', { accountId }], - enabled: Boolean(CoreProxy && accountId), - queryFn: async function () { - if (!CoreProxy || !accountId) throw new Error('Core Proxy or account id is not defined'); - - const [lastInteraction, accountTimeoutWithdraw] = await Promise.all([ - CoreProxy.getAccountLastInteraction(accountId), - CoreProxy.getConfigUint(ethers.utils.formatBytes32String('accountTimeoutWithdraw')), - ]); - - const collateralUnlock = lastInteraction.add(accountTimeoutWithdraw); - - return new Date(collateralUnlock.toNumber() * 1000); - }, - }); -} diff --git a/liquidity/lib/useAccountInfo/index.ts b/liquidity/lib/useAccountInfo/index.ts deleted file mode 100644 index e4fa819aa..000000000 --- a/liquidity/lib/useAccountInfo/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useAccountPermissions'; diff --git a/liquidity/lib/useAccountInfo/package.json b/liquidity/lib/useAccountInfo/package.json deleted file mode 100644 index e085f9b22..000000000 --- a/liquidity/lib/useAccountInfo/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useAccountPermissions", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/useAccountProxy": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2" - } -} diff --git a/liquidity/lib/useAccountInfo/useAccountPermissions.ts b/liquidity/lib/useAccountInfo/useAccountPermissions.ts deleted file mode 100644 index 0578cce22..000000000 --- a/liquidity/lib/useAccountInfo/useAccountPermissions.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { useAccountProxy } from '@snx-v3/useAccountProxy'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useQuery } from '@tanstack/react-query'; -import { utils } from 'ethers'; - -export function useAccountPermissions(accountId: string | undefined) { - const { data: CoreProxy } = useCoreProxy(); - const { network } = useNetwork(); - - return useQuery({ - queryKey: [`${network?.id}-${network?.preset}`, 'account-permissions', accountId], - queryFn: async function () { - if (!CoreProxy || !accountId) throw new Error('Should be disabled'); - const permissions = await CoreProxy.getAccountPermissions(accountId); - - return permissions.reduce( - ( - acc: { [key: string]: string[] }, - { user, permissions }: { user: string; permissions: string[] } - ) => ({ - ...acc, - [user.toLowerCase()]: permissions.map((r: string) => utils.parseBytes32String(r)), - }), - {} - ); - }, - enabled: Boolean(CoreProxy?.address), - }); -} - -export function useAccountOwner(accountId: string | undefined) { - const { data: AccountProxy } = useAccountProxy(); - const { network } = useNetwork(); - - return useQuery({ - queryKey: [`${network?.id}-${network?.preset}`, 'account-owner', accountId], - queryFn: async function () { - if (!AccountProxy || !accountId) throw new Error('Should be disabled'); - return (await AccountProxy.ownerOf(accountId)) as string; - }, - enabled: Boolean(AccountProxy?.address), - }); -} diff --git a/liquidity/lib/useAccountProxy/index.ts b/liquidity/lib/useAccountProxy/index.ts deleted file mode 100644 index afd6e13b8..000000000 --- a/liquidity/lib/useAccountProxy/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useAccountProxy'; diff --git a/liquidity/lib/useAccountProxy/package.json b/liquidity/lib/useAccountProxy/package.json deleted file mode 100644 index d2514274e..000000000 --- a/liquidity/lib/useAccountProxy/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@snx-v3/useAccountProxy", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@ethersproject/contracts": "^5.7.0", - "@snx-v3/contracts": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3" - } -} diff --git a/liquidity/lib/useAccountProxy/useAccountProxy.ts b/liquidity/lib/useAccountProxy/useAccountProxy.ts deleted file mode 100644 index 0db21945c..000000000 --- a/liquidity/lib/useAccountProxy/useAccountProxy.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { Contract } from '@ethersproject/contracts'; -import { useQuery } from '@tanstack/react-query'; -import { useDefaultProvider, useNetwork, useWallet } from '@snx-v3/useBlockchain'; -import { importAccountProxy } from '@snx-v3/contracts'; - -export function useAccountProxy() { - const { network } = useNetwork(); - const provider = useDefaultProvider(); - const { activeWallet } = useWallet(); - - return useQuery({ - queryKey: [`${network?.id}-${network?.preset}`, 'AccountProxy', activeWallet?.address], - queryFn: async function () { - if (!provider || !network) throw new Error('Should be disabled'); - const { address, abi } = await importAccountProxy(network.id, network?.preset); - return new Contract(address, abi, provider); - }, - enabled: Boolean(provider), - staleTime: Infinity, - }); -} diff --git a/liquidity/lib/useAccounts/index.ts b/liquidity/lib/useAccounts/index.ts deleted file mode 100644 index 0434fcfe7..000000000 --- a/liquidity/lib/useAccounts/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useAccounts'; diff --git a/liquidity/lib/useAccounts/package.json b/liquidity/lib/useAccounts/package.json deleted file mode 100644 index 4c871943e..000000000 --- a/liquidity/lib/useAccounts/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "@snx-v3/useAccounts", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/useAccountProxy": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3" - } -} diff --git a/liquidity/lib/useAccounts/useAccounts.ts b/liquidity/lib/useAccounts/useAccounts.ts deleted file mode 100644 index 97a42f845..000000000 --- a/liquidity/lib/useAccounts/useAccounts.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; -import { useAccountProxy } from '@snx-v3/useAccountProxy'; -import { useNetwork, useWallet } from '@snx-v3/useBlockchain'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useGasPrice } from '@snx-v3/useGasPrice'; -import { wei } from '@synthetixio/wei'; - -export function useAccounts() { - const { activeWallet } = useWallet(); - const { data: AccountProxy } = useAccountProxy(); - const { network } = useNetwork(); - - return useQuery({ - queryKey: [ - `${network?.id}-${network?.preset}`, - 'Accounts', - { accountAddress: activeWallet?.address, AccountProxy: AccountProxy?.address }, - ], - enabled: Boolean(AccountProxy && activeWallet?.address), - queryFn: async function () { - if (!(AccountProxy && activeWallet?.address)) throw new Error('Should be disabled'); - - const numberOfAccountTokens = await AccountProxy.balanceOf(activeWallet.address); - - if (numberOfAccountTokens.eq(0)) { - // No accounts created yet - return []; - } - const accountIndexes = Array.from(Array(numberOfAccountTokens.toNumber()).keys()); - const accounts = await Promise.all( - accountIndexes.map(async (i) => { - if (!activeWallet?.address) throw new Error('OMG!'); - return await AccountProxy.tokenOfOwnerByIndex(activeWallet.address, i); - }) - ); - return accounts.map((accountId) => accountId.toString()); - }, - placeholderData: [], - }); -} - -export function useCreateAccount() { - const { data: CoreProxy } = useCoreProxy({ - isWrite: true, - }); - const { network } = useNetwork(); - const client = useQueryClient(); - const { data: gasPrices } = useGasPrice(); - return { - getTransactionCost: useQuery({ - enabled: !!gasPrices, - queryKey: ['Transaction-Cost-Account'], - queryFn: async () => { - const gasUnits = await CoreProxy?.estimateGas['createAccount()'](); - if (gasPrices) { - if ('baseFeePerGas' in gasPrices?.average && gasUnits) { - const { coins } = await ( - await fetch('https://coins.llama.fi/prices/current/coingecko:ethereum?searchWidth=4h') - ).json(); - return ( - wei(gasPrices?.average.baseFeePerGas.mul(gasUnits), 18).toNumber() * - coins['coingecko:ethereum'].price - ).toFixed(2); - } - } - return '0.00'; - }, - }), - mutation: useMutation({ - mutationFn: async function () { - try { - if (!CoreProxy) throw new Error('CoreProxy undefined'); - const tx = await CoreProxy['createAccount()'](); - const res = await tx.wait(); - - await client.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'Accounts'], - }); - - let newAccountId: string | undefined; - - res.logs.forEach((log: any) => { - if (log.topics[0] === CoreProxy.interface.getEventTopic('AccountCreated')) { - const accountId = CoreProxy.interface.decodeEventLog( - 'AccountCreated', - log.data, - log.topics - )?.accountId; - newAccountId = accountId?.toString(); - } - }); - - return [newAccountId]; - } catch (error) { - console.error(error); - throw error; - } - }, - }), - }; -} diff --git a/liquidity/lib/useAllCollateralPriceIds/index.ts b/liquidity/lib/useAllCollateralPriceIds/index.ts deleted file mode 100644 index b4146f326..000000000 --- a/liquidity/lib/useAllCollateralPriceIds/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useAllCollateralPriceIds'; diff --git a/liquidity/lib/useAllCollateralPriceIds/package.json b/liquidity/lib/useAllCollateralPriceIds/package.json deleted file mode 100644 index f8e3e263d..000000000 --- a/liquidity/lib/useAllCollateralPriceIds/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "@snx-v3/useAllCollateralPriceIds", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useMulticall3": "workspace:*", - "@snx-v3/useOracleManagerProxy": "workspace:*", - "@snx-v3/zod": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0", - "zod": "^3.22.4" - } -} diff --git a/liquidity/lib/useAllCollateralPriceIds/useAllCollateralPriceIds.ts b/liquidity/lib/useAllCollateralPriceIds/useAllCollateralPriceIds.ts deleted file mode 100644 index dec983cb1..000000000 --- a/liquidity/lib/useAllCollateralPriceIds/useAllCollateralPriceIds.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { deploymentsWithERC7412, Network, useNetwork } from '@snx-v3/useBlockchain'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useMulticall3 } from '@snx-v3/useMulticall3'; -import { useCollateralTypes } from '@snx-v3/useCollateralTypes'; -import { useOracleManagerProxy } from '@snx-v3/useOracleManagerProxy'; -import { ZodBigNumber } from '@snx-v3/zod'; -import { wei } from '@synthetixio/wei'; -import { useQuery } from '@tanstack/react-query'; -import { ethers } from 'ethers'; -import { z } from 'zod'; - -const NodeSchema = z.object({ - nodeType: z.number(), - parameters: z.string(), - parents: z.array(z.string()), -}); - -const PythParametersSchema = z.object({ - address: z.string(), - priceFeedId: z.string(), - stalenessTolerance: ZodBigNumber.transform((x) => wei(x)), -}); - -const EXTERNAL_NODE_TYPE = 2; - -export const useAllCollateralPriceIds = (customNetwork?: Network) => { - const { network } = useNetwork(); - const targetNetwork = customNetwork || network; - const { data: Multicall3 } = useMulticall3(customNetwork); - const { data: OracleProxy } = useOracleManagerProxy(customNetwork); - const { data: CoreProxy } = useCoreProxy({ customNetwork }); - const { data: collateralConfigs } = useCollateralTypes(false, customNetwork); - - return useQuery({ - enabled: Boolean( - targetNetwork?.id && - targetNetwork?.preset && - Multicall3 && - OracleProxy && - CoreProxy && - !!collateralConfigs?.length - ), - staleTime: Infinity, - queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, 'AllCollateralPriceIds'], - queryFn: async () => { - if ( - !( - targetNetwork?.id && - targetNetwork?.preset && - Multicall3 && - OracleProxy && - CoreProxy && - collateralConfigs - ) - ) { - throw Error('useAllCollateralPriceIds should not be enabled '); - } - - if (!deploymentsWithERC7412.includes(`${targetNetwork.id}-${targetNetwork.preset}`)) - return []; - - const oracleNodeIds = collateralConfigs.map((x: { oracleNodeId: string }) => x.oracleNodeId); - - const calls = oracleNodeIds.map((oracleNodeId: string) => ({ - target: OracleProxy.address, - callData: OracleProxy.interface.encodeFunctionData('getNode', [oracleNodeId]), - })); - - const { returnData } = await Multicall3.callStatic.aggregate(calls); - - const decoded = returnData - .map((bytes: ethers.utils.BytesLike, i: number) => { - const nodeResp = OracleProxy.interface.decodeFunctionResult('getNode', bytes)[0]; - - const { nodeType, parameters } = NodeSchema.parse({ ...nodeResp }); - - if (nodeType !== EXTERNAL_NODE_TYPE) return undefined; - - try { - const [address, priceFeedId, stalenessTolerance] = ethers.utils.defaultAbiCoder.decode( - ['address', 'bytes32', 'uint256'], - parameters - ); - const parametersDecoded = PythParametersSchema.parse({ - address, - priceFeedId, - stalenessTolerance, - }); - return { - parameters, - priceFeedId: parametersDecoded.priceFeedId, - address: parametersDecoded.address, - stalenessTolerance: parametersDecoded.stalenessTolerance, - }; - } catch (error) { - console.error(`Decoding parameters failed, config:`, collateralConfigs[i]); - console.error('parameters: ', parameters); - console.error(error); - return null; - } - }) - .filter(Boolean); - - const seen = new Set(); - return decoded.filter((item: { priceFeedId: string }) => { - if (seen.has(item.priceFeedId)) { - return false; - } - seen.add(item.priceFeedId); - return true; - }); - }, - }); -}; diff --git a/liquidity/lib/useAllowance/index.ts b/liquidity/lib/useAllowance/index.ts deleted file mode 100644 index fd3ed3881..000000000 --- a/liquidity/lib/useAllowance/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useAllowance'; diff --git a/liquidity/lib/useAllowance/package.json b/liquidity/lib/useAllowance/package.json deleted file mode 100644 index c06323b1f..000000000 --- a/liquidity/lib/useAllowance/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useAllowance", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/zod": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2" - } -} diff --git a/liquidity/lib/useAllowance/useAllowance.ts b/liquidity/lib/useAllowance/useAllowance.ts deleted file mode 100644 index 959459ccb..000000000 --- a/liquidity/lib/useAllowance/useAllowance.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { useWallet, useNetwork, useDefaultProvider } from '@snx-v3/useBlockchain'; -import { Contract } from 'ethers'; -import { ZodBigNumber } from '@snx-v3/zod'; -import { wei } from '@synthetixio/wei'; - -const AllowanceSchema = ZodBigNumber.transform((x) => wei(x)); -const abi = ['function allowance(address, address) view returns (uint256)']; - -export const useAllowance = ({ - contractAddress, - spender, -}: { - contractAddress?: string; - spender?: string; -}) => { - const { activeWallet } = useWallet(); - const { network } = useNetwork(); - const provider = useDefaultProvider(); - - return useQuery({ - queryKey: [ - `${network?.id}-${network?.preset}`, - 'Allowance', - { accountAddress: activeWallet?.address }, - { contractAddress, spender }, - ], - queryFn: async () => { - if (!(contractAddress && spender && activeWallet?.address && provider)) - throw new Error('OMG'); - const contract = new Contract(contractAddress, abi, provider); - const allowance = await contract.allowance(activeWallet.address, spender); - return AllowanceSchema.parse(allowance); - }, - enabled: Boolean(activeWallet?.address && contractAddress && spender && provider), - }); -}; diff --git a/liquidity/lib/useApprove/index.ts b/liquidity/lib/useApprove/index.ts deleted file mode 100644 index 01407f812..000000000 --- a/liquidity/lib/useApprove/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useApprove'; diff --git a/liquidity/lib/useApprove/package.json b/liquidity/lib/useApprove/package.json deleted file mode 100644 index 60b8f79aa..000000000 --- a/liquidity/lib/useApprove/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "@snx-v3/useApprove", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useAllowance": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useApprove/useApprove.ts b/liquidity/lib/useApprove/useApprove.ts deleted file mode 100644 index 6dca25420..000000000 --- a/liquidity/lib/useApprove/useApprove.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { useReducer } from 'react'; -import { useAllowance } from '@snx-v3/useAllowance'; -import { BigNumberish, ethers } from 'ethers'; -import { useMutation } from '@tanstack/react-query'; -import { useProvider, useSigner } from '@snx-v3/useBlockchain'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; - -export const approveAbi = ['function approve(address spender, uint256 amount) returns (bool)']; - -export const useApprove = ( - { - contractAddress, - amount, - spender, - }: { - contractAddress?: string; - amount: BigNumberish; - spender?: string; - }, - eventHandlers?: { - onSuccess?: () => void; - onMutate?: () => void; - onError?: (e: Error) => void; - } -) => { - const [txnState, dispatch] = useReducer(reducer, initialState); - const { data: allowance, refetch: refetchAllowance } = useAllowance({ contractAddress, spender }); - - const sufficientAllowance = Boolean(allowance?.gte(amount)); - - const signer = useSigner(); - const { gasSpeed } = useGasSpeed(); - const provider = useProvider(); - - const mutation = useMutation({ - mutationFn: async (infiniteApproval: boolean) => { - if (!signer || !contractAddress || !spender || !provider) - throw new Error('Signer, contract address or spender is not defined'); - if (sufficientAllowance) return; - - try { - dispatch({ type: 'prompting' }); - - const contract = new ethers.Contract(contractAddress, approveAbi, signer); - const amountToAppove = infiniteApproval ? ethers.constants.MaxUint256 : amount; - - const gasPricesPromised = getGasPrice({ provider }); - const gasLimitPromised = contract.estimateGas.approve(spender, amountToAppove); - - const populatedTxnPromised = contract.populateTransaction.approve(spender, amountToAppove, { - gasLimit: gasLimitPromised, - }); - - const [gasPrices, gasLimit, populatedTxn] = await Promise.all([ - gasPricesPromised, - gasLimitPromised, - populatedTxnPromised, - ]); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit, - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...populatedTxn, ...gasOptionsForTransaction }); - dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - - await txn.wait(); - dispatch({ type: 'success' }); - refetchAllowance(); - } catch (error: any) { - dispatch({ type: 'error', payload: { error } }); - throw error; - } - }, - ...eventHandlers, - }); - return { - mutation, - txnState, - isLoading: mutation.isPending, - approve: mutation.mutateAsync, - refetchAllowance, - requireApproval: !sufficientAllowance, - }; -}; diff --git a/liquidity/lib/useApr/index.ts b/liquidity/lib/useApr/index.ts deleted file mode 100644 index c0297abdb..000000000 --- a/liquidity/lib/useApr/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useApr'; diff --git a/liquidity/lib/useApr/package.json b/liquidity/lib/useApr/package.json deleted file mode 100644 index 895857150..000000000 --- a/liquidity/lib/useApr/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@snx-v3/useApr", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useApr/useApr.ts b/liquidity/lib/useApr/useApr.ts deleted file mode 100644 index 6be1dd026..000000000 --- a/liquidity/lib/useApr/useApr.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { getAprUrl } from '@snx-v3/constants'; -import { ARBITRUM, BASE_ANDROMEDA, MAINNET, Network, useNetwork } from '@snx-v3/useBlockchain'; -import { useQuery } from '@tanstack/react-query'; - -export function useApr(customNetwork?: Network) { - const { network } = useNetwork(); - const chain = customNetwork || network; - - return useQuery({ - queryKey: ['apr', chain?.id], - queryFn: async () => { - try { - return await fetchApr(chain?.id); - } catch (error) { - return; - } - }, - staleTime: 60000, - enabled: Boolean(chain?.id), - }); -} - -const supportedAprNetworks = [BASE_ANDROMEDA.id, ARBITRUM.id, MAINNET.id]; - -export async function fetchApr(networkId?: number) { - try { - const isSupported = networkId && supportedAprNetworks.includes(networkId); - if (!isSupported) { - throw new Error('Apr endpoint not supported for this network'); - } - - const response = await fetch(getAprUrl(networkId)); - - const data = await response.json(); - - const highestAprCollateral = data?.sort( - (a: { apr28d: number }, b: { apr28d: number }) => b.apr28d - a.apr28d - )[0]; - - return { - combinedApr: highestAprCollateral.apr28d * 100, - cumulativePnl: isSupported ? highestAprCollateral.cumulativePnl : 0, - collateralAprs: data, - }; - } catch (error) { - console.error(error); - return { - combinedApr: 0, - cumulativePnl: 0, - collateralAprs: [], - }; - } -} diff --git a/liquidity/lib/useAprHistory/index.ts b/liquidity/lib/useAprHistory/index.ts deleted file mode 100644 index b0fdd698c..000000000 --- a/liquidity/lib/useAprHistory/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useAprHistory'; diff --git a/liquidity/lib/useAprHistory/package.json b/liquidity/lib/useAprHistory/package.json deleted file mode 100644 index 83c15527c..000000000 --- a/liquidity/lib/useAprHistory/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@snx-v3/useAprHistory", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useAprHistory/useAprHistory.ts b/liquidity/lib/useAprHistory/useAprHistory.ts deleted file mode 100644 index 4df58c016..000000000 --- a/liquidity/lib/useAprHistory/useAprHistory.ts +++ /dev/null @@ -1,177 +0,0 @@ -import { Network, useNetwork } from '@snx-v3/useBlockchain'; -import { useQuery } from '@tanstack/react-query'; - -interface PoolData { - apr7d: number; - apr7dPnl: number; - apr7dRewards: number; - apr24h: number; - apr24hPnl: number; - apr24hRewards: number; - apr28d: number; - apr28dPnl: number; - apr28dRewards: number; - aprCombined: number; - aprPnl: number; - aprRewards: number; - apy7d: number; - apy7dPnl: number; - apy7dRewards: number; - apy24h: number; - apy24hPnl: number; - apy24hRewards: number; - apy28d: number; - apy28dPnl: number; - apy28dRewards: number; - collateralType: string; - collateralValue: number; - cumulativeIssuance: number; - cumulativePnl: number; - debtAmount: number; - hourlyIssuance: number; - hourlyPnl: number; - hourlyPnlPct: number; - hourlyRewardsPct: number; - poolId: number; - rewardsUSD: number; - timestamp: string; -} - -const sevenDays = new Date(); -sevenDays.setDate(sevenDays.getDate() - 7); -const sevenWeeks = new Date(); -sevenWeeks.setDate(sevenWeeks.getDate() - 7 * 7); -const sevenMonth = new Date(); -sevenMonth.setDate(sevenMonth.getDate() - 7 * 4 * 7); -const oneYear = new Date(); -oneYear.setDate(oneYear.getDate() - 365); - -export function useAprHistory(customNetwork?: Network) { - const { network } = useNetwork(); - const chain = customNetwork || network; - - return useQuery({ - queryKey: ['apr-history', chain?.id], - queryFn: async () => { - if (!chain?.id) return {}; - try { - const response = await fetch('https://api.synthetix.io/v3/base/sc-pool-apy-history'); - - const data: PoolData[] = await response.json(); - - const sevenDaysAPR = data - .filter((d) => new Date(d.timestamp).getTime() >= sevenDays.getTime()) - .map((d) => ({ - timestamp: d.timestamp, - value: d.apr24h * 100, - pnl: d.apr24hPnl * 100, - rewards: d.apr24hRewards * 100, - combined: d.aprCombined * 100, - pnlCombined: d.aprPnl * 100, - rewardsCombined: d.aprRewards * 100, - })) - .reverse(); - - const sevenWeeksAPR = data - .filter((d) => new Date(d.timestamp).getTime() >= sevenWeeks.getTime()) - .filter((_, index) => index % 7 === 0) - .map((d) => ({ - timestamp: d.timestamp, - value: d.apr7d * 100, - pnl: d.apr7dPnl * 100, - rewards: d.apr7dRewards * 100, - combined: d.aprCombined * 100, - pnlCombined: d.aprPnl * 100, - rewardsCombined: d.aprRewards * 100, - })) - - .reverse(); - const sevenMonthAPR = data - .filter((d) => new Date(d.timestamp).getTime() >= sevenMonth.getTime()) - .filter((_, index) => index % 30 === 0) - .map((d) => ({ - timestamp: d.timestamp, - value: d.apr28d * 100, - pnl: d.apr28dPnl * 100, - rewards: d.apr28dRewards * 100, - combined: d.aprCombined * 100, - pnlCombined: d.aprPnl * 100, - rewardsCombined: d.aprRewards * 100, - })) - .reverse(); - const oneYearAPR = data - .filter((d) => new Date(d.timestamp).getTime() >= oneYear.getTime()) - .map((d) => ({ - timestamp: d.timestamp, - value: d.apr28d * 100, - pnl: d.apr28dPnl * 100, - rewards: d.apr28dRewards * 100, - combined: d.aprCombined * 100, - pnlCombined: d.aprPnl * 100, - rewardsCombined: d.aprRewards * 100, - })) - .reverse(); - - const sevenDaysTVL = data - .filter((d) => new Date(d.timestamp).getTime() >= sevenDays.getTime()) - .map((d) => ({ - timestamp: d.timestamp, - value: d.collateralValue, - })) - .reverse(); - const sevenWeeksTVL = data - .filter((d) => new Date(d.timestamp).getTime() >= sevenWeeks.getTime()) - .map((d) => ({ - timestamp: d.timestamp, - value: d.collateralValue, - })) - .filter((_, index) => index % 7 === 0) - .reverse(); - const sevenMonthTVL = data - .filter((d) => new Date(d.timestamp).getTime() >= sevenMonth.getTime()) - .filter((_, index) => index % 30 === 0) - .map((d) => ({ - timestamp: d.timestamp, - value: d.collateralValue, - })) - .reverse(); - const oneYearTVL = data - .filter((d) => new Date(d.timestamp).getTime() >= oneYear.getTime()) - .map((d) => ({ - timestamp: d.timestamp, - value: d.collateralValue, - })) - .reverse(); - return { - sevenDaysTVL, - sevenWeeksTVL, - sevenMonthTVL, - oneYearTVL, - allTVL: data - .map((d) => ({ - timestamp: d.timestamp, - value: d.collateralValue, - })) - .reverse(), - allAPR: data - .map((d) => ({ - timestamp: d.timestamp, - value: d.apr24h * 100, - pnl: d.apr24hPnl * 100, - rewards: d.apr24hRewards * 100, - combined: d.aprCombined * 100, - pnlCombined: d.aprPnl * 100, - rewardsCombined: d.aprRewards * 100, - })) - .reverse(), - sevenDaysAPR, - sevenWeeksAPR, - sevenMonthAPR, - oneYearAPR, - }; - } catch (error) { - return; - } - }, - }); -} diff --git a/liquidity/lib/useBlockNumber/index.ts b/liquidity/lib/useBlockNumber/index.ts deleted file mode 100644 index 23f6b23b6..000000000 --- a/liquidity/lib/useBlockNumber/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useBlockNumber'; diff --git a/liquidity/lib/useBlockNumber/package.json b/liquidity/lib/useBlockNumber/package.json deleted file mode 100644 index 563e10dd8..000000000 --- a/liquidity/lib/useBlockNumber/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@snx-v3/useBlockNumber", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useBlockNumber/useBlockNumber.ts b/liquidity/lib/useBlockNumber/useBlockNumber.ts deleted file mode 100644 index 2b4ace434..000000000 --- a/liquidity/lib/useBlockNumber/useBlockNumber.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { useNetwork, useProvider } from '@snx-v3/useBlockchain'; -import { useQuery } from '@tanstack/react-query'; - -const BLOCKS = (60 * 60 * 24) / 2; - -export const useBlockNumber = () => { - const provider = useProvider(); - const { network } = useNetwork(); - - return useQuery({ - queryKey: ['block-number', network?.id], - queryFn: async () => { - if (!provider) throw 'Missing data required for useBlockNumber'; - const block = await provider.getBlockNumber(); - - const blocks = () => { - if (!block) { - return []; - } - - // We take the last 8 blocks as the PnL is calculated between two blocks - // Interim take last 6 periods (last 7 blocks) - - // TEMP WORKAROUND PLEASE REVERT - return [ - // block - BLOCKS * 7, - // block - BLOCKS * 6, - // block - BLOCKS * 5, - // block - BLOCKS * 4, - block - BLOCKS * 3, - block - BLOCKS * 2, - block - BLOCKS, - block, - ]; - }; - - return { - currentBlock: block, - lastPeriodBlocks: blocks(), - }; - }, - enabled: !!provider, - }); -}; diff --git a/liquidity/lib/useBorrow/index.ts b/liquidity/lib/useBorrow/index.ts deleted file mode 100644 index dad6f3218..000000000 --- a/liquidity/lib/useBorrow/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useBorrow'; diff --git a/liquidity/lib/useBorrow/package.json b/liquidity/lib/useBorrow/package.json deleted file mode 100644 index 981cd7ccf..000000000 --- a/liquidity/lib/useBorrow/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "@snx-v3/useBorrow", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useBorrow/useBorrow.tsx b/liquidity/lib/useBorrow/useBorrow.tsx deleted file mode 100644 index 62c8cb2c7..000000000 --- a/liquidity/lib/useBorrow/useBorrow.tsx +++ /dev/null @@ -1,99 +0,0 @@ -import { useReducer } from 'react'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useMutation } from '@tanstack/react-query'; -import { useNetwork, useProvider, useSigner } from '@snx-v3/useBlockchain'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import Wei from '@synthetixio/wei'; -import { BigNumber } from 'ethers'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; -import { withERC7412 } from '@snx-v3/withERC7412'; -import { useCollateralPriceUpdates } from '@snx-v3/useCollateralPriceUpdates'; - -export const useBorrow = ({ - accountId, - poolId, - collateralTypeAddress, - debtChange, -}: { - accountId?: string; - poolId?: string; - collateralTypeAddress?: string; - debtChange: Wei; -}) => { - const [txnState, dispatch] = useReducer(reducer, initialState); - const { data: CoreProxy } = useCoreProxy(); - const { data: priceUpdateTx } = useCollateralPriceUpdates(); - - const signer = useSigner(); - const { gasSpeed } = useGasSpeed(); - const provider = useProvider(); - const { network } = useNetwork(); - - const mutation = useMutation({ - mutationFn: async () => { - if ( - !( - signer && - CoreProxy && - poolId && - accountId && - collateralTypeAddress && - network && - provider - ) - ) { - return; - } - - if (debtChange.eq(0)) { - return; - } - - try { - dispatch({ type: 'prompting' }); - - const populatedTxnPromised = CoreProxy.populateTransaction.mintUsd( - BigNumber.from(accountId), - BigNumber.from(poolId), - collateralTypeAddress, - debtChange.abs().toBN() - ); - - const callsPromise = Promise.all([populatedTxnPromised]); - const [calls, gasPrices] = await Promise.all([callsPromise, getGasPrice({ provider })]); - - if (priceUpdateTx) { - calls.unshift(priceUpdateTx as any); - } - - const walletAddress = await signer.getAddress(); - const erc7412Tx = await withERC7412(network, calls, 'borrow', walletAddress); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: erc7412Tx.gasLimit, - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...erc7412Tx, ...gasOptionsForTransaction }); - - dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - - await txn.wait(); - dispatch({ type: 'success' }); - } catch (error: any) { - dispatch({ type: 'error', payload: { error } }); - throw error; - } - }, - }); - return { - mutation, - txnState, - settle: () => dispatch({ type: 'settled' }), - isLoading: mutation.isPending, - exec: mutation.mutateAsync, - }; -}; diff --git a/liquidity/lib/useBurnMintFee/index.ts b/liquidity/lib/useBurnMintFee/index.ts deleted file mode 100644 index 6dd00dfed..000000000 --- a/liquidity/lib/useBurnMintFee/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useBurnMintFee'; diff --git a/liquidity/lib/useBurnMintFee/package.json b/liquidity/lib/useBurnMintFee/package.json deleted file mode 100644 index bb6c28b7e..000000000 --- a/liquidity/lib/useBurnMintFee/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useBurnMintFee", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useBurnMintFee/useBurnMintFee.ts b/liquidity/lib/useBurnMintFee/useBurnMintFee.ts deleted file mode 100644 index 5d416cdf4..000000000 --- a/liquidity/lib/useBurnMintFee/useBurnMintFee.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { ethers } from 'ethers'; -import { useQuery } from '@tanstack/react-query'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useNetwork } from '@snx-v3/useBlockchain'; - -export function useBurnMintFee() { - const { data: CoreProxy } = useCoreProxy(); - const { network } = useNetwork(); - - return useQuery({ - queryKey: [`${network?.id}-${network?.preset}`, 'BurnMintFee'], - enabled: Boolean(CoreProxy), - queryFn: async function () { - if (!CoreProxy) throw new Error('Core Proxy is not defined'); - - const [burnUsdFeeRatio, mintUsdFeeRatio] = await Promise.all([ - CoreProxy.getConfigUint(ethers.utils.formatBytes32String('burnUsd_feeRatio')), - CoreProxy.getConfigUint(ethers.utils.formatBytes32String('mintUsd_feeRatio')), - ]); - - return { - burnUsdFeeRatio, - mintUsdFeeRatio, - }; - }, - }); -} diff --git a/liquidity/lib/useClaimRewards/index.ts b/liquidity/lib/useClaimRewards/index.ts deleted file mode 100644 index ce7dcf773..000000000 --- a/liquidity/lib/useClaimRewards/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useClaimRewards'; diff --git a/liquidity/lib/useClaimRewards/package.json b/liquidity/lib/useClaimRewards/package.json deleted file mode 100644 index d937a130e..000000000 --- a/liquidity/lib/useClaimRewards/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "@snx-v3/useClaimRewards", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@chakra-ui/react": "^2.8.2", - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useClaimRewards/useClaimRewards.ts b/liquidity/lib/useClaimRewards/useClaimRewards.ts deleted file mode 100644 index 904d76779..000000000 --- a/liquidity/lib/useClaimRewards/useClaimRewards.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { useReducer } from 'react'; -import { useMutation, useQueryClient } from '@tanstack/react-query'; -import { BigNumber } from 'ethers'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import { useNetwork } from '@snx-v3/useBlockchain'; - -import { useToast } from '@chakra-ui/react'; - -export function useClaimRewards( - poolId?: string, - collateralAddress?: string, - accountId?: string, - distributorAddress?: string, - amount?: number -) { - const toast = useToast({ isClosable: true, duration: 9000 }); - - const { network } = useNetwork(); - const { data: CoreProxy } = useCoreProxy({ - isWrite: true, - }); - const [txnState, dispatch] = useReducer(reducer, initialState); - const client = useQueryClient(); - - const mutation = useMutation({ - mutationFn: async function () { - try { - if (!amount) return; - if (!poolId || !collateralAddress || !accountId || !distributorAddress || !network) - throw new Error('Parameters Undefined'); - if (!CoreProxy) throw new Error('CoreProxy undefined'); - - dispatch({ type: 'prompting' }); - - const tx = await CoreProxy.claimRewards( - BigNumber.from(accountId), - BigNumber.from(poolId), - collateralAddress, - distributorAddress - ); - - dispatch({ type: 'pending', payload: { txnHash: tx.hash } }); - - const res = await tx.wait(); - - let claimedAmount: BigNumber | undefined; - - res.logs.forEach((log: any) => { - if (log.topics[0] === CoreProxy.interface.getEventTopic('RewardsClaimed')) { - const { amount } = CoreProxy.interface.decodeEventLog( - 'RewardsClaimed', - log.data, - log.topics - ); - claimedAmount = amount; - } - }); - - dispatch({ type: 'success' }); - client.invalidateQueries({ queryKey: [`${network?.id}-${network?.preset}`, 'Rewards'] }); - - toast.closeAll(); - toast({ - title: 'Success', - description: 'Your rewards has been claimed.', - status: 'success', - duration: 5000, - variant: 'left-accent', - }); - - return claimedAmount; - } catch (error) { - const err = error as Error; - dispatch({ type: 'error', payload: { error: err } }); - - toast.closeAll(); - toast({ - title: 'Claiming failed', - description: 'Please try again.', - status: 'error', - variant: 'left-accent', - }); - - return 0; - } - }, - }); - - return { - mutation, - txnState, - settle: () => dispatch({ type: 'settled' }), - isLoading: mutation.isPending, - exec: mutation.mutateAsync, - }; -} diff --git a/liquidity/lib/useClearDebt/index.ts b/liquidity/lib/useClearDebt/index.ts deleted file mode 100644 index 55586c26f..000000000 --- a/liquidity/lib/useClearDebt/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useClearDebt'; diff --git a/liquidity/lib/useClearDebt/package.json b/liquidity/lib/useClearDebt/package.json deleted file mode 100644 index ee1a1bb9c..000000000 --- a/liquidity/lib/useClearDebt/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "@snx-v3/useClearDebt", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useAllCollateralPriceIds": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/useSpotMarketProxy": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useClearDebt/useClearDebt.tsx b/liquidity/lib/useClearDebt/useClearDebt.tsx deleted file mode 100644 index 849b817e8..000000000 --- a/liquidity/lib/useClearDebt/useClearDebt.tsx +++ /dev/null @@ -1,133 +0,0 @@ -import { useReducer } from 'react'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { useMutation } from '@tanstack/react-query'; -import { useNetwork, useProvider, useSigner } from '@snx-v3/useBlockchain'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import Wei from '@synthetixio/wei'; -import { BigNumber, Contract } from 'ethers'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; -import { notNil } from '@snx-v3/tsHelpers'; -import { withERC7412 } from '@snx-v3/withERC7412'; -import { useAllCollateralPriceIds } from '@snx-v3/useAllCollateralPriceIds'; -import { useSpotMarketProxy } from '@snx-v3/useSpotMarketProxy'; -import { USDC_BASE_MARKET, getRepayerContract } from '@snx-v3/isBaseAndromeda'; -import { useCollateralPriceUpdates } from '@snx-v3/useCollateralPriceUpdates'; - -export const DEBT_REPAYER_ABI = [ - { - inputs: [ - { internalType: 'contract ISynthetixCore', name: 'synthetixCore', type: 'address' }, - { internalType: 'contract ISpotMarket', name: 'spotMarket', type: 'address' }, - { internalType: 'uint128', name: 'accountId', type: 'uint128' }, - { internalType: 'uint128', name: 'poolId', type: 'uint128' }, - { internalType: 'address', name: 'collateralType', type: 'address' }, - { internalType: 'uint128', name: 'spotMarketId', type: 'uint128' }, - ], - name: 'depositDebtToRepay', - outputs: [], - stateMutability: 'nonpayable', - type: 'function', - }, -]; - -export const useClearDebt = ({ - accountId, - poolId, - collateralTypeAddress, - availableUSDCollateral, - debt, -}: { - accountId?: string; - poolId?: string; - collateralTypeAddress?: string; - availableUSDCollateral?: Wei; - debt?: Wei; -}) => { - const [txnState, dispatch] = useReducer(reducer, initialState); - const { data: CoreProxy } = useCoreProxy(); - const { data: SpotMarketProxy } = useSpotMarketProxy(); - const { data: collateralPriceIds } = useAllCollateralPriceIds(); - const { data: priceUpdateTx } = useCollateralPriceUpdates(); - - const signer = useSigner(); - const { network } = useNetwork(); - const { gasSpeed } = useGasSpeed(); - const provider = useProvider(); - - const mutation = useMutation({ - mutationFn: async () => { - if (!signer || !network || !provider) throw new Error('No signer or network'); - - if ( - !( - CoreProxy && - poolId && - accountId && - collateralTypeAddress && - SpotMarketProxy && - collateralPriceIds - ) - ) { - return; - } - - const repayer = new Contract(getRepayerContract(network.id), DEBT_REPAYER_ABI, signer); - - if (!availableUSDCollateral) return; - - try { - dispatch({ type: 'prompting' }); - - const depositDebtToRepay = repayer.populateTransaction.depositDebtToRepay( - CoreProxy.address, - SpotMarketProxy.address, - accountId, - poolId, - collateralTypeAddress, - USDC_BASE_MARKET - ); - - const burn = CoreProxy.populateTransaction.burnUsd( - BigNumber.from(accountId), - BigNumber.from(poolId), - collateralTypeAddress, - debt?.mul(110).div(100).toBN().toString() || '0' - ); - - const callsPromise = Promise.all([depositDebtToRepay, burn].filter(notNil)); - - const [calls, gasPrices] = await Promise.all([callsPromise, getGasPrice({ provider })]); - - if (priceUpdateTx) { - calls.unshift(priceUpdateTx as any); - } - const walletAddress = await signer.getAddress(); - const erc7412Tx = await withERC7412(network, calls, 'useRepay', walletAddress); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: erc7412Tx.gasLimit, - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...erc7412Tx, ...gasOptionsForTransaction }); - dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - - await txn.wait(); - dispatch({ type: 'success' }); - } catch (error: any) { - dispatch({ type: 'error', payload: { error } }); - throw error; - } - }, - }); - return { - mutation, - txnState, - settle: () => dispatch({ type: 'settled' }), - isLoading: mutation.isPending, - exec: mutation.mutateAsync, - }; -}; diff --git a/liquidity/lib/useCollateralPriceUpdates/index.ts b/liquidity/lib/useCollateralPriceUpdates/index.ts deleted file mode 100644 index 424dd38b4..000000000 --- a/liquidity/lib/useCollateralPriceUpdates/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useCollateralPriceUpdates'; diff --git a/liquidity/lib/useCollateralPriceUpdates/package.json b/liquidity/lib/useCollateralPriceUpdates/package.json deleted file mode 100644 index bd4ccccc2..000000000 --- a/liquidity/lib/useCollateralPriceUpdates/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "@snx-v3/useCollateralPriceUpdates", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@pythnetwork/pyth-evm-js": "^1.42.0", - "@snx-v3/constants": "workspace:*", - "@snx-v3/contracts": "workspace:*", - "@snx-v3/format": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/usePoolsList": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useCollateralPriceUpdates/useCollateralPriceUpdates.ts b/liquidity/lib/useCollateralPriceUpdates/useCollateralPriceUpdates.ts deleted file mode 100644 index 504fee91c..000000000 --- a/liquidity/lib/useCollateralPriceUpdates/useCollateralPriceUpdates.ts +++ /dev/null @@ -1,259 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { BigNumberish, ethers } from 'ethers'; -import { Network, useDefaultProvider, useNetwork, useWallet } from '@snx-v3/useBlockchain'; -import { EvmPriceServiceConnection } from '@pythnetwork/pyth-evm-js'; -import { offchainMainnetEndpoint } from '@snx-v3/constants'; -import { ERC7412_ABI } from '@snx-v3/withERC7412'; -import { importMulticall3, importExtras } from '@snx-v3/contracts'; -import { networksOffline } from '@snx-v3/usePoolsList'; -import { wei } from '@synthetixio/wei'; -import { importPythERC7412Wrapper } from '@snx-v3/contracts'; -import { parseUnits } from '@snx-v3/format'; - -const priceService = new EvmPriceServiceConnection(offchainMainnetEndpoint); - -function getAllPriceIdsEntries(extras: any) { - return Object.entries(extras).filter( - ([key, value]) => - String(value).length === 66 && - (key.startsWith('pyth_feed_id_') || (key.startsWith('pyth') && key.endsWith('FeedId'))) - ); -} - -async function getPythFeedIds(network: Network) { - const extras = await importExtras(network.id, network.preset); - return getAllPriceIdsEntries(extras).map(([_key, value]) => value); -} - -async function getPythFeedIdsFromCollateralList( - collateralList: { - symbol: string; - }[] -) { - const extras = await Promise.all( - networksOffline.map((network) => importExtras(network.id, network.preset)) - ); - - // Go over extras and find everything that starts with pyth and ends with FeedId, store in array - const priceIds = extras.map(getAllPriceIdsEntries).flat(); - - const deduped = Array.from( - new Set( - priceIds - .map(([key, priceId]) => { - if (key.startsWith('pyth_feed_id_')) { - return { - symbol: key.replace('pyth_feed_id_', '').toUpperCase(), - priceId, - }; - } - if (key.startsWith('pyth') && key.endsWith('FeedId')) { - return { - symbol: key.replace('pyth', '').replace('FeedId', '').toUpperCase(), - priceId, - }; - } - return { symbol: null, priceId: null }; - }) - .filter(({ symbol, priceId }) => symbol && priceId) - ) - ); - - // Find the corresponding price feed id for each symbol - return collateralList.map((collateral) => { - const symbol = collateral.symbol === 'WETH' ? 'ETH' : collateral.symbol; - const id = deduped.find((x) => x.symbol?.toUpperCase() === symbol.toUpperCase()); - return { - ...collateral, - priceId: id?.priceId, - }; - }); -} - -const getPriceUpdates = async ( - priceIds: string[], - stalenessTolerance: number, - network?: Network -) => { - const signedOffchainData = await priceService.getPriceFeedsUpdateData(priceIds); - const updateType = 1; - const data = ethers.utils.defaultAbiCoder.encode( - ['uint8', 'uint64', 'bytes32[]', 'bytes[]'], - [updateType, stalenessTolerance, priceIds, signedOffchainData] - ); - const erc7412Interface = new ethers.utils.Interface(ERC7412_ABI); - - const { address } = await importPythERC7412Wrapper(network?.id, network?.preset); - - return { - // pyth wrapper - to: address, - data: erc7412Interface.encodeFunctionData('fulfillOracleQuery', [data]), - value: priceIds.length, - }; -}; - -export const useAllCollateralPriceUpdates = (customNetwork?: Network) => { - const { network } = useNetwork(); - const targetNetwork = customNetwork || network; - return useQuery({ - queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, 'all-price-updates'], - enabled: Boolean(targetNetwork?.id && targetNetwork?.preset), - queryFn: async () => { - if (!(targetNetwork?.id && targetNetwork?.preset)) { - throw 'useAllCollateralPriceUpdates is missing required data'; - } - const stalenessTolerance = 1; - - const pythFeedIds = (await getPythFeedIds(targetNetwork)) as string[]; - if (!pythFeedIds.length) { - return null; - } - const tx = await getPriceUpdates(pythFeedIds, stalenessTolerance, targetNetwork); - - return { - ...tx, - value: tx.value, - }; - }, - refetchInterval: 5 * 60000, - }); -}; - -interface Collaterals { - symbol: string; - oracleId: string; - id: string; -} - -export const useOfflinePrices = (collaterals?: Collaterals[]) => { - return useQuery({ - queryKey: ['offline-prices', collaterals?.map((collateral) => collateral.id).join('-')], - enabled: Boolean(collaterals && collaterals.length > 0), - queryFn: async () => { - if (!collaterals) { - throw 'useOfflinePrices is missing required data'; - } - - const stables = ['sUSDC', 'USDC']; - const filteredCollaterals = collaterals.filter((item) => !stables.includes(item.symbol)); - - const returnData: { symbol: string; price: BigNumberish }[] = [ - { - symbol: 'sUSDC', - price: wei(1).toBN(), - }, - { - symbol: 'USDC', - price: wei(1).toBN(), - }, - { - symbol: 'USDx', - price: wei(1).toBN(), - }, - ]; - - if (!filteredCollaterals.length) { - return returnData; - } - - const collateralsWithPriceId = await getPythFeedIdsFromCollateralList(filteredCollaterals); - const prices = await priceService.getLatestPriceFeeds( - collateralsWithPriceId.map((x) => x.priceId) as string[] - ); - prices?.forEach((item) => { - const col = collateralsWithPriceId.find(({ priceId }) => priceId === `0x${item.id}`); - const price = item.getPriceUnchecked(); - if (col) { - returnData.push({ - symbol: col.symbol, - price: parseUnits(price.price, 18 + price.expo), - }); - } - }); - return returnData; - }, - refetchInterval: 60000, - }); -}; - -export const useCollateralPriceUpdates = () => { - const { network } = useNetwork(); - const provider = useDefaultProvider(); - const { activeWallet } = useWallet(); - - return useQuery({ - queryKey: [`${network?.id}-${network?.preset}`, 'price-updates', activeWallet?.address], - enabled: Boolean(network?.id && network?.preset), - queryFn: async () => { - const stalenessTolerance = 600; - if (!(network?.id && network?.preset)) { - throw 'OMG'; - } - - try { - const { address: multicallAddress, abi: multiCallAbi } = await importMulticall3( - network.id, - network.preset - ); - - const multicallInterface = new ethers.utils.Interface(multiCallAbi); - const pythInterface = new ethers.utils.Interface([ - 'function getLatestPrice(bytes32 priceId, uint256 stalenessTolerance) external view returns (int256)', - ]); - - const pythFeedIds = (await getPythFeedIds(network)) as string[]; - - if (pythFeedIds.length === 0) { - return null; - } - - const { address } = await importPythERC7412Wrapper(network?.id, network?.preset); - - const txs = [ - ...pythFeedIds.map((priceId) => ({ - target: address, - callData: pythInterface.encodeFunctionData('getLatestPrice', [ - priceId, - stalenessTolerance, - ]), - value: 0, - requireSuccess: false, - })), - ]; - - const getPricesTx = multicallInterface.encodeFunctionData('aggregate3Value', [txs]); - - const result = await provider?.call({ - data: getPricesTx, - to: multicallAddress, - }); - - const decodedMultiCall: { success: boolean }[] = multicallInterface.decodeFunctionResult( - 'aggregate3Value', - result || '' - )[0]; - - const outdatedPriceIds: string[] = []; - - decodedMultiCall.forEach(({ success }, i) => { - if (!success) { - outdatedPriceIds.push(pythFeedIds[i]); - } - }); - - if (outdatedPriceIds.length) { - return { - ...(await getPriceUpdates(outdatedPriceIds, stalenessTolerance, network)), - from: activeWallet?.address, - }; - } - - return null; - } catch (error) { - return null; - } - }, - refetchInterval: 60000, - }); -}; diff --git a/liquidity/lib/useCollateralPrices/index.ts b/liquidity/lib/useCollateralPrices/index.ts deleted file mode 100644 index 59130eba4..000000000 --- a/liquidity/lib/useCollateralPrices/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useCollateralPrices'; diff --git a/liquidity/lib/useCollateralPrices/package.json b/liquidity/lib/useCollateralPrices/package.json deleted file mode 100644 index dfb5d468b..000000000 --- a/liquidity/lib/useCollateralPrices/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "@snx-v3/useCollateralPrices", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGetUSDTokens": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@snx-v3/zod": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useCollateralPrices/useCollateralPrices.ts b/liquidity/lib/useCollateralPrices/useCollateralPrices.ts deleted file mode 100644 index c96ca1e7c..000000000 --- a/liquidity/lib/useCollateralPrices/useCollateralPrices.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { stringToHash } from '@snx-v3/tsHelpers'; -import { - Network, - useDefaultProvider, - useNetwork, - useProviderForChain, -} from '@snx-v3/useBlockchain'; -import { useCollateralTypes } from '@snx-v3/useCollateralTypes'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useGetUSDTokens } from '@snx-v3/useGetUSDTokens'; -import { erc7412Call } from '@snx-v3/withERC7412'; -import { ZodBigNumber } from '@snx-v3/zod'; -import Wei, { wei } from '@synthetixio/wei'; -import { useQuery } from '@tanstack/react-query'; -import { ethers } from 'ethers'; -import { useAllCollateralPriceUpdates } from '@snx-v3/useCollateralPriceUpdates'; - -const PriceSchema = ZodBigNumber.transform((x) => wei(x)); - -export async function loadPrices({ - CoreProxy, - collateralAddresses, -}: { - CoreProxy: ethers.Contract; - collateralAddresses: string[]; -}) { - const calls = await Promise.all( - collateralAddresses.map((address) => { - return CoreProxy.populateTransaction.getCollateralPrice(address); - }) - ); - if (calls.length === 0) return { calls: [], decoder: () => [] }; - - const decoder = (multicallEncoded: string | string[]) => { - if (Array.isArray(multicallEncoded)) { - return multicallEncoded.map((encoded) => { - const pricesEncoded = CoreProxy.interface.decodeFunctionResult( - 'getCollateralPrice', - encoded - )[0]; - - return PriceSchema.parse(pricesEncoded); - }); - } else { - const pricesEncoded = CoreProxy.interface.decodeFunctionResult( - 'getCollateralPrice', - multicallEncoded - )[0]; - return PriceSchema.parse(pricesEncoded); - } - }; - return { calls, decoder }; -} - -export const useCollateralPrices = (customNetwork?: Network) => { - const { network } = useNetwork(); - const { data: CoreProxy } = useCoreProxy({ customNetwork }); - const { data: collateralData } = useCollateralTypes(false, customNetwork); - const { data: usdTokens } = useGetUSDTokens(customNetwork); - - const targetNetwork = customNetwork || network; - const isBase = isBaseAndromeda(targetNetwork?.id, targetNetwork?.preset); - - const collateralAddresses = - isBase && usdTokens?.sUSD - ? collateralData?.map((x) => x.tokenAddress).concat(usdTokens.sUSD) - : collateralData?.map((x) => x.tokenAddress); - - const connectedProvider = useDefaultProvider(); - const offlineProvider = useProviderForChain(customNetwork); - const { data: priceUpdateTx } = useAllCollateralPriceUpdates(customNetwork); - - const provider = customNetwork ? offlineProvider : connectedProvider; - - return useQuery({ - enabled: Boolean(CoreProxy && collateralAddresses && collateralAddresses?.length > 0), - queryKey: [ - `${targetNetwork?.id}-${targetNetwork?.preset}`, - 'CollateralPrices', - { - collateralAddresses: collateralAddresses?.filter( - (item, pos) => collateralAddresses.indexOf(item) === pos - ), - priceUpdateTx: stringToHash(priceUpdateTx?.data), - }, - ], - queryFn: async () => { - if ( - !CoreProxy || - !collateralAddresses || - collateralAddresses.length == 0 || - !targetNetwork || - !provider - ) { - throw 'useCollateralPrices missing required data'; - } - - const { calls, decoder } = await loadPrices({ CoreProxy, collateralAddresses }); - - const allCalls = [...calls]; - if (priceUpdateTx) { - allCalls.unshift(priceUpdateTx as any); - } - - const prices = await erc7412Call( - targetNetwork, - provider, - allCalls, - decoder, - 'useCollateralPrices' - ); - - return collateralAddresses.reduce((acc: Record, address, i) => { - if (Array.isArray(prices)) { - acc[address] = prices[i]; - } else { - acc[address] = prices; - } - return acc; - }, {}); - }, - }); -}; diff --git a/liquidity/lib/useCollateralTypes/index.ts b/liquidity/lib/useCollateralTypes/index.ts deleted file mode 100644 index d60b01e2a..000000000 --- a/liquidity/lib/useCollateralTypes/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useCollateralTypes'; diff --git a/liquidity/lib/useCollateralTypes/package.json b/liquidity/lib/useCollateralTypes/package.json deleted file mode 100644 index 9e1fa75dc..000000000 --- a/liquidity/lib/useCollateralTypes/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "@snx-v3/useCollateralTypes", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/contracts": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useSystemToken": "workspace:*", - "@snx-v3/zod": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0", - "zod": "^3.22.4" - } -} diff --git a/liquidity/lib/useCollateralTypes/useCollateralTypes.ts b/liquidity/lib/useCollateralTypes/useCollateralTypes.ts deleted file mode 100644 index a4f78d7de..000000000 --- a/liquidity/lib/useCollateralTypes/useCollateralTypes.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { importCollateralTokens } from '@snx-v3/contracts'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { Network, useNetwork } from '@snx-v3/useBlockchain'; -import { ZodBigNumber } from '@snx-v3/zod'; -import { wei } from '@synthetixio/wei'; -import { useQuery } from '@tanstack/react-query'; -import { ethers } from 'ethers'; -import { z } from 'zod'; -import { useSystemToken } from '@snx-v3/useSystemToken'; - -const CollateralConfigurationSchema = z.object({ - symbol: z.string(), - name: z.string(), - decimals: z.number().transform((x) => String(x)), - depositingEnabled: z.boolean(), - issuanceRatioD18: ZodBigNumber.transform((x) => wei(x)), - liquidationRatioD18: ZodBigNumber.transform((x) => wei(x)), - liquidationRewardD18: ZodBigNumber.transform((x) => wei(x)), - oracleNodeId: z.string(), - tokenAddress: z.string().startsWith('0x'), // As of current version in zod this will be a string: https://github.com/colinhacks/zod/issues/1747 - minDelegationD18: ZodBigNumber.transform((x) => wei(x)), -}); - -const CollateralTypeSchema = CollateralConfigurationSchema.extend({ - displaySymbol: z.string(), -}); - -export type CollateralType = z.infer; - -async function loadCollateralTypes(chainId: number, preset: string): Promise { - const tokenConfigsRaw = await importCollateralTokens(chainId, preset); - - const tokenConfigs = tokenConfigsRaw - .map((config) => ({ - ...config, - issuanceRatioD18: ethers.BigNumber.from(config.issuanceRatioD18), - liquidationRatioD18: ethers.BigNumber.from(config.liquidationRatioD18), - liquidationRewardD18: ethers.BigNumber.from(config.liquidationRewardD18), - minDelegationD18: ethers.BigNumber.from(config.minDelegationD18), - })) - .map((x) => CollateralConfigurationSchema.parse({ ...x })) - .filter(({ depositingEnabled }) => depositingEnabled); - - return tokenConfigs.map((config) => ({ - ...config, - displaySymbol: config.symbol, - })); -} - -export function useCollateralTypes(includeDelegationOff = false, customNetwork?: Network) { - const { network } = useNetwork(); - const targetNetwork = customNetwork || network; - const { data: systemToken } = useSystemToken(customNetwork); - - const query = useQuery({ - enabled: Boolean(targetNetwork?.id && targetNetwork?.preset && systemToken), - queryKey: [ - `${targetNetwork?.id}-${targetNetwork?.preset}`, - 'CollateralTypes', - { systemToken: systemToken?.symbol, includeDelegationOff }, - ], - queryFn: async () => { - if (!(targetNetwork?.id && targetNetwork?.preset && systemToken)) - throw Error('useCollateralTypes should not be enabled when contracts missing'); - - const collateralTypes = (await loadCollateralTypes(targetNetwork.id, targetNetwork.preset)) - .map((collateralType) => { - const isBase = isBaseAndromeda(targetNetwork?.id, targetNetwork?.preset); - if (isBase && collateralType.symbol === 'sUSDC') { - return { - ...collateralType, - symbol: 'USDC', - displaySymbol: 'USDC', - name: 'USD Coin', - }; - } - if (isBase && collateralType.symbol === 'sStataUSDC') { - return { - ...collateralType, - symbol: 'stataUSDC', - displaySymbol: 'stataUSDC', - name: 'Static aUSDC', - }; - } - return { - ...collateralType, - displaySymbol: collateralType.displaySymbol ?? collateralType.symbol, - }; - }) - .filter((collateralType) => collateralType.tokenAddress !== systemToken.address); - - if (includeDelegationOff) { - return collateralTypes; - } - - // By default we only return collateral types that have minDelegationD18 < MaxUint256 - // When minDelegationD18 === MaxUint256, delegation is effectively disabled - return collateralTypes.filter((collateralType) => - collateralType.minDelegationD18.lt(ethers.constants.MaxUint256) - ) as CollateralType[]; - }, - // one hour in ms - staleTime: Infinity, - placeholderData: [], - }); - - return { - ...query, - isLoading: - query.isLoading || !Boolean(targetNetwork?.id && targetNetwork?.preset && systemToken), - }; -} - -export function useCollateralType(collateralSymbol?: string) { - const { data: collateralTypes, isFetching: isCollateralTypesFetching } = useCollateralTypes(); - - function getCollateralType(collateralSymbol?: string) { - if (!collateralTypes || !collateralTypes?.length) { - return; - } - - if (!collateralSymbol) { - return collateralTypes[0]; - } - - return collateralTypes?.find( - (collateral) => `${collateral.symbol}`.toLowerCase() === `${collateralSymbol}`.toLowerCase() - ); - } - - return { - isFetching: isCollateralTypesFetching, - data: getCollateralType(collateralSymbol), - }; -} diff --git a/liquidity/lib/useContractErrorParser/index.ts b/liquidity/lib/useContractErrorParser/index.ts deleted file mode 100644 index 2eae43ebd..000000000 --- a/liquidity/lib/useContractErrorParser/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useContractErrorParser'; diff --git a/liquidity/lib/useContractErrorParser/package.json b/liquidity/lib/useContractErrorParser/package.json deleted file mode 100644 index 3e80bcac1..000000000 --- a/liquidity/lib/useContractErrorParser/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@snx-v3/useContractErrorParser", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/withERC7412": "workspace:*", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useContractErrorParser/useContractErrorParser.ts b/liquidity/lib/useContractErrorParser/useContractErrorParser.ts deleted file mode 100644 index 612220c96..000000000 --- a/liquidity/lib/useContractErrorParser/useContractErrorParser.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { ethers, utils } from 'ethers'; -import { useCallback } from 'react'; -import { ERC7412_ABI } from '@snx-v3/withERC7412'; - -export type ContractErrorType = { - data: string; - name: string; - signature: string; - args: Record; -}; - -export function useContractErrorParser(Contract?: ethers.Contract) { - return useCallback( - (error: any): ContractErrorType | undefined => { - if (!Contract) { - return undefined; - } - try { - const errorData = error?.error?.data?.data || error?.error?.error?.data; // add more options as we find them - if (!errorData) { - console.error({ error }); // intentional logging as object so we can inspect all properties - return undefined; - } - - const contractAbi = Contract.interface.format(utils.FormatTypes.full) as string[]; - const newContract = new ethers.Contract( - Contract.address, - Array.from( - new Set( - contractAbi.concat(ERC7412_ABI).concat([ - // ERC721 errors - 'error CannotSelfApprove(address addr)', - 'error InvalidTransferRecipient(address addr)', - 'error InvalidOwner(address addr)', - 'error TokenDoesNotExist(uint256 id)', - 'error TokenAlreadyMinted(uint256 id)', - ]) - ) - ), // uniq - Contract.signer || Contract.provider - ); - const errorParsed = newContract.interface.parseError(errorData); - const errorArgs = Object.fromEntries( - Object.entries(errorParsed.args) - .filter(([key]) => `${parseInt(key)}` !== key) - .map(([key, value]) => { - if (value instanceof ethers.BigNumber) { - // Guess wei - const unwei = parseFloat(ethers.utils.formatEther(value.toString())); - if (unwei > 0.001) { - // must be wei - return [key, unwei]; - } - - // Guess date - if ( - value.toNumber() > new Date(2000, 1, 1).getTime() / 1000 && - value.toNumber() < new Date(2100, 1, 1).getTime() / 1000 - ) { - return [key, new Date(value.toNumber() * 1000)]; - } - - // Just a number - return [key, parseFloat(value.toString())]; - } - - // Not a number - return [key, value]; - }) - ); - - return { - data: errorData, - name: errorParsed.name, - signature: errorParsed.signature, - args: errorArgs, - }; - } catch (e) { - console.error(e); - return undefined; - } - }, - [Contract] - ); -} diff --git a/liquidity/lib/useCoreProxy/index.ts b/liquidity/lib/useCoreProxy/index.ts deleted file mode 100644 index b77abba71..000000000 --- a/liquidity/lib/useCoreProxy/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useCoreProxy'; diff --git a/liquidity/lib/useCoreProxy/package.json b/liquidity/lib/useCoreProxy/package.json deleted file mode 100644 index 0ab5de156..000000000 --- a/liquidity/lib/useCoreProxy/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useCoreProxy", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@ethersproject/contracts": "^5.7.0", - "@snx-v3/contracts": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useCoreProxy/useCoreProxy.ts b/liquidity/lib/useCoreProxy/useCoreProxy.ts deleted file mode 100644 index baca966e7..000000000 --- a/liquidity/lib/useCoreProxy/useCoreProxy.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { Contract } from '@ethersproject/contracts'; -import { useQuery } from '@tanstack/react-query'; -import { - Network, - useNetwork, - useProvider, - useProviderForChain, - useSigner, - useWallet, -} from '@snx-v3/useBlockchain'; -import { importCoreProxy } from '@snx-v3/contracts'; - -export function useCoreProxy({ - customNetwork, - isWrite = false, -}: { - customNetwork?: Network; - isWrite?: boolean; -} = {}) { - const { network } = useNetwork(); - const provider = useProvider(); - const signer = useSigner(); - const { activeWallet } = useWallet(); - const targetNetwork = customNetwork || network; - const providerForChain = useProviderForChain(targetNetwork); - - return useQuery({ - queryKey: [ - `${targetNetwork?.id}-${targetNetwork?.preset}`, - 'CoreProxy', - isWrite, - activeWallet?.address, - ], - queryFn: async function () { - const signerOrProvider = signer || provider; - if (isWrite && signerOrProvider) { - const { address, abi } = await importCoreProxy(network?.id, network?.preset); - return new Contract(address, abi, signerOrProvider); - } - if (targetNetwork) { - const { address, abi } = await importCoreProxy(targetNetwork.id, targetNetwork.preset); - return new Contract(address, abi, providerForChain || provider || undefined); - } - - if (!signerOrProvider || !network) throw new Error('Should be disabled CP'); - }, - enabled: Boolean(signer || provider || providerForChain), - staleTime: Infinity, - }); -} diff --git a/liquidity/lib/useDeposit/index.ts b/liquidity/lib/useDeposit/index.ts deleted file mode 100644 index 43798d9df..000000000 --- a/liquidity/lib/useDeposit/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useDeposit'; diff --git a/liquidity/lib/useDeposit/package.json b/liquidity/lib/useDeposit/package.json deleted file mode 100644 index a46997226..000000000 --- a/liquidity/lib/useDeposit/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "@snx-v3/useDeposit", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/fetchPythPrices": "workspace:*", - "@snx-v3/format": "workspace:*", - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useAllCollateralPriceIds": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useDeposit/useDeposit.tsx b/liquidity/lib/useDeposit/useDeposit.tsx deleted file mode 100644 index ce99b843b..000000000 --- a/liquidity/lib/useDeposit/useDeposit.tsx +++ /dev/null @@ -1,140 +0,0 @@ -import { useReducer } from 'react'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useMutation } from '@tanstack/react-query'; -import { useNetwork, useProvider, useSigner } from '@snx-v3/useBlockchain'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import Wei, { wei } from '@synthetixio/wei'; -import { BigNumber } from 'ethers'; - -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; -import { withERC7412 } from '@snx-v3/withERC7412'; -import { notNil } from '@snx-v3/tsHelpers'; -import { useAllCollateralPriceIds } from '@snx-v3/useAllCollateralPriceIds'; -import { fetchPriceUpdates, priceUpdatesToPopulatedTx } from '@snx-v3/fetchPythPrices'; -import { parseUnits } from '@snx-v3/format'; - -export const useDeposit = ({ - accountId, - newAccountId, - poolId, - collateralTypeAddress, - collateralChange, - currentCollateral, - availableCollateral, - decimals, -}: { - accountId?: string; - newAccountId: string; - poolId?: string; - collateralTypeAddress?: string; - currentCollateral: Wei; - availableCollateral?: Wei; - collateralChange: Wei; - decimals: number; -}) => { - const [txnState, dispatch] = useReducer(reducer, initialState); - const { data: CoreProxy } = useCoreProxy(); - const { data: collateralPriceUpdates } = useAllCollateralPriceIds(); - - const { gasSpeed } = useGasSpeed(); - - const { network } = useNetwork(); - const signer = useSigner(); - const provider = useProvider(); - - const mutation = useMutation({ - mutationFn: async () => { - if ( - !( - network && - provider && - signer && - CoreProxy && - poolId && - collateralTypeAddress && - availableCollateral && - collateralPriceUpdates - ) - ) { - return; - } - if (collateralChange.eq(0)) { - return; - } - - try { - dispatch({ type: 'prompting' }); - const walletAddress = await signer.getAddress(); - const id = accountId ?? newAccountId; - - // create account only when no account exists - const createAccount = accountId - ? undefined - : CoreProxy.populateTransaction['createAccount(uint128)'](BigNumber.from(id)); - - const amount = collateralChange.sub(availableCollateral); - - const collateralAmount = amount.gt(0) - ? parseUnits(amount.toString(), decimals) - : BigNumber.from(0); - - // optionally deposit if available collateral not enough - const deposit = collateralAmount.gt(0) - ? CoreProxy.populateTransaction.deposit( - BigNumber.from(id), - collateralTypeAddress, - collateralAmount // only deposit what's needed - ) - : undefined; - - const delegate = CoreProxy.populateTransaction.delegateCollateral( - BigNumber.from(id), - BigNumber.from(poolId), - collateralTypeAddress, - currentCollateral.add(collateralChange).toBN(), - wei(1).toBN() - ); - const callsPromise = Promise.all([createAccount, deposit, delegate].filter(notNil)); - const collateralPriceCallsPromise = fetchPriceUpdates( - collateralPriceUpdates, - network?.isTestnet - ).then((signedData) => - priceUpdatesToPopulatedTx(walletAddress, collateralPriceUpdates, signedData) - ); - - const [calls, gasPrices, collateralPriceCalls] = await Promise.all([ - callsPromise, - getGasPrice({ provider }), - collateralPriceCallsPromise, - ]); - const allCalls = collateralPriceCalls.concat(calls); - - const erc7412Tx = await withERC7412(network, allCalls, 'useDeposit', walletAddress); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: erc7412Tx.gasLimit, - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...erc7412Tx, ...gasOptionsForTransaction }); - dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - - await txn.wait(); - dispatch({ type: 'success' }); - } catch (error: any) { - dispatch({ type: 'error', payload: { error } }); - throw error; - } - }, - }); - return { - mutation, - txnState, - settle: () => dispatch({ type: 'settled' }), - isLoading: mutation.isPending, - exec: mutation.mutateAsync, - }; -}; diff --git a/liquidity/lib/useDepositBaseAndromeda/index.ts b/liquidity/lib/useDepositBaseAndromeda/index.ts deleted file mode 100644 index 19d374ebe..000000000 --- a/liquidity/lib/useDepositBaseAndromeda/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useDepositBaseAndromeda'; diff --git a/liquidity/lib/useDepositBaseAndromeda/package.json b/liquidity/lib/useDepositBaseAndromeda/package.json deleted file mode 100644 index 9bbab3bee..000000000 --- a/liquidity/lib/useDepositBaseAndromeda/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "@snx-v3/useDepositBaseAndromeda", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/format": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useApprove": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/useGetUSDTokens": "workspace:*", - "@snx-v3/useSpotMarketProxy": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useDepositBaseAndromeda/useDepositBaseAndromeda.tsx b/liquidity/lib/useDepositBaseAndromeda/useDepositBaseAndromeda.tsx deleted file mode 100644 index b497b8840..000000000 --- a/liquidity/lib/useDepositBaseAndromeda/useDepositBaseAndromeda.tsx +++ /dev/null @@ -1,173 +0,0 @@ -import { useReducer } from 'react'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useMutation } from '@tanstack/react-query'; -import { useNetwork, useProvider, useSigner } from '@snx-v3/useBlockchain'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import Wei, { wei } from '@synthetixio/wei'; -import { BigNumber, ethers } from 'ethers'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; -import { withERC7412 } from '@snx-v3/withERC7412'; -import { notNil } from '@snx-v3/tsHelpers'; -import { useSpotMarketProxy } from '@snx-v3/useSpotMarketProxy'; -import { parseUnits } from '@snx-v3/format'; -import { getSpotMarketId } from '@snx-v3/isBaseAndromeda'; -import { approveAbi } from '@snx-v3/useApprove'; -import { useCollateralPriceUpdates } from '@snx-v3/useCollateralPriceUpdates'; -import { useGetUSDTokens } from '@snx-v3/useGetUSDTokens'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; - -export const useDepositBaseAndromeda = ({ - accountId, - newAccountId, - poolId, - collateralTypeAddress, - collateralChange, - currentCollateral, - availableCollateral, - collateralSymbol, -}: { - accountId?: string; - newAccountId: string; - poolId?: string; - collateralTypeAddress?: string; - currentCollateral: Wei; - availableCollateral?: Wei; - collateralChange: Wei; - collateralSymbol?: string; -}) => { - const [txnState, dispatch] = useReducer(reducer, initialState); - const { data: CoreProxy } = useCoreProxy(); - const { data: SpotMarketProxy } = useSpotMarketProxy(); - const { data: priceUpdateTx } = useCollateralPriceUpdates(); - const { data: usdTokens } = useGetUSDTokens(); - const { data: collateralType } = useCollateralType(collateralSymbol); - - const { gasSpeed } = useGasSpeed(); - - const { network } = useNetwork(); - const signer = useSigner(); - const provider = useProvider(); - - const mutation = useMutation({ - mutationFn: async () => { - if ( - !( - network && - provider && - signer && - CoreProxy && - SpotMarketProxy && - poolId && - collateralTypeAddress && - availableCollateral && - usdTokens?.sUSD - ) - ) { - return; - } - if (collateralChange.eq(0)) return; - - try { - // Steps: - // 1. Create an account if not exists - // 2. Wrap USDC or stataUSDC to sUSDC or sStataUSDC - // 3. Approve sUSDC or sStataUSDC - // 4. Deposit sUSDC or sStataUSDC - // 5. Delegate collateral - - dispatch({ type: 'prompting' }); - const id = accountId ?? newAccountId; - - // create account only when no account exists - const createAccount = accountId - ? undefined - : CoreProxy.populateTransaction['createAccount(uint128)'](BigNumber.from(id)); - - const amount = collateralChange.sub(availableCollateral); - - const collateralAmount = amount.gt(0) - ? parseUnits(amount.toString(), 6) - : BigNumber.from(0); - - const spotMarketId = getSpotMarketId(collateralSymbol); - const amountD18 = amount.gt(0) ? parseUnits(amount.toString(), 18) : BigNumber.from(0); - - // Wrap - const wrap = collateralAmount.gt(0) - ? SpotMarketProxy.populateTransaction.wrap(spotMarketId, collateralAmount, amountD18) - : undefined; - - // Synth - const synthAddress = collateralType?.tokenAddress; - if (!synthAddress) { - throw 'synth not found'; - } - const synthContract = new ethers.Contract(synthAddress, approveAbi, signer); - - const synthApproval = amountD18.gt(0) - ? synthContract.populateTransaction.approve(CoreProxy.address, amountD18) - : undefined; - - // optionally deposit if available collateral not enough - const deposit = amountD18.gt(0) - ? CoreProxy.populateTransaction.deposit( - BigNumber.from(id), - synthAddress, - amountD18 // only deposit what's needed - ) - : undefined; - - const delegate = CoreProxy.populateTransaction.delegateCollateral( - BigNumber.from(id), - BigNumber.from(poolId), - synthAddress, - currentCollateral.toBN().add(parseUnits(collateralChange.toString(), 18)).toString(), - wei(1).toBN() - ); - - const callsPromise = Promise.all( - [wrap, synthApproval, createAccount, deposit, delegate].filter(notNil) - ); - - const [calls, gasPrices] = await Promise.all([callsPromise, getGasPrice({ provider })]); - - if (priceUpdateTx) { - calls.unshift(priceUpdateTx as any); - } - - const walletAddress = await signer.getAddress(); - - const erc7412Tx = await withERC7412( - network, - calls, - 'useDepositBaseAndromeda', - walletAddress - ); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: erc7412Tx.gasLimit, - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...erc7412Tx, ...gasOptionsForTransaction }); - dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - - await txn.wait(); - dispatch({ type: 'success' }); - } catch (error: any) { - dispatch({ type: 'error', payload: { error } }); - throw error; - } - }, - }); - return { - mutation, - txnState, - settle: () => dispatch({ type: 'settled' }), - isLoading: mutation.isPending, - exec: mutation.mutateAsync, - }; -}; diff --git a/liquidity/lib/useEthBalance/index.ts b/liquidity/lib/useEthBalance/index.ts deleted file mode 100644 index a0558568e..000000000 --- a/liquidity/lib/useEthBalance/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useEthBalance'; diff --git a/liquidity/lib/useEthBalance/package.json b/liquidity/lib/useEthBalance/package.json deleted file mode 100644 index 3154ecd93..000000000 --- a/liquidity/lib/useEthBalance/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@snx-v3/useEthBalance", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/zod": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3" - } -} diff --git a/liquidity/lib/useEthBalance/useEthBalance.ts b/liquidity/lib/useEthBalance/useEthBalance.ts deleted file mode 100644 index ee0fd2644..000000000 --- a/liquidity/lib/useEthBalance/useEthBalance.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { useWallet, useNetwork, useDefaultProvider } from '@snx-v3/useBlockchain'; -import { ZodBigNumber } from '@snx-v3/zod'; -import { wei } from '@synthetixio/wei'; - -const BalanceSchema = ZodBigNumber.transform((x) => wei(x)); - -export function useEthBalance(networkId?: number) { - const { activeWallet } = useWallet(); - const provider = useDefaultProvider(); - const { network } = useNetwork(); - - return useQuery({ - queryKey: [ - `${network?.id}-${network?.preset}`, - 'EthBalance', - { accountAddress: activeWallet?.address }, - ], - queryFn: async () => { - if (!activeWallet || !provider) throw Error('useEthBalance should not be enabled'); - return BalanceSchema.parse(await provider.getBalance(activeWallet.address)); - }, - enabled: Boolean((networkId ?? network?.id) && activeWallet?.address), - }); -} diff --git a/liquidity/lib/useGasOptions/index.ts b/liquidity/lib/useGasOptions/index.ts deleted file mode 100644 index b604665b3..000000000 --- a/liquidity/lib/useGasOptions/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useGasOptions'; diff --git a/liquidity/lib/useGasOptions/package.json b/liquidity/lib/useGasOptions/package.json deleted file mode 100644 index 12f0fc4e9..000000000 --- a/liquidity/lib/useGasOptions/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useGasOptions", - "private": true, - "main": "index.ts", - "version": "0.0.3", - "dependencies": { - "@ethersproject/bignumber": "^5.7.0", - "@snx-v3/constants": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useGasOptions/useGasOptions.ts b/liquidity/lib/useGasOptions/useGasOptions.ts deleted file mode 100644 index eee815254..000000000 --- a/liquidity/lib/useGasOptions/useGasOptions.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type { GasPrices } from '@snx-v3/useGasPrice'; -import type { BigNumber } from '@ethersproject/bignumber'; -import { wei } from '@synthetixio/wei'; -import { GWEI_DECIMALS, GAS_LIMIT_MULTIPLIER } from '@snx-v3/constants'; - -// Note it looks like gas limit estimation is coming in higher slightly higher than what gets used according to etherscan -// Will try without a buffer, if we get user report of out of gas we can increase it again. -const GAS_LIMIT_BUFFER = wei(GAS_LIMIT_MULTIPLIER, GWEI_DECIMALS); - -function addGasLimitBuffer(gasLimit?: BigNumber) { - return wei(gasLimit ?? 0, GWEI_DECIMALS) - .mul(GAS_LIMIT_BUFFER) - .toBN(); -} - -export function formatGasPriceForTransaction({ - gasPrices, - gasSpeed, - gasLimit, -}: { - gasPrices: GasPrices; - gasSpeed: keyof GasPrices; - gasLimit: BigNumber; -}) { - const gasPrice = gasPrices[gasSpeed]; - if ('baseFeePerGas' in gasPrice) { - const { baseFeePerGas: _baseFeePerGas, ...gasPriceToReturn } = gasPrice; - return { ...gasPriceToReturn, gasLimit: addGasLimitBuffer(gasLimit) }; - } - return { ...gasPrice, gasLimit: addGasLimitBuffer(gasLimit) }; -} diff --git a/liquidity/lib/useGasPrice/index.ts b/liquidity/lib/useGasPrice/index.ts deleted file mode 100644 index 2fa32c224..000000000 --- a/liquidity/lib/useGasPrice/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useGasPrice'; diff --git a/liquidity/lib/useGasPrice/package.json b/liquidity/lib/useGasPrice/package.json deleted file mode 100644 index 19637b5b4..000000000 --- a/liquidity/lib/useGasPrice/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "@snx-v3/useGasPrice", - "private": true, - "main": "index.ts", - "version": "0.0.3", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/feeSuggestion": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useGasPrice/useGasPrice.test.ts b/liquidity/lib/useGasPrice/useGasPrice.test.ts deleted file mode 100644 index 125cba1e3..000000000 --- a/liquidity/lib/useGasPrice/useGasPrice.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { GWEI_DECIMALS } from '@snx-v3/constants'; -import { wei } from '@synthetixio/wei'; - -describe('useGasPrice', () => { - let useGasPrice; - let react; - let reactQuery; - let useNetwork; - let provider; - let useProvider; - let feeSuggestion; - - beforeEach(async () => { - provider = { - getBlock: jest.fn(() => ({})), - getGasPrice: jest.fn(() => wei(2, GWEI_DECIMALS).toBN()), - }; - useNetwork = jest.fn(() => ({ network: { id: 10, name: 'optimism-mainnet', preset: 'main' } })); - useProvider = jest.fn(() => provider); - - reactQuery = { - useQuery: jest.fn(() => 'useQuery'), - }; - - feeSuggestion = jest.fn(() => 'suggested fee'); - - jest.doMock('react', () => react); - jest.doMock('@tanstack/react-query', () => reactQuery); - jest.doMock('@snx-v3/useBlockchain', () => ({ useNetwork, useProvider })); - jest.doMock('@snx-v3/useGasPrice', () => ({ useGasPrice })); - jest.doMock('@snx-v3/feeSuggestion', () => ({ feeSuggestion })); - - ({ useGasPrice } = await import('./useGasPrice')); - }); - - afterEach(() => { - jest.resetModules(); - }); - - test('Returns gas prices for mainnet', async () => { - useNetwork.mockReturnValue({ network: { id: 1, name: 'mainnet', preset: 'main' } }); - provider.getBlock.mockReturnValue({ baseFeePerGas: wei(2, GWEI_DECIMALS).toBN() }); - - const result = useGasPrice(); - const { queryKey, queryFn, enabled } = reactQuery.useQuery.mock.lastCall[0]; - - expect(result.data).toEqual(undefined); - expect(queryKey).toEqual(['1-main', 'GasPrice']); - expect(enabled).toEqual(true); - - const queryResult = await queryFn(); - expect(queryResult).toEqual('suggested fee'); - }); - - test('Returns gas prices for optimism', async () => { - const result = useGasPrice(); - const { queryKey, queryFn, enabled } = reactQuery.useQuery.mock.lastCall[0]; - expect(result.data).toEqual(undefined); - expect(queryKey).toEqual(['10-main', 'GasPrice']); - expect(enabled).toEqual(true); - const queryResult = await queryFn(); - expect(provider.getGasPrice).toBeCalled(); - - expect(queryResult).toEqual({ - average: { - gasPrice: wei(2, GWEI_DECIMALS).toBN(), - }, - fast: { - gasPrice: wei(2, GWEI_DECIMALS).toBN(), - }, - fastest: { - gasPrice: wei(2, GWEI_DECIMALS).toBN(), - }, - }); - }); -}); diff --git a/liquidity/lib/useGasPrice/useGasPrice.ts b/liquidity/lib/useGasPrice/useGasPrice.ts deleted file mode 100644 index 9d72ecb6c..000000000 --- a/liquidity/lib/useGasPrice/useGasPrice.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { ethers } from 'ethers'; -import { useNetwork, useProvider } from '@snx-v3/useBlockchain'; -import { feeSuggestion } from '@snx-v3/feeSuggestion'; - -const getGasPriceFromProvider = async (provider: ethers.providers.JsonRpcProvider) => { - try { - const gasPrice = await provider.getGasPrice(); - return { - fastest: { gasPrice }, - fast: { gasPrice }, - average: { gasPrice }, - }; - } catch (e) { - throw new Error('Could not retrieve gas price from provider'); - } -}; - -export const getGasPrice = async ({ provider }: { provider: ethers.providers.JsonRpcProvider }) => { - try { - const block = await provider.getBlock('latest'); - if (block.baseFeePerGas) { - return feeSuggestion(provider); - } - // When missing baseFeePerGas we get the Gas Price through the provider - return getGasPriceFromProvider(provider); - } catch (e) { - throw new Error(`Could not fetch and compute network fee. ${e}`); - } -}; - -export type GasPrices = Awaited>; - -export const useGasPrice = () => { - const { network } = useNetwork(); - const provider = useProvider(); - - return useQuery({ - enabled: Boolean(provider), - queryKey: [`${network?.id}-${network?.preset}`, 'GasPrice'], - queryFn: () => { - if (!provider) throw new Error('useGasPrice should not be enabled'); - return getGasPrice({ provider }); - }, - }); -}; diff --git a/liquidity/lib/useGasSpeed/GasSpeedContext.tsx b/liquidity/lib/useGasSpeed/GasSpeedContext.tsx deleted file mode 100644 index dcad3fcc8..000000000 --- a/liquidity/lib/useGasSpeed/GasSpeedContext.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import React, { - createContext, - useState, - PropsWithChildren, - Dispatch, - SetStateAction, - useContext, -} from 'react'; - -export type GasSpeed = 'average' | 'fast' | 'fastest'; - -export const GasSpeedContext = createContext<{ - gasSpeed: GasSpeed; - setGasSpeed: Dispatch>; -}>({ - gasSpeed: 'average', - // eslint-disable-next-line @typescript-eslint/no-empty-function - setGasSpeed: () => {}, -}); - -export const GasSpeedProvider: React.FC = ({ children }) => { - const [gasSpeed, setGasSpeed] = useState('average'); - return ( - - {children} - - ); -}; - -export const useGasSpeed = () => { - return useContext(GasSpeedContext); -}; diff --git a/liquidity/lib/useGasSpeed/index.ts b/liquidity/lib/useGasSpeed/index.ts deleted file mode 100644 index ee2191cb1..000000000 --- a/liquidity/lib/useGasSpeed/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './GasSpeedContext'; diff --git a/liquidity/lib/useGasSpeed/package.json b/liquidity/lib/useGasSpeed/package.json deleted file mode 100644 index b2a73d7f3..000000000 --- a/liquidity/lib/useGasSpeed/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "@snx-v3/useGasSpeed", - "private": true, - "main": "index.ts", - "version": "0.0.0", - "dependencies": { - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useGetBorrow/index.ts b/liquidity/lib/useGetBorrow/index.ts deleted file mode 100644 index cf6dfcc6a..000000000 --- a/liquidity/lib/useGetBorrow/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useGetBorrow'; diff --git a/liquidity/lib/useGetBorrow/package.json b/liquidity/lib/useGetBorrow/package.json deleted file mode 100644 index 969724454..000000000 --- a/liquidity/lib/useGetBorrow/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@snx-v3/useGetBorrow", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3" - } -} diff --git a/liquidity/lib/useGetBorrow/useGetBorrow.tsx b/liquidity/lib/useGetBorrow/useGetBorrow.tsx deleted file mode 100644 index 54c1a132f..000000000 --- a/liquidity/lib/useGetBorrow/useGetBorrow.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import { getSubgraphUrl } from '@snx-v3/constants'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useQuery } from '@tanstack/react-query'; - -export const useGetBorrow = ({ - accountId, - poolId, - collateralTypeAddress, -}: { - accountId?: string; - poolId?: string; - collateralTypeAddress?: string; -}) => { - const { network } = useNetwork(); - - return useQuery({ - enabled: Boolean(!isBaseAndromeda(network?.id, network?.preset) && network), - queryKey: ['useGetBorrow', accountId, poolId, collateralTypeAddress], - queryFn: async () => { - if (!network) throw new Error('useGetBorrow requires network'); - - const url = getSubgraphUrl(network.name); - const response = await fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: ` - query getPosition($id: ID!){ - position(id: $id) { - net_issuance - } - } - `, - variables: { - id: `${accountId}-${poolId}-${collateralTypeAddress?.toLowerCase()}`, - }, - }), - }); - - const { data } = await response.json(); - - return data; - }, - }); -}; diff --git a/liquidity/lib/useGetHistoricalTVL/index.ts b/liquidity/lib/useGetHistoricalTVL/index.ts deleted file mode 100644 index e0f3e2684..000000000 --- a/liquidity/lib/useGetHistoricalTVL/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useGetHistoricalTVL'; diff --git a/liquidity/lib/useGetHistoricalTVL/package.json b/liquidity/lib/useGetHistoricalTVL/package.json deleted file mode 100644 index e0c499471..000000000 --- a/liquidity/lib/useGetHistoricalTVL/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@snx-v3/useGetHistoricalTVL", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3" - } -} diff --git a/liquidity/lib/useGetHistoricalTVL/useGetHistoricalTVL.tsx b/liquidity/lib/useGetHistoricalTVL/useGetHistoricalTVL.tsx deleted file mode 100644 index a8cb7cda5..000000000 --- a/liquidity/lib/useGetHistoricalTVL/useGetHistoricalTVL.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import { getSubgraphUrl } from '@snx-v3/constants'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useQuery } from '@tanstack/react-query'; - -export const useGetHistoricalTVL = ({ - poolId, - collateralTypeAddresses, -}: { - poolId?: string; - collateralTypeAddresses?: string[]; -}) => { - const { network } = useNetwork(); - return useQuery({ - queryKey: ['useGetHistoricalTVL', poolId, collateralTypeAddresses?.toString(), network?.name], - queryFn: async () => { - if (!network?.name || !collateralTypeAddresses?.length) return; - const responses = await Promise.all( - collateralTypeAddresses.map(() => - fetch(getSubgraphUrl(network?.name), { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: ` - query { - vaultSnapshotByYears(first:1000) { - id - collateral_amount - collateral_type - created_at - created_at_block - updated_at - updated_at_block - } - } - `, - // variables: { id: `${poolId}-${address.toLowerCase()}-2024-20` }, - }), - }) - ) - ); - - const data = await Promise.all(responses.map((response) => response.json())); - return data; - }, - }); -}; - -// query getTVL($id: ID!){ -// vaultSnapshotByWeek(id: $id) { -// id -// collateral_amount -// collateral_type -// created_at -// created_at_block -// updated_at -// updated_at_block -// } -// } diff --git a/liquidity/lib/useGetUSDTokens/index.ts b/liquidity/lib/useGetUSDTokens/index.ts deleted file mode 100644 index 7d614a4c7..000000000 --- a/liquidity/lib/useGetUSDTokens/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useGetUSDTokens'; diff --git a/liquidity/lib/useGetUSDTokens/package.json b/liquidity/lib/useGetUSDTokens/package.json deleted file mode 100644 index e5009fc72..000000000 --- a/liquidity/lib/useGetUSDTokens/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "@snx-v3/useGetUSDTokens", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useSpotMarketProxy": "workspace:*", - "@snx-v3/useSystemToken": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useGetUSDTokens/useGetUSDTokens.ts b/liquidity/lib/useGetUSDTokens/useGetUSDTokens.ts deleted file mode 100644 index aba96bfda..000000000 --- a/liquidity/lib/useGetUSDTokens/useGetUSDTokens.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { Network, useNetwork } from '@snx-v3/useBlockchain'; -import { useCollateralTypes } from '@snx-v3/useCollateralTypes'; -import { useSpotMarketProxy } from '@snx-v3/useSpotMarketProxy'; -import { USDC_BASE_MARKET, isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useSystemToken } from '@snx-v3/useSystemToken'; - -export function useGetUSDTokens(customNetwork?: Network) { - const { network } = useNetwork(); - - const targetNetwork = customNetwork || network; - - const isBase = isBaseAndromeda(targetNetwork?.id, targetNetwork?.preset); - - const { data: collateralTypes } = useCollateralTypes(false, customNetwork); - const { data: SpotMarket } = useSpotMarketProxy(customNetwork); - const { data: systemToken } = useSystemToken(customNetwork); - - return useQuery({ - queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, 'GetUSDTokens'], - enabled: Boolean(targetNetwork?.id && collateralTypes?.length && systemToken && SpotMarket), - queryFn: async () => { - if (!targetNetwork?.id || !systemToken || !SpotMarket) { - throw 'useGetUSDTokens queries are not ready'; - } - const USDC: string = isBase - ? (await (SpotMarket as any)?.getWrapper(USDC_BASE_MARKET))?.wrapCollateralType - : undefined; - - return { - snxUSD: systemToken.address, - sUSD: collateralTypes?.find((type) => - isBase ? type.symbol.toLowerCase() === 'usdc' : type.symbol.toLowerCase() === 'susdc' - )?.tokenAddress, - USDC, - }; - }, - }); -} - -export const useGetWrapperToken = (marketId: string, customNetwork?: Network) => { - const { network } = useNetwork(); - - const targetNetwork = customNetwork || network; - - const isBase = isBaseAndromeda(targetNetwork?.id, targetNetwork?.preset); - - const { data: SpotMarket } = useSpotMarketProxy(customNetwork); - - return useQuery({ - queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, 'GetWrapperToken', marketId], - enabled: Boolean(targetNetwork?.id && SpotMarket && isBase), - queryFn: async () => { - if (!targetNetwork?.id || !SpotMarket) { - throw 'useGetWrapperToken queries are not ready'; - } - - return isBase - ? (await (SpotMarket as any)?.getWrapper(marketId))?.wrapCollateralType - : undefined; - }, - }); -}; diff --git a/liquidity/lib/useLegacyMarket/index.ts b/liquidity/lib/useLegacyMarket/index.ts deleted file mode 100644 index fee19472f..000000000 --- a/liquidity/lib/useLegacyMarket/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useLegacyMarket'; diff --git a/liquidity/lib/useLegacyMarket/package.json b/liquidity/lib/useLegacyMarket/package.json deleted file mode 100644 index 656e9cf9b..000000000 --- a/liquidity/lib/useLegacyMarket/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useLegacyMarket", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@ethersproject/contracts": "^5.7.0", - "@snx-v3/contracts": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useLegacyMarket/useLegacyMarket.ts b/liquidity/lib/useLegacyMarket/useLegacyMarket.ts deleted file mode 100644 index 8ed45c8fd..000000000 --- a/liquidity/lib/useLegacyMarket/useLegacyMarket.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { Contract } from '@ethersproject/contracts'; -import { useQuery } from '@tanstack/react-query'; -import { - Network, - useNetwork, - useProvider, - useProviderForChain, - useSigner, -} from '@snx-v3/useBlockchain'; -import { importLegacyMarket } from '@snx-v3/contracts'; - -export function useLegacyMarket(customNetwork?: Network) { - const providerForChain = useProviderForChain(customNetwork); - const { network } = useNetwork(); - const provider = useProvider(); - const signer = useSigner(); - const targetNetwork = customNetwork || network; - - const withSigner = Boolean(signer); - - return useQuery({ - queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, 'LegacyMarket', { withSigner }], - queryFn: async function () { - if (providerForChain && customNetwork) { - const { address: lmAddress, abi: lmAbi } = await importLegacyMarket( - customNetwork.id, - customNetwork.preset - ); - return new Contract(lmAddress, lmAbi, providerForChain); - } - - const signerOrProvider = signer || provider; - if (!signerOrProvider || !network) throw new Error('Should be disabled CP'); - - const { address: lmAddress, abi: lmAbi } = await importLegacyMarket( - network?.id, - network?.preset - ); - - return new Contract(lmAddress, lmAbi, signerOrProvider); - }, - enabled: Boolean(signer || provider || providerForChain), - staleTime: Infinity, - }); -} diff --git a/liquidity/lib/useLiquidityPosition/index.ts b/liquidity/lib/useLiquidityPosition/index.ts deleted file mode 100644 index e45560371..000000000 --- a/liquidity/lib/useLiquidityPosition/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useLiquidityPosition'; diff --git a/liquidity/lib/useLiquidityPosition/package.json b/liquidity/lib/useLiquidityPosition/package.json deleted file mode 100644 index 0eb706453..000000000 --- a/liquidity/lib/useLiquidityPosition/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "@snx-v3/useLiquidityPosition", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/useAccountCollateral": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCollateralPrices": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useSystemToken": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@snx-v3/zod": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0", - "zod": "^3.22.4" - } -} diff --git a/liquidity/lib/useLiquidityPosition/useLiquidityPosition.ts b/liquidity/lib/useLiquidityPosition/useLiquidityPosition.ts deleted file mode 100644 index 4adc2c090..000000000 --- a/liquidity/lib/useLiquidityPosition/useLiquidityPosition.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { useMemo } from 'react'; -import { stringToHash } from '@snx-v3/tsHelpers'; -import { AccountCollateralType, loadAccountCollateral } from '@snx-v3/useAccountCollateral'; -import { useNetwork, useProviderForChain } from '@snx-v3/useBlockchain'; -import { loadPrices } from '@snx-v3/useCollateralPrices'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { erc7412Call } from '@snx-v3/withERC7412'; -import { ZodBigNumber } from '@snx-v3/zod'; -import Wei, { wei } from '@synthetixio/wei'; -import { useQuery } from '@tanstack/react-query'; -import { ethers } from 'ethers'; -import { z } from 'zod'; -import { useAllCollateralPriceUpdates } from '@snx-v3/useCollateralPriceUpdates'; -import { useCollateralTypes } from '@snx-v3/useCollateralTypes'; - -const PositionCollateralSchema = z.object({ - value: ZodBigNumber.transform((x) => wei(x)).optional(), // This is currently only removed on base-goreli - amount: ZodBigNumber.transform((x) => wei(x)), -}); - -const DebtSchema = ZodBigNumber.transform((x) => wei(x)); - -export const loadPosition = async ({ - CoreProxy, - accountId, - poolId, - tokenAddress, -}: { - CoreProxy: ethers.Contract; - accountId: string; - poolId: string; - tokenAddress: string; -}) => { - const calls = await Promise.all([ - CoreProxy.populateTransaction.getPositionCollateral(accountId, poolId, tokenAddress), - CoreProxy.populateTransaction.getPositionDebt(accountId, poolId, tokenAddress), - ]); - - const decoder = (multicallEncoded: string | string[]) => { - if (Array.isArray(multicallEncoded) && multicallEncoded.length === 2) { - const decodedCollateral = CoreProxy.interface.decodeFunctionResult( - 'getPositionCollateral', - multicallEncoded[0] - ); - const decodedDebt = CoreProxy.interface.decodeFunctionResult( - 'getPositionDebt', - multicallEncoded[1] - )[0]; - return { - debt: DebtSchema.parse(decodedDebt), - collateral: PositionCollateralSchema.parse({ ...decodedCollateral }), - }; - } - throw Error('Expected array with two items'); - }; - - return { calls, decoder }; -}; - -export type LiquidityPosition = { - collateralAmount: Wei; - collateralPrice: Wei; - collateralValue: Wei; - debt: Wei; - accountCollateral: AccountCollateralType; - usdCollateral: AccountCollateralType; - tokenAddress: string; - accountId: string; -}; - -export const useLiquidityPosition = ({ - tokenAddress, - accountId, - poolId, -}: { - tokenAddress?: string; - accountId?: string; - poolId?: string; -}) => { - const { data: CoreProxy } = useCoreProxy(); - const { data: systemToken } = useSystemToken(); - const { network } = useNetwork(); - const { data: priceUpdateTx } = useAllCollateralPriceUpdates(); - const provider = useProviderForChain(network!); - const { data: collateralTypes } = useCollateralTypes(true); - - const priceUpdateTxHash = useMemo( - () => (priceUpdateTx?.data ? stringToHash(priceUpdateTx?.data) : null), - [priceUpdateTx?.data] - ); - - return useQuery({ - queryKey: [ - `${network?.id}-${network?.preset}`, - 'LiquidityPosition', - { accountId }, - { - pool: poolId, - token: tokenAddress, - systemToken: systemToken?.address, - provider: !!provider, - }, - { priceUpdateTxHash }, - ], - staleTime: 60000 * 5, - enabled: !!tokenAddress && !!accountId, - queryFn: async () => { - if ( - !(CoreProxy && accountId && poolId && tokenAddress && systemToken && network && provider) - ) { - throw Error('useLiquidityPosition not ready'); - } - const { calls: priceCalls, decoder: priceDecoder } = await loadPrices({ - collateralAddresses: [tokenAddress], - CoreProxy, - }); - - const { calls: positionCalls, decoder: positionDecoder } = await loadPosition({ - CoreProxy, - accountId, - poolId, - tokenAddress, - }); - - const { calls: accountCollateralCalls, decoder: accountCollateralDecoder } = - await loadAccountCollateral({ - accountId, - tokenAddresses: [tokenAddress, systemToken.address], - CoreProxy, - }); - - const allCalls = priceCalls.concat(positionCalls).concat(accountCollateralCalls); - - if (priceUpdateTx) { - allCalls.unshift(priceUpdateTx as any); - } - - return await erc7412Call( - network, - provider, - allCalls, - (encoded) => { - if (!Array.isArray(encoded)) throw Error('Expected array'); - - const startOfPrice = 0; - const endOfPrice = priceCalls.length; - const startOfPosition = endOfPrice; - const endOfPosition = startOfPosition + positionCalls.length; - - const startOfAccountCollateral = endOfPosition; - const collateralPrice = priceDecoder(encoded.slice(startOfPrice, endOfPrice)); - const decodedPosition = positionDecoder(encoded.slice(startOfPosition, endOfPosition)); - const [accountCollateral, usdCollateral] = accountCollateralDecoder( - encoded.slice(startOfAccountCollateral) - ); - - const collateralType = collateralTypes?.find( - (x) => x.tokenAddress.toLowerCase() === accountCollateral.tokenAddress.toLowerCase() - ); - if (collateralType) { - accountCollateral.symbol = collateralType.symbol; - accountCollateral.displaySymbol = collateralType.displaySymbol; - accountCollateral.decimals = collateralType.decimals; - } - - return { - collateralPrice: Array.isArray(collateralPrice) ? collateralPrice[0] : collateralPrice, - collateralAmount: decodedPosition.collateral.amount, - collateralValue: decodedPosition.collateral.amount.mul(collateralPrice), - debt: decodedPosition.debt, - tokenAddress, - accountCollateral, - usdCollateral, - accountId, - }; - }, - `useLiquidityPosition` - ); - }, - }); -}; diff --git a/liquidity/lib/useLiquidityPositions/index.ts b/liquidity/lib/useLiquidityPositions/index.ts deleted file mode 100644 index 6b8b10b43..000000000 --- a/liquidity/lib/useLiquidityPositions/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useLiquidityPositions'; diff --git a/liquidity/lib/useLiquidityPositions/package.json b/liquidity/lib/useLiquidityPositions/package.json deleted file mode 100644 index 35b896fe5..000000000 --- a/liquidity/lib/useLiquidityPositions/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "@snx-v3/useLiquidityPositions", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/calculations": "workspace:*", - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCollateralPrices": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useLiquidityPosition": "workspace:*", - "@snx-v3/usePools": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3" - } -} diff --git a/liquidity/lib/useLiquidityPositions/useLiquidityPositions.ts b/liquidity/lib/useLiquidityPositions/useLiquidityPositions.ts deleted file mode 100644 index a234f2e50..000000000 --- a/liquidity/lib/useLiquidityPositions/useLiquidityPositions.ts +++ /dev/null @@ -1,195 +0,0 @@ -import { CollateralType, useCollateralTypes } from '@snx-v3/useCollateralTypes'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { loadPosition } from '@snx-v3/useLiquidityPosition'; -import { usePools } from '@snx-v3/usePools'; -import Wei, { wei } from '@synthetixio/wei'; -import { useQuery } from '@tanstack/react-query'; -import { useNetwork, useProviderForChain } from '@snx-v3/useBlockchain'; -import { loadPrices } from '@snx-v3/useCollateralPrices'; -import { calculateCRatio } from '@snx-v3/calculations'; -import { erc7412Call } from '@snx-v3/withERC7412'; -import { keyBy, stringToHash } from '@snx-v3/tsHelpers'; -import { useAllCollateralPriceUpdates } from '@snx-v3/useCollateralPriceUpdates'; - -export type LiquidityPositionType = { - id: `${string}-${string}`; - accountId: string; - poolId: string; - isPreferred: boolean; - poolName: string; - collateralAmount: Wei; - collateralPrice: Wei; - collateralValue: Wei; - collateralType: CollateralType; - availableCollateral: Wei; - cRatio: Wei; - debt: Wei; -}; - -export type LiquidityPositionsById = { - [poolIdDashSymbol: `${string}-${string}`]: LiquidityPositionType; -}; - -function toPairs(array: T[]): [T, T][] { - return Array.from( - { length: array.length / 2 }, - (_, i) => [array[i * 2], array[i * 2 + 1]] as [T, T] - ); -} - -export const useLiquidityPositions = ({ accountId }: { accountId?: string }) => { - const { data: CoreProxy } = useCoreProxy(); - - const { data: pools } = usePools(); - const { data: collateralTypes } = useCollateralTypes(); - const { data: priceUpdateTx, isLoading: collateralPriceUpdatesIsLoading } = - useAllCollateralPriceUpdates(); - - const { network } = useNetwork(); - const provider = useProviderForChain(network!); - - const query = useQuery({ - queryKey: [ - `${network?.id}-${network?.preset}`, - 'LiquidityPositions', - { accountId }, - { - pools: pools ? pools.map((pool) => pool.id).sort() : [], - tokens: collateralTypes ? collateralTypes.map((x) => x.tokenAddress).sort() : [], - priceUpdateTx: stringToHash(priceUpdateTx?.data), - CoreProxy: !!CoreProxy, - }, - ], - staleTime: 60000 * 5, - enabled: !!accountId, - queryFn: async () => { - if (!pools || !collateralTypes || !CoreProxy || !accountId || !network || !provider) { - throw Error('Query should not be enabled'); - } - - const positionCallsAndDataNested = await Promise.all( - pools.map(async ({ id: poolId, name: poolName, isPreferred }) => - Promise.all( - collateralTypes.map(async (collateralType) => { - const { calls, decoder } = await loadPosition({ - CoreProxy, - accountId, - poolId, - tokenAddress: collateralType.tokenAddress, - }); - return { calls, decoder, poolName, collateralType, poolId, isPreferred }; - }) - ) - ) - ); - - const positionCallsAndData = positionCallsAndDataNested.flat(); - - const { calls: priceCalls, decoder: priceDecoder } = await loadPrices({ - collateralAddresses: collateralTypes.map((x) => x.tokenAddress), - CoreProxy, - }); - - const positionCalls = positionCallsAndData.map((x) => x.calls).flat(); - - const availableCollateralCalls = await Promise.all( - collateralTypes.map( - (collateralType) => - CoreProxy.populateTransaction.getAccountAvailableCollateral( - accountId, - collateralType.tokenAddress - ), - [] - ) - ); - - const allCalls = priceCalls.concat(positionCalls).concat(availableCollateralCalls); - const singlePositionDecoder = positionCallsAndData.at(0)?.decoder; - - if (priceUpdateTx) { - allCalls.unshift(priceUpdateTx as any); - } - - return await erc7412Call( - network, - provider!, - allCalls, - (encoded) => { - if (!Array.isArray(encoded)) throw Error('Expected array'); - if (!singlePositionDecoder) return {}; - - const prices = priceDecoder(encoded.slice(0, priceCalls.length)); - const pricesByAddress = keyBy( - 'address', - Array.isArray(prices) - ? prices.map((price, i) => ({ - price, - address: collateralTypes[i].tokenAddress, - })) - : [{ price: prices, address: collateralTypes[0].tokenAddress }] - ); - - const pairedPositionsEncoded = toPairs( - encoded.slice(priceCalls.length, priceCalls.length + positionCalls.length) - ); - const positionData = pairedPositionsEncoded.map((x) => singlePositionDecoder(x)); - - const availableCollaterals = encoded - .slice(priceCalls.length + positionCalls.length) - .map((encode) => - CoreProxy.interface.decodeFunctionResult('getAccountAvailableCollateral', encode) - ); - const availableCollateralByAddress = keyBy( - 'address', - Array.isArray(availableCollaterals) - ? availableCollaterals.map((availableCollateral, i) => ({ - availableCollateral: wei(availableCollateral[0]), - address: collateralTypes[i].tokenAddress, - })) - : [ - { - availableCollateral: wei(availableCollaterals[0]), - address: collateralTypes[0].tokenAddress, - }, - ] - ); - - const positions = positionData.map(({ debt, collateral }, index) => { - const { poolName, collateralType, poolId, isPreferred } = positionCallsAndData[index]; - // Value will be removed from the collateral call in next release, so to prepare for that calculate it manually - const collateralAmount = collateral.amount; - const collateralPrice = pricesByAddress?.[collateralType.tokenAddress].price; - const collateralValue = collateralPrice - ? collateralAmount.mul(collateralPrice) - : wei(0); - const availableCollateral = - availableCollateralByAddress?.[collateralType.tokenAddress].availableCollateral; - const cRatio = calculateCRatio(debt, collateralValue); - - return { - id: `${poolId}-${collateralType.symbol}` as const, - accountId, - poolId, - poolName, - collateralPrice, - collateralAmount, - collateralValue, - collateralType, - cRatio, - debt, - isPreferred, - availableCollateral, - }; - }); - return keyBy('id', positions); - }, - 'useLiquidityPositions' - ); - }, - }); - - return { - ...query, - isLoading: query.isLoading || collateralPriceUpdatesIsLoading, - }; -}; diff --git a/liquidity/lib/useLocalStorage/index.ts b/liquidity/lib/useLocalStorage/index.ts deleted file mode 100644 index 01cda12e7..000000000 --- a/liquidity/lib/useLocalStorage/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useLocalStorage'; diff --git a/liquidity/lib/useLocalStorage/package.json b/liquidity/lib/useLocalStorage/package.json deleted file mode 100644 index 789369240..000000000 --- a/liquidity/lib/useLocalStorage/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "@snx-v3/useLocalStorage", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useLocalStorage/useLocalStorage.ts b/liquidity/lib/useLocalStorage/useLocalStorage.ts deleted file mode 100644 index 2d2b891a5..000000000 --- a/liquidity/lib/useLocalStorage/useLocalStorage.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { useState } from 'react'; - -export const set = (key: string, value: any) => { - if (typeof window !== 'undefined') { - window.localStorage.setItem(key, JSON.stringify(value)); - } -}; - -export function get(key: string): T | null { - if (typeof window !== 'undefined') { - const item = window.localStorage.getItem(key); - try { - if (item != null) { - return JSON.parse(item); - } - } catch (e) { - console.error(e); - } - } - return null; -} - -export function useLocalStorage(key: string, initialValue: T) { - const [storedValue, setStoredValue] = useState(() => { - const item = get(key); - return item != null ? item : initialValue; - }); - - const setValue = (value: T) => { - const valueToStore = value instanceof Function ? value(storedValue) : value; - setStoredValue(valueToStore); - set(key, valueToStore); - }; - - return [storedValue, setValue] as const; -} diff --git a/liquidity/lib/useManagePermissions/index.ts b/liquidity/lib/useManagePermissions/index.ts deleted file mode 100644 index 3484ae487..000000000 --- a/liquidity/lib/useManagePermissions/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useManagePermissions'; diff --git a/liquidity/lib/useManagePermissions/package.json b/liquidity/lib/useManagePermissions/package.json deleted file mode 100644 index a17ee837e..000000000 --- a/liquidity/lib/useManagePermissions/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@snx-v3/useManagePermissions", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useMulticall3": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2" - } -} diff --git a/liquidity/lib/useManagePermissions/useManagePermissions.ts b/liquidity/lib/useManagePermissions/useManagePermissions.ts deleted file mode 100644 index 42b2a1e82..000000000 --- a/liquidity/lib/useManagePermissions/useManagePermissions.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { utils } from 'ethers'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useMutation } from '@tanstack/react-query'; -import { useMulticall3 } from '@snx-v3/useMulticall3'; - -type Permissions = Array; -const getPermissionDiff = ( - existing: Permissions, - selected: Permissions -): { - grants: Permissions; - revokes: Permissions; -} => { - let grants: Permissions = [], - revokes: Permissions = []; - existing.concat(selected).forEach((permission) => { - if (!existing.includes(permission)) { - grants = [...grants, permission]; - } - if (!selected.includes(permission)) { - revokes = [...revokes, permission]; - } - }); - return { grants, revokes }; -}; - -export const useManagePermissions = ({ - accountId, - target, - existing = [], - selected = [], -}: { - accountId: string; - target: string; - existing: Permissions; - selected: Permissions; -}) => { - const { data: CoreProxy } = useCoreProxy(); - const { data: multicall } = useMulticall3(); - - return useMutation({ - mutationFn: async () => { - if (!CoreProxy || !multicall) { - return; - } - - const { grants, revokes } = getPermissionDiff(existing, selected); - - try { - const grantCalls = grants.map((permission) => ({ - target: CoreProxy.address, - callData: CoreProxy.interface.encodeFunctionData('grantPermission', [ - accountId, - utils.formatBytes32String(permission), - target, - ]), - allowFailure: false, - requireSuccess: true, - })); - - const revokeCalls = revokes.map((permission) => ({ - target: CoreProxy.address, - callData: CoreProxy.interface.encodeFunctionData('revokePermission', [ - accountId, - utils.formatBytes32String(permission), - target, - ]), - allowFailure: false, - requireSuccess: true, - })); - - const tx = await multicall.aggregate3([...grantCalls, ...revokeCalls]); - await tx.wait(); - } catch (error: any) { - throw error; - } - }, - }); -}; diff --git a/liquidity/lib/useMarketNamesById/index.ts b/liquidity/lib/useMarketNamesById/index.ts deleted file mode 100644 index 8c1d095f5..000000000 --- a/liquidity/lib/useMarketNamesById/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useMarketNamesById'; diff --git a/liquidity/lib/useMarketNamesById/package.json b/liquidity/lib/useMarketNamesById/package.json deleted file mode 100644 index 118d4a107..000000000 --- a/liquidity/lib/useMarketNamesById/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useMarketNamesById", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useMulticall3": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "zod": "^3.22.4" - } -} diff --git a/liquidity/lib/useMarketNamesById/useMarketNamesById.ts b/liquidity/lib/useMarketNamesById/useMarketNamesById.ts deleted file mode 100644 index acbb6f805..000000000 --- a/liquidity/lib/useMarketNamesById/useMarketNamesById.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { ethers } from 'ethers'; -import { useMulticall3 } from '@snx-v3/useMulticall3'; -import { z } from 'zod'; -import { Network, useNetwork } from '@snx-v3/useBlockchain'; - -const MarketNamesSchema = z.array(z.string()); - -const marketAbi = ['function name(uint128 marketId) external view returns (string memory)']; -const marketInterface = new ethers.utils.Interface(marketAbi); - -export const useMarketNamesById = ( - marketIdsAndAddresses?: { marketId: string; address: string }[], - customNetwork?: Network -) => { - const { network } = useNetwork(); - const { data: MultiCall3 } = useMulticall3(customNetwork); - - const targetNetwork = customNetwork || network; - - return useQuery({ - queryKey: [ - `${targetNetwork?.id}-${targetNetwork?.preset}`, - 'MarketNamesById', - { - markets: marketIdsAndAddresses - ? marketIdsAndAddresses.map((market) => market.marketId).sort() - : [], - }, - ], - queryFn: async () => { - if (!marketIdsAndAddresses || !MultiCall3) { - throw Error('Query should not be enable when contract or marketIdsAndAddresses missing'); - } - const calls = marketIdsAndAddresses.map((x) => ({ - target: x.address, - callData: marketInterface.encodeFunctionData('name', [x.marketId]), - })); - const result = await MultiCall3.callStatic.aggregate(calls); - const decoded = result.returnData.map( - (bytes: ethers.utils.BytesLike) => marketInterface.decodeFunctionResult('name', bytes)[0] - ); - return MarketNamesSchema.parse(decoded); - }, - select: (marketNames) => - marketNames.reduce((acc: Record, marketName, index) => { - const marketId = marketIdsAndAddresses?.[index].marketId; - if (!marketId) return acc; - acc[marketId] = marketName; - return acc; - }, {}), - enabled: Boolean(MultiCall3 && marketIdsAndAddresses && marketIdsAndAddresses.length > 0), - }); -}; diff --git a/liquidity/lib/useMigrate/index.ts b/liquidity/lib/useMigrate/index.ts deleted file mode 100644 index 5c2229ea6..000000000 --- a/liquidity/lib/useMigrate/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useMigrate'; diff --git a/liquidity/lib/useMigrate/package.json b/liquidity/lib/useMigrate/package.json deleted file mode 100644 index d80876d8c..000000000 --- a/liquidity/lib/useMigrate/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "@snx-v3/useMigrate", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/parser": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/useLegacyMarket": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useMigrate/useMigrate.ts b/liquidity/lib/useMigrate/useMigrate.ts deleted file mode 100644 index b5636a987..000000000 --- a/liquidity/lib/useMigrate/useMigrate.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { useQuery, useQueryClient } from '@tanstack/react-query'; -import { useDefaultProvider, useNetwork, useSigner } from '@snx-v3/useBlockchain'; -import { useCallback, useMemo, useState } from 'react'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { ZEROWEI } from '@snx-v3/constants'; -import { wei } from '@synthetixio/wei'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; -import { parseTxError } from '@snx-v3/parser'; -import { useLegacyMarket } from '@snx-v3/useLegacyMarket'; - -export function useMigrate() { - const [isLoading, setIsLoading] = useState(false); - const [isSuccess, setIsSuccess] = useState(false); - const { network } = useNetwork(); - const provider = useDefaultProvider(); - const signer = useSigner(); - const { data: legacyMarket } = useLegacyMarket(); - const { gasSpeed } = useGasSpeed(); - const queryClient = useQueryClient(); - - const accountId = useMemo(() => Math.floor(Math.random() * 1000000000000).toString(), []); - - const { data: transaction } = useQuery({ - queryKey: [`${network?.id}-${network?.preset}`, 'MigrateTxn'], - queryFn: async function () { - if (!legacyMarket || !signer) { - return; - } - const signerAddress = await signer!.getAddress(); - const populateTransaction = await legacyMarket.populateTransaction.migrate(accountId, { - from: signerAddress, - }); - try { - const [gasLimit, feeData] = await Promise.all([ - await provider?.estimateGas(populateTransaction), - await provider?.getFeeData(), - ]); - - const gasPrices = await getGasPrice({ provider: signer!.provider }); - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: wei(gasLimit || ZEROWEI).toBN(), - gasPrices, - gasSpeed, - }); - - return { - ...populateTransaction, - gasLimit: gasOptionsForTransaction.gasLimit, - gasPrice: feeData?.gasPrice, - }; - } catch (error) { - const parsedError = parseTxError(error); - const errorResult = legacyMarket.interface.parseError(parsedError as string); - console.error('error:', errorResult); - - return null; - } - }, - enabled: Boolean(signer && !!legacyMarket), - staleTime: 60 * 1000, - }); - - const migrate = useCallback(async () => { - try { - if (!legacyMarket || !transaction) { - return; - } - setIsLoading(true); - setIsSuccess(false); - const gasPrices = await getGasPrice({ provider: signer!.provider }); - const signerAddress = await signer!.getAddress(); - - const populateTransaction = await legacyMarket.populateTransaction.migrate(accountId, { - from: signerAddress, - }); - const gasLimit = await provider?.estimateGas(populateTransaction); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: wei(gasLimit || ZEROWEI).toBN(), - gasPrices, - gasSpeed, - }); - - const txn = await legacyMarket - .connect(signer!) - .migrate(accountId, { ...gasOptionsForTransaction }); - await txn.wait(); - - setIsLoading(false); - setIsSuccess(true); - - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'Accounts'], - }); - } catch (error) { - setIsLoading(false); - throw error; - } - }, [ - accountId, - gasSpeed, - legacyMarket, - network?.id, - network?.preset, - provider, - queryClient, - signer, - transaction, - ]); - - return { - migrate, - transaction, - isLoading, - isSuccess, - accountId, - }; -} diff --git a/liquidity/lib/useMigrateUSD/index.ts b/liquidity/lib/useMigrateUSD/index.ts deleted file mode 100644 index 351e3f563..000000000 --- a/liquidity/lib/useMigrateUSD/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useMigrateUSD'; diff --git a/liquidity/lib/useMigrateUSD/package.json b/liquidity/lib/useMigrateUSD/package.json deleted file mode 100644 index 7f58085f6..000000000 --- a/liquidity/lib/useMigrateUSD/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "@snx-v3/useMigrateUSD", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/parser": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/useLegacyMarket": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useMigrateUSD/useMigrateUSD.ts b/liquidity/lib/useMigrateUSD/useMigrateUSD.ts deleted file mode 100644 index 64a7fae17..000000000 --- a/liquidity/lib/useMigrateUSD/useMigrateUSD.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { useDefaultProvider, useNetwork, useSigner } from '@snx-v3/useBlockchain'; -import { useLegacyMarket } from '@snx-v3/useLegacyMarket'; -import { useCallback, useState } from 'react'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { ZEROWEI } from '@snx-v3/constants'; -import Wei, { wei } from '@synthetixio/wei'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; -import { parseTxError } from '@snx-v3/parser'; -import { useQueryClient } from '@tanstack/react-query'; - -export function useMigrateUSD({ amount }: { amount: Wei }) { - const [isLoading, setIsLoading] = useState(false); - const [isSuccess, setIsSuccess] = useState(false); - const signer = useSigner(); - const { data: legacyMarket } = useLegacyMarket(); - const { gasSpeed } = useGasSpeed(); - const provider = useDefaultProvider(); - const queryClient = useQueryClient(); - const { network } = useNetwork(); - - const migrate = useCallback(async () => { - try { - if (!legacyMarket || !signer) { - return; - } - setIsLoading(true); - setIsSuccess(false); - const gasPrices = await getGasPrice({ provider: signer!.provider }); - - const transaction = await legacyMarket.populateTransaction.convertUSD(amount.toBN()); - const gasLimit = await provider?.estimateGas(transaction); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: wei(gasLimit || ZEROWEI).toBN(), - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...transaction, ...gasOptionsForTransaction }); - - await txn.wait(); - - setIsLoading(false); - setIsSuccess(true); - - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'TokenBalance'], - }); - } catch (error) { - const parsedError = parseTxError(error); - const errorResult = legacyMarket?.interface.parseError(parsedError as string); - console.error('error:', errorResult); - setIsLoading(false); - throw error; - } - }, [amount, gasSpeed, legacyMarket, network?.id, network?.preset, provider, queryClient, signer]); - - return { - migrate, - isLoading, - isSuccess, - }; -} diff --git a/liquidity/lib/useMulticall3/index.ts b/liquidity/lib/useMulticall3/index.ts deleted file mode 100644 index 7690b671a..000000000 --- a/liquidity/lib/useMulticall3/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useMulticall3'; diff --git a/liquidity/lib/useMulticall3/package.json b/liquidity/lib/useMulticall3/package.json deleted file mode 100644 index fd865412c..000000000 --- a/liquidity/lib/useMulticall3/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useMulticall3", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@ethersproject/contracts": "^5.7.0", - "@snx-v3/contracts": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useMulticall3/useMulticall3.ts b/liquidity/lib/useMulticall3/useMulticall3.ts deleted file mode 100644 index af9031027..000000000 --- a/liquidity/lib/useMulticall3/useMulticall3.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { Contract } from '@ethersproject/contracts'; -import { useQuery } from '@tanstack/react-query'; -import { - Network, - useNetwork, - useProvider, - useProviderForChain, - useSigner, - useWallet, -} from '@snx-v3/useBlockchain'; -import { importMulticall3 } from '@snx-v3/contracts'; - -export function useMulticall3(customNetwork?: Network) { - const { network } = useNetwork(); - const providerForChain = useProviderForChain(customNetwork); - const provider = useProvider(); - const signer = useSigner(); - const signerOrProvider = signer || provider || providerForChain; - const withSigner = Boolean(signer); - const { activeWallet } = useWallet(); - - const targetNetwork = customNetwork || network; - - return useQuery({ - queryKey: [ - `${targetNetwork?.id}-${targetNetwork?.preset}`, - 'Multicall3', - { withSigner }, - activeWallet?.address, - ], - queryFn: async function () { - if (providerForChain && customNetwork) { - const { address, abi } = await importMulticall3(customNetwork.id, customNetwork.preset); - return new Contract(address, abi, providerForChain); - } - - if (!network || !signerOrProvider) throw new Error('Network or signer not available'); - const { address, abi } = await importMulticall3(network.id, network.preset); - return new Contract(address, abi, signerOrProvider); - }, - enabled: Boolean(signerOrProvider), - staleTime: Infinity, - }); -} diff --git a/liquidity/lib/useOracleManagerProxy/index.ts b/liquidity/lib/useOracleManagerProxy/index.ts deleted file mode 100644 index a5fc9d5ff..000000000 --- a/liquidity/lib/useOracleManagerProxy/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useOracleManagerProxy'; diff --git a/liquidity/lib/useOracleManagerProxy/package.json b/liquidity/lib/useOracleManagerProxy/package.json deleted file mode 100644 index 9992592bd..000000000 --- a/liquidity/lib/useOracleManagerProxy/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useOracleManagerProxy", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@ethersproject/contracts": "^5.7.0", - "@snx-v3/contracts": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useOracleManagerProxy/useOracleManagerProxy.ts b/liquidity/lib/useOracleManagerProxy/useOracleManagerProxy.ts deleted file mode 100644 index 3980f77fa..000000000 --- a/liquidity/lib/useOracleManagerProxy/useOracleManagerProxy.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { Contract } from '@ethersproject/contracts'; -import { useQuery } from '@tanstack/react-query'; -import { - Network, - useNetwork, - useProvider, - useProviderForChain, - useSigner, - useWallet, -} from '@snx-v3/useBlockchain'; -import { importOracleManagerProxy } from '@snx-v3/contracts'; - -export function useOracleManagerProxy(customNetwork?: Network) { - const { network } = useNetwork(); - const providerForChain = useProviderForChain(customNetwork); - const provider = useProvider(); - const signer = useSigner(); - const signerOrProvider = providerForChain || signer || provider; - const withSigner = Boolean(signer); - const { activeWallet } = useWallet(); - - const targetNetwork = customNetwork || network; - - return useQuery({ - queryKey: [ - `${targetNetwork?.id}-${targetNetwork?.preset}`, - 'OracleManagerProxy', - { withSigner }, - activeWallet?.address, - ], - queryFn: async function () { - if (providerForChain && customNetwork) { - const { address, abi } = await importOracleManagerProxy( - customNetwork.id, - customNetwork.preset - ); - return new Contract(address, abi, providerForChain); - } - if (!network || !signerOrProvider) throw new Error('Network or signer not available'); - const { address, abi } = await importOracleManagerProxy(network?.id, network?.preset); - return new Contract(address, abi, signerOrProvider); - }, - enabled: Boolean(signerOrProvider), - staleTime: Infinity, - }); -} diff --git a/liquidity/lib/useOraclePrice/index.ts b/liquidity/lib/useOraclePrice/index.ts deleted file mode 100644 index ff19f1da4..000000000 --- a/liquidity/lib/useOraclePrice/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useOraclePrice'; diff --git a/liquidity/lib/useOraclePrice/package.json b/liquidity/lib/useOraclePrice/package.json deleted file mode 100644 index e8e4a4c2a..000000000 --- a/liquidity/lib/useOraclePrice/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "@snx-v3/useOraclePrice", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/contracts": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useOraclePrice/useOraclePrice.ts b/liquidity/lib/useOraclePrice/useOraclePrice.ts deleted file mode 100644 index ccab55680..000000000 --- a/liquidity/lib/useOraclePrice/useOraclePrice.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { Network, useNetwork, useProviderForChain } from '@snx-v3/useBlockchain'; -import { erc7412Call, getDefaultFromAddress } from '@snx-v3/withERC7412'; -import { importOracleManagerProxy } from '@snx-v3/contracts'; -import { Contract } from 'ethers'; -import { Wei } from '@synthetixio/wei'; - -export function useOraclePrice(nodeId?: string, customNetwork?: Network) { - const { network } = useNetwork(); - const targetNetwork = customNetwork || network; - const provider = useProviderForChain(targetNetwork); - - return useQuery({ - refetchInterval: 15000, - retry: false, - staleTime: 99999, - enabled: !!targetNetwork && !!provider && !!nodeId, - queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, 'oracle-price'], - queryFn: async () => { - if (targetNetwork && provider) { - try { - const { address, abi } = await importOracleManagerProxy( - targetNetwork.id, - targetNetwork.preset - ); - - const OracleManagerProxy = new Contract(address, abi, provider); - - const price = [await OracleManagerProxy.populateTransaction.process(nodeId)]; - - price[0].from = getDefaultFromAddress(targetNetwork?.name || ''); - - return await erc7412Call( - targetNetwork, - provider, - price, - (txs) => { - const result = OracleManagerProxy.interface.decodeFunctionResult( - 'process', - Array.isArray(txs) ? txs[0] : txs - ); - if (result?.node) { - return { - price: new Wei(result.node.price), - timestamp: new Date(Number(result.node.timestamp.mul(1000).toString())), - }; - } else { - return { - price: new Wei(result.price), - timestamp: new Date(Number(result.timestamp.mul(1000).toString())), - }; - } - }, - 'oraclePriceCall' - ); - } catch (error) { - console.error(error); - throw error; - } - } else { - throw new Error('BaseProvider and BaseNetwork undefined'); - } - }, - }); -} diff --git a/liquidity/lib/useParams/index.ts b/liquidity/lib/useParams/index.ts deleted file mode 100644 index 15663ba75..000000000 --- a/liquidity/lib/useParams/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useParams'; diff --git a/liquidity/lib/useParams/package.json b/liquidity/lib/useParams/package.json deleted file mode 100644 index 8906727e7..000000000 --- a/liquidity/lib/useParams/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@snx-v3/useParams", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "react": "^18.2.0", - "react-router-dom": "^6.18.0" - } -} diff --git a/liquidity/lib/useParams/useParams.ts b/liquidity/lib/useParams/useParams.ts deleted file mode 100644 index 7ea5a898e..000000000 --- a/liquidity/lib/useParams/useParams.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { useParams as useParamsRouter, useSearchParams } from 'react-router-dom'; -import { useMemo } from 'react'; - -export function searchParamsToObject(searchParams: URLSearchParams) { - return Object.fromEntries(Array.from(searchParams)); -} - -export function sortObject(params: Record): Record { - return Object.fromEntries(Object.entries(params).sort(([a], [b]) => a.localeCompare(b))); -} - -export function cleanObject(params: Record): Record { - const cleaned = Object.entries(params).filter(([, value]) => value !== undefined) as [ - [string, string], - ]; - return Object.fromEntries(cleaned); -} - -export const useParams = (): Record => { - const pathParams = useParamsRouter(); - const [queryParams] = useSearchParams(); - - return useMemo( - () => sortObject({ ...cleanObject(pathParams), ...searchParamsToObject(queryParams) }), - [pathParams, queryParams] - ); -}; diff --git a/liquidity/lib/usePoolConfiguration/index.ts b/liquidity/lib/usePoolConfiguration/index.ts deleted file mode 100644 index 673f3a9d2..000000000 --- a/liquidity/lib/usePoolConfiguration/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './usePoolConfiguration'; diff --git a/liquidity/lib/usePoolConfiguration/package.json b/liquidity/lib/usePoolConfiguration/package.json deleted file mode 100644 index 9cbaddaa7..000000000 --- a/liquidity/lib/usePoolConfiguration/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "@snx-v3/usePoolConfiguration", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/fetchPythPrices": "workspace:*", - "@snx-v3/useAllCollateralPriceIds": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@snx-v3/zod": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0", - "zod": "^3.22.4" - } -} diff --git a/liquidity/lib/usePoolConfiguration/usePoolConfiguration.ts b/liquidity/lib/usePoolConfiguration/usePoolConfiguration.ts deleted file mode 100644 index bb18d195a..000000000 --- a/liquidity/lib/usePoolConfiguration/usePoolConfiguration.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useDefaultProvider, useNetwork } from '@snx-v3/useBlockchain'; -import { z } from 'zod'; -import { SmallIntSchema, WeiSchema } from '@snx-v3/zod'; -import { ethers } from 'ethers'; -import { erc7412Call } from '@snx-v3/withERC7412'; -import { fetchPriceUpdates, priceUpdatesToPopulatedTx } from '@snx-v3/fetchPythPrices'; -import { useAllCollateralPriceIds } from '@snx-v3/useAllCollateralPriceIds'; -import { useAllCollateralPriceUpdates } from '@snx-v3/useCollateralPriceUpdates'; - -export const MarketConfigurationSchema = z.object({ - id: SmallIntSchema, - weight: WeiSchema, - maxDebtShareValue: WeiSchema, - isLocked: z.boolean(), -}); - -export const PoolConfigurationSchema = z.object({ - id: z.number(), - markets: MarketConfigurationSchema.array(), - isAnyMarketLocked: z.boolean(), -}); - -const isLockedSchema = z.boolean(); - -export const usePoolConfiguration = (poolId?: string) => { - const { network } = useNetwork(); - const { data: CoreProxy } = useCoreProxy(); - const { data: collateralPriceUpdates } = useAllCollateralPriceIds(); - const provider = useDefaultProvider(); - const { data: priceUpdateTx } = useAllCollateralPriceUpdates(); - - return useQuery({ - enabled: Boolean(CoreProxy && poolId && collateralPriceUpdates), - queryKey: [`${network?.id}-${network?.preset}`, 'PoolConfiguration', { poolId }], - queryFn: async () => { - if (!CoreProxy || !poolId || !collateralPriceUpdates || !network || !provider) { - throw Error('usePoolConfiguration should not be enabled'); - } - const marketsData: { - marketId: ethers.BigNumber; - maxDebtShareValueD18: ethers.BigNumber; - weightD18: ethers.BigNumber; - }[] = await CoreProxy.getPoolConfiguration(ethers.BigNumber.from(poolId)); - const markets = marketsData.map(({ marketId, maxDebtShareValueD18, weightD18 }) => ({ - id: marketId, - weight: maxDebtShareValueD18, - maxDebtShareValue: weightD18, - })); - - const collateralPriceCalls = await fetchPriceUpdates( - collateralPriceUpdates, - network.isTestnet - ).then((signedData) => priceUpdatesToPopulatedTx('0x', collateralPriceUpdates, signedData)); - - const calls = await Promise.all( - markets.map((m) => CoreProxy.populateTransaction.isMarketCapacityLocked(m.id)) - ); - - const allCalls = collateralPriceCalls.concat(calls); - if (priceUpdateTx) { - allCalls.unshift(priceUpdateTx as any); - } - - const decoded = await erc7412Call( - network, - provider, - allCalls, - (encoded) => { - const result = Array.isArray(encoded) ? encoded : [encoded]; - return result.map((x) => - isLockedSchema.parse( - CoreProxy.interface.decodeFunctionResult('isMarketCapacityLocked', x)[0] - ) - ); - }, - 'isMarketCapacityLocked' - ); - - return PoolConfigurationSchema.parse({ - id: parseInt(poolId), - markets: markets.map((market, i) => ({ - ...market, - isLocked: decoded[i], - })), - isAnyMarketLocked: decoded.some(Boolean), - }); - }, - }); -}; diff --git a/liquidity/lib/usePoolData/index.ts b/liquidity/lib/usePoolData/index.ts deleted file mode 100644 index 580a749c6..000000000 --- a/liquidity/lib/usePoolData/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './usePoolData'; diff --git a/liquidity/lib/usePoolData/package.json b/liquidity/lib/usePoolData/package.json deleted file mode 100644 index fce1dac10..000000000 --- a/liquidity/lib/usePoolData/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "@snx-v3/usePoolData", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0", - "zod": "^3.22.4" - } -} diff --git a/liquidity/lib/usePoolData/usePoolData.tsx b/liquidity/lib/usePoolData/usePoolData.tsx deleted file mode 100644 index cd041a3ab..000000000 --- a/liquidity/lib/usePoolData/usePoolData.tsx +++ /dev/null @@ -1,161 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { getSubgraphUrl } from '@snx-v3/constants'; -import { z } from 'zod'; -import Wei, { wei } from '@synthetixio/wei'; -import { useNetwork } from '@snx-v3/useBlockchain'; - -const GraphBigIntSchema = z.string().transform((src) => wei(src, 18, true)); -const GraphBigDecimalSchema = z.string().transform((src) => wei(src, 18, true)); - -const calculateMarketPnl = (netIssuance: Wei, reportedDebt: Wei) => - reportedDebt.add(netIssuance).mul(-1); - -export const MarketSnapshotByWeekSchema = z - .object({ - id: z.string(), - usd_deposited: GraphBigDecimalSchema, - usd_withdrawn: GraphBigDecimalSchema, - net_issuance: GraphBigDecimalSchema, // withdrawn - deposited - reported_debt: GraphBigDecimalSchema, - updated_at: z.string(), - updates_in_period: z.string(), - }) - .transform((market) => ({ - ...market, - pnl: calculateMarketPnl(market.net_issuance, market.reported_debt), - })); - -const MarketSchema = z - .object({ - id: z.string(), - address: z.string(), - usd_deposited: GraphBigDecimalSchema, - usd_withdrawn: GraphBigDecimalSchema, - net_issuance: GraphBigDecimalSchema, // withdrawn - deposited - reported_debt: GraphBigDecimalSchema, - updated_at: z.string(), - market_snapshots_by_week: z.array(MarketSnapshotByWeekSchema), - }) - .transform((market) => ({ - ...market, - pnl: calculateMarketPnl(market.net_issuance, market.reported_debt), - })); - -const MarketConfigurationSchema = z.object({ - id: z.string(), //PoolId-MarketId - market: MarketSchema, - weight: GraphBigIntSchema, - max_debt_share_value: GraphBigDecimalSchema, -}); - -const RewardDistributorSchema = z.object({ - id: z.string(), - total_distributed: z.string(), - rewards_distributions: z - .array( - z.object({ - amount: z.string(), - duration: z.string(), - created_at: z.string(), - }) - ) - .default([]), -}); - -export const PoolSchema = z.object({ - id: z.string(), - name: z.union([z.string(), z.null()]).transform((name) => (name ? name : 'Unnamed Pool')), - total_weight: z.union([z.null(), GraphBigIntSchema]), - configurations: z.array(MarketConfigurationSchema), - registered_distributors: z.array(RewardDistributorSchema).default([]), -}); - -export type PoolType = z.infer; - -export const PoolDataResultSchema = z.object({ - data: z.object({ - pool: z.union([PoolSchema, z.null()]), - }), -}); - -const gql = (data: TemplateStringsArray) => data[0]; - -const PoolsDataDocument = gql` - query pool($id: String) { - pool(id: $id) { - id - name - registered_distributors(where: { isActive: true }) { - id - total_distributed - rewards_distributions(orderBy: created_at, orderDirection: desc) { - amount - duration - created_at - } - } - total_weight - configurations { - id - weight - max_debt_share_value - market { - id - address - usd_deposited - usd_withdrawn - net_issuance - reported_debt - updated_at - market_snapshots_by_week(first: 2, orderBy: updated_at, orderDirection: desc) { - id - usd_deposited - usd_withdrawn - net_issuance - reported_debt - updated_at - updates_in_period - } - } - } - } - } -`; - -const getPoolData = async (chainName: string, id: string) => { - const url = getSubgraphUrl(chainName); - - const res = await fetch(url, { - method: 'POST', - body: JSON.stringify({ query: PoolsDataDocument, variables: { id } }), - }); - - const json = await res.json(); - - if (json.errors) { - const { message } = json.errors[0]; - throw new Error(message); - } - - return PoolDataResultSchema.parse(json); -}; - -export const usePoolData = (poolId?: string, networkName?: string) => { - const { network } = useNetwork(); - - return useQuery({ - queryKey: [`${network?.id}-${network?.preset}`, 'PoolData', { pool: poolId }], - queryFn: async () => { - const name = networkName || network?.name; - if (!poolId || !name) throw Error('No poolId or networkId'); - const poolData = await getPoolData(name, poolId); - - if (!poolData.data.pool) { - throw Error(`Pool ${poolId} not found`); - } - - return poolData.data.pool; - }, - enabled: Boolean(poolId && parseInt(poolId) > 0), - }); -}; diff --git a/liquidity/lib/usePools/index.ts b/liquidity/lib/usePools/index.ts deleted file mode 100644 index 74d4752e4..000000000 --- a/liquidity/lib/usePools/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './usePools'; diff --git a/liquidity/lib/usePools/package.json b/liquidity/lib/usePools/package.json deleted file mode 100644 index b6ace1408..000000000 --- a/liquidity/lib/usePools/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "@snx-v3/usePools", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/contracts": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/zod": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0", - "zod": "^3.22.4" - } -} diff --git a/liquidity/lib/usePools/usePools.ts b/liquidity/lib/usePools/usePools.ts deleted file mode 100644 index a90bc1620..000000000 --- a/liquidity/lib/usePools/usePools.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { NETWORKS, Network, useNetwork } from '@snx-v3/useBlockchain'; -import { ZodBigNumber } from '@snx-v3/zod'; -import { z } from 'zod'; -import { ethers } from 'ethers'; -import { importCoreProxy } from '@snx-v3/contracts'; - -export const PoolIdSchema = ZodBigNumber.transform((x) => x.toString()); - -export const PoolSchema = z.object({ - id: PoolIdSchema, - name: z.string().default('Unnamed Pool'), - isPreferred: z.boolean(), -}); - -export type PoolType = z.infer; - -export const PoolsSchema = z.array(PoolSchema); -export type PoolsType = z.infer; - -export function usePools(customNetwork?: Network) { - const { network } = useNetwork(); - const targetNetwork = customNetwork || network; - - const { data: CoreProxy } = useCoreProxy({ customNetwork: targetNetwork }); - - return useQuery({ - enabled: Boolean(targetNetwork), - queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, CoreProxy?.address, 'Pools'], - queryFn: async () => { - if (!CoreProxy) { - throw 'usePools is missing required data'; - } - - const [prefferedPoolId, approvedPoolIds] = await Promise.all([ - CoreProxy.callStatic.getPreferredPool(), - CoreProxy.callStatic.getApprovedPools(), - ]); - - const incompletePools = [ - { - id: prefferedPoolId, - isPreferred: true, - }, - ].concat( - approvedPoolIds.map((id: ethers.BigNumber) => ({ - id: id, - isPreferred: false, - })) - ); - - const poolNames = await Promise.all( - incompletePools.map(async ({ id }) => await CoreProxy.getPoolName(id)) - ); - - const poolsRaw = incompletePools.map(({ id, isPreferred }, i) => ({ - id, - isPreferred, - name: poolNames[i], - })); - - return PoolsSchema.parse(poolsRaw); - }, - }); -} - -export function usePool(poolId?: string, customNetwork?: Network) { - const { isFetching, error, data } = usePools(customNetwork); - - return { - isLoading: isFetching, - error, - data: data?.find((item) => item.id === poolId), - }; -} - -export function usePreferredPool(customNetwork?: Network) { - const { isLoading, error, data } = usePools(customNetwork); - - return { - isLoading, - error, - data: data?.find((item) => item.isPreferred), - }; -} - -const supportedNetworks = [1, 8453, 42161]; -const supportedTestNetworks = [1, 11155111, 8453, 84532, 421614, 42161]; - -export function useGetAllPools(withTestnets: boolean) { - const networks = NETWORKS.filter((n) => - withTestnets ? supportedTestNetworks.includes(n.id) : supportedNetworks.includes(n.id) - ).map((n) => ({ - id: n.id, - token: n.token, - label: n.label, - rpcUrl: n.rpcUrl(), - preset: n.preset, - })); - - return useQuery({ - queryKey: ['AllPools'], - queryFn: async () => { - const allCoreProxies = (await Promise.all( - networks.map((network) => importCoreProxy(network.id, network.preset)) - )) as any[]; - - const allCoreProxiesConnected = allCoreProxies.map( - (proxies, index) => - new ethers.Contract( - proxies.address, - proxies.abi, - new ethers.providers.JsonRpcProvider(networks[index].rpcUrl) - ) - ); - - const prefferedPools = await Promise.all( - allCoreProxiesConnected.map((contract) => { - return contract.callStatic.getPreferredPool(); - }) - ); - // TODO @dev reimplement when used - // const approvedPoolIds: ethers.BigNumber[][] = await Promise.all( - // allCoreProxiesConnected.map((contract) => { - // return contract.callStatic.getApprovedPools(); - // }) - // ); - - const incompletePools = prefferedPools.map((prefferedPool, index) => ({ - id: prefferedPool, - isPreferred: true, - network: networks[index].label, - })); - - const poolNames = await Promise.all( - incompletePools.map( - async ({ id }, index) => await allCoreProxiesConnected[index].getPoolName(id) - ) - ); - - const poolsRaw = incompletePools.map(({ id, isPreferred, network }, i) => ({ - id, - isPreferred, - name: poolNames[i] as string, - network, - })); - - return poolsRaw; - }, - }); -} diff --git a/liquidity/lib/usePoolsList/index.ts b/liquidity/lib/usePoolsList/index.ts deleted file mode 100644 index a0239a6cc..000000000 --- a/liquidity/lib/usePoolsList/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './usePoolsList'; diff --git a/liquidity/lib/usePoolsList/package.json b/liquidity/lib/usePoolsList/package.json deleted file mode 100644 index a9e65fb0d..000000000 --- a/liquidity/lib/usePoolsList/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/usePoolsList", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/useApr": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "humanize-plus": "^1.8.2" - } -} diff --git a/liquidity/lib/usePoolsList/usePoolsList.ts b/liquidity/lib/usePoolsList/usePoolsList.ts deleted file mode 100644 index 6b7973e42..000000000 --- a/liquidity/lib/usePoolsList/usePoolsList.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { getSubgraphUrl } from '@snx-v3/constants'; -import { ARBITRUM, BASE_ANDROMEDA, MAINNET, NETWORKS } from '@snx-v3/useBlockchain'; -import { compactInteger } from 'humanize-plus'; -import { fetchApr } from '@snx-v3/useApr'; -import { useQuery } from '@tanstack/react-query'; - -export function usePoolsList() { - return useQuery({ - queryKey: ['poolsList'], - queryFn: async () => { - try { - const [pools, aprs, toros] = await Promise.all([ - fetchPoolsList(), - fetchAprs(), - fetchTorosPool(), - ]); - - const synthetixPools = pools.map((p, i) => ({ - ...p, - apr: aprs[i], - })); - - return { synthetixPools, toros }; - } catch (error) { - throw error; - } - }, - staleTime: 60000 * 10, - }); -} - -export function usePool(networkId: number, poolId: string) { - const { data, isLoading } = usePoolsList(); - - // TODO: In the future if we have multiple pools per network filter by poolId also - return { - data: data?.synthetixPools.find( - (p) => p.network.id === networkId && p.poolInfo[0].pool.id === poolId - ), - isLoading, - }; -} - -const supportedNetworks = [MAINNET.id, BASE_ANDROMEDA.id, ARBITRUM.id]; - -async function fetchTorosPool() { - return fetch('https://api-v2.dhedge.org/graphql', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - query: ` - query GetFund($address: String!) { - fund(address: $address) { - totalValue - apy { - monthly - weekly - } - } - }`, - variables: { address: '0xc1e02884af4a283ca25ab63c45360d220d69da52' }, - }), - }) - .then((response) => response.json()) - .then(({ data }) => { - return { - tvl: compactInteger(data.fund.totalValue / 1e18, 1), - apy: data.fund.apy.monthly, - }; - }); -} - -export const networksOffline = NETWORKS.filter( - (n) => supportedNetworks.includes(n.id) && n.isSupported -).map((n) => n); - -async function fetchAprs() { - return Promise.all(networksOffline.map((network) => fetchApr(network.id))); -} - -async function fetchPoolsList() { - const urls = networksOffline.map((network) => getSubgraphUrl(network.name)); - - // Fetch all the pools from the subgraphs - const responses = await Promise.all( - urls.map((url) => - fetch(url, { method: 'POST', body: JSON.stringify({ query: PoolsListData }) }).then((res) => - res.json() - ) - ) - ); - - return responses.map((response, i) => ({ - network: networksOffline[i], - poolInfo: response.data.vaults as PoolInfo[], - })); -} - -const gql = (data: TemplateStringsArray) => data[0]; - -const PoolsListData = gql` - query PoolsListData { - vaults(where: { pool: "1" }) { - collateral_type { - id - oracle_node_id - total_amount_deposited - } - pool { - name - id - } - } - } -`; - -interface PoolInfo { - collateral_type: { - id: string; - oracle_node_id: string; - total_amount_deposited: string; - }; - pool: { - name: string; - id: string; - }; -} diff --git a/liquidity/lib/useRates/index.ts b/liquidity/lib/useRates/index.ts deleted file mode 100644 index 3ac0c3b4d..000000000 --- a/liquidity/lib/useRates/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useRates'; diff --git a/liquidity/lib/useRates/package.json b/liquidity/lib/useRates/package.json deleted file mode 100644 index 37605a4e5..000000000 --- a/liquidity/lib/useRates/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "@snx-v3/useRates", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@synthetixio/contracts": "^1.2.3", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useRates/useRates.ts b/liquidity/lib/useRates/useRates.ts deleted file mode 100644 index 423310468..000000000 --- a/liquidity/lib/useRates/useRates.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { MAINNET, useProviderForChain } from '@snx-v3/useBlockchain'; -import { Contract } from 'ethers'; -import { formatBytes32String } from 'ethers/lib/utils'; -import { wei } from '@synthetixio/wei'; - -export function useRates() { - const mainnetProvider = useProviderForChain(MAINNET); - - return useQuery({ - queryKey: ['rates-mainnet'], - queryFn: async function () { - const { address, abi } = await import( - '@synthetixio/contracts/build/mainnet/deployment/ExchangeRates' - ); - const ExchangeRates = new Contract(address, abi, mainnetProvider); - - const result = await ExchangeRates.ratesForCurrencies([ - formatBytes32String('SNX'), - formatBytes32String('ETH'), - ]); - return { - snx: wei(result[0] || 0), - eth: wei(result[1] || 0), - }; - }, - staleTime: Infinity, - refetchInterval: 60000, - }); -} diff --git a/liquidity/lib/useRepay/index.ts b/liquidity/lib/useRepay/index.ts deleted file mode 100644 index e73d091a7..000000000 --- a/liquidity/lib/useRepay/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useRepay'; diff --git a/liquidity/lib/useRepay/package.json b/liquidity/lib/useRepay/package.json deleted file mode 100644 index 4acda5ffe..000000000 --- a/liquidity/lib/useRepay/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "@snx-v3/useRepay", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/fetchPythPrices": "workspace:*", - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useAllCollateralPriceIds": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/useSystemToken": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useRepay/useRepay.tsx b/liquidity/lib/useRepay/useRepay.tsx deleted file mode 100644 index fb33a550e..000000000 --- a/liquidity/lib/useRepay/useRepay.tsx +++ /dev/null @@ -1,125 +0,0 @@ -import { useReducer } from 'react'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { useMutation } from '@tanstack/react-query'; -import { useNetwork, useProvider, useSigner } from '@snx-v3/useBlockchain'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import Wei from '@synthetixio/wei'; -import { BigNumber } from 'ethers'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { notNil } from '@snx-v3/tsHelpers'; -import { withERC7412 } from '@snx-v3/withERC7412'; -import { useAllCollateralPriceIds } from '@snx-v3/useAllCollateralPriceIds'; -import { fetchPriceUpdates, priceUpdatesToPopulatedTx } from '@snx-v3/fetchPythPrices'; -import { ZEROWEI } from '@snx-v3/constants'; - -export const useRepay = ({ - accountId, - poolId, - collateralTypeAddress, - debtChange, - availableUSDCollateral, -}: { - accountId?: string; - poolId?: string; - collateralTypeAddress?: string; - balance?: Wei; - availableUSDCollateral?: Wei; - debtChange: Wei; -}) => { - const [txnState, dispatch] = useReducer(reducer, initialState); - const { data: CoreProxy } = useCoreProxy(); - const { data: systemToken } = useSystemToken(); - const { data: collateralPriceIds } = useAllCollateralPriceIds(); - - const signer = useSigner(); - const { network } = useNetwork(); - const { gasSpeed } = useGasSpeed(); - const provider = useProvider(); - - const mutation = useMutation({ - mutationFn: async () => { - if (!signer || !network || !provider) throw new Error('No signer or network'); - if ( - !( - CoreProxy && - poolId && - accountId && - collateralTypeAddress && - systemToken && - collateralPriceIds - ) - ) { - return; - } - if (debtChange.eq(0)) { - return; - } - - const debtChangeAbs = debtChange.abs(); - const amountToDeposit = debtChangeAbs.sub(availableUSDCollateral || ZEROWEI); - - try { - dispatch({ type: 'prompting' }); - - // Only deposit if user doesn't have enough sUSD collateral - const deposit = amountToDeposit.lte(0) - ? undefined - : CoreProxy.populateTransaction.deposit( - BigNumber.from(accountId), - systemToken.address, - amountToDeposit.toBN() // only deposit what's needed - ); - - const burn = CoreProxy.populateTransaction.burnUsd( - BigNumber.from(accountId), - BigNumber.from(poolId), - collateralTypeAddress, - debtChangeAbs.toBN() - ); - - const callsPromise = Promise.all([deposit, burn].filter(notNil)); - const walletAddress = await signer.getAddress(); - const collateralPriceCallsPromise = fetchPriceUpdates( - collateralPriceIds, - network.isTestnet - ).then((signedData) => - priceUpdatesToPopulatedTx(walletAddress, collateralPriceIds, signedData) - ); - - const [calls, gasPrices, collateralPriceCalls] = await Promise.all([ - callsPromise, - getGasPrice({ provider }), - collateralPriceCallsPromise, - ]); - const allCalls = collateralPriceCalls.concat(calls); - - const erc7412Tx = await withERC7412(network, allCalls, 'useRepay', walletAddress); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: erc7412Tx.gasLimit, - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...erc7412Tx, ...gasOptionsForTransaction }); - dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - - await txn.wait(); - dispatch({ type: 'success' }); - } catch (error: any) { - dispatch({ type: 'error', payload: { error } }); - throw error; - } - }, - }); - return { - mutation, - txnState, - settle: () => dispatch({ type: 'settled' }), - isLoading: mutation.isPending, - exec: mutation.mutateAsync, - }; -}; diff --git a/liquidity/lib/useRepayBaseAndromeda/index.ts b/liquidity/lib/useRepayBaseAndromeda/index.ts deleted file mode 100644 index 2b3a4d9e7..000000000 --- a/liquidity/lib/useRepayBaseAndromeda/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useRepayBaseAndromeda'; diff --git a/liquidity/lib/useRepayBaseAndromeda/package.json b/liquidity/lib/useRepayBaseAndromeda/package.json deleted file mode 100644 index 784c13ed3..000000000 --- a/liquidity/lib/useRepayBaseAndromeda/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "@snx-v3/useRepayBaseAndromeda", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/format": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useApprove": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/useGetUSDTokens": "workspace:*", - "@snx-v3/useSpotMarketProxy": "workspace:*", - "@snx-v3/useSystemToken": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useRepayBaseAndromeda/useRepayBaseAndromeda.tsx b/liquidity/lib/useRepayBaseAndromeda/useRepayBaseAndromeda.tsx deleted file mode 100644 index 2468eb526..000000000 --- a/liquidity/lib/useRepayBaseAndromeda/useRepayBaseAndromeda.tsx +++ /dev/null @@ -1,160 +0,0 @@ -import { useReducer } from 'react'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { useMutation } from '@tanstack/react-query'; -import { useNetwork, useProvider, useSigner } from '@snx-v3/useBlockchain'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import Wei from '@synthetixio/wei'; -import { BigNumber, ethers } from 'ethers'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { notNil } from '@snx-v3/tsHelpers'; -import { withERC7412 } from '@snx-v3/withERC7412'; -import { useSpotMarketProxy } from '@snx-v3/useSpotMarketProxy'; -import { getSpotMarketId } from '@snx-v3/isBaseAndromeda'; -import { parseUnits } from '@snx-v3/format'; -import { approveAbi } from '@snx-v3/useApprove'; -import { useCollateralPriceUpdates } from '@snx-v3/useCollateralPriceUpdates'; -import { useGetUSDTokens } from '@snx-v3/useGetUSDTokens'; - -export const useRepayBaseAndromeda = ({ - accountId, - poolId, - collateralTypeAddress, - debtChange, - availableUSDCollateral, - collateralSymbol, -}: { - accountId?: string; - poolId?: string; - collateralTypeAddress?: string; - availableUSDCollateral?: Wei; - debtChange: Wei; - collateralSymbol?: string; -}) => { - const [txnState, dispatch] = useReducer(reducer, initialState); - const { data: CoreProxy } = useCoreProxy(); - const { data: systemToken } = useSystemToken(); - const { data: SpotMarketProxy } = useSpotMarketProxy(); - const { data: priceUpdateTx } = useCollateralPriceUpdates(); - const { data: usdTokens } = useGetUSDTokens(); - - const signer = useSigner(); - const { network } = useNetwork(); - const { gasSpeed } = useGasSpeed(); - const provider = useProvider(); - - const mutation = useMutation({ - mutationFn: async () => { - if (!signer || !network || !provider) throw new Error('No signer or network'); - - if ( - !( - CoreProxy && - poolId && - accountId && - collateralTypeAddress && - systemToken && - SpotMarketProxy && - usdTokens?.sUSD - ) - ) { - return; - } - - if (!availableUSDCollateral) return; - if (debtChange.eq(0)) return; - const debtChangeAbs = debtChange.abs(); - const amountToDeposit = debtChangeAbs.sub(availableUSDCollateral); - const collateralAmount = amountToDeposit.gt(0) - ? parseUnits(amountToDeposit.toString(), 6) - : BigNumber.from(0); - - try { - dispatch({ type: 'prompting' }); - - const spotMarketId = getSpotMarketId(collateralSymbol); - - // USDC or stataUSDC to sUSDC or sStataUSDC - const wrap = collateralAmount.gt(0) - ? SpotMarketProxy.populateTransaction.wrap(spotMarketId, collateralAmount, 0) - : undefined; - - const Synth_Contract = new ethers.Contract(collateralTypeAddress, approveAbi, signer); - const synth_approval = amountToDeposit.gt(0) - ? Synth_Contract.populateTransaction.approve( - SpotMarketProxy.address, - amountToDeposit.toBN() - ) - : undefined; - - // sUSDC or sStataUSDC => snxUSD - const sell_synth = amountToDeposit.gt(0) - ? SpotMarketProxy.populateTransaction.sell( - spotMarketId, - amountToDeposit.toBN(), - 0, - ethers.constants.AddressZero - ) - : undefined; - - // approve sUSD to Core - const sUSD_Contract = new ethers.Contract(systemToken.address, approveAbi, signer); - const sUSD_Approval = amountToDeposit.gt(0) - ? sUSD_Contract.populateTransaction.approve(CoreProxy.address, amountToDeposit.toBN()) - : undefined; - - // Only deposit if user doesn't have enough sUSD collateral - const deposit = amountToDeposit.lte(0) - ? undefined - : CoreProxy.populateTransaction.deposit( - BigNumber.from(accountId), - systemToken.address, - amountToDeposit.toBN() // only deposit what's needed - ); - - const burn = CoreProxy.populateTransaction.burnUsd( - BigNumber.from(accountId), - BigNumber.from(poolId), - collateralTypeAddress, - debtChangeAbs.toBN() - ); - - const callsPromise = Promise.all( - [wrap, synth_approval, sell_synth, sUSD_Approval, deposit, burn].filter(notNil) - ); - - const [calls, gasPrices] = await Promise.all([callsPromise, getGasPrice({ provider })]); - if (priceUpdateTx) { - calls.push(priceUpdateTx as any); - } - - const walletAddress = await signer.getAddress(); - const erc7412Tx = await withERC7412(network, calls, 'useRepay', walletAddress); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: erc7412Tx.gasLimit, - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...erc7412Tx, ...gasOptionsForTransaction }); - dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - - await txn.wait(); - dispatch({ type: 'success' }); - } catch (error: any) { - dispatch({ type: 'error', payload: { error } }); - throw error; - } - }, - }); - return { - mutation, - txnState, - settle: () => dispatch({ type: 'settled' }), - isLoading: mutation.isPending, - exec: mutation.mutateAsync, - }; -}; diff --git a/liquidity/lib/useRewards/index.ts b/liquidity/lib/useRewards/index.ts deleted file mode 100644 index b16bc8003..000000000 --- a/liquidity/lib/useRewards/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useRewards'; diff --git a/liquidity/lib/useRewards/package.json b/liquidity/lib/useRewards/package.json deleted file mode 100644 index 88c916648..000000000 --- a/liquidity/lib/useRewards/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "@snx-v3/useRewards", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useMulticall3": "workspace:*", - "@snx-v3/useRewardsDistributors": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0", - "zod": "^3.22.4" - } -} diff --git a/liquidity/lib/useRewards/useRewards.ts b/liquidity/lib/useRewards/useRewards.ts deleted file mode 100644 index e6d1e583d..000000000 --- a/liquidity/lib/useRewards/useRewards.ts +++ /dev/null @@ -1,218 +0,0 @@ -import { getSubgraphUrl } from '@snx-v3/constants'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useMulticall3 } from '@snx-v3/useMulticall3'; -import { useRewardsDistributors } from '@snx-v3/useRewardsDistributors'; -import { Wei, wei } from '@synthetixio/wei'; -import { useQuery } from '@tanstack/react-query'; -import { BigNumber } from 'ethers'; -import { z } from 'zod'; - -const RewardsResponseSchema = z.array( - z.object({ - address: z.string(), - name: z.string(), - symbol: z.string(), - distributorAddress: z.string(), - decimals: z.number(), - claimableAmount: z.instanceof(Wei), - lifetimeClaimed: z.number(), - }) -); - -export type RewardsResponseType = z.infer; - -const RewardsDataDocument = ` - query RewardsData($accountId: String!, $distributor: String!) { - rewardsClaimeds(where: { distributor: $distributor, account: $accountId }) { - id - amount - } - } -`; - -const RewardsDistributionsDocument = ` - query RewardsDistributions($distributor: String!) { - rewardsDistributions(where: { distributor: $distributor}) { - collateral_type - amount - duration - start - created_at - } - } -`; - -export function useRewards({ - poolId, - collateralSymbol, - accountId, -}: { - poolId?: string; - collateralSymbol?: string; - accountId?: string; -}) { - const { data: collateralType } = useCollateralType(collateralSymbol); - const collateralAddress = collateralType?.tokenAddress; - const { network } = useNetwork(); - - const { data: Multicall3 } = useMulticall3(network); - const { data: CoreProxy } = useCoreProxy({ customNetwork: network }); - const { data: rewardsDistributors } = useRewardsDistributors(network); - - // We need to filter the distributors, so we only query for this particular collateral type - // Also include all pool level distributors - const filteredDistributors = - rewardsDistributors && collateralAddress - ? rewardsDistributors - .filter((distributor) => distributor.isRegistered) - .filter( - (distributor) => - !distributor.collateralType || - (distributor.collateralType && - distributor.collateralType.address.toLowerCase() === - collateralAddress.toLowerCase()) - ) - : []; - - const distributorsCacheKey = filteredDistributors.map((distributor) => - distributor.address.slice(2, 6) - ); - - return useQuery({ - enabled: Boolean( - network && - CoreProxy && - Multicall3 && - rewardsDistributors && - poolId && - collateralAddress && - accountId - ), - queryKey: [ - `${network?.id}-${network?.preset}`, - 'Rewards', - { accountId }, - { collateralAddress }, - { distributors: distributorsCacheKey }, - ], - queryFn: async () => { - if ( - !( - network && - CoreProxy && - Multicall3 && - filteredDistributors && - poolId && - collateralAddress && - accountId - ) - ) { - throw new Error('OMG'); - } - - if (filteredDistributors.length === 0) return []; - - try { - const returnData = await Promise.all([ - // Historical data for account id / distributor address pair - ...filteredDistributors.map((distributor) => - fetch(getSubgraphUrl(network?.name), { - method: 'POST', - body: JSON.stringify({ - query: RewardsDataDocument, - variables: { accountId, distributor: distributor.address.toLowerCase() }, - }), - }).then((res) => res.json()) - ), - // Metadata for each distributor - ...filteredDistributors.map((distributor) => - fetch(getSubgraphUrl(network?.name), { - method: 'POST', - body: JSON.stringify({ - query: RewardsDistributionsDocument, - variables: { distributor: distributor.address.toLowerCase() }, - }), - }).then((res) => res.json()) - ), - ]); - - const historicalData = returnData.slice(0, filteredDistributors.length); - const metaData = returnData.slice(filteredDistributors.length); - - // Get claimable amount for each distributor - const calls = filteredDistributors.map(({ address }: { address: string }) => - CoreProxy.populateTransaction.getAvailableRewards( - BigNumber.from(accountId), - BigNumber.from(poolId), - collateralAddress.toLowerCase(), - address.toLowerCase() - ) - ); - - const txs = await Promise.all(calls); - - const multicallData = txs.map((tx) => ({ - target: CoreProxy.address, - callData: tx.data, - })); - - const data = await Multicall3.callStatic.aggregate(multicallData); - - const amounts = data.returnData.map((data: string) => { - const amount = CoreProxy.interface.decodeFunctionResult('getAvailableRewards', data)[0]; - return wei(amount); - }); - - const results: RewardsResponseType = filteredDistributors.map((item: any, i: number) => { - // Amount claimable for this distributor - const claimableAmount = amounts[i]; - const historicalClaims = historicalData[i]?.data?.rewardsClaimeds; - const distributions = metaData[i]?.data?.rewardsDistributions; - - if (!distributions || !distributions.length) { - return { - address: item.address, - name: item.name, - symbol: item.payoutToken.symbol, - distributorAddress: item.address, - decimals: item.payoutToken.decimals, - claimableAmount: wei(0), - lifetimeClaimed: historicalClaims - .reduce( - (acc: Wei, item: { amount: string }) => acc.add(wei(item.amount, 18, true)), - wei(0) - ) - .toNumber(), - }; - } - - return { - address: item.address, - name: item.name, - symbol: item.payoutToken.symbol, - distributorAddress: item.address, - decimals: item.payoutToken.decimals, - claimableAmount, - lifetimeClaimed: historicalClaims - .reduce( - (acc: Wei, item: { amount: string }) => acc.add(wei(item.amount, 18, true)), - wei(0) - ) - .toNumber(), - }; - }); - - const sortedBalances = results.sort( - (a, b) => b.claimableAmount.toNumber() - a.claimableAmount.toNumber() - ); - - return RewardsResponseSchema.parse(sortedBalances); - } catch (error) { - console.error(error); - return []; - } - }, - }); -} diff --git a/liquidity/lib/useRewardsDistributors/index.ts b/liquidity/lib/useRewardsDistributors/index.ts deleted file mode 100644 index 163908002..000000000 --- a/liquidity/lib/useRewardsDistributors/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useRewardsDistributors'; diff --git a/liquidity/lib/useRewardsDistributors/package.json b/liquidity/lib/useRewardsDistributors/package.json deleted file mode 100644 index d3534c2c9..000000000 --- a/liquidity/lib/useRewardsDistributors/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@snx-v3/useRewardsDistributors", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/contracts": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3" - } -} diff --git a/liquidity/lib/useRewardsDistributors/useRewardsDistributors.ts b/liquidity/lib/useRewardsDistributors/useRewardsDistributors.ts deleted file mode 100644 index 1113c7408..000000000 --- a/liquidity/lib/useRewardsDistributors/useRewardsDistributors.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Network, useNetwork } from '@snx-v3/useBlockchain'; -import { useQuery } from '@tanstack/react-query'; -import { importRewardsDistributors } from '@snx-v3/contracts'; - -export function useRewardsDistributors(customNetwork?: Network) { - const { network } = useNetwork(); - const targetNetwork = customNetwork || network; - - return useQuery({ - enabled: Boolean(targetNetwork), - queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, 'RewardsDistributors'], - queryFn: async function () { - if (!targetNetwork) { - throw new Error('OMG'); - } - const rewardDistributors = await importRewardsDistributors( - targetNetwork?.id, - targetNetwork?.preset - ); - return rewardDistributors; - }, - staleTime: Infinity, - }); -} diff --git a/liquidity/lib/useSpotMarketProxy/index.ts b/liquidity/lib/useSpotMarketProxy/index.ts deleted file mode 100644 index a29db2a41..000000000 --- a/liquidity/lib/useSpotMarketProxy/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useSpotMarketProxy'; diff --git a/liquidity/lib/useSpotMarketProxy/package.json b/liquidity/lib/useSpotMarketProxy/package.json deleted file mode 100644 index ace344efa..000000000 --- a/liquidity/lib/useSpotMarketProxy/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useSpotMarketProxy", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@ethersproject/contracts": "^5.7.0", - "@snx-v3/contracts": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useSpotMarketProxy/useSpotMarketProxy.ts b/liquidity/lib/useSpotMarketProxy/useSpotMarketProxy.ts deleted file mode 100644 index 93efcb1d4..000000000 --- a/liquidity/lib/useSpotMarketProxy/useSpotMarketProxy.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { Contract } from '@ethersproject/contracts'; -import { useQuery } from '@tanstack/react-query'; -import { - Network, - useNetwork, - useProvider, - useProviderForChain, - useSigner, - useWallet, -} from '@snx-v3/useBlockchain'; -import { importSpotMarketProxy } from '@snx-v3/contracts'; - -export function useSpotMarketProxy(customNetwork?: Network) { - const { network } = useNetwork(); - const provider = useProvider(); - const signer = useSigner(); - const providerForChain = useProviderForChain(customNetwork); - const signerOrProvider = signer || provider; - const { activeWallet } = useWallet(); - - const targetNetwork = customNetwork || network; - - const withSigner = Boolean(signer); - - return useQuery({ - queryKey: [ - `${targetNetwork?.id}-${targetNetwork?.preset}`, - 'SpotMarketProxy', - { withSigner }, - activeWallet?.address, - ], - queryFn: async function () { - if (!signerOrProvider || !targetNetwork) throw new Error('Should be disabled'); - - if (providerForChain && customNetwork) { - const { address, abi } = await importSpotMarketProxy( - targetNetwork.id, - targetNetwork.preset - ); - return new Contract(address, abi, providerForChain); - } - - const { address, abi } = await importSpotMarketProxy( - targetNetwork?.id, - targetNetwork?.preset - ); - - return new Contract(address, abi, signerOrProvider); - }, - enabled: Boolean(signerOrProvider && ![1, 10].includes(targetNetwork?.id || 0)), - staleTime: Infinity, - }); -} diff --git a/liquidity/lib/useSystemToken/index.ts b/liquidity/lib/useSystemToken/index.ts deleted file mode 100644 index 010da30ab..000000000 --- a/liquidity/lib/useSystemToken/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useSystemToken'; diff --git a/liquidity/lib/useSystemToken/package.json b/liquidity/lib/useSystemToken/package.json deleted file mode 100644 index 8035a1f86..000000000 --- a/liquidity/lib/useSystemToken/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@snx-v3/useSystemToken", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/contracts": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3" - } -} diff --git a/liquidity/lib/useSystemToken/useSystemToken.ts b/liquidity/lib/useSystemToken/useSystemToken.ts deleted file mode 100644 index bb86bf903..000000000 --- a/liquidity/lib/useSystemToken/useSystemToken.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { importSystemToken } from '@snx-v3/contracts'; -import { Network, useNetwork } from '@snx-v3/useBlockchain'; -import { useQuery } from '@tanstack/react-query'; - -export function useSystemToken(customNetwork?: Network) { - const { network } = useNetwork(); - const targetNetwork = customNetwork || network; - - return useQuery({ - queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, 'SystemToken'], - enabled: Boolean(targetNetwork), - queryFn: async function () { - if (!targetNetwork) { - throw new Error('OMFG'); - } - return await importSystemToken(targetNetwork.id, targetNetwork.preset); - }, - staleTime: Infinity, - }); -} diff --git a/liquidity/lib/useTeleport/index.ts b/liquidity/lib/useTeleport/index.ts deleted file mode 100644 index 95bad4b73..000000000 --- a/liquidity/lib/useTeleport/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useTeleport'; diff --git a/liquidity/lib/useTeleport/package.json b/liquidity/lib/useTeleport/package.json deleted file mode 100644 index 34af54e87..000000000 --- a/liquidity/lib/useTeleport/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "@snx-v3/useTeleport", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useTeleport/useTeleport.tsx b/liquidity/lib/useTeleport/useTeleport.tsx deleted file mode 100644 index 691ecb9bc..000000000 --- a/liquidity/lib/useTeleport/useTeleport.tsx +++ /dev/null @@ -1,113 +0,0 @@ -import { useReducer } from 'react'; -import { ethers } from 'ethers'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useMutation } from '@tanstack/react-query'; -import { useProvider, useSigner } from '@snx-v3/useBlockchain'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import Wei from '@synthetixio/wei'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; - -/** - * This is the function that estimates the fee for the teleport. - * value is used to pay for the chainlink + destination fee. - * We don't know how much that is, so we use a static call with a lot of eth - * Then call will return the fee we need to pay. - * This can also be called from the component to show the fee before the user clicks on the button. - */ -export const estimateTeleport = async ({ - CoreProxy, - toNetworkId, - amount, - ethBalance, -}: { - CoreProxy: ethers.Contract; - toNetworkId: number; - amount: Wei; - ethBalance: Wei; -}) => { - const fee = await CoreProxy.callStatic.transferCrossChain(toNetworkId, amount.toBN(), { - value: ethBalance.mul(0.9).toBN(), - }); - return fee; -}; - -export const useTeleport = ({ - toNetworkId, - amount, - ethBalance, -}: { - toNetworkId: number; - amount: Wei; - ethBalance?: Wei; -}) => { - const [txnState, dispatch] = useReducer(reducer, initialState); - const { data: CoreProxy } = useCoreProxy(); - - const signer = useSigner(); - const { gasSpeed } = useGasSpeed(); - const provider = useProvider(); - - const mutation = useMutation({ - mutationFn: async () => { - if (!signer || !CoreProxy || !provider) throw new Error('No signer or CoreProxy'); - - if (!ethBalance) return; - if (ethBalance.eq(0)) return; - if (amount.eq(0)) return; - - try { - dispatch({ type: 'prompting' }); - const fee = await estimateTeleport({ - CoreProxy, - toNetworkId, - amount, - ethBalance, - }); - const gasPricesPromised = getGasPrice({ provider }); - const gasLimitPromised = CoreProxy.estimateGas.transferCrossChain( - toNetworkId, - amount.toBN(), - { value: fee } - ); - - const populatedTxnPromised = CoreProxy.populateTransaction.transferCrossChain( - toNetworkId, - amount.toBN(), - { - gasLimit: gasLimitPromised, - value: fee, - } - ); - const [gasPrices, gasLimit, populatedTxn] = await Promise.all([ - gasPricesPromised, - gasLimitPromised, - populatedTxnPromised, - ]); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit, - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...populatedTxn, ...gasOptionsForTransaction }); - dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - - await txn.wait(); - dispatch({ type: 'success' }); - } catch (error: any) { - dispatch({ type: 'error', payload: { error } }); - throw error; - } - }, - }); - return { - mutation, - txnState, - settle: () => dispatch({ type: 'settled' }), - isLoading: mutation.isPending, - exec: mutation.mutateAsync, - }; -}; diff --git a/liquidity/lib/useTokenBalance/index.ts b/liquidity/lib/useTokenBalance/index.ts deleted file mode 100644 index 2c6b54930..000000000 --- a/liquidity/lib/useTokenBalance/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './useTokenBalance'; -export * from './useTokenBalanceForChain'; diff --git a/liquidity/lib/useTokenBalance/package.json b/liquidity/lib/useTokenBalance/package.json deleted file mode 100644 index 491fd4050..000000000 --- a/liquidity/lib/useTokenBalance/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "@snx-v3/useTokenBalance", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/assertAddressType": "workspace:*", - "@snx-v3/constants": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/zod": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2" - } -} diff --git a/liquidity/lib/useTokenBalance/useTokenBalance.ts b/liquidity/lib/useTokenBalance/useTokenBalance.ts deleted file mode 100644 index 965c57d21..000000000 --- a/liquidity/lib/useTokenBalance/useTokenBalance.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { assertAddressType } from '@snx-v3/assertAddressType'; -import { wei } from '@synthetixio/wei'; -import { useQuery } from '@tanstack/react-query'; -import { - Network, - useDefaultProvider, - useNetwork, - useProviderForChain, - useWallet, -} from '@snx-v3/useBlockchain'; -import { ethers, providers } from 'ethers'; -import { ZodBigNumber } from '@snx-v3/zod'; -import { ZEROWEI } from '@snx-v3/constants'; - -export const BalanceSchema = ZodBigNumber.transform((x) => wei(x)); - -export const abi = [ - 'function balanceOf(address) view returns (uint256)', - 'function decimals() view returns (uint8)', -]; - -export const useTokenBalance = (address?: string, customNetwork?: Network) => { - const { activeWallet } = useWallet(); - const { network } = useNetwork(); - - const targetNetwork = customNetwork || network; - const provider = useProviderForChain(targetNetwork); - - const tokenAddress = assertAddressType(address) ? address : undefined; - return useQuery({ - queryKey: [ - `${targetNetwork?.id}-${targetNetwork?.preset}`, - 'TokenBalance', - { accountAddress: activeWallet?.address }, - { tokenAddress }, - ], - queryFn: async () => await fetchTokenBalance(address!, activeWallet!.address, provider!), - enabled: Boolean(activeWallet?.address && tokenAddress && provider && targetNetwork?.id), - refetchInterval: 15000, - }); -}; - -export const useTokenBalances = (addresses: string[], customNetwork?: Network) => { - const { activeWallet } = useWallet(); - const defaultProvider = useDefaultProvider(); - - const provider = customNetwork - ? new ethers.providers.JsonRpcProvider(customNetwork.rpcUrl()) - : defaultProvider; - - const { network } = useNetwork(); - - const targetNetwork = customNetwork || network; - - return useQuery({ - queryKey: [ - `${targetNetwork?.id}-${targetNetwork?.preset}`, - 'TokenBalance', - { accountAddress: activeWallet?.address }, - addresses.toString(), - ], - queryFn: async () => - await Promise.all( - addresses.map((address) => fetchTokenBalance(address, activeWallet!.address, provider!)) - ), - enabled: Boolean(activeWallet?.address && addresses.length && provider && targetNetwork?.id), - refetchInterval: 15000, - }); -}; - -export async function fetchTokenBalance( - tokenAddress: string, - walletAddress: string, - provider: providers.JsonRpcProvider -) { - if (!tokenAddress) { - return ZEROWEI; - } - const contract = new ethers.Contract(tokenAddress, abi, provider); - const balance = wei(await contract.balanceOf(walletAddress), await contract.decimals()); - return balance; -} diff --git a/liquidity/lib/useTokenBalance/useTokenBalanceForChain.ts b/liquidity/lib/useTokenBalance/useTokenBalanceForChain.ts deleted file mode 100644 index d69f272d2..000000000 --- a/liquidity/lib/useTokenBalance/useTokenBalanceForChain.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { assertAddressType } from '@snx-v3/assertAddressType'; -import { useQuery } from '@tanstack/react-query'; -import { Network, useProviderForChain, useWallet } from '@snx-v3/useBlockchain'; -import { fetchTokenBalance } from './useTokenBalance'; - -export const useTokenBalanceForChain = (address?: string, network?: Network) => { - const { activeWallet } = useWallet(); - const provider = useProviderForChain(network); - const tokenAddress = assertAddressType(address) ? address : undefined; - - return useQuery({ - queryKey: [ - `${network?.id}-${network?.preset}`, - 'TokenBalanceForChain', - { accountAddress: activeWallet?.address }, - { tokenAddress }, - ], - queryFn: async () => { - if (activeWallet?.address && tokenAddress && provider) { - return await fetchTokenBalance(tokenAddress, activeWallet?.address, provider); - } - }, - enabled: Boolean(activeWallet?.address && tokenAddress && provider), - refetchInterval: 5000, - }); -}; diff --git a/liquidity/lib/useTokenInfo/index.ts b/liquidity/lib/useTokenInfo/index.ts deleted file mode 100644 index 03db3ef7b..000000000 --- a/liquidity/lib/useTokenInfo/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useTokenInfo'; diff --git a/liquidity/lib/useTokenInfo/package.json b/liquidity/lib/useTokenInfo/package.json deleted file mode 100644 index f75b566b6..000000000 --- a/liquidity/lib/useTokenInfo/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useTokenInfo", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useMulticall3": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useTokenInfo/useTokenInfo.ts b/liquidity/lib/useTokenInfo/useTokenInfo.ts deleted file mode 100644 index 48669ff5c..000000000 --- a/liquidity/lib/useTokenInfo/useTokenInfo.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useMulticall3 } from '@snx-v3/useMulticall3'; -import { useQuery, useQueryClient } from '@tanstack/react-query'; -import { ethers } from 'ethers'; -import React from 'react'; - -export type TokenInfoType = { - tokenAddress: string; - symbol?: string; - name?: string; - decimals?: number; -}; -export type TokensInfoType = { [key: string]: TokenInfoType }; - -export async function getTokensInfo({ - Multicall3, - addresses, -}: { - Multicall3: ethers.Contract; - addresses: string[]; -}): Promise { - const Interface = new ethers.utils.Interface([ - 'function symbol() view returns (string)', - 'function name() view returns (string)', - 'function decimals() view returns (uint8)', - ]); - - const { returnData } = await Multicall3.callStatic.aggregate( - addresses.flatMap((target) => [ - { target, callData: Interface.encodeFunctionData('symbol') }, - { target, callData: Interface.encodeFunctionData('name') }, - { target, callData: Interface.encodeFunctionData('decimals') }, - ]) - ); - return returnData.reduce((result: TokensInfoType, value: ethers.BytesLike, i: number) => { - const batchId = Math.floor(i / 3); - const tokenAddress = addresses[batchId]; - if (!result[tokenAddress]) { - result[tokenAddress] = { - tokenAddress, - symbol: undefined, - name: undefined, - decimals: undefined, - }; - } - if (i % 3 === 0) { - const [symbol] = Interface.decodeFunctionResult('symbol', value); - result[tokenAddress].symbol = symbol; - } - if (i % 3 === 1) { - const [name] = Interface.decodeFunctionResult('name', value); - result[tokenAddress].name = name; - } - if (i % 3 === 2) { - const [decimals] = Interface.decodeFunctionResult('decimals', value); - result[tokenAddress].decimals = decimals; - } - return result; - }, {}); -} - -export const useTokenInfo = (tokenAddress?: string) => { - const { network } = useNetwork(); - const { data: Multicall3 } = useMulticall3(network || undefined); - return useQuery({ - enabled: Boolean(network?.id && network?.preset && Multicall3 && tokenAddress), - queryKey: [`${network?.id}-${network?.preset}`, 'Token', { tokenAddress }], - queryFn: async () => { - if (!(Multicall3 && tokenAddress)) throw new Error('OMFG!'); - const tokensInfo = await getTokensInfo({ Multicall3, addresses: [tokenAddress] }); - return tokensInfo[tokenAddress]; - }, - staleTime: Infinity, - refetchInterval: Infinity, - }); -}; - -export const useTokensInfo = (addresses: string[]) => { - const { network } = useNetwork(); - const { data: Multicall3 } = useMulticall3(network || undefined); - const queryClient = useQueryClient(); - const tokenAddresses = React.useMemo( - () => addresses.map((address) => address.toLowerCase()).sort(), - [addresses] - ); - return useQuery({ - enabled: Boolean(network?.id && network?.preset && Multicall3 && tokenAddresses.length > 0), - queryKey: [`${network?.id}-${network?.preset}`, 'Tokens', { tokenAddresses }], - queryFn: async () => { - if (!(Multicall3 && tokenAddresses.length > 0)) throw new Error('OMFG!'); - const unknownAddresses = tokenAddresses.filter( - (tokenAddress) => - queryClient.getQueryData([ - `${network?.id}-${network?.preset}`, - 'Token', - { tokenAddress }, - ]) === undefined - ); - - const tokensInfo = await getTokensInfo({ Multicall3, addresses: unknownAddresses }); - for (const [tokenAddress, tokenInfo] of Object.entries(tokensInfo)) { - queryClient.setQueryData( - [`${network?.id}-${network?.preset}`, 'Token', { tokenAddress }], - tokenInfo - ); - } - return Object.fromEntries( - tokenAddresses.map((tokenAddress) => [ - tokenAddress, - queryClient.getQueryData([ - `${network?.id}-${network?.preset}`, - 'Token', - { tokenAddress }, - ]), - ]) - ) as TokensInfoType; - }, - staleTime: Infinity, - refetchInterval: Infinity, - }); -}; diff --git a/liquidity/lib/useTokenPrice/index.ts b/liquidity/lib/useTokenPrice/index.ts deleted file mode 100644 index c3665433f..000000000 --- a/liquidity/lib/useTokenPrice/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useTokenPrice'; diff --git a/liquidity/lib/useTokenPrice/package.json b/liquidity/lib/useTokenPrice/package.json deleted file mode 100644 index 188077cfa..000000000 --- a/liquidity/lib/useTokenPrice/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "@snx-v3/useTokenPrice", - "private": true, - "main": "index.ts", - "version": "0.0.2", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useOraclePrice": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useTokenPrice/useTokenPrice.ts b/liquidity/lib/useTokenPrice/useTokenPrice.ts deleted file mode 100644 index 94796315c..000000000 --- a/liquidity/lib/useTokenPrice/useTokenPrice.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { useOfflinePrices } from '@snx-v3/useCollateralPriceUpdates'; -import { useCollateralTypes } from '@snx-v3/useCollateralTypes'; -import { useMemo } from 'react'; -import { ZEROWEI } from '@snx-v3/constants'; -import { wei } from '@synthetixio/wei'; -import { useOraclePrice } from '@snx-v3/useOraclePrice'; - -// TODO: Update this hook to use a multicall through the oracle manager proxy -export const useTokenPrice = (symbol?: string) => { - const { data: collateralTypes } = useCollateralTypes(true); - - const pythCollateralPrices = collateralTypes?.filter((item) => item.symbol !== 'stataUSDC'); - const omCollateralPrices = collateralTypes?.filter((item) => item.symbol === 'stataUSDC'); - - const { data: collateralPrices } = useOfflinePrices( - (pythCollateralPrices || []).map((item) => ({ - id: item.tokenAddress, - oracleId: item.oracleNodeId, - symbol: item.symbol, - })) - ); - - const { data: omPrices } = useOraclePrice(omCollateralPrices?.[0]?.oracleNodeId); - - return useMemo(() => { - if (!collateralTypes || !collateralPrices) { - return ZEROWEI; - } - - const collateralPrice = collateralPrices - .concat(omPrices ? [{ symbol: 'stataUSDC', price: omPrices.price.toString() }] : []) - .find((price) => `${price?.symbol}`.toUpperCase() === `${symbol}`.toUpperCase()); - - return collateralPrice?.price ? wei(collateralPrice?.price) : ZEROWEI; - }, [collateralPrices, collateralTypes, symbol, omPrices]); -}; diff --git a/liquidity/lib/useTransferAccountId/index.ts b/liquidity/lib/useTransferAccountId/index.ts deleted file mode 100644 index dcdc21f3c..000000000 --- a/liquidity/lib/useTransferAccountId/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useTransferAccountId'; diff --git a/liquidity/lib/useTransferAccountId/package.json b/liquidity/lib/useTransferAccountId/package.json deleted file mode 100644 index bcc73e882..000000000 --- a/liquidity/lib/useTransferAccountId/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@snx-v3/useTransferAccountId", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/useAccountProxy": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3" - } -} diff --git a/liquidity/lib/useTransferAccountId/useTransferAccountId.ts b/liquidity/lib/useTransferAccountId/useTransferAccountId.ts deleted file mode 100644 index 69069d1f6..000000000 --- a/liquidity/lib/useTransferAccountId/useTransferAccountId.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { useAccountProxy } from '@snx-v3/useAccountProxy'; -import { useSigner, useWallet } from '@snx-v3/useBlockchain'; -import { useMutation } from '@tanstack/react-query'; - -export function useTransferAccountId(to: string, accountId: string) { - const { data: AccountProxy } = useAccountProxy(); - const { activeWallet } = useWallet(); - const signer = useSigner(); - - return useMutation({ - mutationFn: async () => { - if (!AccountProxy) throw new Error('CoreProxy or Multicall not defined'); - if (!activeWallet?.address) throw new Error('Wallet is not connected'); - const tx = await AccountProxy.connect(signer!).transferFrom( - activeWallet.address, - to, - accountId - ); - const response = await tx.wait(); - return response; - }, - }); -} diff --git a/liquidity/lib/useTransferableSynthetix/index.ts b/liquidity/lib/useTransferableSynthetix/index.ts deleted file mode 100644 index 47f6f6cdd..000000000 --- a/liquidity/lib/useTransferableSynthetix/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useTransferableSynthetix'; diff --git a/liquidity/lib/useTransferableSynthetix/package.json b/liquidity/lib/useTransferableSynthetix/package.json deleted file mode 100644 index d0bb51cf6..000000000 --- a/liquidity/lib/useTransferableSynthetix/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useTransferableSynthetix", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2" - } -} diff --git a/liquidity/lib/useTransferableSynthetix/useTransferableSynthetix.ts b/liquidity/lib/useTransferableSynthetix/useTransferableSynthetix.ts deleted file mode 100644 index 325768e51..000000000 --- a/liquidity/lib/useTransferableSynthetix/useTransferableSynthetix.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { useNetwork, useProvider, useWallet } from '@snx-v3/useBlockchain'; -import { Wei, wei } from '@synthetixio/wei'; -import { ethers } from 'ethers'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; - -export function useTransferableSynthetix() { - const { network } = useNetwork(); - const { activeWallet } = useWallet(); - const provider = useProvider(); - const { data: snxCollateral } = useCollateralType('SNX'); - - const accountAddress = activeWallet?.address; - const snxAddress = snxCollateral?.tokenAddress; - - return useQuery({ - enabled: Boolean(provider && accountAddress && snxAddress), - queryKey: [ - `${network?.id}-${network?.preset}`, - 'TransferableSynthetix', - { address: activeWallet?.address }, - ], - queryFn: async function (): Promise<{ transferable: Wei; collateral?: Wei }> { - if (!(provider && accountAddress && snxAddress)) { - throw 'useTransferableSynthetix should not be enabled'; - } - const contract = new ethers.Contract( - snxAddress, - [ - 'function balanceOf(address owner) view returns (uint256)', - 'function transferableSynthetix(address account) view returns (uint256 transferable)', - 'function collateral(address account) view returns (uint256 collateral)', - ], - provider - ); - try { - // Cannon case - if (network?.name === 'cannon') { - const balanceOf = await contract.balanceOf(accountAddress); - return { - transferable: wei(balanceOf), - }; - } - - // Normal case for SNX case - const [transferableSynthetix, collateral] = await Promise.all([ - contract.transferableSynthetix(accountAddress), - contract.collateral(accountAddress), - ]); - - return { - transferable: wei(transferableSynthetix), - collateral: wei(collateral), - }; - } catch (e) { - console.error(e); - throw e; - } - }, - }); -} diff --git a/liquidity/lib/useUSDProxy/index.ts b/liquidity/lib/useUSDProxy/index.ts deleted file mode 100644 index 1c2836db9..000000000 --- a/liquidity/lib/useUSDProxy/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './useUSDProxy'; -export * from './useUSDProxyForChain'; diff --git a/liquidity/lib/useUSDProxy/package.json b/liquidity/lib/useUSDProxy/package.json deleted file mode 100644 index d8537edeb..000000000 --- a/liquidity/lib/useUSDProxy/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "@snx-v3/useUSDProxy", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@ethersproject/contracts": "^5.7.0", - "@snx-v3/contracts": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3" - } -} diff --git a/liquidity/lib/useUSDProxy/useUSDProxy.ts b/liquidity/lib/useUSDProxy/useUSDProxy.ts deleted file mode 100644 index 0b380f9dd..000000000 --- a/liquidity/lib/useUSDProxy/useUSDProxy.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Contract } from '@ethersproject/contracts'; -import { useQuery } from '@tanstack/react-query'; -import { useNetwork, useProvider, useSigner, useWallet } from '@snx-v3/useBlockchain'; -import { importUSDProxy } from '@snx-v3/contracts'; - -export function useUSDProxy() { - const { network } = useNetwork(); - const provider = useProvider(); - const signer = useSigner(); - const signerOrProvider = signer || provider; - const withSigner = Boolean(signer); - const { activeWallet } = useWallet(); - - return useQuery({ - queryKey: [ - `${network?.id}-${network?.preset}`, - 'USDProxy', - { withSigner }, - activeWallet?.address, - ], - queryFn: async function () { - if (!signerOrProvider || !network) throw new Error('Should be disabled'); - const { address, abi } = await importUSDProxy(network.id, network.preset); - return new Contract(address, abi, signerOrProvider); - }, - enabled: Boolean(signerOrProvider), - staleTime: Infinity, - }); -} diff --git a/liquidity/lib/useUSDProxy/useUSDProxyForChain.ts b/liquidity/lib/useUSDProxy/useUSDProxyForChain.ts deleted file mode 100644 index d780608ae..000000000 --- a/liquidity/lib/useUSDProxy/useUSDProxyForChain.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { Contract } from '@ethersproject/contracts'; -import { useQuery } from '@tanstack/react-query'; -import { Network, useProviderForChain } from '@snx-v3/useBlockchain'; -import { importUSDProxy } from '@snx-v3/contracts'; - -export function useUSDProxyForChain(network?: Network) { - const provider = useProviderForChain(network); - - return useQuery({ - queryKey: [`${network?.id}-${network?.preset}`, 'USDProxyForChain'], - queryFn: async function () { - if (network && provider) { - const { address, abi } = await importUSDProxy(network.id, network.preset); - return new Contract(address, abi, provider); - } - }, - enabled: Boolean(network && provider), - staleTime: Infinity, - }); -} diff --git a/liquidity/lib/useUndelegate/index.ts b/liquidity/lib/useUndelegate/index.ts deleted file mode 100644 index 24c07326f..000000000 --- a/liquidity/lib/useUndelegate/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useUndelegate'; diff --git a/liquidity/lib/useUndelegate/package.json b/liquidity/lib/useUndelegate/package.json deleted file mode 100644 index 928d2b94e..000000000 --- a/liquidity/lib/useUndelegate/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "@snx-v3/useUndelegate", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/fetchPythPrices": "workspace:*", - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useAllCollateralPriceIds": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useUndelegate/useUndelegate.tsx b/liquidity/lib/useUndelegate/useUndelegate.tsx deleted file mode 100644 index 704cca55c..000000000 --- a/liquidity/lib/useUndelegate/useUndelegate.tsx +++ /dev/null @@ -1,94 +0,0 @@ -import { useReducer } from 'react'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useMutation } from '@tanstack/react-query'; -import { useNetwork, useProvider, useSigner } from '@snx-v3/useBlockchain'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import Wei, { wei } from '@synthetixio/wei'; -import { BigNumber } from 'ethers'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; -import { withERC7412 } from '@snx-v3/withERC7412'; -import { useAllCollateralPriceIds } from '@snx-v3/useAllCollateralPriceIds'; -import { fetchPriceUpdates, priceUpdatesToPopulatedTx } from '@snx-v3/fetchPythPrices'; - -export const useUndelegate = ({ - accountId, - poolId, - collateralTypeAddress, - collateralChange, - currentCollateral, -}: { - accountId?: string; - poolId?: string; - collateralTypeAddress?: string; - currentCollateral: Wei; - collateralChange: Wei; -}) => { - const [txnState, dispatch] = useReducer(reducer, initialState); - const { data: CoreProxy } = useCoreProxy(); - const signer = useSigner(); - const { gasSpeed } = useGasSpeed(); - const provider = useProvider(); - const { data: collateralPriceUpdates } = useAllCollateralPriceIds(); - const { network } = useNetwork(); - - const mutation = useMutation({ - mutationFn: async () => { - if (!signer || !network || !provider) throw new Error('No signer or network'); - if (!(CoreProxy && poolId && collateralTypeAddress && collateralPriceUpdates)) return; - if (collateralChange.eq(0)) return; - if (currentCollateral.eq(0)) return; - try { - dispatch({ type: 'prompting' }); - - const populatedTxnPromised = CoreProxy.populateTransaction.delegateCollateral( - BigNumber.from(accountId), - BigNumber.from(poolId), - collateralTypeAddress, - currentCollateral.add(collateralChange).toBN(), - wei(1).toBN() - ); - - const walletAddress = await signer.getAddress(); - - const collateralPriceCallsPromise = fetchPriceUpdates( - collateralPriceUpdates, - network.isTestnet - ).then((signedData) => - priceUpdatesToPopulatedTx(walletAddress, collateralPriceUpdates, signedData) - ); - const [calls, gasPrices, collateralPriceCalls] = await Promise.all([ - populatedTxnPromised, - getGasPrice({ provider }), - collateralPriceCallsPromise, - ]); - const allCalls = collateralPriceCalls.concat(calls); - - const erc7412Tx = await withERC7412(network, allCalls, 'useUndelegate', walletAddress); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: erc7412Tx.gasLimit, - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...erc7412Tx, ...gasOptionsForTransaction }); - dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - - await txn.wait(); - dispatch({ type: 'success' }); - } catch (error: any) { - dispatch({ type: 'error', payload: { error } }); - throw error; - } - }, - }); - return { - mutation, - txnState, - settle: () => dispatch({ type: 'settled' }), - isLoading: mutation.isPending, - exec: mutation.mutateAsync, - }; -}; diff --git a/liquidity/lib/useUndelegateBaseAndromeda/index.ts b/liquidity/lib/useUndelegateBaseAndromeda/index.ts deleted file mode 100644 index 2bd53f145..000000000 --- a/liquidity/lib/useUndelegateBaseAndromeda/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useUndelegateBaseAndromeda'; diff --git a/liquidity/lib/useUndelegateBaseAndromeda/package.json b/liquidity/lib/useUndelegateBaseAndromeda/package.json deleted file mode 100644 index 02c384ee7..000000000 --- a/liquidity/lib/useUndelegateBaseAndromeda/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "@snx-v3/useUndelegateBaseAndromeda", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/format": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useAllCollateralPriceIds": "workspace:*", - "@snx-v3/useApprove": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useClearDebt": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/useGetUSDTokens": "workspace:*", - "@snx-v3/useLiquidityPosition": "workspace:*", - "@snx-v3/useSpotMarketProxy": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useUndelegateBaseAndromeda/useUndelegateBaseAndromeda.tsx b/liquidity/lib/useUndelegateBaseAndromeda/useUndelegateBaseAndromeda.tsx deleted file mode 100644 index 9b5646feb..000000000 --- a/liquidity/lib/useUndelegateBaseAndromeda/useUndelegateBaseAndromeda.tsx +++ /dev/null @@ -1,146 +0,0 @@ -import { useReducer } from 'react'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useMutation } from '@tanstack/react-query'; -import { useNetwork, useProvider, useSigner } from '@snx-v3/useBlockchain'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import Wei, { wei } from '@synthetixio/wei'; -import { BigNumber, Contract, PopulatedTransaction } from 'ethers'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; -import { TransactionRequest, withERC7412 } from '@snx-v3/withERC7412'; -import { useAllCollateralPriceIds } from '@snx-v3/useAllCollateralPriceIds'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { useApprove } from '@snx-v3/useApprove'; -import { USDC_BASE_MARKET, getRepayerContract } from '@snx-v3/isBaseAndromeda'; -import { parseUnits } from '@snx-v3/format'; -import { DEBT_REPAYER_ABI } from '@snx-v3/useClearDebt'; -import { useSpotMarketProxy } from '@snx-v3/useSpotMarketProxy'; -import { notNil } from '@snx-v3/tsHelpers'; -import { useCollateralPriceUpdates } from '@snx-v3/useCollateralPriceUpdates'; -import { useGetUSDTokens } from '@snx-v3/useGetUSDTokens'; - -export const useUndelegateBaseAndromeda = ({ - accountId, - poolId, - collateralTypeAddress, - collateralChange, - currentCollateral, - liquidityPosition, -}: { - accountId?: string; - poolId?: string; - collateralTypeAddress?: string; - currentCollateral: Wei; - collateralChange: Wei; - liquidityPosition?: LiquidityPosition; -}) => { - const [txnState, dispatch] = useReducer(reducer, initialState); - const { data: CoreProxy } = useCoreProxy(); - const { data: SpotMarketProxy } = useSpotMarketProxy(); - const { data: priceUpdateTx } = useCollateralPriceUpdates(); - - const signer = useSigner(); - const { gasSpeed } = useGasSpeed(); - const provider = useProvider(); - const { data: collateralPriceUpdates } = useAllCollateralPriceIds(); - const { network } = useNetwork(); - const { data: usdTokens } = useGetUSDTokens(); - - const debtExists = liquidityPosition?.debt.gt(0); - const currentDebt = debtExists && liquidityPosition ? liquidityPosition.debt : wei(0); - - const { approve, requireApproval } = useApprove({ - contractAddress: usdTokens?.USDC, - //slippage for approval - amount: parseUnits(currentDebt.toString(), 6).mul(110).div(100), - spender: getRepayerContract(network?.id), - }); - - const mutation = useMutation({ - mutationFn: async () => { - if (!signer || !network || !provider) throw new Error('No signer or network'); - if ( - !(CoreProxy && poolId && collateralTypeAddress && collateralPriceUpdates && SpotMarketProxy) - ) - return; - if (collateralChange.eq(0)) return; - if (currentCollateral.eq(0)) return; - try { - dispatch({ type: 'prompting' }); - - if (debtExists && requireApproval) { - await approve(false); - } - - const transactions: Promise[] = []; - - const repayer = new Contract(getRepayerContract(network.id), DEBT_REPAYER_ABI, signer); - - const depositDebtToRepay = repayer.populateTransaction.depositDebtToRepay( - CoreProxy.address, - SpotMarketProxy.address, - accountId, - poolId, - collateralTypeAddress, - USDC_BASE_MARKET - ); - transactions.push(depositDebtToRepay); - - const burn = CoreProxy.populateTransaction.burnUsd( - BigNumber.from(accountId), - BigNumber.from(poolId), - collateralTypeAddress, - currentDebt.abs().mul(10).toBN() - ); - transactions.push(burn); - - const populatedTxnPromised = CoreProxy.populateTransaction.delegateCollateral( - BigNumber.from(accountId), - BigNumber.from(poolId), - collateralTypeAddress, - currentCollateral.add(collateralChange).toBN(), - wei(1).toBN() - ); - transactions.push(populatedTxnPromised); - - const callsPromise = Promise.all([...transactions].filter(notNil)); - - const [calls, gasPrices] = await Promise.all([callsPromise, getGasPrice({ provider })]); - - const allCalls: TransactionRequest[] = [...calls]; - - allCalls[1].requireSuccess = false; - if (priceUpdateTx) { - allCalls.unshift(priceUpdateTx as any); - } - - const walletAddress = await signer.getAddress(); - - const erc7412Tx = await withERC7412(network, allCalls, 'useUndelegateBase', walletAddress); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: erc7412Tx.gasLimit, - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...erc7412Tx, ...gasOptionsForTransaction }); - dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - - await txn.wait(); - dispatch({ type: 'success' }); - } catch (error: any) { - dispatch({ type: 'error', payload: { error } }); - throw error; - } - }, - }); - return { - mutation, - txnState, - settle: () => dispatch({ type: 'settled' }), - isLoading: mutation.isPending, - exec: mutation.mutateAsync, - }; -}; diff --git a/liquidity/lib/useV2Position/index.ts b/liquidity/lib/useV2Position/index.ts deleted file mode 100644 index 3ab04b59d..000000000 --- a/liquidity/lib/useV2Position/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useV2Position'; diff --git a/liquidity/lib/useV2Position/package.json b/liquidity/lib/useV2Position/package.json deleted file mode 100644 index ec4b8bee5..000000000 --- a/liquidity/lib/useV2Position/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "@snx-v3/useV2Position", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useV2xSynthetix": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useV2Position/useV2Position.ts b/liquidity/lib/useV2Position/useV2Position.ts deleted file mode 100644 index af5253d56..000000000 --- a/liquidity/lib/useV2Position/useV2Position.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { Network, useNetwork, useWallet } from '@snx-v3/useBlockchain'; -import { useV2xSynthetix } from '@snx-v3/useV2xSynthetix'; -import { wei } from '@synthetixio/wei'; -import { utils } from 'ethers'; - -export function useV2Position(customNetwork?: Network) { - const { data: v2xSynthetix } = useV2xSynthetix(customNetwork); - const { network } = useNetwork(); - const { activeWallet } = useWallet(); - const targetNetwork = customNetwork || network; - - return useQuery({ - queryKey: [ - `${targetNetwork?.id}-${targetNetwork?.preset}`, - 'V2Position', - { - wallet: activeWallet?.address, - }, - ], - queryFn: async function () { - if (!v2xSynthetix) { - return; - } - const [collateral, balance, debt, cratio, transferableSynthetix] = await Promise.all([ - wei(await v2xSynthetix.collateral(activeWallet?.address)), - wei(await v2xSynthetix.balanceOf(activeWallet?.address)), - wei( - await v2xSynthetix.debtBalanceOf(activeWallet?.address, utils.formatBytes32String('sUSD')) - ), - wei(await v2xSynthetix.collateralisationRatio(activeWallet?.address)), - wei(await v2xSynthetix.transferableSynthetix(activeWallet?.address)), - ]); - - return { - collateral, - balance, - debt, - cratio, - transferableSynthetix, - }; - }, - enabled: Boolean(v2xSynthetix && activeWallet?.address), - staleTime: Infinity, - }); -} diff --git a/liquidity/lib/useV2sUSD/index.ts b/liquidity/lib/useV2sUSD/index.ts deleted file mode 100644 index 7602fc8ac..000000000 --- a/liquidity/lib/useV2sUSD/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useV2sUSD'; diff --git a/liquidity/lib/useV2sUSD/package.json b/liquidity/lib/useV2sUSD/package.json deleted file mode 100644 index 1535ea0ec..000000000 --- a/liquidity/lib/useV2sUSD/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useV2sUSD", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useV2xSynthetix": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useV2sUSD/useV2sUSD.ts b/liquidity/lib/useV2sUSD/useV2sUSD.ts deleted file mode 100644 index 6d147b8d3..000000000 --- a/liquidity/lib/useV2sUSD/useV2sUSD.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { useQuery } from '@tanstack/react-query'; -import { Network, useNetwork } from '@snx-v3/useBlockchain'; -import { useV2xSynthetix } from '@snx-v3/useV2xSynthetix'; -import { utils } from 'ethers'; - -export function useV2sUSD(customNetwork?: Network) { - const { data: v2xSynthetix } = useV2xSynthetix(customNetwork); - const { network } = useNetwork(); - const targetNetwork = customNetwork || network; - - return useQuery({ - queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, 'v2-sUSD'], - queryFn: async function () { - if (!v2xSynthetix) { - return; - } - return (await v2xSynthetix.synths(utils.formatBytes32String('sUSD'))) as string; - }, - enabled: Boolean(v2xSynthetix), - }); -} diff --git a/liquidity/lib/useV2xSynthetix/index.ts b/liquidity/lib/useV2xSynthetix/index.ts deleted file mode 100644 index dbd223e33..000000000 --- a/liquidity/lib/useV2xSynthetix/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useV2xSynthetix'; diff --git a/liquidity/lib/useV2xSynthetix/package.json b/liquidity/lib/useV2xSynthetix/package.json deleted file mode 100644 index f635f2acf..000000000 --- a/liquidity/lib/useV2xSynthetix/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "@snx-v3/useV2xSynthetix", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@ethersproject/contracts": "^5.7.0", - "@snx-v3/contracts": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useV2xSynthetix/useV2xSynthetix.ts b/liquidity/lib/useV2xSynthetix/useV2xSynthetix.ts deleted file mode 100644 index ff89bfddc..000000000 --- a/liquidity/lib/useV2xSynthetix/useV2xSynthetix.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { Contract } from '@ethersproject/contracts'; -import { useQuery } from '@tanstack/react-query'; -import { - Network, - useNetwork, - useProvider, - useProviderForChain, - useSigner, -} from '@snx-v3/useBlockchain'; -import { importV2x } from '@snx-v3/contracts'; - -export function useV2xSynthetix(customNetwork?: Network) { - const providerForChain = useProviderForChain(customNetwork); - const { network } = useNetwork(); - const provider = useProvider(); - const signer = useSigner(); - const targetNetwork = customNetwork || network; - - const withSigner = Boolean(signer); - - return useQuery({ - queryKey: [`${targetNetwork?.id}-${targetNetwork?.preset}`, 'V2xSynthetix', { withSigner }], - queryFn: async function () { - if (providerForChain && customNetwork) { - const { address: v2xAddress, abi: v2xAbi } = await importV2x( - customNetwork.id, - customNetwork.preset - ); - return new Contract(v2xAddress, v2xAbi, providerForChain); - } - - const signerOrProvider = signer || provider; - if (!signerOrProvider || !network) throw new Error('Should be disabled CP'); - - const { address: v2xAddress, abi: v2xAbi } = await importV2x(network?.id, network?.preset); - return new Contract(v2xAddress, v2xAbi, signerOrProvider); - }, - enabled: Boolean(signer || provider || providerForChain), - staleTime: Infinity, - }); -} diff --git a/liquidity/lib/useVaultsData/index.ts b/liquidity/lib/useVaultsData/index.ts deleted file mode 100644 index 4aa23396e..000000000 --- a/liquidity/lib/useVaultsData/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useVaultsData'; diff --git a/liquidity/lib/useVaultsData/package.json b/liquidity/lib/useVaultsData/package.json deleted file mode 100644 index b3f808c38..000000000 --- a/liquidity/lib/useVaultsData/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "@snx-v3/useVaultsData", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/fetchPythPrices": "workspace:*", - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/useAllCollateralPriceIds": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@snx-v3/zod": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "react": "^18.2.0", - "zod": "^3.22.4" - } -} diff --git a/liquidity/lib/useVaultsData/useVaultsData.ts b/liquidity/lib/useVaultsData/useVaultsData.ts deleted file mode 100644 index a68657437..000000000 --- a/liquidity/lib/useVaultsData/useVaultsData.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { useCollateralTypes } from '@snx-v3/useCollateralTypes'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { wei } from '@synthetixio/wei'; -import { useQuery } from '@tanstack/react-query'; -import { z } from 'zod'; -import { ZodBigNumber } from '@snx-v3/zod'; -import { Network, useNetwork, useProviderForChain } from '@snx-v3/useBlockchain'; -import { erc7412Call } from '@snx-v3/withERC7412'; -import { useAllCollateralPriceIds } from '@snx-v3/useAllCollateralPriceIds'; -import { fetchPriceUpdates, priceUpdatesToPopulatedTx } from '@snx-v3/fetchPythPrices'; -import { useAllCollateralPriceUpdates } from '@snx-v3/useCollateralPriceUpdates'; -import { stringToHash } from '@snx-v3/tsHelpers'; - -const VaultCollateralSchema = z - .object({ value: ZodBigNumber, amount: ZodBigNumber }) - .transform(({ value, amount }) => ({ value: wei(value), amount: wei(amount) })); -const VaultDebtSchema = ZodBigNumber.transform((x) => wei(x)); - -export const useVaultsData = (poolId?: number, customNetwork?: Network) => { - const { network } = useNetwork(); - const targetNetwork = customNetwork || network; - - const { data: collateralTypes } = useCollateralTypes(false, customNetwork); - const { data: CoreProxy } = useCoreProxy({ customNetwork }); - const { data: collateralPriceUpdates } = useAllCollateralPriceIds(customNetwork); - - const provider = useProviderForChain(targetNetwork); - - const { data: priceUpdateTx } = useAllCollateralPriceUpdates(customNetwork); - - return useQuery({ - queryKey: [ - `${targetNetwork?.id}-${targetNetwork?.preset}`, - 'VaultCollaterals', - { - pool: poolId, - tokens: collateralTypes ? collateralTypes?.map((x) => x.tokenAddress).sort() : [], - priceUpdateTx: stringToHash(priceUpdateTx?.data), - }, - ], - queryFn: async () => { - if ( - !CoreProxy || - !collateralTypes || - !poolId || - !collateralPriceUpdates || - !targetNetwork || - !provider - ) { - throw Error('useVaultsData should not be enabled when missing data'); - } - - const collateralCallsP = Promise.all( - collateralTypes.map((collateralType) => - CoreProxy.populateTransaction.getVaultCollateral(poolId, collateralType.tokenAddress) - ) - ); - - const debtCallsP = Promise.all( - collateralTypes.map((collateralType) => - CoreProxy.populateTransaction.getVaultDebt(poolId, collateralType.tokenAddress) - ) - ); - - const collateralPriceUpdateCallsP = fetchPriceUpdates( - collateralPriceUpdates, - targetNetwork.isTestnet - ).then((signedData) => priceUpdatesToPopulatedTx('0x', collateralPriceUpdates, signedData)); - - const calls = await Promise.all([collateralPriceUpdateCallsP, collateralCallsP, debtCallsP]); - - if (priceUpdateTx) { - calls.unshift(priceUpdateTx as any); - } - - return await erc7412Call( - targetNetwork, - provider, - calls.flat(), - (multicallResult) => { - if (!Array.isArray(multicallResult)) throw Error('Expected array'); - - const collateralResult = multicallResult.slice(0, collateralTypes.length); - const debtResult = multicallResult.slice(collateralTypes.length); - - return collateralResult.map((bytes: string, i: number) => { - const debtBytes = - debtResult[i] || '0x0000000000000000000000000000000000000000000000000000000000000000'; - - const decodedDebt = CoreProxy.interface.decodeFunctionResult('getVaultDebt', debtBytes); - - const decodedCollateral = CoreProxy.interface.decodeFunctionResult( - 'getVaultCollateral', - bytes - ); - const collateral = VaultCollateralSchema.parse({ ...decodedCollateral }); - const debt = VaultDebtSchema.parse(decodedDebt[0]); - return { - debt, - collateral, - collateralType: collateralTypes[i], - }; - }); - }, - 'useVaultsData' - ); - }, - enabled: Boolean(collateralTypes?.length && CoreProxy && poolId && collateralPriceUpdates), - }); -}; - -export type VaultsDataType = ReturnType['data']; diff --git a/liquidity/lib/useWithdraw/index.ts b/liquidity/lib/useWithdraw/index.ts deleted file mode 100644 index e5143fc16..000000000 --- a/liquidity/lib/useWithdraw/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useWithdraw'; diff --git a/liquidity/lib/useWithdraw/package.json b/liquidity/lib/useWithdraw/package.json deleted file mode 100644 index e9009c1bb..000000000 --- a/liquidity/lib/useWithdraw/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "@snx-v3/useWithdraw", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/fetchPythPrices": "workspace:*", - "@snx-v3/format": "workspace:*", - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useAllCollateralPriceIds": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useWithdraw/useWithdraw.tsx b/liquidity/lib/useWithdraw/useWithdraw.tsx deleted file mode 100644 index 02a080fe8..000000000 --- a/liquidity/lib/useWithdraw/useWithdraw.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import { useReducer } from 'react'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useMutation } from '@tanstack/react-query'; -import { useNetwork, useProvider, useSigner } from '@snx-v3/useBlockchain'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import { BigNumber, ethers } from 'ethers'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; -import { useAllCollateralPriceIds } from '@snx-v3/useAllCollateralPriceIds'; -import { fetchPriceUpdates, priceUpdatesToPopulatedTx } from '@snx-v3/fetchPythPrices'; -import { withERC7412 } from '@snx-v3/withERC7412'; -import Wei from '@synthetixio/wei'; -import { parseUnits } from '@snx-v3/format'; - -export const useWithdraw = ({ - accountId, - collateralTypeAddress, - amount, -}: { - accountId?: string; - collateralTypeAddress?: string; - amount: Wei; -}) => { - const [txnState, dispatch] = useReducer(reducer, initialState); - const { data: CoreProxy } = useCoreProxy(); - const { data: collateralPriceIds } = useAllCollateralPriceIds(); - const { network } = useNetwork(); - - const { gasSpeed } = useGasSpeed(); - const signer = useSigner(); - const provider = useProvider(); - - const mutation = useMutation({ - mutationFn: async () => { - if (!signer || !network || !provider) throw new Error('No signer or network'); - - if (!(CoreProxy && collateralTypeAddress && amount && collateralPriceIds)) { - throw new Error('Not ready'); - } - if (amount?.eq(0)) { - throw new Error('Amount less than 0'); - } - - const walletAddress = await signer.getAddress(); - - try { - dispatch({ type: 'prompting' }); - - const gasPricesPromised = getGasPrice({ provider }); - - const contract = new ethers.Contract( - collateralTypeAddress, - ['function decimals() view returns (uint8)'], - provider - ); - - const decimals = await contract.decimals(); - - const collateralAmount = amount.gt(0) - ? parseUnits(amount.toString(), decimals) - : BigNumber.from(0); - - const populatedTxnPromised = CoreProxy.populateTransaction.withdraw( - BigNumber.from(accountId), - collateralTypeAddress, - collateralAmount - ); - - const collateralPriceCallsPromise = fetchPriceUpdates( - collateralPriceIds, - network.isTestnet - ).then((signedData) => - priceUpdatesToPopulatedTx(walletAddress, collateralPriceIds, signedData) - ); - const [gasPrices, populatedTxn, collateralPriceCalls] = await Promise.all([ - gasPricesPromised, - populatedTxnPromised, - collateralPriceCallsPromise, - ]); - const allCalls = collateralPriceCalls.concat(populatedTxn); - - const erc7412Tx = await withERC7412(network, allCalls, 'useWithdraw', walletAddress); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: erc7412Tx.gasLimit, - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...erc7412Tx, ...gasOptionsForTransaction }); - dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - - await txn.wait(); - dispatch({ type: 'success' }); - } catch (error: any) { - dispatch({ type: 'error', payload: { error } }); - throw error; - } - }, - }); - return { - mutation, - txnState, - settle: () => dispatch({ type: 'settled' }), - isLoading: mutation.isPending, - exec: mutation.mutateAsync, - }; -}; diff --git a/liquidity/lib/useWithdrawBaseAndromeda/index.ts b/liquidity/lib/useWithdrawBaseAndromeda/index.ts deleted file mode 100644 index 9cf775ae5..000000000 --- a/liquidity/lib/useWithdrawBaseAndromeda/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useWithdrawBaseAndromeda'; diff --git a/liquidity/lib/useWithdrawBaseAndromeda/package.json b/liquidity/lib/useWithdrawBaseAndromeda/package.json deleted file mode 100644 index 7a8a745bd..000000000 --- a/liquidity/lib/useWithdrawBaseAndromeda/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "@snx-v3/useWithdrawBaseAndromeda", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/constants": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/txnReducer": "workspace:*", - "@snx-v3/useAccountCollateral": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useGasOptions": "workspace:*", - "@snx-v3/useGasPrice": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/useGetUSDTokens": "workspace:*", - "@snx-v3/useSpotMarketProxy": "workspace:*", - "@snx-v3/useUSDProxy": "workspace:*", - "@snx-v3/withERC7412": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useWithdrawBaseAndromeda/useWithdrawBaseAndromeda.tsx b/liquidity/lib/useWithdrawBaseAndromeda/useWithdrawBaseAndromeda.tsx deleted file mode 100644 index 5bdf0725c..000000000 --- a/liquidity/lib/useWithdrawBaseAndromeda/useWithdrawBaseAndromeda.tsx +++ /dev/null @@ -1,174 +0,0 @@ -import { useReducer } from 'react'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useMutation } from '@tanstack/react-query'; -import { useNetwork, useProvider, useSigner } from '@snx-v3/useBlockchain'; -import { initialState, reducer } from '@snx-v3/txnReducer'; -import { BigNumber, constants, utils } from 'ethers'; -import { formatGasPriceForTransaction } from '@snx-v3/useGasOptions'; -import { getGasPrice } from '@snx-v3/useGasPrice'; -import { useGasSpeed } from '@snx-v3/useGasSpeed'; -import { withERC7412 } from '@snx-v3/withERC7412'; -import { useSpotMarketProxy } from '@snx-v3/useSpotMarketProxy'; -import { getSpotMarketId } from '@snx-v3/isBaseAndromeda'; -import { notNil } from '@snx-v3/tsHelpers'; -import { useUSDProxy } from '@snx-v3/useUSDProxy'; -import { Wei } from '@synthetixio/wei'; -import { useCollateralPriceUpdates } from '@snx-v3/useCollateralPriceUpdates'; -import { useGetUSDTokens } from '@snx-v3/useGetUSDTokens'; -import { ZEROWEI } from '@snx-v3/constants'; -import { AccountCollateralType } from '@snx-v3/useAccountCollateral'; - -export const useWithdrawBaseAndromeda = ({ - accountId, - availableCollateral, - snxUSDCollateral, - amountToWithdraw, - accountCollateral, - collateralSymbol, -}: { - availableCollateral: Wei; - snxUSDCollateral: Wei; - amountToWithdraw: Wei; - accountId?: string; - collateralSymbol?: string; - accountCollateral: AccountCollateralType | undefined; -}) => { - const [txnState, dispatch] = useReducer(reducer, initialState); - const { data: CoreProxy } = useCoreProxy(); - const { data: SpotProxy } = useSpotMarketProxy(); - const { data: UsdProxy } = useUSDProxy(); - const { data: priceUpdateTx } = useCollateralPriceUpdates(); - const { network } = useNetwork(); - const { data: usdTokens } = useGetUSDTokens(); - - const { gasSpeed } = useGasSpeed(); - const signer = useSigner(); - const provider = useProvider(); - - const mutation = useMutation({ - mutationFn: async () => { - if (!signer || !network || !provider) throw new Error('No signer or network'); - if (!(CoreProxy && SpotProxy && accountId && usdTokens?.sUSD && usdTokens.snxUSD)) { - throw new Error('Not ready'); - } - - const total = snxUSDCollateral.add(availableCollateral); - - if (total.lt(amountToWithdraw)) { - throw new Error('Exceeds balance'); - } - - const wrappedCollateralAmount = amountToWithdraw.gt(availableCollateral) - ? availableCollateral - : amountToWithdraw; - - const snxUSDAmount = amountToWithdraw.sub(wrappedCollateralAmount).gt(0) - ? amountToWithdraw.sub(wrappedCollateralAmount) - : ZEROWEI; - - try { - const spotMarketId = getSpotMarketId(collateralSymbol); - - dispatch({ type: 'prompting' }); - - const gasPricesPromised = getGasPrice({ provider }); - - const withdraw_collateral = wrappedCollateralAmount.gt(0) - ? CoreProxy.populateTransaction.withdraw( - BigNumber.from(accountId), - accountCollateral?.tokenAddress, - wrappedCollateralAmount.toBN() - ) - : undefined; - - const withdraw_snxUSD = snxUSDAmount.gt(0) - ? CoreProxy.populateTransaction.withdraw( - BigNumber.from(accountId), - usdTokens?.snxUSD, - snxUSDAmount.toBN() - ) - : undefined; - const snxUSDApproval = snxUSDAmount.gt(0) - ? UsdProxy?.populateTransaction.approve(SpotProxy.address, snxUSDAmount.toBN()) - : undefined; - const buy_wrappedCollateral = snxUSDAmount.gt(0) - ? SpotProxy.populateTransaction.buy( - spotMarketId, - snxUSDAmount.toBN(), - 0, - constants.AddressZero - ) - : undefined; - - const synthAmount = snxUSDAmount.gt(0) - ? (await SpotProxy.callStatic.quoteBuyExactIn(spotMarketId, snxUSDAmount.toBN(), 0)) - .synthAmount - : ZEROWEI; - const withdrawAmount = availableCollateral.add(synthAmount); - - const unwrapTxnPromised = SpotProxy.populateTransaction.unwrap( - spotMarketId, - withdrawAmount.toBN(), - // 2% slippage - Number( - utils.formatUnits(withdrawAmount.toBN().mul(98).div(100).toString(), 12).toString() - ).toFixed() - ); - - const [ - gasPrices, - withdraw_collateral_txn, - withdraw_snxUSD_txn, - snxUSDApproval_txn, - buy_wrappedCollateral_txn, - unwrapTxnPromised_txn, - ] = await Promise.all([ - gasPricesPromised, - withdraw_collateral, - withdraw_snxUSD, - snxUSDApproval, - buy_wrappedCollateral, - unwrapTxnPromised, - ]); - - const allCalls = [ - withdraw_collateral_txn, - withdraw_snxUSD_txn, - snxUSDApproval_txn, - buy_wrappedCollateral_txn, - unwrapTxnPromised_txn, - ].filter(notNil); - - if (priceUpdateTx) { - allCalls.unshift(priceUpdateTx as any); - } - - const walletAddress = await signer.getAddress(); - const erc7412Tx = await withERC7412(network, allCalls, 'useWithdrawBase', walletAddress); - - const gasOptionsForTransaction = formatGasPriceForTransaction({ - gasLimit: erc7412Tx.gasLimit, - gasPrices, - gasSpeed, - }); - - const txn = await signer.sendTransaction({ ...erc7412Tx, ...gasOptionsForTransaction }); - dispatch({ type: 'pending', payload: { txnHash: txn.hash } }); - - await txn.wait(); - dispatch({ type: 'success' }); - } catch (error: any) { - dispatch({ type: 'error', payload: { error } }); - throw error; - } - }, - }); - - return { - mutation, - txnState, - settle: () => dispatch({ type: 'settled' }), - isLoading: mutation.isPending, - exec: mutation.mutateAsync, - }; -}; diff --git a/liquidity/lib/useWithdrawTimer/index.ts b/liquidity/lib/useWithdrawTimer/index.ts deleted file mode 100644 index 5f40464d5..000000000 --- a/liquidity/lib/useWithdrawTimer/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useWithdrawTimer'; diff --git a/liquidity/lib/useWithdrawTimer/package.json b/liquidity/lib/useWithdrawTimer/package.json deleted file mode 100644 index c31113976..000000000 --- a/liquidity/lib/useWithdrawTimer/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@snx-v3/useWithdrawTimer", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/useAccountCollateralUnlockDate": "workspace:*", - "react": "^18.2.0", - "react-timer-hook": "^3.0.7" - } -} diff --git a/liquidity/lib/useWithdrawTimer/useWithdrawTimer.ts b/liquidity/lib/useWithdrawTimer/useWithdrawTimer.ts deleted file mode 100644 index f981d4f9e..000000000 --- a/liquidity/lib/useWithdrawTimer/useWithdrawTimer.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { useEffect } from 'react'; -import { useAccountCollateralUnlockDate } from '@snx-v3/useAccountCollateralUnlockDate'; -import { useTimer } from 'react-timer-hook'; - -export function useWithdrawTimer(accountId: string | undefined) { - const { data: accountCollateralUnlockDate, isLoading: isLoadingDate } = - useAccountCollateralUnlockDate({ - accountId, - }); - const { minutes, hours, seconds, isRunning, restart } = useTimer({ - expiryTimestamp: new Date(), - autoStart: false, - }); - - useEffect(() => { - if (accountCollateralUnlockDate && !isLoadingDate) { - restart(accountCollateralUnlockDate, true); - } - }, [accountCollateralUnlockDate, isLoadingDate, restart]); - - return { - minutes, - hours, - seconds, - isRunning: isRunning && !![minutes, hours, seconds].find((a) => a > 0), - accountCollateralUnlockDate, - }; -} diff --git a/liquidity/lib/useWrapEth/index.ts b/liquidity/lib/useWrapEth/index.ts deleted file mode 100644 index a0225dfc5..000000000 --- a/liquidity/lib/useWrapEth/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useWrapEth'; diff --git a/liquidity/lib/useWrapEth/package.json b/liquidity/lib/useWrapEth/package.json deleted file mode 100644 index 63405caa0..000000000 --- a/liquidity/lib/useWrapEth/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "@snx-v3/useWrapEth", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useEthBalance": "workspace:*", - "@snx-v3/useTokenBalance": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query": "^5.8.3", - "ethers": "^5.7.2", - "react": "^18.2.0" - } -} diff --git a/liquidity/lib/useWrapEth/useWrapEth.ts b/liquidity/lib/useWrapEth/useWrapEth.ts deleted file mode 100644 index 4221f5773..000000000 --- a/liquidity/lib/useWrapEth/useWrapEth.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { useSigner } from '@snx-v3/useBlockchain'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { useEthBalance } from '@snx-v3/useEthBalance'; -import { useTokenBalance } from '@snx-v3/useTokenBalance'; -import { Contract } from 'ethers'; -import { useMutation } from '@tanstack/react-query'; -import Wei from '@synthetixio/wei'; -import { useCallback } from 'react'; - -const minimalWETHABI = ['function deposit() payable', 'function withdraw(uint256 wad)']; - -export const useWrapEth = () => { - const signer = useSigner(); - - const { data: ethCollateral } = useCollateralType('WETH'); - const { data: ethBalance, refetch: refetchETHBalance } = useEthBalance(); - const { data: wethBalance, refetch: refetchWETHBalance } = useTokenBalance( - ethCollateral?.tokenAddress - ); - - const { mutateAsync, isPending } = useMutation({ - mutationFn: async (amount: Wei) => { - if (!ethCollateral || !signer) return; - const contract = new Contract(ethCollateral?.tokenAddress, minimalWETHABI, signer); - const txn = await contract.deposit({ value: amount.toBN() }); - await txn.wait(); - }, - }); - - const exec = useCallback( - async (amount: Wei) => { - if (!ethBalance) return; - if (ethBalance.lt(amount)) { - throw new Error('Amount exceeds balance'); - } - await mutateAsync(amount); - refetchETHBalance(); - refetchWETHBalance(); - }, - [ethBalance, mutateAsync, refetchETHBalance, refetchWETHBalance] - ); - - return { - exec, - isLoading: isPending, - wethBalance, - ethBalance, - }; -}; - -export const useUnWrapEth = () => { - const signer = useSigner(); - - const { data: ethCollateral } = useCollateralType('WETH'); - const { data: ethBalance, refetch: refetchETHBalance } = useEthBalance(); - const { data: wethBalance, refetch: refetchWETHBalance } = useTokenBalance( - ethCollateral?.tokenAddress - ); - - const { mutateAsync, isPending } = useMutation({ - mutationFn: async (amount: Wei) => { - if (!ethCollateral || !signer) return; - const contract = new Contract(ethCollateral?.tokenAddress, minimalWETHABI, signer); - const txn = await contract.withdraw(amount.toBN()); - await txn.wait(); - }, - }); - - const exec = useCallback( - async (amount: Wei) => { - if (!wethBalance) return; - if (wethBalance.lt(amount)) return; - await mutateAsync(amount); - await Promise.all([refetchETHBalance(), refetchWETHBalance()]); - }, - [mutateAsync, refetchETHBalance, refetchWETHBalance, wethBalance] - ); - - return { - exec, - isLoading: isPending, - wethBalance, - ethBalance, - }; -}; diff --git a/liquidity/lib/validatePosition/index.ts b/liquidity/lib/validatePosition/index.ts deleted file mode 100644 index 86de1b78b..000000000 --- a/liquidity/lib/validatePosition/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './validatePosition'; diff --git a/liquidity/lib/validatePosition/package.json b/liquidity/lib/validatePosition/package.json deleted file mode 100644 index b4a93972f..000000000 --- a/liquidity/lib/validatePosition/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "@snx-v3/validatePosition", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@snx-v3/calculations": "workspace:*", - "@synthetixio/wei": "^2.74.4" - } -} diff --git a/liquidity/lib/validatePosition/validatePosition.test.ts b/liquidity/lib/validatePosition/validatePosition.test.ts deleted file mode 100644 index ad2bd79b0..000000000 --- a/liquidity/lib/validatePosition/validatePosition.test.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { wei } from '@synthetixio/wei'; -import { validatePosition } from './validatePosition'; -test('handles undefined values', () => { - const result = validatePosition({ - issuanceRatioD18: undefined, - collateralAmount: undefined, - collateralPrice: undefined, - debt: undefined, - collateralChange: wei(0), - debtChange: wei(0), - }); - expect(result).toEqual({ - isValid: true, - hasChanges: false, - newCRatio: wei(0), - newCollateralAmount: wei(0), - newDebt: wei(0), - maxDebt: wei(0), - }); -}); -test('handles no changes', () => { - const result = validatePosition({ - issuanceRatioD18: wei(3), - collateralAmount: wei(10), - collateralPrice: wei(2), - debt: wei(1), - collateralChange: wei(0), - debtChange: wei(0), - }); - expect(result).toEqual({ - isValid: true, - hasChanges: false, - newCRatio: wei(20), - newCollateralAmount: wei(10), - newDebt: wei(1), - maxDebt: wei('5.666666666666666666'), - }); -}); -test('handles no debt and no changes', () => { - const result = validatePosition({ - issuanceRatioD18: wei(3), - collateralAmount: wei(10), - collateralPrice: wei(2), - debt: wei(0), - collateralChange: wei(0), - debtChange: wei(0), - }); - expect(result).toEqual({ - isValid: true, - hasChanges: false, - newCRatio: wei(0), - newCollateralAmount: wei(10), - newDebt: wei(0), - maxDebt: wei('6.666666666666666666'), - }); -}); -test('handles debt increase from no debt', () => { - const result = validatePosition({ - issuanceRatioD18: wei(3), - collateralAmount: wei(10), - collateralPrice: wei(2), - debt: wei(0), - collateralChange: wei(0), - debtChange: wei(2), - }); - expect(result).toEqual({ - isValid: true, - hasChanges: true, - newCRatio: wei(10), - newCollateralAmount: wei(10), - newDebt: wei(2), - maxDebt: wei('6.666666666666666666'), - }); -}); -test('handles debt increase with existing debt', () => { - const result = validatePosition({ - issuanceRatioD18: wei(3), - collateralAmount: wei(10), - collateralPrice: wei(2), - debt: wei(1), - collateralChange: wei(0), - debtChange: wei(1), - }); - expect(result).toEqual({ - isValid: true, - hasChanges: true, - newCRatio: wei(10), - newCollateralAmount: wei(10), - newDebt: wei(2), - maxDebt: wei('5.666666666666666666'), - }); -}); -test('handles debt decrease with existing debt', () => { - const result = validatePosition({ - issuanceRatioD18: wei(3), - collateralAmount: wei(10), - collateralPrice: wei(2), - debt: wei(1), - collateralChange: wei(0), - debtChange: wei(-1), - }); - expect(result).toEqual({ - isValid: true, - hasChanges: true, - newCRatio: wei(0), - newCollateralAmount: wei(10), - newDebt: wei(0), - maxDebt: wei('5.666666666666666666'), - }); -}); -test('handles collateral deposited with no collateral', () => { - const result = validatePosition({ - issuanceRatioD18: wei(3), - collateralAmount: wei(0), - collateralPrice: wei(0), - debt: wei(0), - collateralChange: wei(10), - debtChange: wei(0), - }); - expect(result).toEqual({ - isValid: true, - hasChanges: true, - newCRatio: wei(0), - newCollateralAmount: wei(10), - newDebt: wei(0), - maxDebt: wei(0), - }); -}); -test('handles collateral deposit with existing collateral', () => { - const result = validatePosition({ - issuanceRatioD18: wei(3), - collateralAmount: wei(10), - collateralPrice: wei(0), - debt: wei(0), - collateralChange: wei(10), - debtChange: wei(0), - }); - expect(result).toEqual({ - isValid: true, - hasChanges: true, - newCRatio: wei(0), - newCollateralAmount: wei(20), - newDebt: wei(0), - maxDebt: wei(0), - }); -}); -test('handles collateral withdrawal ', () => { - const result = validatePosition({ - issuanceRatioD18: wei(3), - collateralAmount: wei(10), - collateralPrice: wei(0), - debt: wei(0), - collateralChange: wei(-10), - debtChange: wei(0), - }); - expect(result).toEqual({ - isValid: true, - hasChanges: true, - newCRatio: wei(0), - newCollateralAmount: wei(0), - newDebt: wei(0), - maxDebt: wei(0), - }); -}); -test('handles collateral withdrawal for more than we have deposited', () => { - const result = validatePosition({ - issuanceRatioD18: wei(3), - collateralAmount: wei(10), - collateralPrice: wei(0), - debt: wei(10), - collateralChange: wei(-30), - debtChange: wei(0), - }); - expect(result).toEqual({ - isValid: false, - hasChanges: true, - newCRatio: wei(0), - newCollateralAmount: wei(-20), - newDebt: wei(10), - maxDebt: wei(0), - }); -}); diff --git a/liquidity/lib/validatePosition/validatePosition.ts b/liquidity/lib/validatePosition/validatePosition.ts deleted file mode 100644 index 132c26806..000000000 --- a/liquidity/lib/validatePosition/validatePosition.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { calculateCRatio } from '@snx-v3/calculations'; -import { Wei, wei } from '@synthetixio/wei'; - -export const validatePosition = ({ - issuanceRatioD18, - collateralAmount, - collateralPrice, - debt, - collateralChange, - debtChange, -}: { - issuanceRatioD18?: Wei; - collateralAmount?: Wei; - collateralPrice?: Wei; - debt?: Wei; - collateralChange: Wei; - debtChange: Wei; -}) => { - const targetCRatio = issuanceRatioD18 ? issuanceRatioD18 : wei(1); - const newDebt = wei(debt || 0).add(debtChange); - const newCollateralAmount = wei(collateralAmount || 0).add(collateralChange); - const newCollateralValue = newCollateralAmount.mul(collateralPrice || 0); - - const newCRatio = calculateCRatio(newDebt, newCollateralValue); - - const maybeMaxDebt = wei(newCollateralAmount) - .mul(collateralPrice || 0) - .div(targetCRatio) - .sub(debt || 0); - - const maxDebt = maybeMaxDebt.gte(0) ? maybeMaxDebt : wei(0); - - const isValid = - (debtChange.lte(0) && collateralChange.gte(0)) || - ((newCRatio.gte(targetCRatio) || newCRatio.lte(0)) && - (newDebt.lte(0) || newCollateralAmount.gt(0))); - - return { - isValid, - hasChanges: !collateralChange.eq(0) || !debtChange.eq(0), - newCRatio, - newDebt, - newCollateralAmount, - maxDebt, - }; -}; diff --git a/liquidity/lib/withERC7412/index.ts b/liquidity/lib/withERC7412/index.ts deleted file mode 100644 index 96a189998..000000000 --- a/liquidity/lib/withERC7412/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './withERC7412'; diff --git a/liquidity/lib/withERC7412/package.json b/liquidity/lib/withERC7412/package.json deleted file mode 100644 index 8847fc2d0..000000000 --- a/liquidity/lib/withERC7412/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "@snx-v3/withERC7412", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@pythnetwork/pyth-evm-js": "^1.42.0", - "@snx-v3/constants": "workspace:*", - "@snx-v3/contracts": "workspace:*", - "@snx-v3/parser": "workspace:*", - "@snx-v3/tsHelpers": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/zod": "workspace:*", - "ethers": "^5.7.2", - "viem": "^2.13.5", - "zod": "^3.22.4" - } -} diff --git a/liquidity/lib/withERC7412/withERC7412.ts b/liquidity/lib/withERC7412/withERC7412.ts deleted file mode 100644 index 504f37c17..000000000 --- a/liquidity/lib/withERC7412/withERC7412.ts +++ /dev/null @@ -1,404 +0,0 @@ -/* eslint-disable no-console */ -import { BigNumber, ethers, providers } from 'ethers'; -import { EvmPriceServiceConnection } from '@pythnetwork/pyth-evm-js'; -import { z } from 'zod'; -import { ZodBigNumber } from '@snx-v3/zod'; -import { offchainMainnetEndpoint, offchainTestnetEndpoint } from '@snx-v3/constants'; -import { Network } from '@snx-v3/useBlockchain'; -import type { Modify } from '@snx-v3/tsHelpers'; -import { importCoreProxy, importMulticall3, importAllErrors } from '@snx-v3/contracts'; -import { withMemoryCache } from './withMemoryCache'; -import * as viem from 'viem'; -import { parseTxError } from '@snx-v3/parser'; - -export const ERC7412_ABI = [ - 'error OracleDataRequired(address oracleContract, bytes oracleQuery)', - 'error FeeRequired(uint feeAmount)', - 'function oracleId() view external returns (bytes32)', - 'function fulfillOracleQuery(bytes calldata signedOffchainData) payable external', -]; - -export const PYTH_ERRORS = [ - // Function arguments are invalid (e.g., the arguments lengths mismatch) - // Signature: 0xa9cb9e0d - 'error InvalidArgument()', - // Update data is coming from an invalid data source. - // Signature: 0xe60dce71 - 'error InvalidUpdateDataSource()', - // Update data is invalid (e.g., deserialization error) - // Signature: 0xe69ffece - 'error InvalidUpdateData()', - // Insufficient fee is paid to the method. - // Signature: 0x025dbdd4 - 'error InsufficientFee()', - // There is no fresh update, whereas expected fresh updates. - // Signature: 0xde2c57fa - 'error NoFreshUpdate()', - // There is no price feed found within the given range or it does not exists. - // Signature: 0x45805f5d - 'error PriceFeedNotFoundWithinRange()', - // Price feed not found or it is not pushed on-chain yet. - // Signature: 0x14aebe68 - 'error PriceFeedNotFound()', - // Requested price is stale. - // Signature: 0x19abf40e - 'error StalePrice()', - // Given message is not a valid Wormhole VAA. - // Signature: 0x2acbe915 - 'error InvalidWormholeVaa()', - // Governance message is invalid (e.g., deserialization error). - // Signature: 0x97363b35 - 'error InvalidGovernanceMessage()', - // Governance message is not for this contract. - // Signature: 0x63daeb77 - 'error InvalidGovernanceTarget()', - // Governance message is coming from an invalid data source. - // Signature: 0x360f2d87 - 'error InvalidGovernanceDataSource()', - // Governance message is old. - // Signature: 0x88d1b847 - 'error OldGovernanceMessage()', - // The wormhole address to set in SetWormholeAddress governance is invalid. - // Signature: 0x13d3ed82 - 'error InvalidWormholeAddressToSet()', -]; - -export type TransactionRequest = ethers.providers.TransactionRequest & { - requireSuccess?: boolean; -}; -type TransactionRequestWithGasLimit = Modify; - -const PRICE_CACHE_LENGTH = 5000; - -const fetchOffchainData = withMemoryCache( - async (oracleQuery: string, isTestnet: boolean, logLabel: string) => { - const priceService = new EvmPriceServiceConnection( - isTestnet ? offchainTestnetEndpoint : offchainMainnetEndpoint - ); - - const OracleQuerySchema = z.tuple([z.number(), ZodBigNumber, z.array(z.string())]); - const decoded = ethers.utils.defaultAbiCoder.decode( - ['uint8', 'uint64', 'bytes32[]'], - oracleQuery - ); - const [updateType, stalenessTolerance, priceIds] = OracleQuerySchema.parse(decoded); - console.log(`[${logLabel}] stale price for priceFeedId: ${priceIds[0]}`); - if (updateType !== 1) { - throw new Error(`update type ${updateType} not supported`); - } - const signedOffchainData = await priceService.getPriceFeedsUpdateData(priceIds); - - return ethers.utils.defaultAbiCoder.encode( - ['uint8', 'uint64', 'bytes32[]', 'bytes[]'], - [updateType, stalenessTolerance, priceIds, signedOffchainData] - ); - }, - PRICE_CACHE_LENGTH -); - -function makeMulticall( - calls: TransactionRequest[], - senderAddr: string, - multicallAddress: string, - multiCallAbi: string[] -): TransactionRequest { - const multicallInterface = new ethers.utils.Interface(multiCallAbi); - - const encodedData = multicallInterface.encodeFunctionData('aggregate3Value', [ - calls.map((call) => ({ - target: call.to, - callData: call.data, - value: call.value || ethers.BigNumber.from(0), - requireSuccess: call.requireSuccess ?? true, - allowFailure: !(call.requireSuccess ?? true), - })), - ]); - - let totalValue = ethers.BigNumber.from(0); - for (const call of calls) { - totalValue = totalValue.add(call.value || ethers.BigNumber.from(0)); - } - - return { - from: senderAddr, - to: multicallAddress, - data: encodedData, - value: totalValue, - }; -} - -// This should be used for networks that doesn't have a multicall setup as a trusted forwarder -// TODO remove when all networks have a trusted forwarder -export const makeCoreProxyMulticall = ( - calls: TransactionRequest[], - senderAddr: string, - coreProxyAddress: string, - coreProxyAbi: string[] -) => { - const CoreProxyInterface = new ethers.utils.Interface(coreProxyAbi); - const encodedData = CoreProxyInterface.encodeFunctionData('multicall', [ - calls.map((call) => call.data), - ]); - - let totalValue = ethers.BigNumber.from(0); - for (const call of calls) { - totalValue = totalValue.add(call.value || ethers.BigNumber.from(0)); - } - - return { - from: senderAddr, - to: coreProxyAddress, - data: encodedData, - value: totalValue, - }; -}; - -const parseError = async (error: any, provider: providers.JsonRpcProvider, network: Network) => { - let errorData = error.data || error.error?.data?.data || error.error?.error?.data; - if (!errorData) { - try { - console.log('Error is missing revert data, trying provider.call, instead of estimate gas..'); - // Some wallets swallows the revert reason when calling estimate gas,try to get the error by using provider.call - // provider.call wont actually revert, instead the error data is just returned - const lookedUpError = await provider.call(error.transaction); - errorData = lookedUpError; - } catch (newError: any) { - console.log('provider.call(error.transaction) failed, trying to extract error'); - console.log('Error data: ', errorData); - } - } - - if (`${errorData}`.startsWith('0x08c379a0')) { - const content = `0x${errorData.substring(10)}`; - // reason: string; for standard revert error string - const reason = ethers.utils.defaultAbiCoder.decode(['string'], content); - console.log(`Reason`, reason); - return { - name: reason[0], - args: [], - }; - } - - try { - const AllErrors = await importAllErrors(network.id, network.preset); - const AllErrorsInterface = new ethers.utils.Interface([...AllErrors.abi, ...PYTH_ERRORS]); - const decodedError = AllErrorsInterface.parseError(errorData); - return decodedError; - // return ERC7412ErrorSchema.parse(decodedError); - } catch (parseError) { - console.error( - 'Error is not a ERC7412 error, re-throwing original error, for better parsing. Parse error reason: ', - parseError - ); - // If we cant parse it, throw the original error - throw error; - } -}; - -// simulate w/ wETH contract because it will have eth balance -// This is useful when we do read/static calls but still need an balance for the price update -// TODO: this probably need to be network aware, maybe look into a different solution even. -export const getDefaultFromAddress = (chainName: string) => { - switch (chainName) { - case 'cannon': - return '0x4200000000000000000000000000000000000006'; // TODO, unclear what to put here - case 'mainnet': - return '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'; - case 'sepolia': - return '0x7b79995e5f793a07bc00c21412e50ecae098e7f9'; - case 'arbitrum': - return '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1'; - case 'arbitrum-sepolia': - return '0x980B62Da83eFf3D4576C647993b0c1D7faf17c73'; - case 'optimism-mainnet': - case 'base': - case 'base-sepolia': - return '0x4200000000000000000000000000000000000006'; - - default: - throw new Error(`Unsupported chain ${chainName}`); - } -}; - -/** - * If a tx requires ERC7412 pattern, wrap your tx with this function. - */ -export const withERC7412 = async ( - network: Network, - tx: TransactionRequest | TransactionRequest[], - logLabel?: string, - _from?: string -): Promise => { - const initialMulticallLength = Array.isArray(tx) ? tx.length : 1; - - const from = ([tx].flat()[0].from || _from) as string; - // eslint-disable-next-line prefer-const - let multicallCalls = [...[tx].flat()].map((tx) => ({ from, ...tx })); // Use let to communicate that we mutate this array - - if (multicallCalls.some((x) => !x.to)) { - throw Error(`Make sure all txs have 'to' field set`); - } - if (multicallCalls.some((x) => !x.from)) { - throw Error(`Make sure all txs have 'from' field set`); - } - - // Make sure we're always using JSONRpcProvider, the web3 provider coming from the signer might have bugs causing errors to miss revert data - const jsonRpcProvider = new ethers.providers.JsonRpcProvider(network?.rpcUrl()); - - // If from is set to the default address (wETH) we can assume it's a read rather than a write - const isRead = from === getDefaultFromAddress(network.name); - // const networkHaveERC7412 = deploymentsWithERC7412.includes(`${network.id}-${network.preset}`); - - const { address: multicallAddress, abi: multiCallAbi } = await importMulticall3( - network.id, - network.preset - ); - - while (true) { - try { - if (window.localStorage.getItem('DEBUG') === 'true') { - const CoryProxyInfo = await importCoreProxy(network.id, network.preset); - const CoreProxyInterface = new ethers.utils.Interface(CoryProxyInfo.abi); - console.log( - `withERC7412`, - multicallCalls.map(({ data, value, ...rest }) => { - try { - // @ts-ignore - const { name, args } = CoreProxyInterface.parseTransaction({ data, value }); - if (Object.keys(args).filter(([key]) => `${key}` !== `${parseInt(key)}`).length > 0) { - const namedArgs = Object.fromEntries( - Object.entries(args).filter(([key]) => `${key}` !== `${parseInt(key)}`) - ); - return { $: name, ...namedArgs }; - } - - const unnamedArgs = Object.entries(args) - .filter(([key]) => `${key}` === `${parseInt(key)}`) - .map(([, value]) => value); - return { $: name, ...unnamedArgs }; - } catch { - return { $: 'unknown', data, value, ...rest }; - } - }) - ); - } - - if (multicallCalls.length == 1) { - const initialCall = multicallCalls[0]; - // The normal flow would go in here, then if the estimate call fail, we catch the error and handle ERC7412 - const gasLimit = await jsonRpcProvider.estimateGas(initialCall); - console.log(`Estimated gas succeeded, with no price updates`); - return { ...initialCall, gasLimit }; - } - // If we're here it means we now added a tx to do . - // Some networks doesn't have ERC7412 and a trusted forwarder setup, on write calls we still need to use the coreproxy for those - const multicallTxn = makeMulticall(multicallCalls, from, multicallAddress, multiCallAbi); - const gasLimit = await jsonRpcProvider.estimateGas(multicallTxn); - - console.log( - `[${logLabel}] Estimated gas succeeded, with ${ - multicallCalls.length - initialMulticallLength - } price updates` - ); - - return { ...multicallTxn, gasLimit }; - } catch (error: any) { - console.error(error); - const parsedError = await parseError(error, jsonRpcProvider, network); - if (window.localStorage.getItem('DEBUG') === 'true') { - console.error('withERC7412', parsedError); - } - if (parsedError.name === 'OracleDataRequired') { - const [oracleAddress, oracleQuery] = parsedError.args; - const ignoreCache = !isRead; - const signedRequiredData = await fetchOffchainData( - oracleQuery, - network.isTestnet, - logLabel || '', - ignoreCache ? 'no-cache' : undefined - ); - const newTransactionRequest = { - from, - to: oracleAddress, - data: new ethers.utils.Interface(ERC7412_ABI).encodeFunctionData('fulfillOracleQuery', [ - signedRequiredData, - ]), - // If from is set to the default address we can add a value directly, before getting FeeRequired revert. - // This will be a static call so no money would be withdrawn either way. - value: isRead ? ethers.utils.parseEther('0.1') : BigNumber.from(0), - }; - // If we get OracleDataRequired, add an extra transaction request just before the last element - multicallCalls.splice( - multicallCalls.length - initialMulticallLength, - 0, - newTransactionRequest - ); - } else if (parsedError.name === 'FeeRequired') { - const requiredFee = parsedError.args[0]; - - const txToUpdate = multicallCalls.find(({ value }) => requiredFee.gt(value || 0)); // The first tx with value less than the required fee, is the one we need to update - if (txToUpdate === undefined) { - throw Error( - `Didn't find any tx with a value less than the required fee ${multicallCalls}` - ); - } - txToUpdate.value = requiredFee; - } else { - const parsedError = parseTxError(error); - - if (parsedError) { - const AllErrors = await importAllErrors(network.id, network.preset); - try { - const errorResult = viem.decodeErrorResult({ - abi: [...AllErrors.abi, ...PYTH_ERRORS], - data: parsedError, - }); - console.log('error: ', errorResult.errorName, errorResult.args); - } catch (_error) {} - } - throw error; - } - } - } -}; - -/** - * This can be used to do reads plus decoding. The return type will be whatever the type of the decode function is. And the arguments passed will have the multicall decoded and price updates removed - */ -export async function erc7412Call( - network: Network, - provider: ethers.providers.Provider, - txRequests: TransactionRequest | TransactionRequest[], - decode: (x: string[] | string) => T, - logLabel?: string -) { - const { address: multicallAddress, abi: multicallAbi } = await importMulticall3( - network.id, - network.preset - ); - - const reqs = [txRequests].flat(); - - for (const txRequest of reqs) { - txRequest.from = getDefaultFromAddress(network.name); // Reads can always use WETH - } - const newCall = await withERC7412(network, reqs, logLabel); - - const res = await provider.call(newCall); - - if (newCall.to?.toLowerCase() === multicallAddress.toLowerCase()) { - // If this was a multicall, decode and remove price updates. - const decodedMultiCall: { returnData: string }[] = new ethers.utils.Interface( - multicallAbi - ).decodeFunctionResult('aggregate3Value', res)[0]; - - // Remove the price updates - const responseWithoutPriceUpdates = decodedMultiCall.filter( - ({ returnData }) => returnData !== '0x' // price updates have 0x as return data - ); - - return decode(responseWithoutPriceUpdates.map(({ returnData }) => returnData)); - } - - return decode(res); -} diff --git a/liquidity/lib/withERC7412/withMemoryCache.ts b/liquidity/lib/withERC7412/withMemoryCache.ts deleted file mode 100644 index 618f4746c..000000000 --- a/liquidity/lib/withERC7412/withMemoryCache.ts +++ /dev/null @@ -1,46 +0,0 @@ -interface CacheItem { - timestamp: number; - value: T; -} - -interface Cache { - [key: string]: CacheItem | undefined; -} - -const cache: Cache = {}; -type MaybeString = 'no-cache' | undefined; - -/** - * This function, `withMemoryCache`, takes a function as an argument. - * The passed function can optionally be given an extra argument to bypass the cache. - * If the last argument passed to `func` is `true`, the cache will be bypassed. - * Otherwise, the function will use the cache, if available. - */ -export const withMemoryCache = ( - func: (...args: T) => Promise, - cacheDuration: number -) => { - return async (...args: [...T, MaybeString]): Promise => { - const lastArg = args[args.length - 1]; - const bypassCache = lastArg === 'no-cache'; - const funcArgs = (bypassCache ? args.slice(0, -1) : args) as T; - const cacheKey = JSON.stringify(funcArgs); - const currentTime = Date.now(); - - if (!bypassCache) { - const cacheItem = cache[cacheKey] as CacheItem | undefined; - if (cacheItem && currentTime - cacheItem.timestamp < cacheDuration) { - return cacheItem.value; - } - } - - const result = await func(...funcArgs); - - cache[cacheKey] = { - timestamp: currentTime, - value: result, - }; - - return result; - }; -}; diff --git a/liquidity/lib/zod/index.ts b/liquidity/lib/zod/index.ts deleted file mode 100644 index 6748f26c1..000000000 --- a/liquidity/lib/zod/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './zod'; diff --git a/liquidity/lib/zod/package.json b/liquidity/lib/zod/package.json deleted file mode 100644 index e41f3f170..000000000 --- a/liquidity/lib/zod/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@snx-v3/zod", - "private": true, - "main": "index.ts", - "version": "0.0.1", - "dependencies": { - "@synthetixio/wei": "^2.74.4", - "ethers": "^5.7.2", - "zod": "^3.22.4" - } -} diff --git a/liquidity/lib/zod/zod.ts b/liquidity/lib/zod/zod.ts deleted file mode 100644 index 7a2c54305..000000000 --- a/liquidity/lib/zod/zod.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { BigNumber } from 'ethers'; -import { z } from 'zod'; -import { wei } from '@synthetixio/wei'; - -export const ZodBigNumber = z.custom((val) => BigNumber.isBigNumber(val)); - -export const SmallIntSchema = ZodBigNumber.transform((x) => wei(x, 0).toNumber()); -export const WeiSchema = ZodBigNumber.transform((x) => wei(x)); diff --git a/liquidity/ui/.env.example b/liquidity/ui/.env.example deleted file mode 100644 index 1c340a7f6..000000000 --- a/liquidity/ui/.env.example +++ /dev/null @@ -1,4 +0,0 @@ -INFURA_KEY='' -WC_PROJECT_ID='' -PYTH_MAINNET_ENDPOINT=https://hermes.pyth.network/ -PYTH_TESTNET_ENDPOINT=https://hermes.pyth.network/ diff --git a/liquidity/ui/README.md b/liquidity/ui/README.md deleted file mode 100644 index 35a007f5e..000000000 --- a/liquidity/ui/README.md +++ /dev/null @@ -1,63 +0,0 @@ -# Accessing Synthetix V3 through Decentralized Frontends - -Explore various methods to access the Synthetix V3 UI via decentralized frontends. The method you choose may depend on -your technical proficiency and preferences: - -## 1. Brave Browser - -- Navigate to [liquidity.synthetix.eth](http://liquidity.synthetix.eth/) using Brave Browser. -- Brave will automatically route you via their public gateway. -- For additional details, check out [Brave's IPFS Support page](https://brave.com/ipfs-support/). - -## 2. Eth Limo - -- Access via [liquidity.synthetix.eth.limo](https://liquidity.synthetix.eth.limo/) using any browser. -- Eth Limo acts as a privacy-centric ENS gateway, resolving Ethereum Name Service (ENS) records and the corresponding IPFS/IPNS/Skynet content (Web 3.0). This gateway simplifies access and hosting of static sites built with a mix of IPFS/IPNS/Arweave and ENS for both users and dApp developers. -- Learn more about Eth Limo at [https://eth.limo/](https://eth.limo/). - -## 3. Run the Synthetix IPFS Node - -- Download and run the [Synthetix IPFS Node](https://github.com/Synthetixio/synthetix-node?ref=blog.synthetix.io) to - connect to the IPFS cluster. -- Once the IPFS node is running, you'll be able to access the V3 UI along with various ecosystem frontends. -- Running a Synthetix IPFS Node allows you to directly contribute to the decentralization, reliability, performance, and - censorship-resistance of the frontends within the Synthetix Ecosystem. -- Download the node and learn more on [GitHub](https://github.com/Synthetixio/synthetix-node?ref=blog.synthetix.io). - -## 4. Locally (Recommended for Technical Users) - -- Make sure you have NodeJS available - - ```sh - node -v - v18.18.0 - yarn -v - ``` - -- Clone the V3 UI repository - - ```sh - git clone git@github.com:Synthetixio/v3ui.git - cd v3ui - ``` - -- Check you have `yarn` installed - - ```sh - yarn -v - 3.6.0 - - # if not available, install it globally with npm: - npm install -g yarn - ``` - -- Install dependencies - - ```sh - yarn install - ``` - -- Run local dev server - ```sh - yarn workspace "@snx-v3/liquidity" start - ``` diff --git a/liquidity/ui/babel.config.js b/liquidity/ui/babel.config.js deleted file mode 100644 index fdea0695c..000000000 --- a/liquidity/ui/babel.config.js +++ /dev/null @@ -1,68 +0,0 @@ -const path = require('path'); -require.resolve('core-js'); -require.resolve('@babel/runtime-corejs3/core-js/date/now'); - -module.exports = { - presets: [ - require.resolve('@babel/preset-typescript'), - [require.resolve('@babel/preset-react'), { runtime: 'automatic' }], - ], - - plugins: [[require.resolve('@babel/plugin-transform-runtime'), { corejs: 3 }]], - - env: { - production: { - presets: [ - [ - require.resolve('@babel/preset-env'), - { - useBuiltIns: 'usage', - corejs: { version: 3, proposals: true }, - modules: false, - targets: { - browsers: require('./package.json').browserslist, - }, - }, - ], - ], - }, - - development: { - presets: [ - [ - require.resolve('@babel/preset-env'), - { - modules: false, - targets: { browsers: ['last 1 Chrome version'] }, - }, - ], - ], - plugins: [require.resolve('react-refresh/babel')], - }, - - test: { - presets: [ - [ - require.resolve('@babel/preset-env'), - { - modules: false, - targets: { node: 'current' }, - }, - ], - ], - plugins: [ - [ - require.resolve('babel-plugin-istanbul'), - { - cwd: path.resolve('../..'), - all: true, - excludeNodeModules: false, - include: ['liquidity', 'theme'], - exclude: ['**/*.test.*', '**/*.cy.*', '**/*.e2e.*'], - }, - 'istanbul', - ], - ], - }, - }, -}; diff --git a/liquidity/ui/index.html b/liquidity/ui/index.html deleted file mode 100644 index 4aa564983..000000000 --- a/liquidity/ui/index.html +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - - - - Synthetix Liquidity - - - - - -
- - - - diff --git a/liquidity/ui/index.js b/liquidity/ui/index.js deleted file mode 100644 index ec860a19f..000000000 --- a/liquidity/ui/index.js +++ /dev/null @@ -1,17 +0,0 @@ -import { safeImport } from '@synthetixio/safe-import/safeImport'; - -async function bootstrap() { - const { bootstrap } = await safeImport( - () => import(/* webpackChunkName: "app" */ './src/index.tsx') - ); - bootstrap(); -} - -bootstrap(); - -if (module.hot) { - module.hot.accept(); - module.hot.dispose(() => { - // do nothing - }); -} diff --git a/liquidity/ui/package.json b/liquidity/ui/package.json deleted file mode 100644 index 82f957119..000000000 --- a/liquidity/ui/package.json +++ /dev/null @@ -1,157 +0,0 @@ -{ - "name": "@snx-v3/liquidity", - "version": "0.0.2", - "private": true, - "scripts": { - "start": "webpack-cli serve", - "build": "NODE_ENV=production webpack-cli", - "focus": "yarn workspaces focus '@synthetixio/v3-ui'" - }, - "dependencies": { - "@chakra-ui/icons": "^2.1.1", - "@chakra-ui/react": "^2.8.2", - "@emotion/react": "^11.11.1", - "@emotion/styled": "^11.11.0", - "@safe-global/safe-apps-provider": "^0.18.3", - "@safe-global/safe-apps-sdk": "^9.1.0", - "@snx-v3/Amount": "workspace:*", - "@snx-v3/BorderBox": "workspace:*", - "@snx-v3/BorrowModal": "workspace:*", - "@snx-v3/ClaimModal": "workspace:*", - "@snx-v3/ContractError": "workspace:*", - "@snx-v3/DepositModal": "workspace:*", - "@snx-v3/HomeLink": "workspace:*", - "@snx-v3/ManagePositionContext": "workspace:*", - "@snx-v3/Multistep": "workspace:*", - "@snx-v3/NumberInput": "workspace:*", - "@snx-v3/RepayModal": "workspace:*", - "@snx-v3/TermsModal": "workspace:*", - "@snx-v3/Tooltip": "workspace:*", - "@snx-v3/UndelegateModal": "workspace:*", - "@snx-v3/WithdrawIncrease": "workspace:*", - "@snx-v3/WithdrawModal": "workspace:*", - "@snx-v3/calculations": "workspace:*", - "@snx-v3/constants": "workspace:*", - "@snx-v3/etherscanLink": "workspace:*", - "@snx-v3/format": "workspace:*", - "@snx-v3/formatters": "workspace:*", - "@snx-v3/icons": "workspace:*", - "@snx-v3/isBaseAndromeda": "workspace:*", - "@snx-v3/useAccountCollateral": "workspace:*", - "@snx-v3/useAccountCollateralUnlockDate": "workspace:*", - "@snx-v3/useAccountPermissions": "workspace:*", - "@snx-v3/useAccounts": "workspace:*", - "@snx-v3/useApprove": "workspace:*", - "@snx-v3/useApr": "workspace:*", - "@snx-v3/useBlockchain": "workspace:*", - "@snx-v3/useBorrow": "workspace:*", - "@snx-v3/useClaimRewards": "workspace:*", - "@snx-v3/useClearDebt": "workspace:*", - "@snx-v3/useCollateralPriceUpdates": "workspace:*", - "@snx-v3/useCollateralPrices": "workspace:*", - "@snx-v3/useCollateralTypes": "workspace:*", - "@snx-v3/useContractErrorParser": "workspace:*", - "@snx-v3/useCoreProxy": "workspace:*", - "@snx-v3/useEthBalance": "workspace:*", - "@snx-v3/useGasSpeed": "workspace:*", - "@snx-v3/useGetUSDTokens": "workspace:*", - "@snx-v3/useLegacyMarket": "workspace:*", - "@snx-v3/useLiquidityPosition": "workspace:*", - "@snx-v3/useLiquidityPositions": "workspace:*", - "@snx-v3/useLocalStorage": "workspace:*", - "@snx-v3/useManagePermissions": "workspace:*", - "@snx-v3/useMigrate": "workspace:*", - "@snx-v3/useMigrateUSD": "workspace:*", - "@snx-v3/useOraclePrice": "workspace:*", - "@snx-v3/useParams": "workspace:*", - "@snx-v3/usePoolConfiguration": "workspace:*", - "@snx-v3/usePoolData": "workspace:*", - "@snx-v3/usePoolsList": "workspace:*", - "@snx-v3/useRates": "workspace:*", - "@snx-v3/useRepay": "workspace:*", - "@snx-v3/useRewards": "workspace:^", - "@snx-v3/useRewardsDistributors": "workspace:*", - "@snx-v3/useSystemToken": "workspace:*", - "@snx-v3/useTokenBalance": "workspace:*", - "@snx-v3/useTokenPrice": "workspace:*", - "@snx-v3/useTransferAccountId": "workspace:*", - "@snx-v3/useTransferableSynthetix": "workspace:*", - "@snx-v3/useUSDProxy": "workspace:*", - "@snx-v3/useUndelegate": "workspace:*", - "@snx-v3/useUndelegateBaseAndromeda": "workspace:*", - "@snx-v3/useV2Position": "workspace:*", - "@snx-v3/useV2sUSD": "workspace:*", - "@snx-v3/useVaultsData": "workspace:*", - "@snx-v3/useWithdrawTimer": "workspace:*", - "@snx-v3/validatePosition": "workspace:*", - "@synthetixio/safe-import": "workspace:*", - "@synthetixio/v3-theme": "workspace:*", - "@synthetixio/wei": "^2.74.4", - "@tanstack/react-query-devtools": "^5.8.3", - "@web3-onboard/coinbase": "^2.4.1", - "@web3-onboard/common": "^2.4.2", - "@web3-onboard/gnosis": "^2.3.1", - "@web3-onboard/injected-wallets": "^2.11.1", - "@web3-onboard/ledger": "2.7.1", - "@web3-onboard/react": "^2.9.1", - "@web3-onboard/trezor": "^2.4.6", - "@web3-onboard/walletconnect": "^2.6.1", - "ethers": "^5.7.2", - "framer-motion": "^10.16.5", - "humanize-plus": "^1.8.2", - "react": "^18.2.0", - "react-dom": "^18.2.0", - "react-helmet": "^6.1.0", - "react-i18next": "^13.4.1", - "react-router-dom": "^6.18.0", - "react-timer-hook": "^3.0.7", - "zod": "^3.22.4" - }, - "devDependencies": { - "@babel/core": "^7.24.6", - "@babel/plugin-transform-runtime": "^7.24.6", - "@babel/preset-env": "^7.24.6", - "@babel/preset-react": "^7.24.6", - "@babel/preset-typescript": "^7.24.6", - "@babel/runtime-corejs3": "^7.24.6", - "@pmmmwh/react-refresh-webpack-plugin": "^0.5.11", - "@tanstack/react-query": "^5.8.3", - "@types/humanize-plus": "^1", - "@types/react": "^18.2.37", - "@types/react-helmet": "^6.1.9", - "babel-loader": "^9.1.3", - "babel-plugin-istanbul": "^6.1.1", - "bn.js": "^5.2.1", - "copy-webpack-plugin": "^11.0.0", - "core-js": "^3.33.2", - "crypto-browserify": "^3.12.0", - "css-loader": "^6.8.1", - "dotenv": "^16.4.3", - "html-webpack-plugin": "^5.5.3", - "process": "^0.11.10", - "react-refresh": "^0.14.0", - "stream-browserify": "^3.0.0", - "style-loader": "^3.3.3", - "terser-webpack-plugin": "^5.3.9", - "webpack": "^5.89.0", - "webpack-bundle-analyzer": "^4.10.0", - "webpack-cli": "^5.1.4", - "webpack-dev-server": "^4.15.1" - }, - "browserslist": [ - "last 1 Chrome version", - "last 1 iOS version", - "last 1 Safari version", - "last 1 Firefox version", - "last 1 Edge version", - "last 1 Opera version" - ], - "depcheck": { - "ignorePatterns": [ - "dist" - ], - "ignoreMatches": [ - "process" - ] - } -} diff --git a/liquidity/ui/public/Liquidity.jpg b/liquidity/ui/public/Liquidity.jpg deleted file mode 100644 index fb83b46ab..000000000 Binary files a/liquidity/ui/public/Liquidity.jpg and /dev/null differ diff --git a/liquidity/ui/public/Migrate Launch.png b/liquidity/ui/public/Migrate Launch.png deleted file mode 100644 index fbf3c4652..000000000 Binary files a/liquidity/ui/public/Migrate Launch.png and /dev/null differ diff --git a/liquidity/ui/public/Rocket.png b/liquidity/ui/public/Rocket.png deleted file mode 100644 index 313bf72b8..000000000 Binary files a/liquidity/ui/public/Rocket.png and /dev/null differ diff --git a/liquidity/ui/public/ballon.png b/liquidity/ui/public/ballon.png deleted file mode 100644 index 9b305377a..000000000 Binary files a/liquidity/ui/public/ballon.png and /dev/null differ diff --git a/liquidity/ui/public/favicon.ico b/liquidity/ui/public/favicon.ico deleted file mode 100644 index 5845395c4..000000000 Binary files a/liquidity/ui/public/favicon.ico and /dev/null differ diff --git a/liquidity/ui/public/pools.svg b/liquidity/ui/public/pools.svg deleted file mode 100644 index a76807d88..000000000 --- a/liquidity/ui/public/pools.svg +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/liquidity/ui/public/snx.svg b/liquidity/ui/public/snx.svg deleted file mode 100644 index 59602a6b6..000000000 --- a/liquidity/ui/public/snx.svg +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/liquidity/ui/public/synthetix-rocket.png b/liquidity/ui/public/synthetix-rocket.png deleted file mode 100644 index c9f3fea57..000000000 Binary files a/liquidity/ui/public/synthetix-rocket.png and /dev/null differ diff --git a/liquidity/ui/src/App.tsx b/liquidity/ui/src/App.tsx deleted file mode 100644 index ac14bec3b..000000000 --- a/liquidity/ui/src/App.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import { useEffect } from 'react'; -import { HashRouter } from 'react-router-dom'; -import { ChakraProvider, extendTheme, useColorMode } from '@chakra-ui/react'; -import { Fonts, theme } from '@synthetixio/v3-theme'; -import { DEFAULT_QUERY_STALE_TIME } from '@snx-v3/constants'; -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; -import { GasSpeedProvider } from '@snx-v3/useGasSpeed'; -import { TermsModal } from '@snx-v3/TermsModal'; -import { SESSION_STORAGE_KEYS } from '@snx-v3/constants'; -import { Router } from './Router'; -import { Web3OnboardProvider } from '@web3-onboard/react'; -import Head from 'react-helmet'; -import { onboard } from './utils/onboard'; -import { Progress } from './utils/theme'; - -const queryClient = new QueryClient({ - defaultOptions: { - queries: { - refetchInterval: false, // if queries needs refetching we should be explicit about it, given erc7412 - staleTime: DEFAULT_QUERY_STALE_TIME, - refetchOnWindowFocus: false, - throwOnError: (e) => { - console.error(e); - return false; - }, - }, - mutations: { - throwOnError: (e) => { - console.error(e); - return false; - }, - }, - }, -}); - -const extendedTheme = extendTheme({ - ...theme, - components: { - ...theme.components, - Progress, - }, -}); - -function ColorMode() { - const { colorMode, toggleColorMode } = useColorMode(); - - useEffect(() => { - if (colorMode === 'light') { - toggleColorMode(); - } - }, [colorMode, toggleColorMode]); - return null; -} - -export const App = () => { - const TERMS_CONDITIONS_ACCEPTED = - localStorage.getItem(SESSION_STORAGE_KEYS.TERMS_CONDITIONS_ACCEPTED) === 'true'; - - return ( - <> - - {/* open graph */} - - - - - - - - {/* twitter */} - - - - - - - - - - - - - - - - - - - - - - - ); -}; diff --git a/liquidity/ui/src/Router.tsx b/liquidity/ui/src/Router.tsx deleted file mode 100644 index 4c06f20d8..000000000 --- a/liquidity/ui/src/Router.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { Suspense } from 'react'; -import { Route, Routes } from 'react-router-dom'; -import { Spinner } from '@chakra-ui/react'; -import { DefaultLayout } from './layouts/Default'; -import { Home, Manage, NotFoundPage, Dashboard, Pool, Pools } from './pages'; -import { Settings } from './pages/Account/Settings'; - -export const Router = () => { - return ( - }> - - }> - } /> - } /> - } /> - } /> - } /> - } /> - } /> - - - - ); -}; diff --git a/liquidity/ui/src/components/AccountBanner/AccountBanner.tsx b/liquidity/ui/src/components/AccountBanner/AccountBanner.tsx deleted file mode 100644 index f8d4bd15c..000000000 --- a/liquidity/ui/src/components/AccountBanner/AccountBanner.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { Button, Flex, FlexProps, Heading } from '@chakra-ui/react'; -import { useAccounts, useCreateAccount } from '@snx-v3/useAccounts'; -import { FC } from 'react'; - -export const AccountBanner: FC = (props) => { - const { - data: accounts, - isLoading: isAccountsLoading, - isFetching: isAccountsFetching, - } = useAccounts(); - const { - mutation: { mutate: createAccount, isPending: isCreateAccountLoading }, - } = useCreateAccount(); - - if (!isAccountsFetching && !isAccountsLoading && accounts && accounts.length === 0) { - return ( - - Create an account to deposit liquidity - - - ); - } - - return null; -}; diff --git a/liquidity/ui/src/components/AccountBanner/index.ts b/liquidity/ui/src/components/AccountBanner/index.ts deleted file mode 100644 index 02ab4b128..000000000 --- a/liquidity/ui/src/components/AccountBanner/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './AccountBanner'; diff --git a/liquidity/ui/src/components/Address/Address.tsx b/liquidity/ui/src/components/Address/Address.tsx deleted file mode 100644 index 5ac85452d..000000000 --- a/liquidity/ui/src/components/Address/Address.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import { CopyIcon, ExternalLinkIcon } from '@chakra-ui/icons'; -import { Flex, Tooltip } from '@chakra-ui/react'; -import { etherscanLink } from '@snx-v3/etherscanLink'; -import { prettyString } from '@snx-v3/format'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { FC, useMemo } from 'react'; - -interface AddressProps { - address: string; -} - -export const Address: FC = ({ address }) => { - const { network } = useNetwork(); - const link = useMemo( - () => - etherscanLink({ - chain: network?.name || '', - address, - }), - [address, network?.name] - ); - return ( - - {prettyString(address)} - { - navigator.clipboard.writeText(address); - }} - cursor="pointer" - _hover={{ - color: 'cyan', - }} - /> - - - - - ); -}; diff --git a/liquidity/ui/src/components/Address/index.ts b/liquidity/ui/src/components/Address/index.ts deleted file mode 100644 index 48615dc14..000000000 --- a/liquidity/ui/src/components/Address/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './Address'; diff --git a/liquidity/ui/src/components/Assets/AssetTable/AssetRowLoading.tsx b/liquidity/ui/src/components/Assets/AssetTable/AssetRowLoading.tsx deleted file mode 100644 index 77040517c..000000000 --- a/liquidity/ui/src/components/Assets/AssetTable/AssetRowLoading.tsx +++ /dev/null @@ -1,90 +0,0 @@ -import { Tr, Td, Flex, Button, Text } from '@chakra-ui/react'; -import { SynthSkeleton as Skeleton, SynthCircle as SkeletonCircle } from '../../SynthSkeleton'; -import { TokenIcon } from '../../TokenIcon'; - -export const AssetRowLoading = ({ final }: { final?: boolean }) => { - return ( - - - - - - - - - - SNX - - - - - Synthetix Network Token - - - - - - - - - - $1,500.00 - - - - - 750.00 SNX - - - - - - - - - $2,000.00 - - - - - 1,000.00 SNX - - - - - - - - - $2,000.00 - - - - - 1,000.00 SNX - - - - - - - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Assets/AssetTable/AssetTableHeader.tsx b/liquidity/ui/src/components/Assets/AssetTable/AssetTableHeader.tsx deleted file mode 100644 index a44cb46b8..000000000 --- a/liquidity/ui/src/components/Assets/AssetTable/AssetTableHeader.tsx +++ /dev/null @@ -1,101 +0,0 @@ -import { InfoIcon } from '@chakra-ui/icons'; -import { Thead, Tr, Th, Flex, Text } from '@chakra-ui/react'; -import { Tooltip } from '@snx-v3/Tooltip'; - -export const AssetTableHeader = () => { - return ( - - - - Asset - - - - - Wallet Balance{' '} - - - - Wallet Balance: - - - Assets currently in your Wallet that can be deposited in your Synthetix Account. - - - Note: Assets on your Account will not show on your Wallet. - - - } - > - - - - - - - - Account Available - - - - Account Available: - - - Assets deposited in your Synthetix Account. These assets are available to be - locked in a pool. - - - } - > - - - - - - - - Locked - - - - Locked Assets: - - - Assets used as collateral in a Position. - - - } - > - - - - - - {' '} - - - - ); -}; diff --git a/liquidity/ui/src/components/Assets/AssetTable/AssetsEmpty.tsx b/liquidity/ui/src/components/Assets/AssetTable/AssetsEmpty.tsx deleted file mode 100644 index d017372a9..000000000 --- a/liquidity/ui/src/components/Assets/AssetTable/AssetsEmpty.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { Flex, Text } from '@chakra-ui/react'; - -export const AssetsEmpty = () => { - return ( - - - No collateral configured for this chain. - - - ); -}; diff --git a/liquidity/ui/src/components/Assets/AssetTable/AssetsRow.tsx b/liquidity/ui/src/components/Assets/AssetTable/AssetsRow.tsx deleted file mode 100644 index f1115d2a9..000000000 --- a/liquidity/ui/src/components/Assets/AssetTable/AssetsRow.tsx +++ /dev/null @@ -1,187 +0,0 @@ -import { Flex, Td, Tr, Text, Button, Fade, useDisclosure } from '@chakra-ui/react'; -import { TokenIcon } from '../../TokenIcon'; -import { formatNumberToUsd, formatNumber } from '@snx-v3/formatters'; -import Wei from '@synthetixio/wei'; -import { Tooltip } from '@snx-v3/Tooltip'; -import { generatePath, useNavigate, useSearchParams } from 'react-router-dom'; -import { useTimer } from 'react-timer-hook'; -import { useWallet } from '@snx-v3/useBlockchain'; - -interface AssetsRowProps { - token: string; - name: string; - walletBalance: number; - walletBalance$: number; - accountBalance: Wei; - accountBalance$: number; - lockedBalance: number; - lockedBalance$: number; - unlockDate?: Date; - final: boolean; // Used for hiding bottom border -} - -export const AssetsRow = ({ - token, - name, - walletBalance, - walletBalance$, - accountBalance, - accountBalance$, - lockedBalance, - lockedBalance$, - unlockDate, - final, -}: AssetsRowProps) => { - const { connect, activeWallet } = useWallet(); - const { onOpen } = useDisclosure(); - const navigate = useNavigate(); - const [queryParams] = useSearchParams(); - const { minutes, hours, isRunning } = useTimer({ - expiryTimestamp: unlockDate || new Date(0), - autoStart: unlockDate && new Date().getTime() < unlockDate?.getTime(), - }); - - return ( - - - - - - - - {token} - - - {name} - - - - - - - - - - {formatNumberToUsd(walletBalance$)} - - - {formatNumber(walletBalance)} - {` ${token}`} - - - - - - - - - {formatNumberToUsd(accountBalance$)} - - - {formatNumber(accountBalance.toNumber())} - {` ${token}`} - - - - - - - - - {formatNumberToUsd(lockedBalance$)} - - - {formatNumber(lockedBalance)} - {` ${token}`} - - - - - - - {/* TODO: Update when multiple pools for LPing available */} - - - - - - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Assets/AssetTable/AssetsTable.tsx b/liquidity/ui/src/components/Assets/AssetTable/AssetsTable.tsx deleted file mode 100644 index 4923f77c3..000000000 --- a/liquidity/ui/src/components/Assets/AssetTable/AssetsTable.tsx +++ /dev/null @@ -1,129 +0,0 @@ -import { InfoIcon } from '@chakra-ui/icons'; -import { - TableContainer, - Table, - Heading, - Flex, - Tbody, - Td, - Tr, - Text, - Button, -} from '@chakra-ui/react'; -import { AssetsRow } from './AssetsRow'; -import { AssetTableHeader } from './AssetTableHeader'; -import { useWallet } from '@snx-v3/useBlockchain'; -import { AssetRowLoading, AssetsEmpty } from '.'; -import { Asset } from '../../../utils/assets'; -import { Tooltip } from '@snx-v3/Tooltip'; - -interface AssetsTableProps { - isLoading: boolean; - assets?: Asset[]; - unlockDate: Date | undefined; -} - -export const AssetsTable = ({ isLoading, assets, unlockDate }: AssetsTableProps) => { - const { activeWallet, connect } = useWallet(); - - return ( - - - - Assets - - - - Assets: - - - All assets used on Synthetix Protocol. As a security precaution, all assets can only - be withdrawn to your wallet after 24hs since your previous account activity - - - } - p="3" - > - - - - {/* Not connected state */} - {!activeWallet?.address ? ( - - - Please connect wallet to view assets - - - - ) : // Empty State - assets && assets.length === 0 && !isLoading ? ( - - ) : ( - - - - - - {isLoading || !assets ? ( - <> - - - - ) : ( - <> - {assets?.map((asset, index) => { - const { collateral, balance, price } = asset; - - return ( - - ); - })} - - )} - -
- - - - -
- )} -
- ); -}; diff --git a/liquidity/ui/src/components/Assets/AssetTable/index.tsx b/liquidity/ui/src/components/Assets/AssetTable/index.tsx deleted file mode 100644 index 5af42d5eb..000000000 --- a/liquidity/ui/src/components/Assets/AssetTable/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -export * from './AssetsTable'; -export * from './AssetsRow'; -export * from './AssetTableHeader'; -export * from './AssetRowLoading'; -export * from './AssetsEmpty'; diff --git a/liquidity/ui/src/components/Assets/AssetsList.tsx b/liquidity/ui/src/components/Assets/AssetsList.tsx deleted file mode 100644 index 94eb91a15..000000000 --- a/liquidity/ui/src/components/Assets/AssetsList.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import { useMemo } from 'react'; -import { useAccountCollateral } from '@snx-v3/useAccountCollateral'; -import { useCollateralPrices } from '@snx-v3/useCollateralPrices'; -import { useTokenBalances } from '@snx-v3/useTokenBalance'; -import { useSearchParams } from 'react-router-dom'; -import { AssetsTable } from './AssetTable'; -import { calculateAssets } from '../../utils/assets'; -import { useCollateralTypes } from '@snx-v3/useCollateralTypes'; -import { useAccountCollateralUnlockDate } from '@snx-v3/useAccountCollateralUnlockDate'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useGetUSDTokens } from '@snx-v3/useGetUSDTokens'; -import { useSystemToken } from '@snx-v3/useSystemToken'; - -export const AssetsList = () => { - const [params] = useSearchParams(); - const { network } = useNetwork(); - const accountId = params.get('accountId') || undefined; - - const { data: accountCollaterals, isLoading: isAccountCollateralsLoading } = useAccountCollateral( - { - accountId, - } - ); - const { data: usdTokens } = useGetUSDTokens(); - - const collateralAddresses = - isBaseAndromeda(network?.id, network?.preset) && usdTokens?.USDC - ? accountCollaterals - ? accountCollaterals - ?.map((collateral) => collateral.tokenAddress) - .concat(usdTokens?.USDC) || [] - : [usdTokens?.USDC] - : accountCollaterals?.map((collateral) => collateral.tokenAddress) || []; - - const { data: userTokenBalances, isLoading: tokenBalancesIsLoading } = useTokenBalances( - collateralAddresses.filter((a) => !!a) - ); - - const associatedUserBalances = userTokenBalances?.map((balance, index) => { - return { - balance, - tokenAddress: collateralAddresses[index], - }; - }); - - const { data: collateralPrices, isLoading: isCollateralPricesLoading } = useCollateralPrices(); - - const { data: collateralTypes, isLoading: isCollateralTypesLoading } = useCollateralTypes(); - - const { data: accountCollateralUnlockDate, isLoading: isAccountCollateralDateLoading } = - useAccountCollateralUnlockDate({ - accountId, - }); - - const combinedCollateral = useMemo(() => { - return accountCollaterals && - accountCollaterals[0] && - isBaseAndromeda(network?.id, network?.preset) - ? [ - accountCollaterals?.reduce((cur, prev, index) => { - //ignore the first iteration cause we are starting witht the first index of the - // array as a default - if (!index) return cur; - return { - ...cur, - availableCollateral: cur.availableCollateral.add(prev.availableCollateral), - }; - }, accountCollaterals[0]), - ] - : accountCollaterals; - }, [accountCollaterals, network?.id, network?.preset]); - - const isBase = isBaseAndromeda(network?.id, network?.preset); - - const { data: systemToken } = useSystemToken(); - const assets = useMemo( - () => - calculateAssets( - combinedCollateral, - associatedUserBalances, - collateralPrices, - collateralTypes, - isBase, - usdTokens?.USDC, - systemToken - ), - [ - combinedCollateral, - associatedUserBalances, - collateralPrices, - collateralTypes, - isBase, - usdTokens?.USDC, - systemToken, - ] - ); - - const isLoading = - isAccountCollateralsLoading || - tokenBalancesIsLoading || - isCollateralPricesLoading || - isCollateralTypesLoading || - isAccountCollateralDateLoading; - - return ( - - ); -}; diff --git a/liquidity/ui/src/components/Assets/index.tsx b/liquidity/ui/src/components/Assets/index.tsx deleted file mode 100644 index 2f04af403..000000000 --- a/liquidity/ui/src/components/Assets/index.tsx +++ /dev/null @@ -1 +0,0 @@ -export * from './AssetsList'; diff --git a/liquidity/ui/src/components/Balance/Balance.tsx b/liquidity/ui/src/components/Balance/Balance.tsx deleted file mode 100644 index 377cad6be..000000000 --- a/liquidity/ui/src/components/Balance/Balance.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { Flex, Text } from '@chakra-ui/react'; -import { TokenIcon } from '../TokenIcon'; -import Wei from '@synthetixio/wei'; - -interface BalanceProps { - isBase: boolean; - balance?: Wei; -} - -export const Balance = ({ isBase, balance }: BalanceProps) => { - return ( - <> - {balance && ( - - - - {balance?.toNumber().toFixed(2)} - - - )} - - ); -}; diff --git a/liquidity/ui/src/components/Balance/index.ts b/liquidity/ui/src/components/Balance/index.ts deleted file mode 100644 index de9bb0894..000000000 --- a/liquidity/ui/src/components/Balance/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './Balance'; diff --git a/liquidity/ui/src/components/Borrow/Borrow.tsx b/liquidity/ui/src/components/Borrow/Borrow.tsx deleted file mode 100644 index 23c4d4de2..000000000 --- a/liquidity/ui/src/components/Borrow/Borrow.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import { Alert, AlertIcon, Button, Collapse, Flex, Text } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { DollarCircle } from '@snx-v3/icons'; -import { SUSDCIcon } from '@snx-v3/icons/SUSDCIcon'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { NumberInput } from '@snx-v3/NumberInput'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { useParams } from '@snx-v3/useParams'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { validatePosition } from '@snx-v3/validatePosition'; -import { wei } from '@synthetixio/wei'; -import { useContext } from 'react'; -import { ZEROWEI } from '@snx-v3/constants'; - -export const Borrow = ({ liquidityPosition }: { liquidityPosition?: LiquidityPosition }) => { - const params = useParams(); - const { network } = useNetwork(); - const { data: systemToken } = useSystemToken(); - - const isBase = isBaseAndromeda(network?.id, network?.preset); - - const { debtChange, collateralChange, setDebtChange } = useContext(ManagePositionContext); - - const { data: collateralType } = useCollateralType(params.collateralSymbol); - - const { maxDebt: actualMaxDebt } = validatePosition({ - issuanceRatioD18: collateralType?.issuanceRatioD18, - collateralAmount: liquidityPosition?.collateralAmount, - collateralPrice: liquidityPosition?.collateralPrice, - debt: liquidityPosition?.debt, - collateralChange: collateralChange, - debtChange: debtChange, - }); - - const maxDebt = wei(actualMaxDebt.toBN().sub(1)); - const symbol = isBase ? params.collateralSymbol : systemToken?.symbol; - - return ( - - - {isBase ? 'Claim' : 'Borrow'} - - - - - {isBase ? : } - {symbol} - - - setDebtChange(val)} - max={maxDebt} - min={ZEROWEI} - /> - - { - if (!maxDebt) { - return; - } - setDebtChange(maxDebt); - }} - > - Max: - {isBase ? 'USDC' : systemToken?.symbol} - - - - - - - - - - As a security precaution, borrowed assets can only be withdrawn to your wallet after 24 - hs since your previous account activity. - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Borrow/index.ts b/liquidity/ui/src/components/Borrow/index.ts deleted file mode 100644 index 44b8c9263..000000000 --- a/liquidity/ui/src/components/Borrow/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './Borrow'; diff --git a/liquidity/ui/src/components/CRatioBar/CRatioAmount.tsx b/liquidity/ui/src/components/CRatioBar/CRatioAmount.tsx deleted file mode 100644 index 73f3fea59..000000000 --- a/liquidity/ui/src/components/CRatioBar/CRatioAmount.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { FC } from 'react'; -import { ratioIsMaxUInt } from './CRatioBar.utils'; -import { Amount } from '@snx-v3/Amount'; -import { wei } from '@synthetixio/wei'; - -export const CRatioAmount: FC<{ - value: number; -}> = ({ value }) => { - if (!value || value < 0) { - return <>N/A; - } - - if (ratioIsMaxUInt(value)) { - return <>Infinite; - } - - return ; -}; diff --git a/liquidity/ui/src/components/CRatioBar/CRatioBadge.tsx b/liquidity/ui/src/components/CRatioBar/CRatioBadge.tsx deleted file mode 100644 index 6f04de11e..000000000 --- a/liquidity/ui/src/components/CRatioBar/CRatioBadge.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { Badge } from '@chakra-ui/react'; -import { FC } from 'react'; -import { getHealthVariant } from './CRatioBar.utils'; - -const badgeColors = { - success: { - colorScheme: 'green', - bg: 'green.900', - label: 'HEALTHY', - }, - error: { - colorScheme: 'red', - bg: 'red.900', - label: 'Unhealthy', - }, - warning: { - colorScheme: 'orange', - bg: 'orange.900', - label: 'MANAGE', - }, -}; - -export const CRatioBadge: FC<{ - liquidationCratio: number; - targetCratio: number; - cRatio: number; -}> = ({ liquidationCratio, targetCratio, cRatio }) => { - const variant = getHealthVariant({ - targetCratio, - liquidationCratio, - cRatio, - }); - return ( - - {badgeColors[variant].label} - - ); -}; diff --git a/liquidity/ui/src/components/CRatioBar/CRatioBar.tsx b/liquidity/ui/src/components/CRatioBar/CRatioBar.tsx deleted file mode 100644 index 20d7313dd..000000000 --- a/liquidity/ui/src/components/CRatioBar/CRatioBar.tsx +++ /dev/null @@ -1,205 +0,0 @@ -import { TriangleDownIcon, TriangleUpIcon, InfoIcon } from '@chakra-ui/icons'; -import { Box, Flex, Progress, Skeleton, Text, Tooltip } from '@chakra-ui/react'; -import { FC } from 'react'; -import { LineWithText } from './LineWithText'; -import { getHealthVariant, getProgressSize, ratioIsMaxUInt } from './CRatioBar.utils'; -import { CRatioBadge } from './CRatioBadge'; -import { CRatioAmount } from './CRatioAmount'; - -export const CRatioBarUi: FC<{ - liquidationCratio: number; - targetCratio: number; - currentCRatio: number; - newCratio?: number; - isLoading: boolean; - hasChanges: boolean; -}> = ({ targetCratio, liquidationCratio, currentCRatio, newCratio, isLoading, hasChanges }) => { - const variant = hasChanges - ? getHealthVariant({ - targetCratio: targetCratio, - liquidationCratio: liquidationCratio, - cRatio: newCratio, - }) - : getHealthVariant({ - targetCratio: targetCratio, - liquidationCratio: liquidationCratio, - cRatio: currentCRatio, - }); - - const newBarSize = getProgressSize({ - cRatio: newCratio, - targetCratio: targetCratio, - liquidationCratio: liquidationCratio, - }); - - const currentBarSize = getProgressSize({ - cRatio: currentCRatio, - targetCratio: targetCratio, - liquidationCratio: liquidationCratio, - }); - - return ( - - - C-Ratio{' '} - - - - - - - - {!!hasChanges && ( - <> - - - {!newCratio || newCratio < 0 - ? 'N/A' - : ratioIsMaxUInt(newCratio) - ? 'Infinite' - : `${newCratio.toFixed(2)} %`} - - - )} - - {(hasChanges ? newCratio || 0 : currentCRatio) !== 0 && ( - - )} - - - - <> - - - - - = 100 && newBarSize > 100) - ? `update-${variant}` - : variant - } - top={0} - bottom={0} - height="12px" - position="absolute" - margin="auto" - left="0" - width="100%" - value={Math.min(newBarSize, currentBarSize)} - /> - = newBarSize ? `update-${variant}` : variant} - top={0} - bottom={0} - height="12px" - position="absolute" - margin="auto" - width="100%" - left={`${Math.min(newBarSize, currentBarSize)}%`} - display={newCratio === 0 ? 'none' : 'block'} - value={Math.abs(newBarSize - currentBarSize)} - /> - - - {currentCRatio > 0 && !isLoading && ( - <> - - - - )} - - - - ); -}; - -export const CRatioBar: FC<{ - liquidationCratio?: number; - targetCratio?: number; - currentCRatio?: number; - newCratio?: number; - isLoading: boolean; - hasChanges: boolean; -}> = ({ newCratio, currentCRatio, targetCratio, liquidationCratio, isLoading, hasChanges }) => { - return ( - - ); -}; diff --git a/liquidity/ui/src/components/CRatioBar/CRatioBar.utils.ts b/liquidity/ui/src/components/CRatioBar/CRatioBar.utils.ts deleted file mode 100644 index 5528079b3..000000000 --- a/liquidity/ui/src/components/CRatioBar/CRatioBar.utils.ts +++ /dev/null @@ -1,53 +0,0 @@ -export const getHealthVariant = ({ - targetCratio, - liquidationCratio, - cRatio, -}: { - liquidationCratio: number | undefined; - targetCratio: number | undefined; - cRatio: number | undefined; -}) => { - if (!liquidationCratio || !targetCratio || !cRatio) { - return 'success'; - } - if (cRatio <= 0) { - return 'success'; - } - if (cRatio < liquidationCratio) { - return 'error'; - } - if (cRatio < targetCratio) { - return 'warning'; - } - return 'success'; -}; - -export const ratioIsMaxUInt = (ratio: number) => ratio >= Number.MAX_SAFE_INTEGER; - -export const getProgressSize = ({ - targetCratio, - liquidationCratio, - cRatio, -}: { - liquidationCratio: number | undefined; - targetCratio: number | undefined; - cRatio: number | undefined; -}) => { - if (!liquidationCratio || !targetCratio || !cRatio) { - return 0; - } - - if (cRatio < 0) { - return 0; - } - - if (cRatio >= targetCratio) { - return 75 + (25 * (cRatio - targetCratio)) / liquidationCratio; - } - - if (cRatio >= liquidationCratio) { - return 25 + (50 * (cRatio - liquidationCratio)) / (targetCratio - liquidationCratio); - } - - return (25 * cRatio) / liquidationCratio; -}; diff --git a/liquidity/ui/src/components/CRatioBar/CRatioChangeStat.tsx b/liquidity/ui/src/components/CRatioBar/CRatioChangeStat.tsx deleted file mode 100644 index 3e9494403..000000000 --- a/liquidity/ui/src/components/CRatioBar/CRatioChangeStat.tsx +++ /dev/null @@ -1,59 +0,0 @@ -import { Text, Flex } from '@chakra-ui/react'; -import { FC } from 'react'; -import Wei from '@synthetixio/wei'; -import { calculateCRatio } from '@snx-v3/calculations'; -import { Amount } from '@snx-v3/Amount'; -import { ZEROWEI } from '@snx-v3/constants'; - -export const CRatioChangeStat: FC<{ - collateralChange: Wei; - currentCollateral?: Wei; - debtChange: Wei; - currentDebt?: Wei; - size?: 'sm' | 'lg'; - collateralPrice?: Wei; -}> = ({ size, currentCollateral, currentDebt, collateralChange, debtChange, collateralPrice }) => ( - - - {!currentCollateral || !currentDebt ? ( - ' N/A' - ) : currentCollateral.gt(0) && currentDebt.eq(0) ? ( - 'Infinite' - ) : ( - - )} - - - {(!collateralChange?.eq(0) || !debtChange.eq(0)) && ( - <> - - - - {(currentCollateral || ZEROWEI).add(collateralChange).gt(0) && - (currentDebt || ZEROWEI).add(debtChange).eq(0) ? ( - 'Infinite' - ) : ( - - )} - - - )} - -); diff --git a/liquidity/ui/src/components/CRatioBar/LineWithText.tsx b/liquidity/ui/src/components/CRatioBar/LineWithText.tsx deleted file mode 100644 index 0f14a746c..000000000 --- a/liquidity/ui/src/components/CRatioBar/LineWithText.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { InfoIcon } from '@chakra-ui/icons'; -import { Box, Tooltip, Text } from '@chakra-ui/react'; -import { FC } from 'react'; - -export const LineWithText: FC<{ - left: string; - text: string; - tooltipText: string; -}> = ({ left, text, tooltipText }) => { - return ( - <> - - - {text}{' '} - - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/ChangeStat/ChangeStat.tsx b/liquidity/ui/src/components/ChangeStat/ChangeStat.tsx deleted file mode 100644 index 767382aed..000000000 --- a/liquidity/ui/src/components/ChangeStat/ChangeStat.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { FC, ReactNode } from 'react'; -import { Flex, Text } from '@chakra-ui/react'; -import Wei from '@synthetixio/wei'; -import { ArrowForwardIcon } from '@chakra-ui/icons'; - -const styles = { - sm: { - fontSize: '12px', - fontWeight: '700', - lineHeight: '14px', - }, - md: { - fontSize: '16px', - fontWeight: '400', - lineHeight: '16px', - }, - lg: { - fontSize: '18px', - fontWeight: '800', - lineHeight: '32px', - }, -}; -export const ChangeStat: FC<{ - value: Wei; - newValue: Wei; - hasChanges: boolean; - dataTestId?: string; - formatFn: (val: Wei) => ReactNode; - withColor?: boolean; - size?: 'sm' | 'md' | 'lg'; -}> = ({ formatFn, value, newValue, hasChanges, dataTestId, withColor, size = 'lg' }) => { - return ( - - - {formatFn(value)} - - {hasChanges && !value.eq(newValue) ? ( - <> - - - {formatFn(newValue)} - - - ) : null} - - ); -}; diff --git a/liquidity/ui/src/components/ChangeStat/index.tsx b/liquidity/ui/src/components/ChangeStat/index.tsx deleted file mode 100644 index b1e112131..000000000 --- a/liquidity/ui/src/components/ChangeStat/index.tsx +++ /dev/null @@ -1 +0,0 @@ -export * from './ChangeStat'; diff --git a/liquidity/ui/src/components/Claim/Claim.tsx b/liquidity/ui/src/components/Claim/Claim.tsx deleted file mode 100644 index 82c0db241..000000000 --- a/liquidity/ui/src/components/Claim/Claim.tsx +++ /dev/null @@ -1,197 +0,0 @@ -import { Alert, AlertIcon, Box, Button, Collapse, Flex, Text } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { NumberInput } from '@snx-v3/NumberInput'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { FC, useContext, useMemo } from 'react'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import Wei, { wei } from '@synthetixio/wei'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ZEROWEI } from '@snx-v3/constants'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { TokenIcon } from '../TokenIcon'; -import { validatePosition } from '@snx-v3/validatePosition'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { useParams } from 'react-router-dom'; -import { useTokenPrice } from '@snx-v3/useTokenPrice'; - -const ClaimUi: FC<{ - maxClaimble: Wei; - maxDebt: Wei; - debtChange: Wei; - setDebtChange: (val: Wei) => void; - collateralSymbol: string; -}> = ({ collateralSymbol, maxDebt, debtChange, setDebtChange, maxClaimble }) => { - const { network } = useNetwork(); - const isBase = isBaseAndromeda(network?.id, network?.preset); - const { data: systemToken } = useSystemToken(); - const max = useMemo(() => maxClaimble.add(maxDebt), [maxClaimble, maxDebt]); - const symbol = isBase ? collateralSymbol : systemToken?.symbol; - const price = useTokenPrice(symbol); - - return ( - - - Claim{isBase ? ' Profit' : '/Borrow'} - - - - - - - {symbol} - - - - Credit: - - {maxClaimble?.gt(0) && ( - { - if (!maxClaimble) { - return; - } - setDebtChange(maxClaimble); - }} - color="cyan.500" - fontWeight={700} - > -  Max - - )} - - - - setDebtChange(val)} - max={max} - min={ZEROWEI} - /> - - {price.gt(0) && } - - - - - - - - Positive market performance has credited your position. Claim up to{' '} - { - if (!maxClaimble) { - return; - } - setDebtChange(maxClaimble); - }} - cursor="pointer" - as="span" - textDecoration="underline" - > - - -  without accruing debt. - - - - - - - - Assets will be available to withdraw 24 hours after your last interaction with this - position. - - - - - - - - You can take an interest-free loan up to   - { - if (!maxDebt) { - return; - } - setDebtChange(maxDebt.add(maxClaimble)); - }} - cursor="pointer" - as="span" - textDecoration="underline" - > - - - - - - - - - - You are about to take a {' '} - interest-free loan - - - - - - ); -}; - -export const Claim = ({ liquidityPosition }: { liquidityPosition?: LiquidityPosition }) => { - const { network } = useNetwork(); - const { debtChange, collateralChange, setDebtChange } = useContext(ManagePositionContext); - const { collateralSymbol } = useParams(); - - const maxClaimble = useMemo(() => { - if (!liquidityPosition || liquidityPosition?.debt.gte(0)) { - return ZEROWEI; - } else { - return wei(liquidityPosition.debt.abs().toBN().mul(99).div(100)); - } - }, [liquidityPosition]); - - const { data: collateralType } = useCollateralType(collateralSymbol); - - const { maxDebt } = validatePosition({ - issuanceRatioD18: collateralType?.issuanceRatioD18, - collateralAmount: liquidityPosition?.collateralAmount, - collateralPrice: liquidityPosition?.collateralPrice, - debt: liquidityPosition?.debt, - collateralChange: collateralChange, - debtChange: debtChange, - }); - - return ( - - ); -}; diff --git a/liquidity/ui/src/components/Claim/index.ts b/liquidity/ui/src/components/Claim/index.ts deleted file mode 100644 index 69525d324..000000000 --- a/liquidity/ui/src/components/Claim/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './Claim'; diff --git a/liquidity/ui/src/components/ClosePosition/ClosePosition.tsx b/liquidity/ui/src/components/ClosePosition/ClosePosition.tsx deleted file mode 100644 index 20baa32e5..000000000 --- a/liquidity/ui/src/components/ClosePosition/ClosePosition.tsx +++ /dev/null @@ -1,160 +0,0 @@ -import { ArrowBackIcon } from '@chakra-ui/icons'; -import { Button, Divider, Flex, Text } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { NumberInput } from '@snx-v3/NumberInput'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { useTokenPrice } from '@snx-v3/useTokenPrice'; -import Wei from '@synthetixio/wei'; -import { FC, useContext, useEffect, useState } from 'react'; -import { useParams } from 'react-router-dom'; -import { ZEROWEI } from '@snx-v3/constants'; -import { TokenIcon } from '../TokenIcon'; -import { ClosePositionTransactions } from './ClosePositionTransactions'; - -const ClosePositionUi: FC<{ - debt: Wei; - collateralAmount: Wei; - onClose: () => void; - onSubmit: () => void; - debtSymbol?: string; - collateralSymbol: string; -}> = ({ onSubmit, debt, collateralAmount, collateralSymbol, onClose, debtSymbol }) => { - const debtPrice = useTokenPrice(debtSymbol); - const collateralPrice = useTokenPrice(collateralSymbol); - - return ( - - - - Close Position - - - - - - {debt.gt(0) ? 'Repay Debt' : 'Claim Profit'} - - - - - - - - {debtSymbol} - - - - {debt.gt(0) ? 'Debt:' : 'Max Claim'} - - - Max - - - - - - - {debtPrice.gt(0) && } - - - - - - - Unlock Collateral - - - - - - - - {collateralSymbol} - - - - Locked: - - - Max - - - - - - - {collateralPrice.gt(0) && ( - - )} - - - - - - - ); -}; - -export const ClosePosition = ({ - liquidityPosition, - onClose, -}: { - liquidityPosition?: LiquidityPosition; - onClose: () => void; -}) => { - const [transactionStep, setTransactions] = useState(false); - const { setCollateralChange, setDebtChange } = useContext(ManagePositionContext); - const params = useParams(); - const { data: collateralType } = useCollateralType(params.collateralSymbol); - const { network } = useNetwork(); - const isBase = isBaseAndromeda(network?.id, network?.preset); - const { data: systemToken } = useSystemToken(); - - useEffect(() => { - if (liquidityPosition) { - setDebtChange(liquidityPosition.debt.mul(-1)); - setCollateralChange(liquidityPosition.collateralAmount.mul(-1)); - } - - return () => { - setDebtChange(ZEROWEI); - setCollateralChange(ZEROWEI); - }; - }, [liquidityPosition, setCollateralChange, setDebtChange]); - - if (!collateralType) { - return null; - } - - return ( - <> - {!transactionStep && ( - setTransactions(true)} - /> - )} - {transactionStep && ( - setTransactions(false)} - onClose={onClose} - collateralType={collateralType} - liquidityPosition={liquidityPosition} - poolId={params.poolId} - /> - )} - - ); -}; diff --git a/liquidity/ui/src/components/ClosePosition/ClosePositionTransactions.tsx b/liquidity/ui/src/components/ClosePosition/ClosePositionTransactions.tsx deleted file mode 100644 index 1c0e77378..000000000 --- a/liquidity/ui/src/components/ClosePosition/ClosePositionTransactions.tsx +++ /dev/null @@ -1,373 +0,0 @@ -import { ArrowBackIcon } from '@chakra-ui/icons'; -import { Button, Divider, Flex, Link, Skeleton, Text, useToast } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { ContractError } from '@snx-v3/ContractError'; -import { parseUnits } from '@snx-v3/format'; -import { getRepayerContract, getSpotMarketId, isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { Multistep } from '@snx-v3/Multistep'; -import { useApprove } from '@snx-v3/useApprove'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useBorrow } from '@snx-v3/useBorrow'; -import { CollateralType } from '@snx-v3/useCollateralTypes'; -import { useContractErrorParser } from '@snx-v3/useContractErrorParser'; -import { useCoreProxy } from '@snx-v3/useCoreProxy'; -import { useGetWrapperToken } from '@snx-v3/useGetUSDTokens'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { useRepay } from '@snx-v3/useRepay'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { useTokenBalance } from '@snx-v3/useTokenBalance'; -import { useUndelegate } from '@snx-v3/useUndelegate'; -import { useUndelegateBaseAndromeda } from '@snx-v3/useUndelegateBaseAndromeda'; -import { useQueryClient } from '@tanstack/react-query'; -import { FC, ReactNode, useCallback, useContext, useEffect, useState } from 'react'; -import { ZEROWEI } from '@snx-v3/constants'; -import { LiquidityPositionUpdated } from '../Manage/LiquidityPositionUpdated'; - -export const ClosePositionTransactions: FC<{ - onClose: () => void; - onBack: () => void; - poolId: string | undefined; - liquidityPosition: LiquidityPosition | undefined; - collateralType: CollateralType; -}> = ({ collateralType, liquidityPosition, poolId, onClose, onBack }) => { - const [steps, setSteps] = useState< - { - title: ReactNode; - subtitle?: ReactNode; - cb: () => Promise; - }[] - >([]); - const { setCollateralChange, setDebtChange } = useContext(ManagePositionContext); - const { data: systemToken } = useSystemToken(); - const { data: balance } = useTokenBalance(systemToken?.address); - const { data: CoreProxy } = useCoreProxy(); - const { network } = useNetwork(); - const toast = useToast({ isClosable: true, duration: 9000 }); - const isBase = isBaseAndromeda(network?.id, network?.preset); - - const debtSymbol = isBase ? collateralType.symbol : systemToken?.symbol; - const collateralSymbol = collateralType.displaySymbol; - - const [txState, setTxState] = useState({ - step: 0, - status: 'idle', - }); - - const { data: wrapperToken } = useGetWrapperToken( - getSpotMarketId(liquidityPosition?.accountCollateral.symbol) - ); - - const collateralAddress = isBaseAndromeda(network?.id, network?.preset) - ? wrapperToken - : systemToken?.address; - const queryClient = useQueryClient(); - const availableUSDCollateral = liquidityPosition?.usdCollateral.availableCollateral || ZEROWEI; - const amountToDeposit = (liquidityPosition?.debt || ZEROWEI).abs().sub(availableUSDCollateral); - const errorParserCoreProxy = useContractErrorParser(CoreProxy); - - //repay approval - const { approve, requireApproval } = useApprove({ - contractAddress: collateralAddress, - amount: amountToDeposit.gt(0) ? amountToDeposit.toBN() : '0', - spender: CoreProxy?.address, - }); - const { exec: execRepay } = useRepay({ - accountId: liquidityPosition?.accountId, - poolId: poolId, - collateralTypeAddress: collateralType?.tokenAddress, - debtChange: liquidityPosition?.debt.mul(-1) || ZEROWEI, - availableUSDCollateral, - balance, - }); - const { exec: undelegate } = useUndelegate({ - accountId: liquidityPosition?.accountId, - poolId: poolId, - collateralTypeAddress: liquidityPosition?.tokenAddress, - collateralChange: liquidityPosition?.collateralAmount.mul(-1) || ZEROWEI, - currentCollateral: liquidityPosition?.collateralAmount || ZEROWEI, - }); - - //repay approval for base - const { - approve: approveUSDC, - requireApproval: requireApprovalUSDC, - isLoading, - } = useApprove({ - contractAddress: wrapperToken, - //slippage for approval - amount: parseUnits(liquidityPosition?.debt.abs().toString(), 6) - .mul(110) - .div(100), - spender: getRepayerContract(network?.id), - }); - const { exec: undelegateBaseAndromeda } = useUndelegateBaseAndromeda({ - accountId: liquidityPosition?.accountId, - poolId: poolId, - collateralTypeAddress: liquidityPosition?.tokenAddress, - collateralChange: liquidityPosition?.collateralAmount.mul(-1) || ZEROWEI, - currentCollateral: liquidityPosition?.collateralAmount || ZEROWEI, - liquidityPosition, - }); - - //claim - const { exec: execBorrow } = useBorrow({ - accountId: liquidityPosition?.accountId, - poolId: poolId, - collateralTypeAddress: collateralType?.tokenAddress, - debtChange: liquidityPosition?.debt.mul(-1) || ZEROWEI, - }); - - const getSteps = useCallback(() => { - const transactions: { - title: ReactNode; - subtitle?: ReactNode; - cb: () => Promise; - }[] = []; - if (!isBase) { - if (liquidityPosition?.debt.gt(0)) { - if (requireApproval) { - transactions.push({ - title: `Approve ${systemToken?.symbol} transfer`, - cb: () => approve(false), - }); - } - transactions.push({ - title: 'Repay', - subtitle: ( - - Repay{' '} - - - ), - cb: () => execRepay(), - }); - } else if (liquidityPosition?.debt.lt(0)) { - transactions.push({ - title: 'Claim', - subtitle: ( - - Claim{' '} - - - ), - cb: () => execBorrow(), - }); - } - - transactions.push({ - title: 'Unlock collateral', - subtitle: ( - - {' '} - will be unlocked from the pool. - - ), - cb: () => undelegate(), - }); - } else { - if (liquidityPosition?.debt.gt(-0.00001)) { - if (requireApprovalUSDC) { - transactions.push({ - title: `Approve ${debtSymbol} transfer`, - cb: () => approveUSDC(false), - }); - } - } - - transactions.push({ - title: 'Unlock collateral', - subtitle: ( - - {' '} - will be unlocked from the pool. - - ), - cb: () => undelegateBaseAndromeda(), - }); - - if (liquidityPosition?.debt.lt(0)) { - transactions.push({ - title: 'Claim', - subtitle: ( - - Claim - - ), - cb: () => execBorrow(), - }); - } - } - - return transactions; - }, [ - approve, - approveUSDC, - collateralSymbol, - debtSymbol, - execBorrow, - execRepay, - isBase, - liquidityPosition?.collateralAmount, - liquidityPosition?.debt, - requireApproval, - requireApprovalUSDC, - systemToken?.symbol, - undelegate, - undelegateBaseAndromeda, - ]); - - useEffect(() => { - if (!steps.length && !isLoading) { - setTxState({ - step: 0, - status: 'idle', - }); - setSteps(getSteps()); - } - }, [getSteps, isLoading, steps.length]); - - const isSuccess = txState.step >= steps.length; - - const handleSubmit = useCallback(async () => { - try { - let i = txState.step > -1 ? txState.step : 0; - - for (; i < steps.length; i++) { - setTxState({ - step: i, - status: 'pending', - }); - - await steps[i].cb(); - } - - setTxState({ - step: steps.length, - status: 'success', - }); - - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPosition'], - }); - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPositions'], - }); - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'Allowance'], - }); - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'AccountSpecificCollateral'], - }); - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'TokenBalance'], - }); - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'AccountCollateralUnlockDate'], - }); - - setCollateralChange(ZEROWEI); - setDebtChange(ZEROWEI); - } catch (error) { - setTxState((state) => ({ - step: state.step, - status: 'error', - })); - - const contractError = errorParserCoreProxy(error); - - if (contractError) { - console.error(new Error(contractError.name), contractError); - } - toast.closeAll(); - toast({ - title: 'Transaction failed', - variant: 'left-accent', - description: contractError ? ( - - ) : ( - 'Please try again.' - ), - status: 'error', - }); - throw Error('Transaction failed', { cause: error }); - } - }, [ - txState.step, - steps, - queryClient, - network?.id, - network?.preset, - setCollateralChange, - setDebtChange, - errorParserCoreProxy, - toast, - ]); - - if (isSuccess) { - return ( - - Your position has been successfully closed, read more about it in the{' '} - - Synthetix V3 Documentation - - - } - alertText={<>Position successfully Closed} - /> - ); - } - - return ( - - - - Close Position - - - - - {isLoading && !steps.length && } - {steps.map((step, i) => ( - i, - loading: txState.step === i && txState.status === 'pending', - }} - /> - ))} - - - - ); -}; diff --git a/liquidity/ui/src/components/ClosePosition/index.ts b/liquidity/ui/src/components/ClosePosition/index.ts deleted file mode 100644 index dc0dc8965..000000000 --- a/liquidity/ui/src/components/ClosePosition/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '.'; diff --git a/liquidity/ui/src/components/CollateralAlert/CollateralAlert.tsx b/liquidity/ui/src/components/CollateralAlert/CollateralAlert.tsx deleted file mode 100644 index 51a08c851..000000000 --- a/liquidity/ui/src/components/CollateralAlert/CollateralAlert.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import { Alert, AlertIcon, AlertProps, Text } from '@chakra-ui/react'; -import Wei from '@synthetixio/wei'; - -interface CollateralAlertProps extends AlertProps { - tokenBalance: Wei; -} - -export const CollateralAlert = ({ tokenBalance, ...props }: CollateralAlertProps) => { - return ( - - - - You have a {tokenBalance.toString(2)} SNX active staking position on V2. - -  Migrate to V3 - - - - ); -}; diff --git a/liquidity/ui/src/components/CollateralAlert/UnsupportedCollateralAlert.tsx b/liquidity/ui/src/components/CollateralAlert/UnsupportedCollateralAlert.tsx deleted file mode 100644 index b14cfb57c..000000000 --- a/liquidity/ui/src/components/CollateralAlert/UnsupportedCollateralAlert.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { - Modal, - ModalOverlay, - ModalContent, - ModalHeader, - Text, - Divider, - Button, -} from '@chakra-ui/react'; -import { Link } from 'react-router-dom'; - -export const UnsupportedCollateralAlert = ({ isOpen }: { isOpen: boolean }) => { - return ( - {}}> - - - Collateral Not Supported - - - This collateral is not supported on this network. Go back to your dashboard to see your - active positions on this network. - - - - - ); -}; diff --git a/liquidity/ui/src/components/CollateralAlert/index.ts b/liquidity/ui/src/components/CollateralAlert/index.ts deleted file mode 100644 index 24417993c..000000000 --- a/liquidity/ui/src/components/CollateralAlert/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './CollateralAlert'; -export * from './UnsupportedCollateralAlert'; diff --git a/liquidity/ui/src/components/CustomTable/CustomTable.tsx b/liquidity/ui/src/components/CustomTable/CustomTable.tsx deleted file mode 100644 index a5defdbcf..000000000 --- a/liquidity/ui/src/components/CustomTable/CustomTable.tsx +++ /dev/null @@ -1,86 +0,0 @@ -import { Skeleton, Table, TableContainer, Tbody, Td, Text, Thead, Tr } from '@chakra-ui/react'; -import { Fragment, ReactNode } from 'react'; - -interface TableProps { - headerColumns: ReactNode[]; - rows: ReactNode[]; - loadingState: { isLoading: boolean; headerLength: number; numberOfRows: number }; -} - -export function CustomTable({ headerColumns, rows, loadingState }: TableProps) { - const loadingHeader = Array(loadingState.headerLength).fill(1, 0); - const loadingRows = Array(loadingState.numberOfRows).fill(1, 0); - - return ( - - - - {loadingState.isLoading ? ( - - {loadingHeader.map((placeholder, index) => ( - - ))} - - ) : ( - headerColumns.map((column, index) => ( - {column} - )) - )} - - - - {headerColumns.map((_, index) => ( - - {loadingState.isLoading - ? loadingRows.map((row, index) => ( - - {loadingHeader.map((placeholder, index) => ( - - ))} - - )) - : rows.map((row, index) => ( - {row} - ))} - -
- - - sUSDC - - -
- ))} -
- - - sUSDC - - -
-
- ); -} diff --git a/liquidity/ui/src/components/CustomTable/index.ts b/liquidity/ui/src/components/CustomTable/index.ts deleted file mode 100644 index 019981825..000000000 --- a/liquidity/ui/src/components/CustomTable/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './CustomTable'; diff --git a/liquidity/ui/src/components/Deposit/Deposit.tsx b/liquidity/ui/src/components/Deposit/Deposit.tsx deleted file mode 100644 index f7a700431..000000000 --- a/liquidity/ui/src/components/Deposit/Deposit.tsx +++ /dev/null @@ -1,300 +0,0 @@ -import { - Alert, - AlertDescription, - AlertIcon, - Button, - Collapse, - Flex, - Text, - Tooltip, -} from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { NumberInput } from '@snx-v3/NumberInput'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { useEthBalance } from '@snx-v3/useEthBalance'; -import Wei from '@synthetixio/wei'; -import { FC, useContext, useMemo } from 'react'; -import { useParams } from '@snx-v3/useParams'; -import { AccountCollateralType } from '@snx-v3/useAccountCollateral'; -import { useTransferableSynthetix } from '@snx-v3/useTransferableSynthetix'; -import { ChangeStat, CollateralAlert, TokenIcon } from '../'; -import { useTokenBalance } from '@snx-v3/useTokenBalance'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { getSpotMarketId, isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useGetWrapperToken } from '@snx-v3/useGetUSDTokens'; -import { WithdrawIncrease } from '@snx-v3/WithdrawIncrease'; -import { formatNumber } from '@snx-v3/formatters'; -import { ZEROWEI } from '@snx-v3/constants'; -import { useTokenPrice } from '@snx-v3/useTokenPrice'; -import { TransactionSummary } from '../TransactionSummary/TransactionSummary'; -import { currency } from '@snx-v3/format'; -import { CRatioChangeStat } from '../CRatioBar/CRatioChangeStat'; - -export const DepositUi: FC<{ - accountCollateral: AccountCollateralType; - collateralChange: Wei; - ethBalance?: Wei; - snxBalance?: { - transferable: Wei; - collateral?: Wei; - }; - tokenBalance?: Wei; - displaySymbol: string; - symbol: string; - setCollateralChange: (val: Wei) => void; - minDelegation: Wei; - currentCollateral: Wei; - currentDebt: Wei; - collateralPrice: Wei; - isBase: boolean; -}> = ({ - accountCollateral, - collateralChange, - setCollateralChange, - displaySymbol, - symbol, - tokenBalance, - ethBalance, - snxBalance, - minDelegation, - currentCollateral, - currentDebt, - collateralPrice, - isBase, -}) => { - const price = useTokenPrice(symbol); - - const combinedTokenBalance = useMemo(() => { - if (symbol === 'SNX') { - return snxBalance?.transferable || ZEROWEI; - } - if (symbol !== 'WETH') { - return tokenBalance || ZEROWEI; - } - if (!tokenBalance || !ethBalance) { - return ZEROWEI; - } - return tokenBalance.add(ethBalance); - }, [symbol, tokenBalance, ethBalance, snxBalance?.transferable]); - - const maxAmount = useMemo( - () => combinedTokenBalance?.add(accountCollateral.availableCollateral.toString()), - [accountCollateral.availableCollateral, combinedTokenBalance] - ); - - const txSummaryItems = useMemo(() => { - const items = [ - { - label: 'Locked ' + symbol, - value: ( - currency(val)} - hasChanges={collateralChange.abs().gt(0)} - size="sm" - /> - ), - }, - ]; - - if (isBase) { - return items; - } - - return [ - ...items, - { - label: 'C-ratio', - value: ( - - ), - }, - ]; - }, [collateralChange, collateralPrice, currentCollateral, currentDebt, isBase, symbol]); - - const overAvailableBalance = collateralChange.abs().gt(maxAmount); - - return ( - - - Deposit & Lock Collateral - - - - - - - {displaySymbol} - - - - - Unlocked Balance: - - - - Wallet Balance: - - - {symbol === 'WETH' ? ( - - ETH Balance: - - - ) : null} - - } - > - - Balance: - {maxAmount?.gt(0) && ( - { - if (!maxAmount) { - return; - } - setCollateralChange(maxAmount); - }} - color="cyan.500" - fontWeight={700} - > -  Max - - )} - - - - - { - setCollateralChange(value); - }} - max={maxAmount} - min={ZEROWEI} - dataTestId="deposit-number-input" - /> - - {price.gt(0) && } - - - - {snxBalance?.collateral && snxBalance?.collateral.gt(0) && symbol === 'SNX' && ( - - )} - - - - - - - - - Your deposit must be {formatNumber(minDelegation.toString())} {symbol} or higher - - - - - - - - You cannot Deposit & Lock more Collateral than your Balance amount - - - - - - - - - - ); -}; - -export const Deposit = ({ liquidityPosition }: { liquidityPosition?: LiquidityPosition }) => { - const { collateralChange, setCollateralChange } = useContext(ManagePositionContext); - const { network } = useNetwork(); - - const { collateralSymbol } = useParams(); - - const { data: collateralType } = useCollateralType(collateralSymbol); - const { data: transferrableSnx } = useTransferableSynthetix(); - const isBase = isBaseAndromeda(network?.id, network?.preset); - const { data: wrapperToken } = useGetWrapperToken(getSpotMarketId(collateralSymbol)); - - // TODO: This will need refactoring - const balanceAddress = isBase ? wrapperToken : collateralType?.tokenAddress; - - const { data: tokenBalance } = useTokenBalance(balanceAddress); - - const { data: ethBalance } = useEthBalance(); - - if (!collateralType || !liquidityPosition?.accountCollateral) { - return null; - } - - return ( - - ); -}; diff --git a/liquidity/ui/src/components/Deposit/index.ts b/liquidity/ui/src/components/Deposit/index.ts deleted file mode 100644 index b29072b60..000000000 --- a/liquidity/ui/src/components/Deposit/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './Deposit'; diff --git a/liquidity/ui/src/components/InitialDeposit/InitialDeposit.tsx b/liquidity/ui/src/components/InitialDeposit/InitialDeposit.tsx deleted file mode 100644 index 51bf8497f..000000000 --- a/liquidity/ui/src/components/InitialDeposit/InitialDeposit.tsx +++ /dev/null @@ -1,316 +0,0 @@ -import { - Alert, - AlertDescription, - AlertIcon, - Button, - Collapse, - Divider, - Flex, - ListItem, - Text, - Tooltip, - UnorderedList, - Link, -} from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { NumberInput } from '@snx-v3/NumberInput'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { useEthBalance } from '@snx-v3/useEthBalance'; -import Wei from '@synthetixio/wei'; -import { FC, useContext, useMemo, useState } from 'react'; -import { useParams } from '@snx-v3/useParams'; -import { useTransferableSynthetix } from '@snx-v3/useTransferableSynthetix'; -import { TokenIcon } from '..'; -import { useTokenBalance } from '@snx-v3/useTokenBalance'; -import { MAINNET, SEPOLIA, useNetwork } from '@snx-v3/useBlockchain'; -import { getSpotMarketId, isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useGetWrapperToken } from '@snx-v3/useGetUSDTokens'; -import { WithdrawIncrease } from '@snx-v3/WithdrawIncrease'; -import { formatNumber } from '@snx-v3/formatters'; -import { ArrowBackIcon } from '@chakra-ui/icons'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { ZEROWEI } from '@snx-v3/constants'; -import { useTokenPrice } from '@snx-v3/useTokenPrice'; -import { MigrationBanner } from '../Migration/MigrationBanner'; - -export const InitialDepositUi: FC<{ - collateralChange: Wei; - ethBalance?: Wei; - snxBalance?: { - transferable: Wei; - collateral?: Wei; - }; - tokenBalance?: Wei; - displaySymbol: string; - symbol: string; - setCollateralChange: (val: Wei) => void; - onSubmit: () => void; - minDelegation: Wei; - hasAccount: boolean; - availableCollateral: Wei; -}> = ({ - collateralChange, - setCollateralChange, - displaySymbol, - symbol, - tokenBalance, - ethBalance, - snxBalance, - onSubmit, - minDelegation, - hasAccount, - availableCollateral, -}) => { - const [step, setStep] = useState(0); - - const price = useTokenPrice(symbol); - const { network } = useNetwork(); - - const combinedTokenBalance = useMemo(() => { - if (symbol === 'SNX') { - return snxBalance?.transferable || ZEROWEI; - } - if (symbol !== 'WETH') { - return tokenBalance || ZEROWEI; - } - if (!tokenBalance || !ethBalance) { - return ZEROWEI; - } - return tokenBalance.add(ethBalance); - }, [symbol, tokenBalance, ethBalance, snxBalance?.transferable]); - - const maxAmount = useMemo(() => { - return combinedTokenBalance?.add(availableCollateral); - }, [availableCollateral, combinedTokenBalance]); - - const overAvailableBalance = collateralChange.gt(maxAmount); - - return ( - - - {step > 0 && setStep(0)} mr={2} />} - Open Liquidity Position - - - {step === 0 && ( - <> - - Deposit & Lock Collateral - - - - - - - - {displaySymbol} - - - - - Unlocked Balance: - - - - Wallet Balance: - - - {symbol === 'WETH' ? ( - - ETH Balance: - - - ) : null} - - } - > - - Balance: - { - if (!maxAmount) { - return; - } - setCollateralChange(maxAmount); - }} - color="cyan.500" - fontWeight={700} - > -  Max - - - - - - { - setCollateralChange(value); - }} - max={combinedTokenBalance} - dataTestId="deposit-number-input" - min={ZEROWEI} - /> - - {price.gt(0) && } - - - - - {symbol === 'SNX' && network && [MAINNET.id, SEPOLIA.id].includes(network.id) && ( - - )} - - - - - - - - Your deposit must be {formatNumber(minDelegation.toString())} {symbol} or higher - - - - - - - - You cannot Deposit & Lock more Collateral than your Balance amount - - - - - - )} - {step === 1 && ( - <> - - In order to open a position on Synthetix Liquidity, you need an Account. It’s a one time - action needed that you won’t have to reproduce for the next positions. Accounts are - represented as ERC-721 compliant tokens (NFTs). Read more about it in the{' '} - - Synthetix V3 Documentation - - -
- - Transferable like any NFT -
- Improve security by delegating permissions -
- Simplify collaborative liquidity positions management -
- - - )} - - ); -}; - -export const InitialDeposit: FC<{ - submit: () => void; - hasAccount: boolean; - liquidityPosition?: LiquidityPosition; -}> = ({ submit, hasAccount, liquidityPosition }) => { - const { collateralChange, setCollateralChange } = useContext(ManagePositionContext); - const { network } = useNetwork(); - const { collateralSymbol } = useParams(); - - const { data: collateralType } = useCollateralType(collateralSymbol); - - const { data: transferrableSnx } = useTransferableSynthetix(); - - const { data: wrapperToken } = useGetWrapperToken(getSpotMarketId(collateralSymbol)); - // TODO: This will need refactoring - const balanceAddress = isBaseAndromeda(network?.id, network?.preset) - ? wrapperToken - : collateralType?.tokenAddress; - - const { data: tokenBalance } = useTokenBalance(balanceAddress); - - const { data: ethBalance } = useEthBalance(); - - if (!collateralType) return null; - - return ( - - ); -}; diff --git a/liquidity/ui/src/components/InitialDeposit/index.ts b/liquidity/ui/src/components/InitialDeposit/index.ts deleted file mode 100644 index 9fd2e7df0..000000000 --- a/liquidity/ui/src/components/InitialDeposit/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './InitialDeposit'; diff --git a/liquidity/ui/src/components/Manage/ChangeStat.tsx b/liquidity/ui/src/components/Manage/ChangeStat.tsx deleted file mode 100644 index 767382aed..000000000 --- a/liquidity/ui/src/components/Manage/ChangeStat.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { FC, ReactNode } from 'react'; -import { Flex, Text } from '@chakra-ui/react'; -import Wei from '@synthetixio/wei'; -import { ArrowForwardIcon } from '@chakra-ui/icons'; - -const styles = { - sm: { - fontSize: '12px', - fontWeight: '700', - lineHeight: '14px', - }, - md: { - fontSize: '16px', - fontWeight: '400', - lineHeight: '16px', - }, - lg: { - fontSize: '18px', - fontWeight: '800', - lineHeight: '32px', - }, -}; -export const ChangeStat: FC<{ - value: Wei; - newValue: Wei; - hasChanges: boolean; - dataTestId?: string; - formatFn: (val: Wei) => ReactNode; - withColor?: boolean; - size?: 'sm' | 'md' | 'lg'; -}> = ({ formatFn, value, newValue, hasChanges, dataTestId, withColor, size = 'lg' }) => { - return ( - - - {formatFn(value)} - - {hasChanges && !value.eq(newValue) ? ( - <> - - - {formatFn(newValue)} - - - ) : null} - - ); -}; diff --git a/liquidity/ui/src/components/Manage/CollateralStats.tsx b/liquidity/ui/src/components/Manage/CollateralStats.tsx deleted file mode 100644 index 23d3a8184..000000000 --- a/liquidity/ui/src/components/Manage/CollateralStats.tsx +++ /dev/null @@ -1,75 +0,0 @@ -import { Flex, Skeleton, Text } from '@chakra-ui/react'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { FC } from 'react'; -import { currency } from '@snx-v3/format'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { CollateralType } from '@snx-v3/useCollateralTypes'; -import Wei from '@synthetixio/wei'; -import { ZEROWEI } from '@snx-v3/constants'; -import { ChangeStat } from './ChangeStat'; - -export const CollateralStats: FC<{ - liquidityPosition?: LiquidityPosition; - collateralType?: CollateralType; - newCollateralAmount: Wei; - collateralValue: Wei; - hasChanges: boolean; - isLoading?: boolean; -}> = ({ liquidityPosition, collateralType, newCollateralAmount, hasChanges, isLoading }) => ( - - - - - Collateral - - - - {isLoading ? ( - Lorem ipsum (this wont be displaye debt) - ) : liquidityPosition && collateralType ? ( - - `${currency(val)} ${collateralType.displaySymbol}`} - hasChanges={hasChanges} - dataTestId="manage stats collateral" - /> - - currency(val, { - currency: 'USD', - style: 'currency', - }) - } - size="md" - hasChanges={hasChanges} - dataTestId="manage stats collateral" - /> - - ) : ( - - `${currency(val)} ${collateralType?.displaySymbol || ''}`} - hasChanges={hasChanges} - /> - - {currency(ZEROWEI, { - currency: 'USD', - style: 'currency', - })} - - - )} - - - -); diff --git a/liquidity/ui/src/components/Manage/DebtStats.tsx b/liquidity/ui/src/components/Manage/DebtStats.tsx deleted file mode 100644 index ca90a6ee4..000000000 --- a/liquidity/ui/src/components/Manage/DebtStats.tsx +++ /dev/null @@ -1,88 +0,0 @@ -import { InfoIcon } from '@chakra-ui/icons'; -import { Flex, Skeleton, Text, Tooltip } from '@chakra-ui/react'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { FC } from 'react'; -import { currency } from '@snx-v3/format'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { CollateralType } from '@snx-v3/useCollateralTypes'; -import Wei from '@synthetixio/wei'; -import { ZEROWEI } from '@snx-v3/constants'; -import { ChangeStat } from './ChangeStat'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { DebtAmount } from '../Positions/PositionsTable/DebtAmount'; - -export const DebtStats: FC<{ - liquidityPosition?: LiquidityPosition; - collateralType?: CollateralType; - newDebt: Wei; - hasChanges: boolean; - isLoading?: boolean; -}> = ({ liquidityPosition, collateralType, newDebt, hasChanges, isLoading }) => { - const { network } = useNetwork(); - const isBase = isBaseAndromeda(network?.id, network?.preset); - return ( - - - - - Debt - - - Debt consists of: -
- - Your portion of the pool's total debt, which fluctuates based on trader - performance and market conditions -
- The amount you've borrowed against your collateral without incurring - interest - - ) - } - textAlign="start" - py={2} - px={3} - > - - - -
-
- - {isLoading ? ( - Lorem ipsum (this wont be displaye debt) - ) : liquidityPosition && collateralType ? ( - } - hasChanges={hasChanges} - dataTestId="manage-stats-debt-value" - /> - ) : ( - - currency(val, { - currency: 'USD', - style: 'currency', - maximumFractionDigits: 4, - }) - } - hasChanges={false} - /> - )} - -
-
- ); -}; diff --git a/liquidity/ui/src/components/Manage/LiquidityPositionUpdated.tsx b/liquidity/ui/src/components/Manage/LiquidityPositionUpdated.tsx deleted file mode 100644 index 99711aec9..000000000 --- a/liquidity/ui/src/components/Manage/LiquidityPositionUpdated.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import { Alert, Button, Divider, Flex, Heading, Text } from '@chakra-ui/react'; -import { CheckIcon } from '@snx-v3/Multistep'; -import { ReactNode } from 'react'; - -export function LiquidityPositionUpdated({ - title, - subline, - alertText, - summary, - onClose, -}: { - title?: ReactNode; - subline?: ReactNode; - alertText?: ReactNode; - summary?: ReactNode; - onClose: () => void; -}) { - return ( - - {title && ( - <> - - {title} - - - - )} - {subline && ( - - {subline} - - )} - - - - - - {alertText} - - - - {summary} - - - - ); -} diff --git a/liquidity/ui/src/components/Manage/ManageActions.tsx b/liquidity/ui/src/components/Manage/ManageActions.tsx deleted file mode 100644 index 102ddf30c..000000000 --- a/liquidity/ui/src/components/Manage/ManageActions.tsx +++ /dev/null @@ -1,367 +0,0 @@ -import { - Box, - Divider, - Flex, - Skeleton, - Tab, - TabList, - TabPanel, - TabPanels, - Tabs, - Text, -} from '@chakra-ui/react'; -import { calculateCRatio } from '@snx-v3/calculations'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { useParams } from '@snx-v3/useParams'; -import { validatePosition } from '@snx-v3/validatePosition'; -import { safeImport } from '@synthetixio/safe-import'; -import { wei } from '@synthetixio/wei'; -import { FormEvent, lazy, Suspense, useCallback, useContext, useEffect, useState } from 'react'; -import { useLocation, useNavigate } from 'react-router-dom'; -import { z } from 'zod'; -import { Borrow, Claim, Deposit, Repay, Undelegate } from '../'; -import { Withdraw } from '../Withdraw/Withdraw'; -import { COLLATERALACTIONS, DEBTACTIONS } from './actions'; - -const RepayModal = lazy(() => safeImport(() => import('@snx-v3/RepayModal'))); -const BorrowModal = lazy(() => safeImport(() => import('@snx-v3/BorrowModal'))); -const ClaimModal = lazy(() => safeImport(() => import('@snx-v3/ClaimModal'))); -const DepositModal = lazy(() => safeImport(() => import('@snx-v3/DepositModal'))); -const UndelegateModal = lazy(() => safeImport(() => import('@snx-v3/UndelegateModal'))); -const WithdrawModal = lazy(() => safeImport(() => import('@snx-v3/WithdrawModal'))); - -const validActions = [ - 'borrow', - 'deposit', - 'repay', - 'claim', - 'undelegate', - 'withdraw', - 'withdraw-debt', -] as const; -const ManageActionSchema = z.enum(validActions); -export type ManageAction = z.infer; - -const getInitialTab = (manageAction?: ManageAction) => { - if (!manageAction || COLLATERALACTIONS.find((aciton) => aciton.link === manageAction)) { - return 'collateral'; - } - - return 'debt'; -}; - -export const ManageAction = ({ - liquidityPosition, - setTxnModalOpen, - txnModalOpen, -}: { - liquidityPosition?: LiquidityPosition; - setTxnModalOpen: (action?: ManageAction) => void; - txnModalOpen?: ManageAction; -}) => { - const params = useParams(); - const { network } = useNetwork(); - - const navigate = useNavigate(); - const location = useLocation(); - - const { debtChange, collateralChange, setCollateralChange, setDebtChange, setWithdrawAmount } = - useContext(ManagePositionContext); - - const { data: collateralType } = useCollateralType(params.collateralSymbol); - const isBase = isBaseAndromeda(network?.id, network?.preset); - - const { isValid } = validatePosition({ - issuanceRatioD18: collateralType?.issuanceRatioD18, - collateralAmount: liquidityPosition?.collateralAmount, - collateralPrice: liquidityPosition?.collateralPrice, - debt: liquidityPosition?.debt, - collateralChange, - debtChange, - }); - - const parsedActionParam = ManageActionSchema.safeParse(params.manageAction); - const parsedAction = parsedActionParam.success ? parsedActionParam.data : undefined; - - const isFormValid = isBase ? true : isValid; - - const onSubmit = useCallback( - (e: FormEvent) => { - e.preventDefault(); - const form = e.target as HTMLFormElement; - if (!form.reportValidity() || !isFormValid) { - return; - } - setTxnModalOpen(parsedAction); - }, - [isFormValid, parsedAction, setTxnModalOpen] - ); - - useEffect(() => { - // This is just for initial state, if we have a manage action selected return - const queryParams = new URLSearchParams(location.search); - - if (queryParams.get('manageAction')) { - return; - } - if (!liquidityPosition) return; - if (!collateralType) return; - - const cRatio = calculateCRatio(liquidityPosition.debt, liquidityPosition.collateralValue); - const canBorrow = - !isBase && (liquidityPosition.debt.eq(0) || cRatio.gt(collateralType.issuanceRatioD18)); - - if (canBorrow) { - queryParams.set('manageAction', 'borrow'); - navigate({ pathname: location.pathname, search: queryParams.toString() }, { replace: true }); - return; - } - - const cRatioIsCloseToLiqRatio = cRatio.mul(0.9).lt(collateralType.liquidationRatioD18); - - if (cRatioIsCloseToLiqRatio) { - queryParams.set('manageAction', isBase ? 'deposit' : 'repay'); - navigate({ pathname: location.pathname, search: queryParams.toString() }, { replace: true }); - return; - } - - queryParams.set('manageAction', 'deposit'); - navigate({ pathname: location.pathname, search: queryParams.toString() }, { replace: true }); - }, [collateralType, isBase, liquidityPosition, location.pathname, location.search, navigate]); - - const setActiveAction = (action: string) => { - setCollateralChange(wei(0)); - setDebtChange(wei(0)); - const queryParams = new URLSearchParams(location.search); - queryParams.set('manageAction', action); - navigate({ pathname: location.pathname, search: queryParams.toString() }, { replace: true }); - }; - const manageAction = parsedAction; - - const [tab, setTab] = useState(getInitialTab(manageAction)); - const debtActions = DEBTACTIONS(isBase); - - useEffect(() => { - setTab(getInitialTab(manageAction)); - }, [manageAction]); - - return ( - <> - {!txnModalOpen ? ( - - - - { - if (tab !== 'collateral') { - setActiveAction(COLLATERALACTIONS[0].link); - } - }} - > - Manage Collateral - - { - if (tab !== 'debt') { - setActiveAction(debtActions[0].link); - } - }} - > - {`Manage ${isBase ? 'PnL' : 'Debt'}`} - - - - - - - {COLLATERALACTIONS.map((action) => ( - setActiveAction(action.link)} - flex="1" - minWidth={['100%', 'auto']} - > - {action.icon(manageAction === action.link ? 'cyan' : 'white')} - - {action.title} - - - ))} - - - - - {debtActions.map((action) => ( - setActiveAction(action.link)} - minWidth={['100%', 'auto']} - > - {action.icon(manageAction === action.link ? 'cyan' : 'white')} - - {action.title} - - - ))} - - - - - - - {manageAction === 'borrow' ? : null} - {manageAction === 'claim' ? : null} - {manageAction === 'withdraw' ? ( - - ) : null} - {manageAction === 'withdraw-debt' ? ( - - ) : null} - {manageAction === 'deposit' ? : null} - {manageAction === 'repay' ? : null} - {manageAction === 'undelegate' ? ( - - ) : null} - - - ) : null} - - - - - - - - } - > - {txnModalOpen === 'repay' ? ( - { - setCollateralChange(wei(0)); - setDebtChange(wei(0)); - setTxnModalOpen(undefined); - }} - isOpen={txnModalOpen === 'repay'} - /> - ) : null} - {txnModalOpen === 'borrow' ? ( - { - setCollateralChange(wei(0)); - setDebtChange(wei(0)); - setTxnModalOpen(undefined); - }} - isOpen={txnModalOpen === 'borrow'} - /> - ) : null} - {txnModalOpen === 'claim' ? ( - { - setCollateralChange(wei(0)); - setDebtChange(wei(0)); - setTxnModalOpen(undefined); - }} - isOpen={txnModalOpen === 'claim'} - liquidityPosition={liquidityPosition} - /> - ) : null} - {txnModalOpen === 'deposit' ? ( - { - setCollateralChange(wei(0)); - setDebtChange(wei(0)); - setTxnModalOpen(undefined); - }} - isOpen={txnModalOpen === 'deposit'} - liquidityPosition={liquidityPosition} - /> - ) : null} - {txnModalOpen === 'undelegate' ? ( - { - setCollateralChange(wei(0)); - setDebtChange(wei(0)); - setTxnModalOpen(undefined); - }} - isOpen={txnModalOpen === 'undelegate'} - /> - ) : null} - {txnModalOpen === 'withdraw' ? ( - { - setCollateralChange(wei(0)); - setDebtChange(wei(0)); - setWithdrawAmount(wei(0)); - setTxnModalOpen(undefined); - }} - isOpen={txnModalOpen === 'withdraw'} - account - /> - ) : null} - - {txnModalOpen === 'withdraw-debt' ? ( - { - setCollateralChange(wei(0)); - setDebtChange(wei(0)); - setWithdrawAmount(wei(0)); - setTxnModalOpen(undefined); - }} - isOpen={txnModalOpen === 'withdraw-debt'} - account - isDebtWithdrawal - /> - ) : null} - - - ); -}; diff --git a/liquidity/ui/src/components/Manage/ManageLoading.tsx b/liquidity/ui/src/components/Manage/ManageLoading.tsx deleted file mode 100644 index 7a0295d42..000000000 --- a/liquidity/ui/src/components/Manage/ManageLoading.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import { Box, Divider, Flex, Skeleton } from '@chakra-ui/react'; -import { FC } from 'react'; -import { PositionTitle } from './PositionTitle'; -import { BorderBox } from '@snx-v3/BorderBox'; - -export const ManageLoading: FC<{ - collateralSymbol?: string; - poolName?: string; -}> = ({ collateralSymbol, poolName }) => { - return ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Manage/ManageStats.tsx b/liquidity/ui/src/components/Manage/ManageStats.tsx deleted file mode 100644 index 92b76801c..000000000 --- a/liquidity/ui/src/components/Manage/ManageStats.tsx +++ /dev/null @@ -1,129 +0,0 @@ -import { FC, useContext } from 'react'; -import { Flex, Text } from '@chakra-ui/react'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { CollateralType, useCollateralType } from '@snx-v3/useCollateralTypes'; -import { useParams } from '@snx-v3/useParams'; -import { validatePosition } from '@snx-v3/validatePosition'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import Wei, { wei } from '@synthetixio/wei'; -import { calculateCRatio } from '@snx-v3/calculations'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { CRatioBar } from '../CRatioBar/CRatioBar'; -import { PnlStats } from './PnlStats'; -import { DebtStats } from './DebtStats'; -import { CollateralStats } from './CollateralStats'; -import { ZEROWEI } from '@snx-v3/constants'; - -export const ManageStatsUi: FC<{ - liquidityPosition?: LiquidityPosition; - collateralType?: CollateralType; - newCollateralAmount: Wei; - newDebt: Wei; - newCratio: Wei; - collateralValue: Wei; - debt: Wei; - cRatio: Wei; - hasChanges: boolean; -}> = ({ - liquidityPosition, - collateralType, - collateralValue, - cRatio, - newCollateralAmount, - newCratio, - newDebt, - hasChanges, - debt, -}) => { - const { network } = useNetwork(); - - return ( - - - Overview - - - - - {isBaseAndromeda(network?.id, network?.preset) && ( - - )} - {!isBaseAndromeda(network?.id, network?.preset) && ( - - )} - - {!isBaseAndromeda(network?.id, network?.preset) && ( - - - - )} - - ); -}; - -export const ManageStats = ({ liquidityPosition }: { liquidityPosition?: LiquidityPosition }) => { - const { collateralSymbol } = useParams(); - const { debtChange, collateralChange } = useContext(ManagePositionContext); - - const { data: collateralType } = useCollateralType(collateralSymbol); - - const collateralValue = liquidityPosition?.collateralValue || wei(0); - - const cRatio = calculateCRatio(liquidityPosition?.debt || wei(0), collateralValue); - - const { newCRatio, newCollateralAmount, newDebt, hasChanges } = validatePosition({ - issuanceRatioD18: collateralType?.issuanceRatioD18, - collateralAmount: liquidityPosition?.collateralAmount, - collateralPrice: liquidityPosition?.collateralPrice, - debt: liquidityPosition?.debt, - collateralChange: collateralChange, - debtChange: debtChange, - }); - - return ( - - ); -}; diff --git a/liquidity/ui/src/components/Manage/NoPosition.tsx b/liquidity/ui/src/components/Manage/NoPosition.tsx deleted file mode 100644 index 504b010be..000000000 --- a/liquidity/ui/src/components/Manage/NoPosition.tsx +++ /dev/null @@ -1,117 +0,0 @@ -import { Box, Flex } from '@chakra-ui/react'; -import { BorderBox } from '@snx-v3/BorderBox'; -import DepositModal from '@snx-v3/DepositModal'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { useAccounts } from '@snx-v3/useAccounts'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { useParams } from '@snx-v3/useParams'; -import { FC, useContext, useState } from 'react'; -import { ZEROWEI } from '@snx-v3/constants'; -import { CRatioBar } from '../CRatioBar/CRatioBar'; -import { InitialDeposit } from '../InitialDeposit'; -import { Rewards } from '../Rewards'; -import { CollateralStats } from './CollateralStats'; -import { DebtStats } from './DebtStats'; -import { PnlStats } from './PnlStats'; -import { PositionTitle } from './PositionTitle'; - -export const NoPosition: FC<{ - poolName?: string; - liquidityPosition?: LiquidityPosition; -}> = ({ liquidityPosition, poolName }) => { - const { collateralSymbol, accountId } = useParams(); - const { data: collateralType } = useCollateralType(collateralSymbol); - - const { refetch } = useAccounts(); - const { collateralChange, setCollateralChange, setDebtChange } = - useContext(ManagePositionContext); - const [txnModalOpen, setTxnModalOpen] = useState<'deposit' | null>(null); - const { network } = useNetwork(); - - return ( - - - - - - - - - - {isBaseAndromeda(network?.id, network?.preset) && ( - - )} - {!isBaseAndromeda(network?.id, network?.preset) && ( - - )} - - - {!isBaseAndromeda(network?.id, network?.preset) && ( - - - - )} - - - - {!txnModalOpen && ( - { - setTxnModalOpen('deposit'); - }} - hasAccount={!!accountId} - liquidityPosition={liquidityPosition} - /> - )} - - {txnModalOpen === 'deposit' ? ( - { - setCollateralChange(ZEROWEI); - setDebtChange(ZEROWEI); - setTxnModalOpen(null); - refetch(); - }} - isOpen={txnModalOpen === 'deposit'} - title="Open Liquidity Position" - /> - ) : null} - - - - ); -}; diff --git a/liquidity/ui/src/components/Manage/PnlStats.tsx b/liquidity/ui/src/components/Manage/PnlStats.tsx deleted file mode 100644 index 91c145f61..000000000 --- a/liquidity/ui/src/components/Manage/PnlStats.tsx +++ /dev/null @@ -1,76 +0,0 @@ -import { InfoIcon } from '@chakra-ui/icons'; -import { Flex, Skeleton, Text } from '@chakra-ui/react'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { FC } from 'react'; -import { currency } from '@snx-v3/format'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { CollateralType } from '@snx-v3/useCollateralTypes'; -import Wei from '@synthetixio/wei'; -import { ChangeStat } from './ChangeStat'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { Tooltip } from '@snx-v3/Tooltip'; - -export const PnlStats: FC<{ - liquidityPosition?: LiquidityPosition; - collateralType?: CollateralType; - newDebt: Wei; - hasChanges: boolean; -}> = ({ liquidityPosition, collateralType, newDebt, hasChanges }) => { - const { network } = useNetwork(); - const isBase = isBaseAndromeda(network?.id, network?.preset); - return ( - - - - - PnL - - - Debt consists of: -
- - Your portion of the pool's total debt, which fluctuates based on trader - performance and market conditions -
- The amount you've borrowed against your collateral without incurring - interest - - ) - } - textAlign="start" - py={2} - px={3} - > - - - -
-
- - {liquidityPosition && collateralType ? ( - - currency(val, { - currency: 'USD', - style: 'currency', - maximumFractionDigits: 4, - }) - } - withColor - hasChanges={hasChanges} - dataTestId="manage-stats-debt-value" - /> - ) : ( - Lorem ipsum (this wont be displaye debt) - )} - -
-
- ); -}; diff --git a/liquidity/ui/src/components/Manage/PositionTitle.tsx b/liquidity/ui/src/components/Manage/PositionTitle.tsx deleted file mode 100644 index 4229ccedb..000000000 --- a/liquidity/ui/src/components/Manage/PositionTitle.tsx +++ /dev/null @@ -1,73 +0,0 @@ -import { Flex, Heading, Text } from '@chakra-ui/react'; -import { FC } from 'react'; -import { useCollateralDisplayName } from '../../pages'; -import { NetworkIcon, useNetwork } from '@snx-v3/useBlockchain'; -import { useNavigate } from 'react-router-dom'; -import { TokenIcon } from '../TokenIcon'; - -export const PositionTitle: FC<{ - collateralSymbol?: string; - poolName?: string; - isOpen?: boolean; - poolId?: string; -}> = ({ collateralSymbol, poolName, isOpen, poolId }) => { - const collateralDisplayName = useCollateralDisplayName(collateralSymbol); - const { network } = useNetwork(); - const navigate = useNavigate(); - - return ( - - - - - - - {isOpen ? 'Open ' : ''} {collateralDisplayName} Liquidity Position - - navigate(`/pools/${network?.id}/${poolId}`)} - > - {poolName && {poolName}} - - - {network?.label} Network - - - - - ); -}; diff --git a/liquidity/ui/src/components/Manage/actions.tsx b/liquidity/ui/src/components/Manage/actions.tsx deleted file mode 100644 index 06cda0446..000000000 --- a/liquidity/ui/src/components/Manage/actions.tsx +++ /dev/null @@ -1,219 +0,0 @@ -export const COLLATERALACTIONS = [ - { - title: 'Deposit & Lock', - link: 'deposit', - icon: (fill: 'white' | 'cyan') => ( - - - - - ), - }, - { - title: 'Unlock', - link: 'undelegate', - icon: (fill: 'white' | 'cyan') => ( - - - - - ), - }, - { - title: 'Withdraw', - link: 'withdraw', - icon: (fill: 'white' | 'cyan') => ( - - - - - ), - }, -]; - -export const DEBTACTIONS = (isBase: boolean) => { - const actions = [ - { - title: isBase ? 'Claim' : 'Claim/Borrow', - link: 'claim', - icon: (fill: 'white' | 'cyan') => ( - - - - - - - - - - - - - - - ), - }, - { - title: 'Repay Debt', - link: 'repay', - icon: (fill: 'white' | 'cyan') => ( - - - - - - - - - - - - - - - ), - }, - ]; - - if (isBase) { - return actions; - } - - return [ - ...actions, - { - title: 'Withdraw', - link: 'withdraw-debt', - icon: (fill: 'white' | 'cyan') => ( - - - - - ), - }, - ]; -}; diff --git a/liquidity/ui/src/components/Manage/index.ts b/liquidity/ui/src/components/Manage/index.ts deleted file mode 100644 index b9fed5b18..000000000 --- a/liquidity/ui/src/components/Manage/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from './ManageActions'; -export * from './ManageStats'; -export * from './NoPosition'; -export * from './ChangeStat'; diff --git a/liquidity/ui/src/components/MigrateUSD/MigrateUSDButton.tsx b/liquidity/ui/src/components/MigrateUSD/MigrateUSDButton.tsx deleted file mode 100644 index fa8633b9c..000000000 --- a/liquidity/ui/src/components/MigrateUSD/MigrateUSDButton.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { Button } from '@chakra-ui/react'; -import { FC, useEffect, useState } from 'react'; -import { Network, useNetwork, useWallet } from '@snx-v3/useBlockchain'; -import { MigrateUSDModal } from './MigrateUSDModal'; -import { TokenIcon } from '../TokenIcon'; -import { useLocation } from 'react-router-dom'; - -interface Props { - network: Network; -} - -export const MigrateUSDButton: FC = ({ network }) => { - const location = useLocation(); - - const [isOpen, setIsOpen] = useState(false); - const { network: currentNetwork } = useNetwork(); - - const { activeWallet } = useWallet(); - - useEffect(() => { - const queryParams = new URLSearchParams(location.search); - - const convert = queryParams.get('convert'); - - if (convert && convert.toLowerCase() === 'snxusd') { - setIsOpen(true); - } - }, [location.search]); - - if (!activeWallet || currentNetwork?.id !== network.id) { - return null; - } - - return ( - <> - setIsOpen(false)} - isOpen={isOpen} - /> - - - ); -}; diff --git a/liquidity/ui/src/components/MigrateUSD/MigrateUSDModal.tsx b/liquidity/ui/src/components/MigrateUSD/MigrateUSDModal.tsx deleted file mode 100644 index d83ee80e5..000000000 --- a/liquidity/ui/src/components/MigrateUSD/MigrateUSDModal.tsx +++ /dev/null @@ -1,103 +0,0 @@ -import { - CloseButton, - Divider, - Flex, - Heading, - Modal, - ModalBody, - ModalContent, - ModalOverlay, -} from '@chakra-ui/react'; -import { FC, useCallback, useEffect, useState } from 'react'; -import { StepIntro } from './StepIntro'; -import { ZEROWEI } from '@snx-v3/constants'; -import { MigrateUSDTransaction } from './MigrateUSDTransaction'; -import { Network } from '@snx-v3/useBlockchain'; -import { StepSuccessFinal } from '../Migration/StepSuccessFinal'; -import { generatePath, useLocation, useNavigate } from 'react-router-dom'; - -interface Props { - onClose: () => void; - isOpen: boolean; - network: Network; - type: 'migration' | 'convert'; - accountId?: string; -} - -export const MigrateUSDModal: FC = ({ onClose, isOpen, network, type, accountId }) => { - const [step, setStep] = useState(0); - const [amount, setAmount] = useState(ZEROWEI); - const location = useLocation(); - const navigate = useNavigate(); - - useEffect(() => { - if (!isOpen) { - setStep(0); - setAmount(ZEROWEI); - } - }, [isOpen]); - - const handleConfirm = useCallback(() => { - if (accountId) { - const queryParams = new URLSearchParams(location.search); - - queryParams.set('accountId', accountId); - - navigate( - { - pathname: generatePath('/dashboard'), - search: queryParams.toString(), - }, - { replace: true } - ); - } - onClose(); - }, [accountId, location.search, navigate, onClose]); - - return ( - - - - - - {step === 2 ? 'Migration successful' : 'Convert your sUSD to V3'} - - - - - - - - {isOpen && ( - <> - {step === 0 && ( - setStep(1)} - network={network} - /> - )} - {step === 1 && ( - { - if (type === 'migration') { - setStep(2); - } else { - onClose(); - } - }} - onBack={() => setStep(0)} - amount={amount} - /> - )} - {step === 2 && } - - )} - - - - ); -}; diff --git a/liquidity/ui/src/components/MigrateUSD/MigrateUSDTransaction.tsx b/liquidity/ui/src/components/MigrateUSD/MigrateUSDTransaction.tsx deleted file mode 100644 index 625e767ba..000000000 --- a/liquidity/ui/src/components/MigrateUSD/MigrateUSDTransaction.tsx +++ /dev/null @@ -1,185 +0,0 @@ -import { Button, Text, useToast, VStack } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { Multistep } from '@snx-v3/Multistep'; -import { useApprove } from '@snx-v3/useApprove'; -import { Wei } from '@synthetixio/wei'; -import { FC, useCallback, useState } from 'react'; -import { Network } from '@snx-v3/useBlockchain'; -import { useV2sUSD } from '@snx-v3/useV2sUSD'; -import { useLegacyMarket } from '@snx-v3/useLegacyMarket'; -import { useMigrateUSD } from '@snx-v3/useMigrateUSD'; -import { StepSuccess } from './StepSuccess'; -import { ZEROWEI } from '@snx-v3/constants'; -import { useTokenBalance } from '@snx-v3/useTokenBalance'; -import { useUSDProxyForChain } from '@snx-v3/useUSDProxy'; - -type Props = FC<{ - amount: Wei; - network: Network; - onSuccess: () => void; - onBack: () => void; -}>; - -export const MigrateUSDTransaction: Props = ({ onSuccess, amount, network, onBack }) => { - const { data: legacyMarket } = useLegacyMarket(); - - const { data: v2_sUSD } = useV2sUSD(network); - const { data: v2_balance } = useTokenBalance(v2_sUSD, network); - const { data: v3_sUSD } = useUSDProxyForChain(network); - const { data: v3_balance } = useTokenBalance(v3_sUSD?.address, network); - - const [infiniteApproval, setInfiniteApproval] = useState(false); - const [txState, setTxState] = useState({ - step: 1, - status: 'idle', - }); - const [txSummary, setTxSummary] = useState({ - amount: ZEROWEI, - v2Balance: ZEROWEI, - v3Balance: ZEROWEI, - }); - - const { approve, refetchAllowance, requireApproval } = useApprove({ - contractAddress: v2_sUSD, - amount: amount.toBN(), - spender: legacyMarket?.address, - }); - - const toast = useToast({ isClosable: true, duration: 9000 }); - - const { migrate, isSuccess } = useMigrateUSD({ - amount, - }); - - const onSubmit = useCallback(async () => { - try { - if (txState.step > 2) { - onSuccess(); - return; - } - - if (txState.step === 1 && requireApproval) { - setTxState({ - step: 1, - status: 'pending', - }); - - await approve(infiniteApproval); - refetchAllowance(); - } - - setTxState({ - step: 2, - status: 'pending', - }); - - setTxSummary({ - amount, - v2Balance: v2_balance || ZEROWEI, - v3Balance: v3_balance || ZEROWEI, - }); - await migrate(); - - setTxState({ - step: 2, - status: 'success', - }); - - toast.closeAll(); - toast({ - title: 'Success', - description: 'Migration executed.', - status: 'success', - duration: 5000, - variant: 'left-accent', - }); - } catch (error) { - setTxState((state) => ({ - step: state.step, - status: 'error', - })); - toast({ - title: 'Migration failed', - description: 'Please try again.', - status: 'error', - variant: 'left-accent', - }); - } - }, [ - amount, - approve, - infiniteApproval, - migrate, - onSuccess, - refetchAllowance, - requireApproval, - toast, - txState.step, - v2_balance, - v3_balance, - ]); - - if (isSuccess) { - return ; - } - - return ( - - 1, - loading: txState.step === 1 && txState.status === 'pending', - }} - checkboxLabel="Approve unlimited sUSD transfers to Synthetix" - checkboxProps={{ - isChecked: infiniteApproval, - onChange: (e) => setInfiniteApproval(e.target.checked), - }} - mt={0} - /> - - - This will convert to v3 sUSD - - } - status={{ - failed: txState.step === 2 && txState.status === 'error', - success: txState.step === 2 && txState.status === 'sucess', - loading: txState.step === 2 && txState.status === 'pending', - }} - /> - - - - {txState.status !== 'pending' && ( - - )} - - ); -}; diff --git a/liquidity/ui/src/components/MigrateUSD/StepIntro.tsx b/liquidity/ui/src/components/MigrateUSD/StepIntro.tsx deleted file mode 100644 index b8f934f0f..000000000 --- a/liquidity/ui/src/components/MigrateUSD/StepIntro.tsx +++ /dev/null @@ -1,154 +0,0 @@ -import React, { useEffect, useState } from 'react'; -import { - VStack, - Text, - Button, - Flex, - Collapse, - Alert, - AlertIcon, - AlertDescription, -} from '@chakra-ui/react'; -import { NumberInput } from '@snx-v3/NumberInput'; -import { Network } from '@snx-v3/useBlockchain'; -import { useTokenBalance } from '@snx-v3/useTokenBalance'; -import Wei from '@synthetixio/wei'; -import { ZEROWEI } from '@snx-v3/constants'; -import { Amount } from '@snx-v3/Amount'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { TokenIcon } from '../TokenIcon'; -import { useUSDProxyForChain } from '@snx-v3/useUSDProxy'; -import { useV2sUSD } from '@snx-v3/useV2sUSD'; - -export const StepIntro = ({ - onClose, - onConfirm, - setAmount, - amount, - network, -}: { - onClose: () => void; - onConfirm: () => void; - setAmount: (val: Wei) => void; - amount: Wei; - network: Network; -}) => { - const [loaded, setLoaded] = useState(false); - const { data: v2_sUSD } = useV2sUSD(network); - const { data: v2_balance } = useTokenBalance(v2_sUSD, network); - const { data: v3_sUSD } = useUSDProxyForChain(network); - const { data: v3_balance } = useTokenBalance(v3_sUSD?.address, network); - - useEffect(() => { - if (v2_balance && amount.eq(0) && !loaded) { - setAmount(v2_balance); - setLoaded(true); - } - }, [amount, loaded, setAmount, v2_balance]); - - return ( - - - Convert your sUSD to V3 compatible sUSD. You will need V3 compatible sUSD to interact with - the new Synthetix products. - - - - - - - - - - V2 sUSD - - - - Balance: - { - if (!v2_balance) { - return; - } - setAmount(v2_balance); - }} - color={v2_balance?.eq(amount) ? 'gray.600' : 'cyan.500'} - fontWeight={700} - > -  Max - - - - - - setAmount(val)} - min={ZEROWEI} - /> - - - - - - - - - - - V3 sUSD - - - - Balance: - - - - - - - - - - - - You cannot convert more than your v2 sUSD balance - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/MigrateUSD/StepSuccess.tsx b/liquidity/ui/src/components/MigrateUSD/StepSuccess.tsx deleted file mode 100644 index c668fd4d2..000000000 --- a/liquidity/ui/src/components/MigrateUSD/StepSuccess.tsx +++ /dev/null @@ -1,82 +0,0 @@ -import React from 'react'; -import { VStack, Text, Button, Alert, Flex } from '@chakra-ui/react'; -import { ArrowUpIcon, CheckIcon } from '@chakra-ui/icons'; -import { TransactionSummary } from '../TransactionSummary/TransactionSummary'; -import Wei from '@synthetixio/wei'; -import { currency } from '@snx-v3/format'; -import { ChangeStat } from '../ChangeStat'; - -export const StepSuccess = ({ - onConfirm, - v2Balance, - v3Balance, - amount, -}: { - onConfirm: () => void; - v2Balance: Wei; - v3Balance: Wei; - amount: Wei; -}) => { - return ( - - - Your V2 sUSD has been converted to V3 sUSD - - - - - - - - sUSD successfully converted - - - - currency(val)} - hasChanges - size="sm" - /> - ), - }, - { - label: 'Total V3 sUSD', - value: ( - currency(val)} - hasChanges - size="sm" - /> - ), - }, - ]} - /> - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Migration/MigrationBanner.tsx b/liquidity/ui/src/components/Migration/MigrationBanner.tsx deleted file mode 100644 index dcf7a8d9b..000000000 --- a/liquidity/ui/src/components/Migration/MigrationBanner.tsx +++ /dev/null @@ -1,158 +0,0 @@ -import { - Alert, - AlertIcon, - Button, - Divider, - Fade, - Flex, - Heading, - Image, - Link, - Text, -} from '@chakra-ui/react'; -import { FC, useCallback, useEffect, useState } from 'react'; -import { Network, useNetwork, useWallet } from '@snx-v3/useBlockchain'; -import { Amount } from '@snx-v3/Amount'; -import { MigrationDialog } from './MigrationDialog'; -import { MigrateUSDModal } from '../MigrateUSD/MigrateUSDModal'; -import { useV2Position } from '@snx-v3/useV2Position'; -import { useLocation, useNavigate } from 'react-router-dom'; - -interface Props { - network: Network; - type?: 'banner' | 'alert'; -} - -export const MigrationBanner: FC = ({ network, type = 'banner' }) => { - const [isOpen, setIsOpen] = useState(false); - const [accountId, setAccountId] = useState(''); - const [isUSDModalOpen, setIsUSDModalOpen] = useState(false); - const { data } = useV2Position(network); - const { network: currentNetwork, setNetwork } = useNetwork(); - const { connect, activeWallet } = useWallet(); - const location = useLocation(); - const navigate = useNavigate(); - - const onClick = useCallback(async () => { - try { - if (!activeWallet) { - connect(); - return; - } - - if (!currentNetwork || currentNetwork.id !== network.id) { - if (!(await setNetwork(network.id))) { - return; - } - } - - setIsOpen(true); - } catch (error) {} - }, [activeWallet, connect, currentNetwork, network.id, setNetwork]); - - useEffect(() => { - const queryParams = new URLSearchParams(location.search); - - const convert = queryParams.get('migrate'); - - if (convert && convert.toLowerCase() === 'snx') { - setIsOpen(true); - - const queryParams = new URLSearchParams(location.search); - queryParams.delete('migrate'); - navigate({ - pathname: location.pathname, - search: queryParams.toString(), - }); - } - }, [location.pathname, location.search, navigate]); - - return ( - <> - { - setAccountId(accountId); - setIsUSDModalOpen(true); - }} - network={network} - onClose={() => setIsOpen(false)} - isOpen={isOpen} - /> - setIsUSDModalOpen(false)} - isOpen={isUSDModalOpen} - type="migration" - accountId={accountId} - /> - - {!!data && data?.collateral.gt(0) && ( - - {type === 'banner' && ( - <> - - - - - - - - You have a SNX position on Synthetix V2 on{' '} - - {network.name} - - - - Migrate your SNX to Synthetix V3 to earn fees from both V2 and V3 markets and - much more. - - - - - - - - - - - - )} - - {type === 'alert' && ( - - - - You have a SNX active staking position on V2 on{' '} - - {network.name} - - . - -  Migrate to V3 - - - - )} - - )} - - ); -}; diff --git a/liquidity/ui/src/components/Migration/MigrationDialog.tsx b/liquidity/ui/src/components/Migration/MigrationDialog.tsx deleted file mode 100644 index 881c9cfa4..000000000 --- a/liquidity/ui/src/components/Migration/MigrationDialog.tsx +++ /dev/null @@ -1,72 +0,0 @@ -import { - CloseButton, - Divider, - Flex, - Heading, - Modal, - ModalBody, - ModalContent, - ModalOverlay, - Text, -} from '@chakra-ui/react'; -import { FC, useEffect, useState } from 'react'; -import { Network } from '@snx-v3/useBlockchain'; -import { StepIntro } from './StepIntro'; -import { StepExplain } from './StepExplain'; -import { StepSummary } from './StepSummary'; -import { useQueryClient } from '@tanstack/react-query'; -interface Props { - network: Network; - onClose: () => void; - onSuccess: (accountId: string) => void; - isOpen: boolean; -} - -export const MigrationDialog: FC = ({ network, onClose, isOpen, onSuccess }) => { - const queryClient = useQueryClient(); - const [step, setStep] = useState(0); - - useEffect(() => { - if (!isOpen) { - setStep(0); - } - }, [isOpen]); - - return ( - - - - - - Migrate to Synthetix V3 on{' '} - - {network.name} - - - - - - - - - {step === 0 && setStep(1)} onClose={onClose} />} - {step === 1 && setStep(2)} onClose={() => setStep(0)} />} - {step === 2 && ( - { - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'V2Position'], - }); - - onSuccess(accountId); - onClose(); - }} - onClose={onClose} - network={network} - /> - )} - - - - ); -}; diff --git a/liquidity/ui/src/components/Migration/StepExplain.tsx b/liquidity/ui/src/components/Migration/StepExplain.tsx deleted file mode 100644 index c23e3c40e..000000000 --- a/liquidity/ui/src/components/Migration/StepExplain.tsx +++ /dev/null @@ -1,154 +0,0 @@ -import React from 'react'; -import { VStack, Alert, Text, Button, AlertIcon, Link, Flex } from '@chakra-ui/react'; - -export const StepExplain = ({ - onClose, - onConfirm, -}: { - onClose: () => void; - onConfirm: () => void; -}) => { - return ( - - Migrating to Synthetix V3 consists of: - - - - - - - - - Creation of an Account on Synthetix V3 - - - - - - - - - - - Migration of your SNX Collateral (including escrowed SNX) and your debt to a New - Liquidity Position on the Liquidity App - - - - - - - - - - Lock of funds for 7 days - - - - - - - - - - (optional) Conversion of your sUSD into V3 compatible sUSD. You can - -  convert your sUSD  - - at anytime - - - - - - - - Migration to V3 is currently only available on Ethereum Mainnet. Learn more about - -  migrating to V3. - - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Migration/StepIntro.tsx b/liquidity/ui/src/components/Migration/StepIntro.tsx deleted file mode 100644 index 60648a7cc..000000000 --- a/liquidity/ui/src/components/Migration/StepIntro.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import React from 'react'; -import { - Flex, - Spacer, - VStack, - Heading, - Text, - ListItem, - Button, - Image, - ListIcon, - List, - Link, -} from '@chakra-ui/react'; -import { CheckIcon } from '@chakra-ui/icons'; - -export const StepIntro = ({ - onClose, - onConfirm, -}: { - onClose: () => void; - onConfirm: () => void; -}) => { - return ( - - - - Synthetix V3 is now live! - - - Migrate to Synthetix V3 to earn fees from both V2 and V3 markets and much more: - - - - - - V2 Legacy Market Fees - - - - V3 SC Pool Fees - - - - LP Incentives - - - - Improved LP experience - - - - Learn more about{' '} - - Synthetix V3 migration process - - - - - Synthetix V3 Launch - - - - - - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Migration/StepSuccess.tsx b/liquidity/ui/src/components/Migration/StepSuccess.tsx deleted file mode 100644 index 30805d894..000000000 --- a/liquidity/ui/src/components/Migration/StepSuccess.tsx +++ /dev/null @@ -1,73 +0,0 @@ -import React, { useState } from 'react'; -import { VStack, Text, Button, Alert, Flex, Tooltip } from '@chakra-ui/react'; -import { CheckIcon, CopyIcon } from '@chakra-ui/icons'; -import { TransactionSummary } from '../TransactionSummary/TransactionSummary'; - -export const StepSuccess = ({ - onConfirm, - collateral, - cRatio, - accountId, -}: { - onConfirm: () => void; - cRatio: string; - collateral: string; - accountId: string; -}) => { - const [toolTipLabel, setTooltipLabel] = useState('Copy'); - return ( - - - Your Collateral has been migrated to Synthetix V3 System - - - - - - - - Collateral successfully migrated - - - - - {`#${accountId}`} - - { - navigator.clipboard.writeText(accountId); - setTooltipLabel('Copied'); - setTimeout(() => { - setTooltipLabel('Copy'); - }, 10000); - }} - cursor="pointer" - /> - - - ), - }, - ]} - /> - - - - ); -}; diff --git a/liquidity/ui/src/components/Migration/StepSuccessFinal.tsx b/liquidity/ui/src/components/Migration/StepSuccessFinal.tsx deleted file mode 100644 index 001e72f82..000000000 --- a/liquidity/ui/src/components/Migration/StepSuccessFinal.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import React from 'react'; -import { VStack, Text, Button, Alert, Flex, Image } from '@chakra-ui/react'; -import { CheckIcon } from '@chakra-ui/icons'; -import { Network } from '@snx-v3/useBlockchain'; - -export const StepSuccessFinal = ({ - onConfirm, - network, -}: { - onConfirm: () => void; - network: Network; -}) => { - return ( - - - Your migration to Synthetix V3 on {network.name} has been successfully Completed. - - - - Synthetix V3 Launch - - - - - - - Migration successfully Completed - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Migration/StepSummary.tsx b/liquidity/ui/src/components/Migration/StepSummary.tsx deleted file mode 100644 index 897a03fd9..000000000 --- a/liquidity/ui/src/components/Migration/StepSummary.tsx +++ /dev/null @@ -1,265 +0,0 @@ -import React, { useCallback, useState } from 'react'; -import { - VStack, - Text, - Heading, - Box, - HStack, - Tooltip, - Checkbox, - Button, - Spinner, - Link, - Flex, - Collapse, - AlertIcon, - Alert, - AlertDescription, -} from '@chakra-ui/react'; -import { wei } from '@synthetixio/wei'; -import { useV2Position } from '@snx-v3/useV2Position'; -import { Network } from '@snx-v3/useBlockchain'; -import { InfoIcon } from '@chakra-ui/icons'; -import { useMigrate } from '@snx-v3/useMigrate'; -import { StepSuccess } from './StepSuccess'; -import { formatEther } from 'ethers/lib/utils'; -import { Amount } from '@snx-v3/Amount'; -import { CRatioBadge } from '../CRatioBar/CRatioBadge'; -import { useRates } from '@snx-v3/useRates'; -import { ZEROWEI } from '@snx-v3/constants'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; - -export const StepSummary = ({ - onClose, - network, - onConfirm, -}: { - onClose: () => void; - onConfirm: (accountId: string) => void; - network: Network; -}) => { - const { data: snxCollateral } = useCollateralType('SNX'); - const [isUnderstanding, setIsUnderstanding] = useState(false); - const { data } = useV2Position(network); - const { migrate, transaction, isLoading, isSuccess, accountId } = useMigrate(); - - const { data: rates } = useRates(); - const snxPrice = rates?.snx || ZEROWEI; - const ethPrice = rates?.eth || ZEROWEI; - - const [txSummary, setTxSummary] = useState({ - collateral: '0', - cRatio: '0', - accountId: '', - }); - - const cRatio = data?.cratio.eq(0) - ? '0' - : wei(1) - .div(data?.cratio || wei(1)) - .mul(100) - .toString(2); - - const handleSubmit = useCallback(() => { - setTxSummary({ - cRatio, - collateral: data?.collateral?.toString(2) || '0', - accountId, - }); - - migrate(); - }, [accountId, cRatio, data?.collateral, migrate]); - - if (isSuccess) { - return ( - onConfirm(txSummary.accountId)} - cRatio={txSummary.cRatio} - collateral={txSummary.collateral} - accountId={txSummary.accountId} - /> - ); - } - - return ( - - Summary of your migration - - - - C-Ratio - - {cRatio}% - - {/* HEALTHY */} - - - - - - Warning: if your c-ratio is below V3 liquidation ratio (105%), your account will be{' '} - - liquidated - {' '} - during the migration. We recommend to commence this migration only if you have a healthy - c-ratio. - - - - - - - SNX Collateral{' '} - - - - - - {data?.collateral?.toString(2)} SNX - {snxPrice?.gt(0) && <> (${snxPrice.mul(data?.collateral).toString(2)})} - - - - Balance - - {data?.balance?.toString(2)} SNX - {snxPrice?.gt(0) && <> (${snxPrice.mul(data?.balance).toString(2)})} - - - - - Escrowed{' '} - - - - - - {data?.collateral?.sub(data?.balance)?.toString(2)} SNX - {snxPrice?.gt(0) && ( - <> (${snxPrice.mul(data?.collateral?.sub(data?.balance)).toString(2)}) - )} - - - - - Debt{' '} - - Your debt amount will be the same on V3. Debt is however now determined by the - collateral deposited. - - } - > - - - - ${data?.debt?.toString(2)} - - - - - setIsUnderstanding(e.currentTarget.checked)}> - I understand that this action cannot be undone - - - - - Estimated Gas - - {transaction !== undefined && ( - <> - {transaction?.gasLimit.gt(0) ? ( - - - - {ethPrice?.gt(0) && ( - <> -  ($ - {ethPrice - .mul( - formatEther( - transaction?.gasLimit.mul(transaction.gasPrice || 1).toString() || 0 - ) - ) - .toString(2)} - ) - - )} - - ) : ( - Transaction error occured, please seek support - )} - - )} - - - - - - - - The minimal locked amount on V3 is {' '} - SNX. You can manually unstake your V2 SNX on the{' '} - - Staking App - - - - - - {!isLoading ? ( - <> - - - - ) : ( - - - Loading - - )} - - ); -}; diff --git a/liquidity/ui/src/components/Permissions/AccountPermissions.ts b/liquidity/ui/src/components/Permissions/AccountPermissions.ts deleted file mode 100644 index bceffe9d7..000000000 --- a/liquidity/ui/src/components/Permissions/AccountPermissions.ts +++ /dev/null @@ -1 +0,0 @@ -export const permissionsList = ['ADMIN', 'BURN', 'DELEGATE', 'MINT', 'REWARDS', 'WITHDRAW']; diff --git a/liquidity/ui/src/components/Permissions/DelegationIcon.tsx b/liquidity/ui/src/components/Permissions/DelegationIcon.tsx deleted file mode 100644 index 008e78e86..000000000 --- a/liquidity/ui/src/components/Permissions/DelegationIcon.tsx +++ /dev/null @@ -1,30 +0,0 @@ -export const DelegationIcon = () => { - return ( - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Permissions/PermissionModal.tsx b/liquidity/ui/src/components/Permissions/PermissionModal.tsx deleted file mode 100644 index 1d6294051..000000000 --- a/liquidity/ui/src/components/Permissions/PermissionModal.tsx +++ /dev/null @@ -1,149 +0,0 @@ -import { - Badge, - Button, - Divider, - Flex, - Input, - Modal, - ModalBody, - ModalCloseButton, - ModalContent, - ModalFooter, - ModalHeader, - ModalOverlay, - Spinner, - Text, -} from '@chakra-ui/react'; -import { useEffect, useMemo, useState } from 'react'; -import { permissionsList } from './AccountPermissions'; -import { utils } from 'ethers'; -import { useManagePermissions } from '@snx-v3/useManagePermissions'; -import { useAccountOwner, useAccountPermissions } from '@snx-v3/useAccountPermissions'; -import PermissionsInfo from './PermissionsInfo'; - -export function PermissionModal({ - accountId, - isOpen, - onClose, - refetch, - existingPermissions, - target, -}: { - accountId: string; - target?: string; - existingPermissions?: string[]; - isOpen: boolean; - onClose: () => void; - refetch: () => void; -}) { - const [address, setAddress] = useState(target || ''); - const [selectedPermissions, setSelectedPermissions] = useState([ - ...(existingPermissions || []), - ]); - const { mutateAsync: submit, isPending } = useManagePermissions({ - target: address, - accountId, - existing: existingPermissions || [], - selected: selectedPermissions, - }); - - const { data: permissionData } = useAccountPermissions(accountId); - const { data: accountOwner } = useAccountOwner(accountId); - - useEffect(() => { - if (!isOpen) { - setSelectedPermissions([...(existingPermissions || [])]); - } - }, [existingPermissions, isOpen]); - - const isAddressValid = useMemo(() => { - return ( - utils.isAddress(address) && - accountOwner?.toLowerCase() !== address.toLowerCase() && - (!!target || (permissionData && !permissionData[address.toLowerCase()])) - ); - }, [accountOwner, address, permissionData, target]); - - const isFormValid = useMemo(() => { - return selectedPermissions.length > 0 && isAddressValid; - }, [isAddressValid, selectedPermissions.length]); - - return ( - - - - {target ? 'Edit' : 'New'} Permission - - - - - {!target && ( - <> - - Address - - { - setAddress(e.target.value.trim()); - }} - value={address} - isInvalid={!isAddressValid && !!address} - /> - - )} - - Select Permissions - - - {permissionsList.map((permission) => { - const isActive = selectedPermissions.includes(permission); - return ( - - setSelectedPermissions((state) => { - if (state.includes(permission)) { - return state.filter((s) => s !== permission); - } - return [...state, permission]; - }) - } - variant="outline" - key={permission} - color={isActive ? 'cyan' : 'gray'} - textTransform="capitalize" - cursor="pointer" - bg="gray.900" - colorScheme={isActive ? 'cyan' : 'gray'} - > - {permission} - - ); - })} - - - - - {isPending ? ( - - ) : ( - - )} - - - - ); -} diff --git a/liquidity/ui/src/components/Permissions/PermissionRow.tsx b/liquidity/ui/src/components/Permissions/PermissionRow.tsx deleted file mode 100644 index 32f33aeb8..000000000 --- a/liquidity/ui/src/components/Permissions/PermissionRow.tsx +++ /dev/null @@ -1,112 +0,0 @@ -import { DeleteIcon, EditIcon } from '@chakra-ui/icons'; -import { Badge, Td, Tr, Text, Flex, IconButton, useDisclosure } from '@chakra-ui/react'; -import { FC, useEffect } from 'react'; -import { useManagePermissions } from '@snx-v3/useManagePermissions'; -import { Address } from '../Address'; -import { PermissionModal } from './PermissionModal'; -import { permissionsList } from './AccountPermissions'; - -interface Props { - address: string; - currentPermissions: Array; - accountId: string; - refetch: () => void; - isOwner: boolean; -} - -export const PermissionRow: FC = ({ - address, - currentPermissions, - accountId, - refetch, - isOwner, -}) => { - const { - isOpen: isPermissionOpen, - onClose: onPermissionClose, - onOpen: onPermissionOpen, - } = useDisclosure(); - - const { - mutate: removePermissions, - isPending, - isSuccess, - } = useManagePermissions({ - accountId, - target: address, - selected: [], - existing: currentPermissions, - }); - - useEffect(() => { - if (isSuccess) { - refetch(); - onPermissionClose(); - } - }, [isSuccess, onPermissionClose, refetch]); - - return ( - - - -
- - - - - {permissionsList.map((permission) => { - const isActive = currentPermissions.includes(permission); - return ( - - {permission} - - ); - })} - - - - - {isOwner && ( - <> - - } - mr="2" - /> - { - removePermissions(); - }} - size="sm" - aria-label="delete" - icon={} - /> - - )} - - - ); -}; diff --git a/liquidity/ui/src/components/Permissions/PermissionTable.tsx b/liquidity/ui/src/components/Permissions/PermissionTable.tsx deleted file mode 100644 index 401d3f334..000000000 --- a/liquidity/ui/src/components/Permissions/PermissionTable.tsx +++ /dev/null @@ -1,206 +0,0 @@ -/* eslint-disable react/no-unescaped-entities */ -import { - Badge, - Button, - Flex, - Heading, - Skeleton, - Table, - TableContainer, - Tbody, - Td, - Text, - Th, - Thead, - Tr, - useDisclosure, -} from '@chakra-ui/react'; -import { PermissionRow } from './PermissionRow'; -import { useAccountOwner, useAccountPermissions } from '@snx-v3/useAccountPermissions'; -import { prettyString } from '@snx-v3/format'; -import { useWallet } from '@snx-v3/useBlockchain'; -import { PermissionModal } from './PermissionModal'; -import { TransferOwnershipModal } from './TransferOwnershipModal'; -import { PermissionTableLoading } from './PermissionTableLoading'; -import { useMemo } from 'react'; -import { Address } from '../Address'; -import PermissionsInfo from './PermissionsInfo'; - -export default function PermissionTable({ - accountId, - refetchAccounts, -}: { - accountId: string; - refetchAccounts: () => void; -}) { - const { - isOpen: isPermissionOpen, - onClose: onPermissionClose, - onOpen: onPermissionOpen, - } = useDisclosure(); - const { - isOpen: isTransferOpen, - onClose: onTransferClose, - onOpen: onTransferOpen, - } = useDisclosure(); - - const { activeWallet } = useWallet(); - const { data: permissions, isLoading, refetch } = useAccountPermissions(accountId); - const { - data: accountOwner, - isLoading: loadingOwner, - refetch: refetchAccountOwner, - } = useAccountOwner(accountId); - - const isOwner = useMemo( - () => !!(accountOwner && accountOwner?.toLowerCase() === activeWallet?.address.toLowerCase()), - [accountOwner, activeWallet?.address] - ); - return ( - <> - - - - Account #{prettyString(accountId, 4, 4)} - - {isOwner && ( - - )} - - - - - - - - - - - - - - - - - - {isLoading && } - - {!isLoading && - permissions && - Object.keys(permissions) - .filter((target) => permissions[target]?.length > 0) - .map((target) => ( - - ))} - -
- Address - - Permissions - -
- - {accountOwner && ( - -
- - )} - -
- - OWNER - - - {isOwner && ( - - )} -
-
- - - {accountOwner && ( - { - refetch(); - refetchAccountOwner(); - refetchAccounts(); - }} - /> - )} - - ); -} diff --git a/liquidity/ui/src/components/Permissions/PermissionTableLoading.tsx b/liquidity/ui/src/components/Permissions/PermissionTableLoading.tsx deleted file mode 100644 index 38a42e468..000000000 --- a/liquidity/ui/src/components/Permissions/PermissionTableLoading.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import { Skeleton, Td, Text, Tr } from '@chakra-ui/react'; -import { prettyString } from '@snx-v3/format'; -import { ethers } from 'ethers'; - -export function PermissionTableLoading() { - const rows = Array.from({ length: 2 }, (_, i) => i); - return ( - <> - {rows.map((row) => { - return ( - - - - - {prettyString(ethers.constants.AddressZero)}{' '} - - - - - - - - - - - - - ); - })} - - ); -} diff --git a/liquidity/ui/src/components/Permissions/Permissions.tsx b/liquidity/ui/src/components/Permissions/Permissions.tsx deleted file mode 100644 index a8b143e07..000000000 --- a/liquidity/ui/src/components/Permissions/Permissions.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import { Button, Flex, Heading, Link, Text } from '@chakra-ui/react'; -import { useAccounts } from '@snx-v3/useAccounts'; -import PermissionTable from './PermissionTable'; -import { DelegationIcon } from './DelegationIcon'; - -export default function Permissions() { - const { data: accounts, refetch: refetchAccounts } = useAccounts(); - - return ( - - - {accounts?.map((account) => ( - - ))} - - - - - Delegate Permissions - - - Delegation enables a wallet to execute functions on behalf of another wallet/account: - lock, borrow, withdraw, claim, but not transfer. Manage addresses and their powers below. - - - - - - - ); -} diff --git a/liquidity/ui/src/components/Permissions/PermissionsInfo.tsx b/liquidity/ui/src/components/Permissions/PermissionsInfo.tsx deleted file mode 100644 index fb7f108e9..000000000 --- a/liquidity/ui/src/components/Permissions/PermissionsInfo.tsx +++ /dev/null @@ -1,26 +0,0 @@ -/* eslint-disable react/no-unescaped-entities */ -import { Text, Tooltip } from '@chakra-ui/react'; -import { InfoIcon } from '@chakra-ui/icons'; - -export default function PermissionsInfo() { - return ( - - - ADMIN: Full control over the account, except for transferring ownership
- WITHDRAW: Ability to withdraw collateral from the account -
- REWARDS: Ability to claim rewards on behalf of the account -
- MINT: Ability to mint snxUSD using the account's collateral -
- DELEGATE: Ability to delegate the account's collateral to pools -
- - } - > - -
- ); -} diff --git a/liquidity/ui/src/components/Permissions/TransferOwnershipModal.tsx b/liquidity/ui/src/components/Permissions/TransferOwnershipModal.tsx deleted file mode 100644 index ae8bb9778..000000000 --- a/liquidity/ui/src/components/Permissions/TransferOwnershipModal.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import { - Alert, - AlertDescription, - AlertIcon, - Button, - Divider, - Flex, - Input, - Modal, - ModalBody, - ModalCloseButton, - ModalContent, - ModalFooter, - ModalHeader, - ModalOverlay, - Spinner, - Text, -} from '@chakra-ui/react'; -import { prettyString } from '@snx-v3/format'; -import { useTransferAccountId } from '@snx-v3/useTransferAccountId'; -import { utils } from 'ethers'; -import { useMemo, useState } from 'react'; - -export function TransferOwnershipModal({ - isOpen, - onClose, - accountId, - refetch, - owner, -}: { - isOpen: boolean; - onClose: () => void; - accountId: string; - owner: string; - refetch: () => void; -}) { - const [to, setTo] = useState(''); - const { isPending, mutateAsync: submit } = useTransferAccountId(to, accountId); - - const isTargetValid = useMemo( - () => !!utils.isAddress(to) && to.toLowerCase() !== owner.toLowerCase(), - [owner, to] - ); - return ( - - - - Transfer Ownership - - - - - Account #{prettyString(accountId, 4, 4)} - - - Will be transfered from: - - - - Will be transfered to: - - { - setTo(e.target.value.trim()); - }} - value={to} - /> - - - - - - This action cannot be undone - - - - {isPending ? ( - - ) : ( - - )} - - - - ); -} diff --git a/liquidity/ui/src/components/Pools/Balloon.tsx b/liquidity/ui/src/components/Pools/Balloon.tsx deleted file mode 100644 index b2882ae01..000000000 --- a/liquidity/ui/src/components/Pools/Balloon.tsx +++ /dev/null @@ -1,494 +0,0 @@ -import { Icon, IconProps } from '@chakra-ui/react'; - -export const Balloon = ({ ...props }: IconProps) => ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -); diff --git a/liquidity/ui/src/components/Pools/ChainFilter.tsx b/liquidity/ui/src/components/Pools/ChainFilter.tsx deleted file mode 100644 index 172f7d4c8..000000000 --- a/liquidity/ui/src/components/Pools/ChainFilter.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import { Dispatch } from 'react'; -import { Flex, Button } from '@chakra-ui/react'; -import { PoolsFilterAction } from './PoolsList'; -import { NETWORKS, NetworkIcon } from '@snx-v3/useBlockchain'; - -interface ChainFilterProps { - activeChains: number[]; - dispatch: Dispatch; -} - -// TODO: Remove filter when mainnet and optimism are supported -const mainnets = NETWORKS.filter(({ isSupported, isTestnet }) => isSupported && !isTestnet).filter( - ({ id }) => id !== 10 && id !== 1 -); - -export const ChainFilter = ({ activeChains, dispatch }: ChainFilterProps) => { - const isAllActive = activeChains.length === 0; - - return ( - - dispatch({ type: 'RESET_CHAIN' })} - color="gray.50" - as={Button} - px="16px" - py="6px" - fontWeight={600} - borderRadius="9999px" - mr={1.5} - fontSize="sm" - > - All Networks - - {mainnets.map((chain) => { - const isActive = activeChains.includes(chain.id); - - const toggle = () => { - if (isActive) { - dispatch({ type: 'REMOVE_CHAIN', payload: { chain: chain.id } }); - } else { - dispatch({ type: 'ADD_CHAIN', payload: { chain: chain.id } }); - } - }; - - return ( - - - - ); - })} - - ); -}; diff --git a/liquidity/ui/src/components/Pools/CollateralFilter.tsx b/liquidity/ui/src/components/Pools/CollateralFilter.tsx deleted file mode 100644 index 8f38a9b17..000000000 --- a/liquidity/ui/src/components/Pools/CollateralFilter.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { Dispatch } from 'react'; -import { Flex, Button } from '@chakra-ui/react'; -import { TokenIcon } from '../TokenIcon'; -import { PoolsFilterAction } from './PoolsList'; - -const supportedCollateralTypes = ['WETH', 'SNX', 'USDC', 'ARB']; - -interface CollateralFilterProps { - activeCollateral: string[]; - dispatch: Dispatch; -} - -export const CollateralFilter = ({ activeCollateral, dispatch }: CollateralFilterProps) => { - const isAllActive = activeCollateral.length === 0; - - return ( - - dispatch({ type: 'RESET_COLLATERAL' })} - color="gray.50" - as={Button} - px="16px" - py="6px" - fontWeight={600} - borderRadius="9999px" - mr={1.5} - fontSize="sm" - > - All Collaterals - - {supportedCollateralTypes.map((collateral) => { - const isActive = activeCollateral.includes(collateral); - - const toggle = () => { - if (isActive) { - dispatch({ type: 'REMOVE_COLLATERAL', payload: { collateral } }); - } else { - dispatch({ type: 'ADD_COLLATERAL', payload: { collateral } }); - } - }; - - return ( - - - - ); - })} - - ); -}; diff --git a/liquidity/ui/src/components/Pools/CollateralSection.tsx b/liquidity/ui/src/components/Pools/CollateralSection.tsx deleted file mode 100644 index 4966206a8..000000000 --- a/liquidity/ui/src/components/Pools/CollateralSection.tsx +++ /dev/null @@ -1,577 +0,0 @@ -import { - Button, - Table, - Fade, - Flex, - Skeleton, - TableContainer, - Text, - Tbody, - Th, - Thead, - Tr, - Td, -} from '@chakra-ui/react'; -import { useVaultsData, VaultsDataType } from '@snx-v3/useVaultsData'; -import React, { FC, useMemo } from 'react'; -import { wei } from '@synthetixio/wei'; -import { formatNumber, formatNumberToUsd, formatPercent } from '@snx-v3/formatters'; -import { useParams } from '@snx-v3/useParams'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { useApr } from '@snx-v3/useApr'; -import { Tooltip } from '@snx-v3/Tooltip'; -import { - ARBITRUM, - BASE_ANDROMEDA, - NETWORKS, - Network, - useNetwork, - useWallet, -} from '@snx-v3/useBlockchain'; -import { useOfflinePrices } from '@snx-v3/useCollateralPriceUpdates'; -import { BigNumberish } from 'ethers'; -import { useNavigate, useSearchParams } from 'react-router-dom'; -import { TokenIcon } from '../TokenIcon'; -import { CollateralType, useCollateralTypes } from '@snx-v3/useCollateralTypes'; -import { calculateCRatio } from '@snx-v3/calculations'; -import { Sparkles } from '@snx-v3/icons'; - -export const calculateVaultTotals = (vaultsData: VaultsDataType) => { - const zeroValues = { collateral: { value: wei(0), amount: wei(0) }, debt: wei(0) }; - if (!vaultsData) return zeroValues; - - return vaultsData.reduce((acc, { collateral, debt }) => { - acc.collateral = { - value: acc.collateral.value.add(collateral.value), - amount: acc.collateral.amount.add(collateral.amount), - }; - acc.debt = acc.debt.add(debt); - return acc; - }, zeroValues); -}; - -export const CollateralSectionUi: FC<{ - vaultsData: VaultsDataType; - collateralPrices?: { symbol: string; price: BigNumberish }[]; - apr?: { - combinedApr: number; - cumulativePnl: number; - collateralAprs: any[]; - }; - isAprLoading?: boolean; - isVaultsLoading?: boolean; - network: Network | undefined; - poolId: string | undefined; -}> = ({ vaultsData, apr, isAprLoading, isVaultsLoading, network, poolId }) => { - const navigate = useNavigate(); - const [queryParams] = useSearchParams(); - - const { network: currentNetwork, setNetwork } = useNetwork(); - const { connect } = useWallet(); - - const { collateral: totalCollateral, debt: totalDebt } = calculateVaultTotals(vaultsData); - - const isInTotalProfit = totalDebt.lt(0); - - return ( - - - Pool Collateralization - - - {/* Total TVL */} - - - Total TVL - - - - - {formatNumberToUsd(totalCollateral.value.toNumber(), { maximumFractionDigits: 0 })} - - - - - {/* Total Debt */} - - - Total Debt/Profit - - - - - {isInTotalProfit ? '+' : '-'} - {formatNumberToUsd(totalDebt.abs().toNumber(), { maximumFractionDigits: 0 })} - - - - - {/* APR */} - - - APR - - - - - - {network?.id === ARBITRUM.id ? 'Up to ' : ''} - {formatApr(apr?.combinedApr, network?.id)} - - - - - - - - - - - - - - - - - - - {(isAprLoading || isVaultsLoading || !vaultsData) && ( - - {[1, 2, 3].map((index) => ( - - - - - - - - ))} - - )} - {vaultsData?.map((vaultCollateral, i) => { - // Calculate c-ratio - const cRatio = calculateCRatio( - vaultCollateral.debt, - vaultCollateral.collateral.value - ); - - const collateralApr = apr?.collateralAprs.find( - (a) => - a.collateralType.toLowerCase() === - vaultCollateral.collateralType.tokenAddress.toLowerCase() - ); - - const { apr28d, apr28dRewards, apr28dPnl } = collateralApr || { - apr28d: 0, - apr28dRewards: 0, - apr28dPnl: 0, - }; - - const isInProfit = vaultCollateral.debt.lt(0); - - const borderTopWidth = i === 0 ? '1px' : '0px'; - - return ( - - - - - - - - ); - })} - -
- Asset - - TVL - - Debt/Profit - - APR - - {' '} -
- - - - - - - - - -
- - - - - - - {vaultCollateral.collateralType.displaySymbol} - - - {vaultCollateral.collateralType.name} - - - - - - - - - - {formatNumberToUsd(vaultCollateral.collateral.value.toNumber(), { - maximumFractionDigits: 0, - minimumFractionDigits: 0, - })} - - - {formatNumber(vaultCollateral.collateral.amount.toNumber(), { - maximumFractionDigits: 0, - minimumFractionDigits: 0, - })}{' '} - {vaultCollateral.collateralType.symbol} - - - - - - - - - {isInProfit ? '+' : '-'} - {formatNumberToUsd(vaultCollateral.debt.abs().toNumber(), { - maximumFractionDigits: 0, - minimumFractionDigits: 0, - })} - - - C-ratio: {cRatio.lte(0) ? 'Infinite' : formatPercent(cRatio.toNumber())} - - - - - - - - - - Total APR: - - {formatApr(apr28d * 100, network?.id)} - - - Performance: - {formatApr(apr28dPnl * 100, network?.id)} - - - Rewards: - {formatApr(apr28dRewards * 100, network?.id)} - - - } - > - - - {formatApr(apr28d * 100, network?.id)} - - - - - - - - - -
-
-
- ); -}; - -export const CollateralSection = () => { - const { poolId, networkId } = useParams(); - - const network = NETWORKS.find((n) => n.id === Number(networkId)); - - const { data: vaultsData, isLoading: isVaultsLoading } = useVaultsData(Number(poolId), network); - const { data: aprData, isLoading: isAprLoading } = useApr(network); - - const { data: BaseCollateralTypes } = useCollateralTypes(false, BASE_ANDROMEDA); - const { data: ArbitrumCollateralTypes } = useCollateralTypes(false, ARBITRUM); - - const allCollaterals: CollateralType[] = useMemo(() => { - if (!BaseCollateralTypes || !ArbitrumCollateralTypes) { - return []; - } - - return BaseCollateralTypes.concat(ArbitrumCollateralTypes); - }, [ArbitrumCollateralTypes, BaseCollateralTypes]); - - const { data: collateralPrices } = useOfflinePrices( - allCollaterals.map((item) => ({ - id: item.tokenAddress, - oracleId: item.oracleNodeId, - symbol: item.symbol, - })) - ); - - return ( - - ); -}; - -export function formatApr(apr?: number, networkId?: number) { - if (!networkId || !apr || apr <= 0) return '-'; - - return `${apr.toFixed(2)}%`; -} diff --git a/liquidity/ui/src/components/Pools/PoolCards/BaseInfoCard.tsx b/liquidity/ui/src/components/Pools/PoolCards/BaseInfoCard.tsx deleted file mode 100644 index cb6fb5fc6..000000000 --- a/liquidity/ui/src/components/Pools/PoolCards/BaseInfoCard.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { Button, Flex, Image, Text, Link } from '@chakra-ui/react'; - -export const BaseInfoCard = () => { - return ( - - - - - Sell SNX at a Premium and watch it Burn - - - Sell your SNX at a premium to the Buyback and Burn contract and get USDC on Base - - - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Pools/PoolCards/PoolCard.tsx b/liquidity/ui/src/components/Pools/PoolCards/PoolCard.tsx deleted file mode 100644 index 46e442e16..000000000 --- a/liquidity/ui/src/components/Pools/PoolCards/PoolCard.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import { Network } from '@snx-v3/useBlockchain'; -import { BigNumberish } from 'ethers'; -import { CollateralType } from '@snx-v3/useCollateralTypes'; -import { PoolRow } from './PoolRow'; - -interface CollateralTypeWithDeposited extends CollateralType { - collateralDeposited: string; -} - -export interface PoolCardProps { - pool: { - name: string; - id: string; - }; - network: Network; - collateralTypes?: CollateralTypeWithDeposited[]; - collateralPrices?: { - symbol: string; - price: BigNumberish; - }[]; - apr: { - combinedApr: number; - cumulativePnl: number; - collateralAprs: any[]; - }; - rewardsPayoutTokens?: string[]; -} - -export const PoolCard = ({ - pool, - network, - apr, - collateralTypes, - collateralPrices, -}: PoolCardProps) => { - return ( - <> - {collateralTypes?.map((collateralType) => { - return ( - - ); - })} - - ); -}; diff --git a/liquidity/ui/src/components/Pools/PoolCards/PoolCardsLoading.tsx b/liquidity/ui/src/components/Pools/PoolCards/PoolCardsLoading.tsx deleted file mode 100644 index edef36b0e..000000000 --- a/liquidity/ui/src/components/Pools/PoolCards/PoolCardsLoading.tsx +++ /dev/null @@ -1,45 +0,0 @@ -import { Flex, Skeleton } from '@chakra-ui/react'; - -export const PoolCardsLoading = () => ( - <> - {Array.from(Array(6).keys()).map((i) => ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - ))} - -); diff --git a/liquidity/ui/src/components/Pools/PoolCards/PoolRow.tsx b/liquidity/ui/src/components/Pools/PoolCards/PoolRow.tsx deleted file mode 100644 index cc652e3c2..000000000 --- a/liquidity/ui/src/components/Pools/PoolCards/PoolRow.tsx +++ /dev/null @@ -1,253 +0,0 @@ -import { Flex, Button, Text, Fade } from '@chakra-ui/react'; -import { useNavigate, useSearchParams } from 'react-router-dom'; -import { - MAINNET, - Network, - NetworkIcon, - SEPOLIA, - useNetwork, - useWallet, -} from '@snx-v3/useBlockchain'; -import { wei } from '@synthetixio/wei'; -import { BigNumberish } from 'ethers'; -import { TokenIcon } from '../../TokenIcon'; -import { CollateralType } from '@snx-v3/useCollateralTypes'; -import { Sparkles } from '@snx-v3/icons'; -import { formatNumber, formatNumberToUsd } from '@snx-v3/formatters'; -import { formatApr } from '../CollateralSection'; -import { Tooltip } from '@snx-v3/Tooltip'; -import { useTokenBalanceForChain } from '@snx-v3/useTokenBalance'; -import { getSpotMarketId, isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useGetWrapperToken } from '@snx-v3/useGetUSDTokens'; -import { ZEROWEI } from '@snx-v3/constants'; -import { MigrationBanner } from '../../Migration/MigrationBanner'; -import { Specifics } from './Specifics'; - -interface CollateralTypeWithDeposited extends CollateralType { - collateralDeposited: string; -} - -export interface Props { - collateralType: CollateralTypeWithDeposited; - pool: { - name: string; - id: string; - }; - network: Network; - collateralPrices?: { - symbol: string; - price: BigNumberish; - }[]; - apr: { - combinedApr: number; - cumulativePnl: number; - collateralAprs: any[]; - }; -} - -export const PoolRow = ({ pool, network, apr, collateralType, collateralPrices }: Props) => { - const { data: wrapperToken } = useGetWrapperToken( - getSpotMarketId(collateralType.symbol), - network - ); - const isBase = isBaseAndromeda(network?.id, network?.preset); - // TODO: This will need refactoring - const balanceAddress = isBase ? wrapperToken : collateralType?.tokenAddress; - - const { data: balance } = useTokenBalanceForChain(balanceAddress, network); - const navigate = useNavigate(); - const [queryParams] = useSearchParams(); - - const { network: currentNetwork, setNetwork } = useNetwork(); - const { connect } = useWallet(); - - const price = wei( - collateralPrices?.find( - (price) => price.symbol.toUpperCase() === collateralType.symbol.toUpperCase() - )?.price || ZEROWEI - ); - - const collateralApr = apr.collateralAprs.find( - (apr) => apr.collateralType === collateralType.tokenAddress.toLowerCase() - ) || { apr28d: 0, apr28dRewards: 0, apr28dPnl: 0 }; - - const { apr28d, apr28dRewards, apr28dPnl } = collateralApr; - - const onClick = async () => { - try { - if (!currentNetwork) { - connect(); - return; - } - - if (currentNetwork.id !== network.id) { - if (!(await setNetwork(network.id))) { - return; - } - } - - queryParams.set('manageAction', 'deposit'); - navigate({ - pathname: `/positions/${collateralType.symbol}/${pool.id}`, - search: queryParams.toString(), - }); - } catch (error) {} - }; - - const buttonText = !currentNetwork ? 'Connect Wallet' : 'Deposit'; - - return ( - - - - - - - - - - - {collateralType.symbol} - - - {network.name} Network - - - - - - {balance ? formatNumberToUsd(balance.mul(price).toNumber()) : '-'} - - - {balance ? formatNumber(balance.toNumber()) : ''} {collateralType.symbol} - - - - - SC Pool - - - Spartan Council - - - - - {price - ? formatNumberToUsd( - wei(collateralType.collateralDeposited, Number(collateralType.decimals), true) - .mul(price) - .toNumber() - ) - : 0} - - - - - {formatApr(apr28d * 100, network?.id)} - - - - Total APR: - - {formatApr(apr28d * 100, network?.id)} - - - Performance: - {formatApr(apr28dPnl * 100, network?.id)} - - - Rewards: - {formatApr(apr28dRewards * 100, network?.id)} - - - } - > - - - - - - - - - - - - - - - {[MAINNET.id, SEPOLIA.id].includes(network.id) && ( - - )} - - - ); -}; diff --git a/liquidity/ui/src/components/Pools/PoolCards/Specifics.tsx b/liquidity/ui/src/components/Pools/PoolCards/Specifics.tsx deleted file mode 100644 index c215f2569..000000000 --- a/liquidity/ui/src/components/Pools/PoolCards/Specifics.tsx +++ /dev/null @@ -1,132 +0,0 @@ -import { Flex, Text, Tooltip } from '@chakra-ui/react'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { Network } from '@snx-v3/useBlockchain'; -import { CollateralType } from '@snx-v3/useCollateralTypes'; - -export const Specifics: React.FC<{ - network?: Network; - isToros?: boolean; - collateralType?: CollateralType; -}> = ({ network, isToros, collateralType }) => { - const isBase = isBaseAndromeda(network?.id, network?.preset); - - if (isToros) { - return ( - - - - - - - - - - - - - - - - - - ); - } - - if (isBase) { - if (collateralType?.symbol.toUpperCase() === 'stataUSDC'.toUpperCase()) { - return ( - - - - - - ); - } - - return ( - - N/A - - ); - } - - return ( - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Pools/PoolCards/TorosPoolCard.tsx b/liquidity/ui/src/components/Pools/PoolCards/TorosPoolCard.tsx deleted file mode 100644 index 1fcbbf613..000000000 --- a/liquidity/ui/src/components/Pools/PoolCards/TorosPoolCard.tsx +++ /dev/null @@ -1,162 +0,0 @@ -import { Flex, Text, Button, Link, Fade, Icon, IconProps } from '@chakra-ui/react'; -import { BASE_ANDROMEDA, NetworkIcon } from '@snx-v3/useBlockchain'; -import { TokenIcon } from '../../TokenIcon'; -import { useGetWrapperToken } from '@snx-v3/useGetUSDTokens'; -import { getSpotMarketId } from '@snx-v3/isBaseAndromeda'; -import { useTokenBalanceForChain } from '@snx-v3/useTokenBalance'; -import { formatNumberToUsd } from '@snx-v3/formatters'; -import { formatNumber } from 'humanize-plus'; -import { Specifics } from './Specifics'; - -interface TorosPoolCardProps { - tvl: string; - apy: number; -} - -export function TorosPoolCard({ tvl, apy }: TorosPoolCardProps) { - const { data: wrapperToken } = useGetWrapperToken(getSpotMarketId('USDC'), BASE_ANDROMEDA); - const { data: balance } = useTokenBalanceForChain(wrapperToken, BASE_ANDROMEDA); - - return ( - - - - - - - - - - USDC - - - Base Network - - - - - - {balance ? formatNumberToUsd(balance.toNumber()) : '-'} - - - {balance ? formatNumber(balance.toNumber()) : ''} USDC - - - - - Toros Yield Vault - - - Toros - - - - - ${tvl} - - - - - {apy}% - - - - - - - - - - - - - ); -} - -const LinkOffIcon = ({ ...props }: IconProps) => ( - - - - - - - - - - -); diff --git a/liquidity/ui/src/components/Pools/PoolHeader.tsx b/liquidity/ui/src/components/Pools/PoolHeader.tsx deleted file mode 100644 index 6cb7fec85..000000000 --- a/liquidity/ui/src/components/Pools/PoolHeader.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import { Flex, Heading, Skeleton, FlexProps, Tag, Text } from '@chakra-ui/react'; -import { MAINNET, ARBITRUM, Network, NetworkIcon } from '@snx-v3/useBlockchain'; - -interface PoolHeaderProps extends FlexProps { - name?: string; - network: Network; -} - -export const PoolHeader = ({ name, network, ...props }: PoolHeaderProps) => { - return ( - <> - - - - {name ? name : 'Unknown Pool'} - - - {[MAINNET.id, ARBITRUM.id].includes(network?.id) && ( - - Borrow Interest-Free - - )} - - - - - {network?.name.charAt(0).toUpperCase() + network?.name.slice(1)} Network - - - - ); -}; diff --git a/liquidity/ui/src/components/Pools/PoolsList.tsx b/liquidity/ui/src/components/Pools/PoolsList.tsx deleted file mode 100644 index f70f75348..000000000 --- a/liquidity/ui/src/components/Pools/PoolsList.tsx +++ /dev/null @@ -1,385 +0,0 @@ -import { useReducer, useMemo } from 'react'; -import { Flex, Heading, Text, Divider } from '@chakra-ui/react'; -import { ChainFilter, CollateralFilter, PoolCard } from './'; -import { TorosPoolCard } from './PoolCards/TorosPoolCard'; -import { usePoolsList } from '@snx-v3/usePoolsList'; -import { PoolCardsLoading } from './PoolCards/PoolCardsLoading'; -import { useOfflinePrices } from '@snx-v3/useCollateralPriceUpdates'; -import { CollateralType, useCollateralTypes } from '@snx-v3/useCollateralTypes'; -import { ARBITRUM, BASE_ANDROMEDA, MAINNET } from '@snx-v3/useBlockchain'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useRewardsDistributors } from '@snx-v3/useRewardsDistributors'; -import { useOraclePrice } from '@snx-v3/useOraclePrice'; -import { Balloon } from './Balloon'; - -export const PoolsList = () => { - const [state, dispatch] = useReducer(poolsReducer, { collateral: [], chain: [] }); - const { data, isLoading: isPoolsListLoading } = usePoolsList(); - - const { data: BaseCollateralTypes, isLoading: isBaseCollateralLoading } = useCollateralTypes( - false, - BASE_ANDROMEDA - ); - - const { data: ArbitrumCollateralTypes, isLoading: isArbCollateralLoading } = useCollateralTypes( - false, - ARBITRUM - ); - - const { data: MainnetCollateralTypes, isLoading: isMainCollateralLoading } = useCollateralTypes( - false, - MAINNET - ); - - const allCollaterals: CollateralType[] = useMemo(() => { - if (!BaseCollateralTypes || !ArbitrumCollateralTypes || !MainnetCollateralTypes) { - return []; - } - - // We want to filter out assets that don't have a pyth price feed - - return BaseCollateralTypes.concat(ArbitrumCollateralTypes) - .concat(MainnetCollateralTypes) - .filter((item) => item.displaySymbol !== 'stataUSDC'); - }, [ArbitrumCollateralTypes, BaseCollateralTypes, MainnetCollateralTypes]); - - const { data: collateralPrices, isLoading: isLoadingCollateralPrices } = useOfflinePrices( - allCollaterals.map((item) => ({ - id: item.tokenAddress, - oracleId: item.oracleNodeId, - symbol: item.symbol, - })) - ); - - // Fetch stata price from oracle manager - const stata = BaseCollateralTypes?.find((item) => item.symbol === 'stataUSDC'); - - const { data: stataPrice, isLoading: isStataPriceLoading } = useOraclePrice( - stata?.oracleNodeId, - BASE_ANDROMEDA - ); - - // Arb Rewards - const { data: ArbitrumRewards, isLoading: isArbitrumRewardsLoading } = - useRewardsDistributors(ARBITRUM); - - // Base Rewards - const { data: BaseRewards, isLoading: isBaseRewardsLoading } = - useRewardsDistributors(BASE_ANDROMEDA); - - // Mainnet Rewards - const { data: MainRewards, isLoading: isMainRewardsLoading } = useRewardsDistributors(MAINNET); - - const { collateral, chain } = state; - - const showToros = - (chain.length === 0 || chain.includes(BASE_ANDROMEDA.id)) && - (collateral.length === 0 || collateral.includes('USDC')); - - const isLoading = - isPoolsListLoading || - isLoadingCollateralPrices || - isBaseCollateralLoading || - isArbCollateralLoading || - isMainCollateralLoading || - isArbitrumRewardsLoading || - isBaseRewardsLoading || - isMainRewardsLoading || - isStataPriceLoading; - - const filteredPools = useMemo(() => { - return ( - data?.synthetixPools - .map(({ network, poolInfo, apr }) => { - const collateralDeposited = poolInfo.map(({ collateral_type }) => ({ - collateralDeposited: collateral_type.total_amount_deposited, - tokenAddress: collateral_type.id, - })); - - let collaterals: typeof ArbitrumCollateralTypes = []; - let rewardsDistributors: any = {}; - - if (network.id === ARBITRUM.id) { - collaterals = ArbitrumCollateralTypes; - rewardsDistributors = ArbitrumRewards; - } else if (network.id === BASE_ANDROMEDA.id) { - collaterals = BaseCollateralTypes; - rewardsDistributors = BaseRewards; - } else if (network.id === MAINNET.id) { - collaterals = MainnetCollateralTypes; - rewardsDistributors = MainRewards; - } - - const collateralTypes = collaterals?.map((item) => ({ - ...item, - collateralDeposited: - collateralDeposited.find( - ({ tokenAddress }) => tokenAddress.toLowerCase() === item.tokenAddress.toLowerCase() - )?.collateralDeposited || '0', - })); - - return { - network, - poolInfo, - apr, - collateralDeposited, - collateralTypes, - rewardsDistributors, - }; - }) - .filter((pool) => { - const { network, collateralTypes } = pool; - if (chain.length > 0 && !chain.includes(network.id)) { - return false; - } - - const isCollateralFiltered = collateralTypes?.some((collateralType) => - collateral.length - ? !!collateral.find((collateral) => { - if ( - isBaseAndromeda(network.id, network.preset) && - collateralType.symbol.toUpperCase() === 'SUSDC' - ) { - return collateral.toUpperCase() === 'USDC'; - } - return collateral.toUpperCase() === collateralType.symbol.toUpperCase(); - }) - : true - ); - - if (!isCollateralFiltered) { - return false; - } - - return true; - }) || [] - ); - }, [ - data?.synthetixPools, - ArbitrumCollateralTypes, - ArbitrumRewards, - BaseCollateralTypes, - BaseRewards, - MainnetCollateralTypes, - MainRewards, - chain, - collateral, - ]); - - const allCollateralPrices = useMemo(() => { - if (stata && stataPrice) { - return collateralPrices?.concat({ symbol: 'stataUSDC', price: stataPrice?.price.toBN() }); - } - }, [stata, collateralPrices, stataPrice]); - - return ( - - - Pools - - - - - - - - - - Collateral/Network - - - - Wallet Balance - - - - Pool / Owner - - - - TVL - - - - APY/APR - - - Specifics - - - - {isLoading && !filteredPools?.length ? : null} - {showToros ? : null} - {filteredPools?.length > 0 - ? filteredPools.map( - ({ network, poolInfo, apr, collateralTypes, rewardsDistributors }) => { - const { pool } = poolInfo[0]; - - const rewardsPayoutTokens = [ - ...new Set( - rewardsDistributors?.map(({ payoutToken }: any) => - payoutToken.symbol.toUpperCase() - ) - ), - ] as string[]; - - return ( - - ); - } - ) - : null} - - {!isLoading && !filteredPools?.length && ( - - - - No results found, select a different network or collateral - - - { - dispatch({ type: 'RESET_CHAIN' }); - dispatch({ type: 'RESET_COLLATERAL' }); - }} - cursor="pointer" - fontWeight={700} - color="cyan.500" - > - Clear Filters - - - )} - - - ); -}; - -interface PoolsFilterState { - collateral: string[]; - chain: number[]; -} - -export interface PoolsFilterAction { - type: - | 'ADD_COLLATERAL' - | 'REMOVE_COLLATERAL' - | 'ADD_CHAIN' - | 'REMOVE_CHAIN' - | 'RESET_COLLATERAL' - | 'RESET_CHAIN'; - payload?: { - collateral?: string; - chain?: number; - }; -} - -function poolsReducer(state: PoolsFilterState, action: PoolsFilterAction): PoolsFilterState { - switch (action.type) { - case 'ADD_COLLATERAL': - if (action.payload?.collateral) { - return { - ...state, - // Only one collateral active at once - collateral: [action.payload.collateral], - }; - } - - case 'REMOVE_COLLATERAL': - return { - ...state, - collateral: state.collateral.filter((item) => item !== action.payload?.collateral), - }; - - case 'ADD_CHAIN': - if (action.payload?.chain) { - // Only one chain active at once - return { - ...state, - chain: [action.payload.chain], - }; - } - - case 'REMOVE_CHAIN': - return { - ...state, - chain: state.chain.filter((item) => item !== action.payload?.chain), - }; - - case 'RESET_COLLATERAL': - return { - collateral: [], - chain: state.chain, - }; - - case 'RESET_CHAIN': - return { - collateral: state.collateral, - chain: [], - }; - - default: - return state; - } -} diff --git a/liquidity/ui/src/components/Pools/index.ts b/liquidity/ui/src/components/Pools/index.ts deleted file mode 100644 index 6f510a9e3..000000000 --- a/liquidity/ui/src/components/Pools/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -export * from './PoolCards/PoolCard'; -export * from './ChainFilter'; -export * from './CollateralFilter'; -export * from './PoolsList'; -export * from './PoolCards/BaseInfoCard'; -export * from './CollateralSection'; -export * from './PoolHeader'; diff --git a/liquidity/ui/src/components/Positions/PositionsList.tsx b/liquidity/ui/src/components/Positions/PositionsList.tsx deleted file mode 100644 index 581c3bc8d..000000000 --- a/liquidity/ui/src/components/Positions/PositionsList.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import { Heading, Flex } from '@chakra-ui/react'; -import { PositionsTable } from './PositionsTable'; -import { useLiquidityPositions } from '@snx-v3/useLiquidityPositions'; -import { calculatePositions } from '../../utils/positions'; -import { useParams } from '@snx-v3/useParams'; -import { useApr } from '@snx-v3/useApr'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useSystemToken } from '@snx-v3/useSystemToken'; - -export const PositionsList = () => { - const { accountId } = useParams(); - const { network } = useNetwork(); - - const { data: positionsByKey, isLoading: isLiquidityPositionsLoading } = useLiquidityPositions({ - accountId, - }); - - const { data: apr } = useApr(); - const { data: systemToken, isLoading: isSystemTokenLoading } = useSystemToken(); - - const isBase = isBaseAndromeda(network?.id, network?.preset); - const positions = calculatePositions(positionsByKey, isBase); - - const parsedPositions = positions.filter( - (position) => position.collateralAmount?.gt(0) || position.availableCollateral?.gt(0) - ); - - const isLoading = isLiquidityPositionsLoading || isSystemTokenLoading; - - return ( - - - Positions - - - - ); -}; diff --git a/liquidity/ui/src/components/Positions/PositionsTable/DebtAmount.tsx b/liquidity/ui/src/components/Positions/PositionsTable/DebtAmount.tsx deleted file mode 100644 index 325f415fb..000000000 --- a/liquidity/ui/src/components/Positions/PositionsTable/DebtAmount.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { Text, TextProps } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import Wei from '@synthetixio/wei'; -import { FC } from 'react'; - -interface Props extends TextProps { - debt: Wei; - showPNL?: boolean; -} - -export const DebtAmount: FC = ({ debt, showPNL, ...props }) => { - const amount = showPNL ? debt.mul(-1) : debt; - - return ( - - - - ); -}; diff --git a/liquidity/ui/src/components/Positions/PositionsTable/PositionEmpty.tsx b/liquidity/ui/src/components/Positions/PositionsTable/PositionEmpty.tsx deleted file mode 100644 index b016829d3..000000000 --- a/liquidity/ui/src/components/Positions/PositionsTable/PositionEmpty.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { Flex, Button, Text } from '@chakra-ui/react'; -import { Link } from 'react-router-dom'; - -export const PositionsEmpty = () => { - return ( - - - You can open a new position by browsing the different Pools and choosing a vault for - collateral type - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Positions/PositionsTable/PositionNotConnected.tsx b/liquidity/ui/src/components/Positions/PositionsTable/PositionNotConnected.tsx deleted file mode 100644 index 56a1bd530..000000000 --- a/liquidity/ui/src/components/Positions/PositionsTable/PositionNotConnected.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { Flex, Button, Text } from '@chakra-ui/react'; -import { useWallet } from '@snx-v3/useBlockchain'; - -export const PositionsNotConnected = () => { - const { connect } = useWallet(); - return ( - - - Please connect wallet to view active positions - - - - ); -}; diff --git a/liquidity/ui/src/components/Positions/PositionsTable/PositionTableHeader.tsx b/liquidity/ui/src/components/Positions/PositionsTable/PositionTableHeader.tsx deleted file mode 100644 index 14a005916..000000000 --- a/liquidity/ui/src/components/Positions/PositionsTable/PositionTableHeader.tsx +++ /dev/null @@ -1,121 +0,0 @@ -import { InfoIcon } from '@chakra-ui/icons'; -import { Thead, Tr, Th, Flex, Text } from '@chakra-ui/react'; -import { Tooltip } from '@snx-v3/Tooltip'; - -export function PositionTableHeader({ isBase }: { isBase: boolean }) { - return ( - - - - Collateral - - - - - Locked - - - Unlocked assets can be locked into a position at any time or withdrawn after 24h - since last activity - - } - > - - - - - - - Unlocked - - - - - - APR - - - - APR is averaged over the trailing 28 days and is comprised of both performance - and rewards - - - } - > - - - - - - - - {isBase ? 'PNL' : 'Debt'} - - - Debt consists of: -
- - Your portion of the pool's total debt, which fluctuates based on trader - performance and market conditions -
- The amount you've borrowed against your collateral without - incurring interest - - ) - } - > - -
-
- - {!isBase && ( - - - - C-Ratio - - - - C-ratio is a dynamic number that represents a ratio between your locked - collateral and your debt - - - } - > - - - - - )} - - {' '} - - - - ); -} diff --git a/liquidity/ui/src/components/Positions/PositionsTable/PositionsRow.tsx b/liquidity/ui/src/components/Positions/PositionsTable/PositionsRow.tsx deleted file mode 100644 index 2ea88593c..000000000 --- a/liquidity/ui/src/components/Positions/PositionsTable/PositionsRow.tsx +++ /dev/null @@ -1,219 +0,0 @@ -import { TimeIcon } from '@chakra-ui/icons'; -import { Box, Button, Collapse, Fade, Flex, Td, Text, Tooltip, Tr } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { LiquidityPositionType } from '@snx-v3/useLiquidityPositions'; -import { useRewards } from '@snx-v3/useRewards'; -import { useTokenPrice } from '@snx-v3/useTokenPrice'; -import { useWithdrawTimer } from '@snx-v3/useWithdrawTimer'; -import { useMemo } from 'react'; -import { useNavigate, useSearchParams } from 'react-router-dom'; -import { CRatioAmount } from '../../CRatioBar/CRatioAmount'; -import { CRatioBadge } from '../../CRatioBar/CRatioBadge'; -import { TokenIcon } from '../../TokenIcon'; -import { DebtAmount } from './DebtAmount'; - -interface PositionRow extends LiquidityPositionType { - final: boolean; - isBase: boolean; - apr?: number; - systemTokenSymbol?: string; -} - -export function PositionRow({ - poolId, - collateralType, - debt, - final, - cRatio, - isBase, - apr, - collateralAmount, - availableCollateral, - accountId, -}: PositionRow) { - const { data: rewardsData } = useRewards({ - poolId, - collateralSymbol: collateralType?.symbol, - accountId, - }); - const collateralPrice = useTokenPrice(collateralType.symbol); - const [queryParams] = useSearchParams(); - const navigate = useNavigate(); - const { minutes, hours, isRunning } = useWithdrawTimer(accountId); - - const handleNavigate = (actions: string) => { - queryParams.set('manageAction', actions); - navigate({ - pathname: `/positions/${collateralType.symbol}/${poolId}`, - search: queryParams.toString(), - }); - }; - - const hasRewards = useMemo( - () => (rewardsData || []).reduce((curr, acc) => curr + acc.claimableAmount.toNumber(), 0) > 0, - [rewardsData] - ); - - return ( - - - - handleNavigate(debt.gt(0) ? 'repay' : 'claim')} - > - - - - {collateralType.symbol} - - - {collateralType.displaySymbol} - - - - - - - - - {collateralPrice.gt(0) && ( - - )} - - - - - - - - - - {collateralPrice.gt(0) && ( - - )} - - {availableCollateral.gt(0) && isRunning && ( - - - - )} - - - {availableCollateral.gt(0) && !isRunning ? ( - handleNavigate('withdraw')} - > - Withdraw - - ) : ( - - )} - - - - - - - - {!!apr ? apr.toFixed(2).concat('%') : '-'} - - {hasRewards && ( - handleNavigate('deposit')} - > - Claim Rewards - - )} - - - - - - - - - handleNavigate(debt.gt(0) ? 'repay' : 'claim')} - > - {debt.gt(0) ? 'Repay Debt' : 'Claim Credit'} - - - - - {!isBase && ( - - - - - - - - - - - )} - - - - - - - ); -} diff --git a/liquidity/ui/src/components/Positions/PositionsTable/PositionsRowLoading.tsx b/liquidity/ui/src/components/Positions/PositionsTable/PositionsRowLoading.tsx deleted file mode 100644 index cbeba51c4..000000000 --- a/liquidity/ui/src/components/Positions/PositionsTable/PositionsRowLoading.tsx +++ /dev/null @@ -1,117 +0,0 @@ -import { Badge, Button, Flex, Td, Text, Tr } from '@chakra-ui/react'; -import { SynthSkeleton as Skeleton, SynthCircle as SkeletonCircle } from '../../'; -import { TokenIcon } from '../../'; - -export function PositionsRowLoading() { - const rows = Array.from({ length: 2 }, (_, i) => i); - return ( - <> - {rows.map((row) => { - return ( - - - - - - - - - - sUSDC - - - - - Synthetic USDC - - - - - - - - - - - $100,000 - - - - - 200 SNX - - - - - - - - - - $100,000 - - - - - 200 SNX - - - - - - - - - $20,000 - - - - - Claim Credit - - - - - - - - - 5000% - - - - - HEALTHY - - - - - - - - - - - - - ); - })} - - ); -} diff --git a/liquidity/ui/src/components/Positions/PositionsTable/PositionsTable.tsx b/liquidity/ui/src/components/Positions/PositionsTable/PositionsTable.tsx deleted file mode 100644 index 4adf20602..000000000 --- a/liquidity/ui/src/components/Positions/PositionsTable/PositionsTable.tsx +++ /dev/null @@ -1,133 +0,0 @@ -import { Button, Fade, Flex, Heading, Table, TableContainer, Tbody } from '@chakra-ui/react'; -import { Link, useNavigate } from 'react-router-dom'; -import { NetworkIcon, useNetwork, useWallet } from '@snx-v3/useBlockchain'; -import { LiquidityPositionType } from '@snx-v3/useLiquidityPositions'; -import { - PositionsNotConnected, - PositionRow, - PositionTableHeader, - PositionsRowLoading, - PositionsEmpty, - TableDivider, -} from './'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; - -interface PositionsTableInterface { - isLoading: boolean; - positions?: LiquidityPositionType[]; - apr?: any[]; - systemToken?: { - symbol?: string; - name?: string; - address?: string; - }; -} - -export const PositionsTable = ({ - isLoading, - positions, - apr, - systemToken, -}: PositionsTableInterface) => { - const navigate = useNavigate(); - const { activeWallet } = useWallet(); - const { network } = useNetwork(); - const isBase = isBaseAndromeda(network?.id, network?.preset); - - return ( - - {!activeWallet?.address ? ( - - ) : positions?.length === 0 && !isLoading ? ( - - ) : ( - <> - - navigate(`/pools/${network?.id}/1`)} - fontSize="18px" - fontWeight={700} - lineHeight="28px" - color="gray.50" - > - Spartan Council Pool - {network && ( - - - - {network.label} Network - - - )} - - - - - - - - - - {isLoading ? ( - - ) : ( - <> - {positions?.map((position, index) => { - const positionApr = apr?.find( - (apr) => - apr.collateralType.toLowerCase() === - position.collateralType.tokenAddress.toLowerCase() - ); - - return ( - - ); - })} - - )} - -
- - )} -
- ); -}; diff --git a/liquidity/ui/src/components/Positions/PositionsTable/TableDivider.tsx b/liquidity/ui/src/components/Positions/PositionsTable/TableDivider.tsx deleted file mode 100644 index 8442cc0f8..000000000 --- a/liquidity/ui/src/components/Positions/PositionsTable/TableDivider.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Tr, Td } from '@chakra-ui/react'; - -export const TableDivider = () => { - return ( - - - - - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Positions/PositionsTable/index.ts b/liquidity/ui/src/components/Positions/PositionsTable/index.ts deleted file mode 100644 index 81db351c3..000000000 --- a/liquidity/ui/src/components/Positions/PositionsTable/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -export * from './PositionsRow'; -export * from './PositionsRowLoading'; -export * from './PositionsTable'; -export * from './PositionTableHeader'; -export * from './PositionNotConnected'; -export * from './PositionEmpty'; -export * from './TableDivider'; diff --git a/liquidity/ui/src/components/Positions/index.tsx b/liquidity/ui/src/components/Positions/index.tsx deleted file mode 100644 index 5ff01d608..000000000 --- a/liquidity/ui/src/components/Positions/index.tsx +++ /dev/null @@ -1,2 +0,0 @@ -export * from './PositionsTable'; -export * from './PositionsList'; diff --git a/liquidity/ui/src/components/Repay/Repay.tsx b/liquidity/ui/src/components/Repay/Repay.tsx deleted file mode 100644 index 4baabf5e6..000000000 --- a/liquidity/ui/src/components/Repay/Repay.tsx +++ /dev/null @@ -1,109 +0,0 @@ -import { Button, Flex, Text } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { NumberInput } from '@snx-v3/NumberInput'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { useTokenBalance } from '@snx-v3/useTokenBalance'; -import { useTokenPrice } from '@snx-v3/useTokenPrice'; -import { wei } from '@synthetixio/wei'; -import { useContext } from 'react'; -import { useParams } from 'react-router-dom'; -import { ZEROWEI } from '@snx-v3/constants'; -import { TokenIcon } from '../TokenIcon'; -import { RepayAllDebt } from './'; - -export const Repay = ({ liquidityPosition }: { liquidityPosition?: LiquidityPosition }) => { - const { debtChange, setDebtChange } = useContext(ManagePositionContext); - const { network } = useNetwork(); - const { collateralSymbol } = useParams(); - - const isBase = isBaseAndromeda(network?.id, network?.preset); - const availableUSDCollateral = liquidityPosition?.usdCollateral.availableCollateral; - const { data: systemToken } = useSystemToken(); - const { data: balance } = useTokenBalance(systemToken?.address); - - const symbol = isBase ? collateralSymbol : systemToken?.symbol; - - const price = useTokenPrice(symbol); - - if (liquidityPosition?.debt.gt(0.01) && isBaseAndromeda(network?.id, network?.preset)) { - return ; - } - - const debtExists = liquidityPosition?.debt.gt(0); - const snxUSDBalance = balance?.gt(0.01) ? balance : wei(0); - const currentDebt = debtExists ? liquidityPosition?.debt : wei(0); - const max = debtExists ? liquidityPosition?.debt : ZEROWEI; - - return ( - - - Repay Debt - - - - - - - {symbol} - - - - - Debt: - - $ - {currentDebt?.gt(0) && ( - { - if (!currentDebt) { - return; - } - setDebtChange(currentDebt.neg()); - }} - color="cyan.500" - fontWeight={700} - > -  Max - - )} - - - - - - setDebtChange(val.mul(-1))} - max={max} - min={ZEROWEI} - /> - - {price.gt(0) && } - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Repay/RepayAllDebt.tsx b/liquidity/ui/src/components/Repay/RepayAllDebt.tsx deleted file mode 100644 index 70a01227a..000000000 --- a/liquidity/ui/src/components/Repay/RepayAllDebt.tsx +++ /dev/null @@ -1,108 +0,0 @@ -import { Button, Flex, Text } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { parseUnits } from '@snx-v3/format'; -import { getRepayerContract, getSpotMarketId, isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useApprove } from '@snx-v3/useApprove'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useClearDebt } from '@snx-v3/useClearDebt'; -import { useGetWrapperToken } from '@snx-v3/useGetUSDTokens'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { useTokenBalance } from '@snx-v3/useTokenBalance'; -import { wei } from '@synthetixio/wei'; -import { useQueryClient } from '@tanstack/react-query'; -import { useCallback, useMemo } from 'react'; -import { useParams, useSearchParams } from 'react-router-dom'; - -export const RepayAllDebt = ({ liquidityPosition }: { liquidityPosition: LiquidityPosition }) => { - const { network } = useNetwork(); - const isBase = isBaseAndromeda(network?.id, network?.preset); - const params = useParams(); - const [searchParams] = useSearchParams(); - - const queryClient = useQueryClient(); - - const debtExists = liquidityPosition.debt.gt(0.01); - const currentDebt = debtExists ? liquidityPosition.debt : wei(0); - const { data: systemToken } = useSystemToken(); - const { data: wrapperToken } = useGetWrapperToken(getSpotMarketId(params.collateralSymbol)); - - const { data: tokenBalance } = useTokenBalance( - isBase ? wrapperToken : liquidityPosition.tokenAddress - ); - - const sufficientBalance = useMemo( - () => Number(tokenBalance?.toString()) >= currentDebt.toNumber(), - [currentDebt, tokenBalance] - ); - - const { - exec: execRepay, - settle: settleRepay, - isLoading, - } = useClearDebt({ - accountId: searchParams.get('accountId') || '', - poolId: params.poolId, - collateralTypeAddress: liquidityPosition?.tokenAddress, - availableUSDCollateral: liquidityPosition.accountCollateral.availableCollateral, - debt: currentDebt, - }); - - const { - approve, - requireApproval, - isLoading: approvalLoading, - } = useApprove({ - contractAddress: wrapperToken, - //slippage for approval - amount: parseUnits(currentDebt.toString(), 6).mul(110).div(100), - spender: getRepayerContract(network?.id), - }); - - const submit = useCallback(async () => { - try { - if (requireApproval) { - await approve(false); - } - await execRepay(); - - await Promise.all([ - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'TokenBalance'], - }), - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'Allowance'], - }), - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPosition'], - }), - queryClient.invalidateQueries({ - queryKey: [`${network?.id}-${network?.preset}`, 'AccountCollateralUnlockDate'], - }), - ]); - - settleRepay(); - } catch (error) {} - }, [approve, execRepay, network?.id, network?.preset, queryClient, requireApproval, settleRepay]); - - return ( - - - Repay {isBase ? params.collateralSymbol : systemToken?.symbol} - - - Your account currently has a positive debt. This amount must be paid to initiate collateral - withdrawal. - - - - ); -}; diff --git a/liquidity/ui/src/components/Repay/index.ts b/liquidity/ui/src/components/Repay/index.ts deleted file mode 100644 index b5611c588..000000000 --- a/liquidity/ui/src/components/Repay/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './Repay'; -export * from './RepayAllDebt'; diff --git a/liquidity/ui/src/components/Rewards/Rewards.tsx b/liquidity/ui/src/components/Rewards/Rewards.tsx deleted file mode 100644 index f1525bba4..000000000 --- a/liquidity/ui/src/components/Rewards/Rewards.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import { InfoIcon } from '@chakra-ui/icons'; -import { - Fade, - Flex, - FlexProps, - Table, - TableContainer, - Tbody, - Text, - Th, - Thead, - Tr, -} from '@chakra-ui/react'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { Tooltip } from '@snx-v3/Tooltip'; -import { useParams } from '@snx-v3/useParams'; -import { useRewards } from '@snx-v3/useRewards'; -import { RewardsLoading } from './RewardsLoading'; -import { RewardsRow } from './RewardsRow'; - -export const Rewards = ({ ...props }: FlexProps) => { - const { accountId, collateralSymbol, poolId } = useParams(); - const { isLoading, data: rewards } = useRewards({ poolId, collateralSymbol, accountId }); - - const hasRewards = rewards && rewards.length > 0; - - return ( - - - Rewards - - - {!isLoading && !hasRewards ? ( - - - - No Rewards Available - - - - ) : null} - - {hasRewards ? ( - - - - - - - - - - {isLoading && !rewards?.length ? : null} - {rewards?.length ? ( - - {rewards?.map((item) => ( - - ))} - - ) : null} -
- Rewards type - - - - - Earnings - - Claim -
-
- ) : null} -
- ); -}; diff --git a/liquidity/ui/src/components/Rewards/RewardsLoading.tsx b/liquidity/ui/src/components/Rewards/RewardsLoading.tsx deleted file mode 100644 index 1e88fd6ef..000000000 --- a/liquidity/ui/src/components/Rewards/RewardsLoading.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { Tbody, Tr, Td, SkeletonCircle, Skeleton, Text } from '@chakra-ui/react'; - -export const RewardsLoading = () => ( - - - - - - - - Loading - - - - - Loading - - - - - - - - - - Loading - - - - - Loading - - - - - - - - - - Loading - - - - - Loading - - - - -); diff --git a/liquidity/ui/src/components/Rewards/RewardsModal.cy.tsx b/liquidity/ui/src/components/Rewards/RewardsModal.cy.tsx deleted file mode 100644 index 6e265291d..000000000 --- a/liquidity/ui/src/components/Rewards/RewardsModal.cy.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { RewardsModal } from './RewardsModal'; -import injectedModule from '@web3-onboard/injected-wallets'; -import { init, Web3OnboardProvider } from '@web3-onboard/react'; - -describe('RewardsModal', () => { - it('should render RewardsModal', () => { - const onboard = init({ - wallets: [injectedModule()], - chains: [{ id: 1 }], - }); - - cy.mount( - - - - ); - - // Add assertions based on your component's UI. - // For example, you can check if the modal content is displayed. - cy.contains('Claiming Rewards').should('exist'); - cy.contains('Claiming 100 ETH').should('exist'); - cy.contains('View Transaction').should('exist'); - }); -}); diff --git a/liquidity/ui/src/components/Rewards/RewardsModal.tsx b/liquidity/ui/src/components/Rewards/RewardsModal.tsx deleted file mode 100644 index 717d13739..000000000 --- a/liquidity/ui/src/components/Rewards/RewardsModal.tsx +++ /dev/null @@ -1,158 +0,0 @@ -import { CheckIcon } from '@chakra-ui/icons'; -import { - Button, - CircularProgress, - Divider, - Flex, - Link, - Modal, - ModalBody, - ModalContent, - ModalOverlay, - Text, -} from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { etherscanLink } from '@snx-v3/etherscanLink'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { WithdrawIncrease } from '@snx-v3/WithdrawIncrease'; -import { wei } from '@synthetixio/wei'; -import { useEffect, useState } from 'react'; - -interface RewardsModalInterface { - collateralSymbol?: string; - amount?: number; - txnStatus?: string; - txnHash: string | null; -} - -export const RewardsModal = ({ - collateralSymbol, - amount, - txnStatus, - txnHash, -}: RewardsModalInterface) => { - const [isOpen, setIsOpen] = useState(false); - - const { network } = useNetwork(); - - useEffect(() => { - if (txnStatus === 'prompting') { - setIsOpen(true); - } - if (txnStatus === 'error') { - setIsOpen(false); - } - if (txnStatus === 'success') { - setTimeout(() => { - setIsOpen(false); - }, 1200); - } - }, [txnStatus]); - - return ( - setIsOpen(false)}> - - - - - Claiming Rewards - - - - - - - {txnStatus === 'success' ? ( - - ) : ( - - )} - - - - - - - Claim your rewards - - - - - {txnStatus === 'success' && ( - - )} - {txnHash && ( - - - View Transaction - - - )} - - - - ); -}; diff --git a/liquidity/ui/src/components/Rewards/RewardsRow.cy.tsx b/liquidity/ui/src/components/Rewards/RewardsRow.cy.tsx deleted file mode 100644 index bd5096a77..000000000 --- a/liquidity/ui/src/components/Rewards/RewardsRow.cy.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import { RewardsRow } from './RewardsRow'; // Replace with the actual path to your component -import { Table } from '@chakra-ui/react'; -import injectedModule from '@web3-onboard/injected-wallets'; -import { init, Web3OnboardProvider } from '@web3-onboard/react'; - -describe('RewardsRow', () => { - it('should render RewardsRow', () => { - const onboard = init({ - wallets: [injectedModule()], - chains: [{ id: 1 }], - }); - const queryClient = new QueryClient(); - cy.mount( - - - - -
-
-
- ); - }); -}); diff --git a/liquidity/ui/src/components/Rewards/RewardsRow.tsx b/liquidity/ui/src/components/Rewards/RewardsRow.tsx deleted file mode 100644 index bcd2dfc05..000000000 --- a/liquidity/ui/src/components/Rewards/RewardsRow.tsx +++ /dev/null @@ -1,122 +0,0 @@ -import { Button, Fade, Flex, Link, Td, Text, Tr } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { etherscanLink } from '@snx-v3/etherscanLink'; -import { truncateAddress } from '@snx-v3/formatters'; -import { Tooltip } from '@snx-v3/Tooltip'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useClaimRewards } from '@snx-v3/useClaimRewards'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { useParams } from '@snx-v3/useParams'; -import { wei } from '@synthetixio/wei'; -import { TokenIcon } from '../TokenIcon'; -import { RewardsModal } from './RewardsModal'; - -interface RewardsRowInterface { - symbol: string; - claimableAmount: number; // The immediate amount claimable as read from the contracts - lifetimeClaimed: number; - address: string; -} - -export const RewardsRow = ({ - symbol, - claimableAmount, - lifetimeClaimed, - address, -}: RewardsRowInterface) => { - const { accountId, collateralSymbol, poolId } = useParams(); - - const { data: collateralData } = useCollateralType(collateralSymbol); - const { network } = useNetwork(); - - const { exec, txnState } = useClaimRewards( - poolId || '', - collateralData?.tokenAddress || '', - accountId, - address, - claimableAmount - ); - - const onClick = () => { - exec(); - }; - - const { txnStatus, txnHash } = txnState; - - return ( - <> - - - - - - - - - - - - {symbol} - - - - - - - - - - - - {lifetimeClaimed > 0 && ( - - Lifetime:   - - - )} - - - - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Rewards/index.tsx b/liquidity/ui/src/components/Rewards/index.tsx deleted file mode 100644 index 363456355..000000000 --- a/liquidity/ui/src/components/Rewards/index.tsx +++ /dev/null @@ -1,2 +0,0 @@ -export * from './Rewards'; -export * from './RewardsRow'; diff --git a/liquidity/ui/src/components/Stats/StatBox.tsx b/liquidity/ui/src/components/Stats/StatBox.tsx deleted file mode 100644 index 4d112a3b2..000000000 --- a/liquidity/ui/src/components/Stats/StatBox.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import { InfoIcon } from '@chakra-ui/icons'; -import { Flex, Text, Fade } from '@chakra-ui/react'; -import { SynthSkeleton as Skeleton } from '../SynthSkeleton'; -import { ReactNode } from 'react'; -import { Tooltip } from '@snx-v3/Tooltip'; - -interface StatBoxProps { - isLoading: boolean; - title: string; - label?: string | ReactNode; - value?: ReactNode; -} - -export const StatBox = ({ isLoading, title, label, value }: StatBoxProps) => { - return ( - - - - {title} - - {label && ( - - - - )} - - - - - - {value || '$0.00'} - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Stats/StatsList.tsx b/liquidity/ui/src/components/Stats/StatsList.tsx deleted file mode 100644 index 836c81c30..000000000 --- a/liquidity/ui/src/components/Stats/StatsList.tsx +++ /dev/null @@ -1,137 +0,0 @@ -import { useMemo } from 'react'; -import { Flex, Text } from '@chakra-ui/react'; -import { StatBox } from './StatBox'; -import { useSearchParams } from 'react-router-dom'; -import { useAccountCollateral } from '@snx-v3/useAccountCollateral'; -import { useCollateralPrices } from '@snx-v3/useCollateralPrices'; -import { useLiquidityPositions } from '@snx-v3/useLiquidityPositions'; -import { useTokenBalances } from '@snx-v3/useTokenBalance'; -import { - calculateAssets, - calculateTotalAssetsAvailable, - calculateTotalAssetsLocked, -} from '../../utils/assets'; -import { calculateDebt } from '../../utils/positions'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useCollateralTypes } from '@snx-v3/useCollateralTypes'; -import { useGetUSDTokens } from '@snx-v3/useGetUSDTokens'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { Amount } from '@snx-v3/Amount'; -import { ZEROWEI } from '@snx-v3/constants'; -import { wei } from '@synthetixio/wei'; - -export const StatsList = () => { - const [params] = useSearchParams(); - const { network } = useNetwork(); - - const { data: usdTokens } = useGetUSDTokens(); - - const { data: positions, isLoading: isLiquidityPositionLoading } = useLiquidityPositions({ - accountId: params.get('accountId') || undefined, - }); - - const { data: collateralTypes, isLoading: isCollateralTypesLoading } = useCollateralTypes(); - - const { data: accountCollaterals, isLoading: isAccountCollateralsLoading } = useAccountCollateral( - { - accountId: params.get('accountId') || undefined, - } - ); - - const collateralAddresses = - isBaseAndromeda(network?.id, network?.preset) && usdTokens?.USDC - ? accountCollaterals?.map((collateral) => collateral.tokenAddress).concat(usdTokens.USDC) || - [] - : accountCollaterals?.map((collateral) => collateral.tokenAddress) || []; - - const { data: userTokenBalances, isLoading: tokenBalancesIsLoading } = useTokenBalances( - collateralAddresses.filter((a) => !!a) - ); - - const associatedUserBalances = userTokenBalances?.map((balance, index) => { - return { - balance, - tokenAddress: collateralAddresses[index], - }; - }); - - const { data: collateralPrices, isLoading: isCollateralPricesLoading } = useCollateralPrices(); - - const isBase = isBaseAndromeda(network?.id, network?.preset); - - const { data: systemToken } = useSystemToken(); - const assets = useMemo( - () => - calculateAssets( - accountCollaterals, - associatedUserBalances, - collateralPrices, - collateralTypes, - isBase, - usdTokens?.USDC, - systemToken - ), - [ - accountCollaterals, - associatedUserBalances, - collateralPrices, - collateralTypes, - isBase, - usdTokens?.USDC, - systemToken, - ] - ); - - const debt = calculateDebt(positions); - const totalAssets = calculateTotalAssetsAvailable(assets); - const totalLocked = calculateTotalAssetsLocked(assets); - - const isLoading = - isAccountCollateralsLoading || - tokenBalancesIsLoading || - isCollateralPricesLoading || - isLiquidityPositionLoading || - isCollateralTypesLoading; - - return ( - - } - label={ - <> - - Total assets that can be Locked, including: -
- Unlocked assets not yet withdrawn -
- Available assets in your wallet -
- - } - /> - } - label={ - <> - All assets locked in Positions - - } - /> - } - label={ - <> - - Aggregated {isBase ? 'PNL' : 'Debt'} of all your open Positions - - - } - /> -
- ); -}; diff --git a/liquidity/ui/src/components/Stats/index.ts b/liquidity/ui/src/components/Stats/index.ts deleted file mode 100644 index 69a990992..000000000 --- a/liquidity/ui/src/components/Stats/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './StatBox'; -export * from './StatsList'; diff --git a/liquidity/ui/src/components/SynthSkeleton/SynthSkeleton.tsx b/liquidity/ui/src/components/SynthSkeleton/SynthSkeleton.tsx deleted file mode 100644 index 9564cf5ad..000000000 --- a/liquidity/ui/src/components/SynthSkeleton/SynthSkeleton.tsx +++ /dev/null @@ -1,21 +0,0 @@ -import { Skeleton, SkeletonCircle, SkeletonProps } from '@chakra-ui/react'; - -interface SynthSkeletonProps extends SkeletonProps { - children: React.ReactNode; -} - -export const SynthSkeleton = ({ children, ...props }: SynthSkeletonProps) => { - return ( - - {children} - - ); -}; - -export const SynthCircle = ({ children, ...props }: SkeletonProps) => { - return ( - - {children} - - ); -}; diff --git a/liquidity/ui/src/components/SynthSkeleton/index.ts b/liquidity/ui/src/components/SynthSkeleton/index.ts deleted file mode 100644 index 1adac4b2d..000000000 --- a/liquidity/ui/src/components/SynthSkeleton/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './SynthSkeleton'; diff --git a/liquidity/ui/src/components/TokenIcon/TokenIcon.tsx b/liquidity/ui/src/components/TokenIcon/TokenIcon.tsx deleted file mode 100644 index b1c93138c..000000000 --- a/liquidity/ui/src/components/TokenIcon/TokenIcon.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { Image, ImageProps } from '@chakra-ui/react'; - -interface TokenIconProps extends ImageProps { - symbol?: string; - width?: number; - height?: number; -} - -export const TokenIcon = ({ symbol, width = 30, height = 30, ...props }: TokenIconProps) => { - return symbol ? ( - {symbol} - ) : ( - {symbol} - ); -}; diff --git a/liquidity/ui/src/components/TokenIcon/index.ts b/liquidity/ui/src/components/TokenIcon/index.ts deleted file mode 100644 index d46233925..000000000 --- a/liquidity/ui/src/components/TokenIcon/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './TokenIcon'; diff --git a/liquidity/ui/src/components/TransactionSummary/TransactionSummary.tsx b/liquidity/ui/src/components/TransactionSummary/TransactionSummary.tsx deleted file mode 100644 index a1f47169f..000000000 --- a/liquidity/ui/src/components/TransactionSummary/TransactionSummary.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { Flex, FlexProps } from '@chakra-ui/react'; -import { ReactNode } from 'react'; - -interface Props extends FlexProps { - items: { - label: ReactNode; - value: ReactNode; - }[]; -} - -export const TransactionSummary = ({ items, ...props }: Props) => ( - - {items.map(({ value, label }, i) => ( - - - {label} - - - {value} - - - ))} - -); diff --git a/liquidity/ui/src/components/Undelegate/Undelegate.tsx b/liquidity/ui/src/components/Undelegate/Undelegate.tsx deleted file mode 100644 index 8f2d03552..000000000 --- a/liquidity/ui/src/components/Undelegate/Undelegate.tsx +++ /dev/null @@ -1,378 +0,0 @@ -import { - Alert, - AlertDescription, - AlertIcon, - AlertTitle, - Button, - Collapse, - Flex, - Text, -} from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { NumberInput } from '@snx-v3/NumberInput'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { validatePosition } from '@snx-v3/validatePosition'; -import { usePoolConfiguration } from '@snx-v3/usePoolConfiguration'; -import Wei, { wei } from '@synthetixio/wei'; -import React, { FC, useCallback, useContext, useMemo } from 'react'; -import { useParams } from '@snx-v3/useParams'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { TokenIcon } from '../TokenIcon'; -import { useTokenPrice } from '@snx-v3/useTokenPrice'; -import { ZEROWEI } from '@snx-v3/constants'; -import { CRatioChangeStat } from '../CRatioBar/CRatioChangeStat'; -import { ChangeStat } from '../Manage'; -import { currency } from '@snx-v3/format'; -import { TransactionSummary } from '../TransactionSummary/TransactionSummary'; -import { useWithdrawTimer } from '@snx-v3/useWithdrawTimer'; -import { useAccountSpecificCollateral } from '@snx-v3/useAccountCollateral'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { useNavigate, useSearchParams } from 'react-router-dom'; - -export const UndelegateUi: FC<{ - collateralChange: Wei; - currentCollateral?: Wei; - minDelegation?: Wei; - currentDebt?: Wei; - max?: Wei; - collateralPrice?: Wei; - displaySymbol: string; - symbol: string; - setCollateralChange: (val: Wei) => void; - isAnyMarketLocked?: boolean; - isLoadingRequiredData: boolean; - isBase: boolean; - accountId: string | undefined; - maxWithdrawable?: Wei; - navigate: (action: string) => void; -}> = ({ - collateralChange, - setCollateralChange, - max, - displaySymbol, - symbol, - currentCollateral, - minDelegation, - isLoadingRequiredData, - isAnyMarketLocked, - isBase, - currentDebt, - collateralPrice, - accountId, - maxWithdrawable, - navigate, -}) => { - const price = useTokenPrice(symbol); - - const onMaxClick = useCallback(() => { - if (!max) { - return; - } - setCollateralChange(max.mul(-1)); - }, [max, setCollateralChange]); - - const { minutes, hours, isRunning } = useWithdrawTimer(accountId); - - const leftoverCollateral = currentCollateral?.add(collateralChange) || wei(0); - const isValidLeftover = - leftoverCollateral.gte(minDelegation || wei(0)) || leftoverCollateral.eq(0); - - const isInputDisabled = isAnyMarketLocked === true; - const overAvailableBalance = collateralChange.abs().gt(max); - const isSubmitDisabled = - isLoadingRequiredData || - isAnyMarketLocked === true || - collateralChange.gte(0) || - !isValidLeftover || - overAvailableBalance || - (currentDebt?.gt(0) && isBase); - - const txSummaryItems = useMemo(() => { - const items = [ - { - label: 'Locked ' + symbol, - value: ( - currency(val)} - hasChanges={collateralChange.abs().gt(0)} - size="sm" - /> - ), - }, - ]; - - if (isBase) { - return items; - } - - return [ - ...items, - { - label: 'C-ratio', - value: ( - - ), - }, - ]; - }, [ - collateralChange, - collateralPrice, - currentCollateral, - currentDebt, - isBase, - leftoverCollateral, - symbol, - ]); - - return ( - - - Unlock Collateral - - - - - - - {displaySymbol} - - - - - Locked: - - - {max?.gt(0) && ( - - Max - - )} - - - - setCollateralChange(val.mul(-1))} - max={max} - min={ZEROWEI} - /> - - {price.gt(0) && } - - - - - - - - Credit capacity reached - - One of the markets has reached its credit capacity and is currently in a locked state. - You cannot unlock collateral from the pool at this time. - - - - - - - - - - - The minimal locked amount is - - - You can close your position by removing all the collateral. - - - - - - - - - - You will be able to withdraw assets in {hours}H{minutes}M. Any account activity will - reset this timer to 24H. - - - - - - - - - You already have unlocked. -   - navigate('withdraw')} - cursor="pointer" - as="span" - textDecoration="underline" - > - Withdraw - {' '} - before unlocking again as it will restart the 24h withdrawal timeout. - - - - - - - - - To Unlock this amount, you need to   - navigate('repay')} - cursor="pointer" - as="span" - textDecoration="underline" - > - repay - {' '} - to your position - - - - - - - - - - - ); -}; - -export const Undelegate = ({ liquidityPosition }: { liquidityPosition?: LiquidityPosition }) => { - const { collateralChange, debtChange, setCollateralChange } = useContext(ManagePositionContext); - const { poolId, accountId, collateralSymbol } = useParams(); - const { data: collateralType } = useCollateralType(collateralSymbol); - - const poolConfiguration = usePoolConfiguration(poolId); - const { network } = useNetwork(); - - const collateralPrice = liquidityPosition?.collateralPrice; - - const { newDebt } = validatePosition({ - issuanceRatioD18: collateralType?.issuanceRatioD18, - collateralAmount: liquidityPosition?.collateralAmount, - collateralPrice, - debt: liquidityPosition?.debt, - collateralChange: collateralChange, - debtChange: debtChange, - }); - - const isBase = isBaseAndromeda(network?.id, network?.preset); - const { data: systemToken } = useSystemToken(); - const { data: systemTokenBalance } = useAccountSpecificCollateral( - accountId, - systemToken?.address - ); - - const [queryParams] = useSearchParams(); - const navigate = useNavigate(); - const handleNavigate = (actions: string) => { - queryParams.set('manageAction', actions); - navigate({ - pathname: `/positions/${collateralType?.symbol}/${poolId}`, - search: queryParams.toString(), - }); - }; - - const maxWithdrawable = useMemo(() => { - if (isBase) { - return (liquidityPosition?.accountCollateral.availableCollateral || ZEROWEI).add( - systemTokenBalance?.availableCollateral || ZEROWEI - ); - } - return liquidityPosition?.accountCollateral.availableCollateral || ZEROWEI; - }, [ - isBase, - liquidityPosition?.accountCollateral.availableCollateral, - systemTokenBalance?.availableCollateral, - ]); - - // To get the max withdrawable collateral we look at the new debt and the issuance ratio. - // This gives us the amount in dollar. We then divide by the collateral price. - // To avoid the transaction failing due to small price deviations, we also apply a 2% buffer by multiplying with 0.98 - const max = (() => { - if (!liquidityPosition || !collateralType) { - return undefined; - } - const { collateralAmount, collateralValue } = liquidityPosition; - - if (isBase) { - return collateralAmount; - } - - // if debt is negative it's actually credit, which means we can undelegate all collateral - if (newDebt.lte(0)) return collateralAmount; - - const minCollateralRequired = newDebt.mul(collateralType.liquidationRatioD18); - - if (collateralValue.lt(minCollateralRequired)) - // If you're below issuance ratio, you can't withdraw anything - return wei(0); - - const maxWithdrawable = collateralValue.sub(minCollateralRequired).mul(0.98); - - return Wei.min(collateralAmount, maxWithdrawable); - })(); - - if (!collateralType) { - return null; - } - - return ( - - ); -}; diff --git a/liquidity/ui/src/components/Undelegate/index.ts b/liquidity/ui/src/components/Undelegate/index.ts deleted file mode 100644 index a0773f7ae..000000000 --- a/liquidity/ui/src/components/Undelegate/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './Undelegate'; diff --git a/liquidity/ui/src/components/WatchAccountBanner/WatchAccountBanner.tsx b/liquidity/ui/src/components/WatchAccountBanner/WatchAccountBanner.tsx deleted file mode 100644 index d484a4b46..000000000 --- a/liquidity/ui/src/components/WatchAccountBanner/WatchAccountBanner.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import { Alert, AlertIcon, Button, Flex, Heading } from '@chakra-ui/react'; -import { useAccounts } from '@snx-v3/useAccounts'; -import { useWallet } from '@snx-v3/useBlockchain'; -import { useParams } from '@snx-v3/useParams'; -import { FC, useEffect, useState } from 'react'; - -export const WatchAccountBanner: FC = () => { - const [isLoaded, setIsLoaded] = useState(false); - const { activeWallet, connect } = useWallet(); - const { accountId } = useParams(); - const { - data: accounts, - isLoading: isAccountsLoading, - isFetching: isAccountsFetching, - } = useAccounts(); - - useEffect(() => { - setTimeout(() => { - setIsLoaded(true); - }, 200); - }, []); - - if (!isLoaded) { - return null; - } - - if (!activeWallet) { - return ( - - - -
- {accountId && ( - You are currently watching Account #{accountId} - )} - - Please connect your wallet to open, manage or view positions. - -
- -
-
- ); - } - - if (!accountId) { - return null; - } - - if ( - !isAccountsFetching && - !isAccountsLoading && - !!accounts?.length && - !accounts.find((a) => a === accountId) - ) { - return ( - - - - You are currently watching Account #{accountId} - - - ); - } - - return null; -}; diff --git a/liquidity/ui/src/components/Withdraw/Withdraw.tsx b/liquidity/ui/src/components/Withdraw/Withdraw.tsx deleted file mode 100644 index 66cd4bef4..000000000 --- a/liquidity/ui/src/components/Withdraw/Withdraw.tsx +++ /dev/null @@ -1,160 +0,0 @@ -import { Alert, AlertIcon, Button, Collapse, Flex, Text } from '@chakra-ui/react'; -import { Amount } from '@snx-v3/Amount'; -import { BorderBox } from '@snx-v3/BorderBox'; -import { isBaseAndromeda } from '@snx-v3/isBaseAndromeda'; -import { ManagePositionContext } from '@snx-v3/ManagePositionContext'; -import { NumberInput } from '@snx-v3/NumberInput'; -import { useAccountSpecificCollateral } from '@snx-v3/useAccountCollateral'; -import { useAccountCollateralUnlockDate } from '@snx-v3/useAccountCollateralUnlockDate'; -import { useNetwork } from '@snx-v3/useBlockchain'; -import { useCollateralType } from '@snx-v3/useCollateralTypes'; -import { LiquidityPosition } from '@snx-v3/useLiquidityPosition'; -import { useSystemToken } from '@snx-v3/useSystemToken'; -import { useTokenPrice } from '@snx-v3/useTokenPrice'; -import { useWithdrawTimer } from '@snx-v3/useWithdrawTimer'; -import { useContext, useMemo } from 'react'; -import { useParams } from 'react-router-dom'; -import { ZEROWEI } from '@snx-v3/constants'; -import { TokenIcon } from '../TokenIcon'; - -export const Withdraw = ({ - liquidityPosition, - isDebtWithdrawal = false, -}: { - liquidityPosition?: LiquidityPosition; - isDebtWithdrawal?: boolean; -}) => { - const { setWithdrawAmount, withdrawAmount } = useContext(ManagePositionContext); - const accountId = liquidityPosition?.accountId; - const params = useParams(); - const { data: collateralType } = useCollateralType(params.collateralSymbol); - const { network } = useNetwork(); - const isBase = isBaseAndromeda(network?.id, network?.preset); - - const { data: systemToken } = useSystemToken(); - const { data: systemTokenBalance } = useAccountSpecificCollateral( - accountId, - systemToken?.address - ); - - const maxWithdrawable = useMemo(() => { - if (isBase) { - return (liquidityPosition?.accountCollateral.availableCollateral || ZEROWEI).add( - systemTokenBalance?.availableCollateral || ZEROWEI - ); - } - if (isDebtWithdrawal) { - return systemTokenBalance?.availableCollateral || ZEROWEI; - } - return liquidityPosition?.accountCollateral.availableCollateral || ZEROWEI; - }, [ - isBase, - isDebtWithdrawal, - liquidityPosition?.accountCollateral.availableCollateral, - systemTokenBalance?.availableCollateral, - ]); - - const { data: accountCollateralUnlockDate, isLoading: isLoadingDate } = - useAccountCollateralUnlockDate({ - accountId, - }); - - const symbol = isDebtWithdrawal ? systemToken?.symbol : collateralType?.symbol; - const price = useTokenPrice(symbol); - const { minutes, hours, isRunning } = useWithdrawTimer(accountId); - const unlockDate = !isLoadingDate ? accountCollateralUnlockDate : null; - - return ( - - - Withdraw {!isDebtWithdrawal ? 'Collateral' : ''} - - - - - - - {symbol} - - - - {isDebtWithdrawal ? 'Max Withdraw:' : 'Unlocked:'} - - {maxWithdrawable.gt(0) && ( - { - if (!maxWithdrawable) { - return; - } - setWithdrawAmount(maxWithdrawable); - }} - color="cyan.500" - fontWeight={700} - > - Max - - )} - - - - setWithdrawAmount(val)} - max={maxWithdrawable} - min={ZEROWEI} - /> - - {price.gt(0) && } - - - - - - - - - You will be able to withdraw assets in {hours}H{minutes}M. Any account activity will - reset this timer to 24H. - - - - - - - - - You can now withdraw - - - - - - - - - You cannot Withdraw more {!isDebtWithdrawal ? 'Collateral' : ''} than your Unlocked - Balance - - - - - - - ); -}; diff --git a/liquidity/ui/src/components/Withdraw/index.ts b/liquidity/ui/src/components/Withdraw/index.ts deleted file mode 100644 index dc0dc8965..000000000 --- a/liquidity/ui/src/components/Withdraw/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from '.'; diff --git a/liquidity/ui/src/components/index.ts b/liquidity/ui/src/components/index.ts deleted file mode 100644 index 49b56ebcd..000000000 --- a/liquidity/ui/src/components/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -export * from './Assets'; -export * from './CollateralAlert'; -export * from './Rewards'; -export * from './SynthSkeleton'; -export * from './Stats'; -export * from './Positions'; -export * from './Balance'; -export * from './TokenIcon'; -export * from './Borrow'; -export * from './Deposit'; -export * from './Manage'; -export * from './Repay'; -export * from './Undelegate'; -export * from './AccountBanner'; -export * from './Pools'; -export * from './Claim'; -export * from './Withdraw'; diff --git a/liquidity/ui/src/index.tsx b/liquidity/ui/src/index.tsx deleted file mode 100644 index 11606e2d9..000000000 --- a/liquidity/ui/src/index.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import ReactDOM from 'react-dom/client'; -import { App } from './App'; - -const container = document.querySelector('#app'); - -export async function bootstrap() { - if (!container) { - throw new Error('Container #app does not exist'); - } - - if (process.env.NODE_ENV === 'development') { - const { Wei, wei } = await import('@synthetixio/wei'); - const { ethers } = await import('ethers'); - // @ts-ignore - window.devtoolsFormatters = window.devtoolsFormatters ?? []; - // @ts-ignore - window.devtoolsFormatters.push({ - header: function (obj: any) { - if (obj instanceof ethers.BigNumber) { - return [ - 'div', - { style: 'color: #f33' }, - ['span', {}, 'ethers.BigNumber('], - ['span', { style: 'color: #3f3' }, wei(obj).toString()], - ['span', {}, ')'], - ]; - } - if (obj instanceof Wei) { - return [ - 'div', - { style: 'color: #f33' }, - ['span', {}, 'Wei('], - ['span', { style: 'color: #3f3' }, obj.toString()], - ['span', {}, ')'], - ]; - } - return null; - }, - hasBody: function () { - return false; - }, - }); - } - - const root = ReactDOM.createRoot(container); - root.render(); -} diff --git a/liquidity/ui/src/layouts/Default/DefaultLayout.tsx b/liquidity/ui/src/layouts/Default/DefaultLayout.tsx deleted file mode 100644 index 2ded60c0b..000000000 --- a/liquidity/ui/src/layouts/Default/DefaultLayout.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { FC } from 'react'; -import { Box, Container, Flex } from '@chakra-ui/react'; -import { Outlet } from 'react-router-dom'; -import Header from './Header'; -import { Footer } from './Footer'; - -export const DefaultLayout: FC = () => ( - - -
- - - -