Showing preview only (8,864K chars total). Download the full file or copy to clipboard to get everything.
Repository: Rari-Capital/rari-dApp
Branch: master
Commit: f95a64b97ad4
Files: 307
Total size: 21.0 MB
Directory structure:
gitextract_warb6kwy/
├── .eslintignore
├── .github/
│ └── workflows/
│ ├── tests.yml
│ └── translations.yml
├── .gitignore
├── .nycrc.json
├── .prettierrc
├── .vscode/
│ └── launch.json
├── LICENSE
├── README.md
├── api/
│ ├── rss.ts
│ ├── stats.ts
│ ├── tokenData.ts
│ └── tsconfig.json
├── cypress/
│ ├── README.md
│ ├── e2e/
│ │ └── E2E.spec.js
│ ├── fixtures/
│ │ └── example.json
│ ├── plugins/
│ │ └── index.js
│ └── support/
│ ├── commands.js
│ └── index.js
├── cypress.json
├── hardhat.config.js
├── i18next-scanner.config.js
├── package.json
├── public/
│ ├── index.html
│ ├── manifest.json
│ └── robots.txt
├── src/
│ ├── components/
│ │ ├── App.tsx
│ │ ├── pages/
│ │ │ ├── ErrorPage.tsx
│ │ │ ├── Fuse/
│ │ │ │ ├── FuseLiquidationsPage.tsx
│ │ │ │ ├── FusePoolCreatePage.tsx
│ │ │ │ ├── FusePoolEditPage.tsx
│ │ │ │ ├── FusePoolInfoPage.tsx
│ │ │ │ ├── FusePoolPage.tsx
│ │ │ │ ├── FusePoolsPage.tsx
│ │ │ │ ├── FuseStatsBar.tsx
│ │ │ │ ├── FuseTabBar.tsx
│ │ │ │ └── Modals/
│ │ │ │ ├── AddAssetModal/
│ │ │ │ │ ├── AddAssetModal.tsx
│ │ │ │ │ ├── AssetConfig.tsx
│ │ │ │ │ ├── AssetSettings.tsx
│ │ │ │ │ ├── DeployButton.tsx
│ │ │ │ │ ├── IRMChart.tsx
│ │ │ │ │ ├── OracleConfig/
│ │ │ │ │ │ ├── BaseTokenOracleConfig.tsx
│ │ │ │ │ │ ├── OracleConfig.tsx
│ │ │ │ │ │ ├── UniswapV2OrSushiPriceOracleConfigurator.tsx
│ │ │ │ │ │ └── UniswapV3PriceOracleConfigurator.tsx
│ │ │ │ │ └── Screens/
│ │ │ │ │ ├── Screen1.tsx
│ │ │ │ │ ├── Screen2.tsx
│ │ │ │ │ └── Screen3.tsx
│ │ │ │ ├── AddAssetModal.tsx
│ │ │ │ ├── AddRewardsDistributorModal.tsx
│ │ │ │ ├── Edit/
│ │ │ │ │ ├── AssetConfiguration.tsx
│ │ │ │ │ ├── MarketCapConfigurator.tsx
│ │ │ │ │ ├── OraclesTable.tsx
│ │ │ │ │ └── PoolConfiguration.tsx
│ │ │ │ ├── EditRewardsDistributorModal.tsx
│ │ │ │ └── PoolModal/
│ │ │ │ ├── AmountSelect.tsx
│ │ │ │ └── index.tsx
│ │ │ ├── InterestRates/
│ │ │ │ ├── InterestRates.tsx
│ │ │ │ ├── InterestRatesTable.tsx
│ │ │ │ ├── InterestRatesView.tsx
│ │ │ │ ├── MultiPicker.tsx
│ │ │ │ └── TokenSearch.tsx
│ │ │ ├── MultiPoolPortal.tsx
│ │ │ ├── Pool2/
│ │ │ │ ├── Pool2Modal/
│ │ │ │ │ ├── AmountSelect.tsx
│ │ │ │ │ ├── OptionsMenu.tsx
│ │ │ │ │ └── index.tsx
│ │ │ │ └── Pool2Page.tsx
│ │ │ ├── PoolPortal.tsx
│ │ │ ├── RariDepositModal/
│ │ │ │ ├── AmountSelect.tsx
│ │ │ │ ├── OptionsMenu.tsx
│ │ │ │ ├── TokenSelect.tsx
│ │ │ │ └── index.tsx
│ │ │ ├── Stats/
│ │ │ │ ├── StatsEarnSection.tsx
│ │ │ │ ├── StatsFuseSection.tsx
│ │ │ │ ├── StatsPage.tsx
│ │ │ │ ├── StatsPool2Section.tsx
│ │ │ │ ├── StatsSubNav.tsx
│ │ │ │ ├── StatsTranchesSection.tsx
│ │ │ │ ├── Totals/
│ │ │ │ │ ├── EarnRow.tsx
│ │ │ │ │ ├── FuseRow.tsx
│ │ │ │ │ ├── Pool2Row.tsx
│ │ │ │ │ ├── StatsTotalSection.tsx
│ │ │ │ │ └── TranchesRow.tsx
│ │ │ │ └── index.ts
│ │ │ └── Tranches/
│ │ │ ├── SaffronContext.tsx
│ │ │ ├── SaffronDepositModal/
│ │ │ │ ├── AmountSelect.tsx
│ │ │ │ └── index.tsx
│ │ │ ├── SaffronPoolABI.json
│ │ │ ├── SaffronStrategyABI.json
│ │ │ └── TranchesPage.tsx
│ │ └── shared/
│ │ ├── AccountButton.tsx
│ │ ├── AdminAlert.tsx
│ │ ├── CTokenIcon.tsx
│ │ ├── CaptionedStat.tsx
│ │ ├── ClaimRGTModal.tsx
│ │ ├── CopyrightSpacer.tsx
│ │ ├── CountdownBanner.tsx
│ │ ├── DashboardBox.tsx
│ │ ├── Footer.tsx
│ │ ├── FullPageSpinner.test.tsx
│ │ ├── FullPageSpinner.tsx
│ │ ├── GlowingButton.tsx
│ │ ├── Header.tsx
│ │ ├── Layout.tsx
│ │ ├── Logos.tsx
│ │ ├── Modal.tsx
│ │ ├── MovingStat.tsx
│ │ ├── PoolsPerformance.tsx
│ │ ├── ProgressBar.tsx
│ │ ├── SimpleTooltip.tsx
│ │ ├── SliderWithLabel.tsx
│ │ ├── SwitchCSS.tsx
│ │ ├── TransactionStepper.tsx
│ │ └── TranslateButton.tsx
│ ├── constants/
│ │ ├── homepage.ts
│ │ ├── networks.ts
│ │ ├── pools.ts
│ │ ├── saffron.ts
│ │ └── tokenData.ts
│ ├── context/
│ │ ├── AddAssetContext.tsx
│ │ ├── PoolContext.tsx
│ │ └── RariContext.tsx
│ ├── fuse-sdk/
│ │ ├── .browserslistrc
│ │ ├── .gitattributes
│ │ ├── .gitignore
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── package.json
│ │ ├── scripts/
│ │ │ └── minify-contracts.js
│ │ ├── src/
│ │ │ ├── abi/
│ │ │ │ ├── FuseFeeDistributor.json
│ │ │ │ ├── FusePoolDirectory.json
│ │ │ │ ├── FusePoolLens.json
│ │ │ │ ├── FusePoolLensSecondary.json
│ │ │ │ ├── FuseSafeLiquidator.json
│ │ │ │ ├── InitializableClones.json
│ │ │ │ └── UniswapV3Pool.slim.json
│ │ │ ├── contracts/
│ │ │ │ ├── compound-protocol.json
│ │ │ │ ├── compound-protocol.min.json
│ │ │ │ ├── open-oracle.json
│ │ │ │ ├── open-oracle.min.json
│ │ │ │ ├── oracles/
│ │ │ │ │ ├── AlphaHomoraV1PriceOracle.json
│ │ │ │ │ ├── BalancerLpTokenPriceOracle.json
│ │ │ │ │ ├── ChainlinkPriceOracle.json
│ │ │ │ │ ├── CurveLpTokenPriceOracle.json
│ │ │ │ │ ├── Keep3rPriceOracle.json
│ │ │ │ │ ├── MasterPriceOracle.json
│ │ │ │ │ ├── PreferredPriceOracle.json
│ │ │ │ │ ├── RecursivePriceOracle.json
│ │ │ │ │ ├── SynthetixPriceOracle.json
│ │ │ │ │ ├── UniswapLpTokenPriceOracle.json
│ │ │ │ │ ├── UniswapTwapPriceOracleV2Factory.json
│ │ │ │ │ ├── UniswapV3TwapPriceOracleV2Factory.json
│ │ │ │ │ ├── YVaultV1PriceOracle.json
│ │ │ │ │ └── YVaultV2PriceOracle.json
│ │ │ │ └── oracles.min.json
│ │ │ ├── index.js
│ │ │ └── irm/
│ │ │ ├── DAIInterestRateModelV2.js
│ │ │ ├── JumpRateModel.js
│ │ │ ├── JumpRateModelV2.js
│ │ │ └── WhitePaperInterestRateModel.js
│ │ ├── test/
│ │ │ ├── launch-pools.js
│ │ │ ├── live-price-oracle.js
│ │ │ ├── oracles.js
│ │ │ ├── public-contracts.js
│ │ │ ├── safe-liquidator.js
│ │ │ └── update-interest-rate-models-v2.js
│ │ └── webpack.config.js
│ ├── hooks/
│ │ ├── fuse/
│ │ │ ├── useCTokenData.ts
│ │ │ ├── useFusePools.ts
│ │ │ ├── useFuseTVL.ts
│ │ │ ├── useFuseTotalBorrowAndSupply.ts
│ │ │ ├── useIRMCurves.ts
│ │ │ ├── useLiquidationIncentive.ts
│ │ │ ├── useOracleData.ts
│ │ │ └── useOraclesForPool.ts
│ │ ├── homepage/
│ │ │ └── useOpportunitySubtitle.ts
│ │ ├── interestRates/
│ │ │ ├── aave/
│ │ │ │ ├── LendingPool.ts
│ │ │ │ └── useReserves.ts
│ │ │ ├── compound/
│ │ │ │ ├── CErc20.ts
│ │ │ │ ├── contracts/
│ │ │ │ │ └── CErc20.json
│ │ │ │ └── useCompoundMarkets.ts
│ │ │ ├── fuse/
│ │ │ │ └── useFuseMarkets.ts
│ │ │ └── types.ts
│ │ ├── pool2/
│ │ │ ├── usePool2APR.ts
│ │ │ ├── usePool2Balance.ts
│ │ │ ├── usePool2TotalStaked.ts
│ │ │ ├── usePool2UnclaimedRGT.ts
│ │ │ └── useSushiswapRewards.ts
│ │ ├── rewards/
│ │ │ ├── useClaimable.ts
│ │ │ ├── usePoolIncentives.ts
│ │ │ ├── useRewardAPY.ts
│ │ │ ├── useRewardsDistributorsForPool.ts
│ │ │ ├── useUnclaimedFuseRewards.ts
│ │ │ └── useUnclaimedRGT.ts
│ │ ├── tranches/
│ │ │ ├── useSFIDistributions.ts
│ │ │ ├── useSFIEarnings.ts
│ │ │ └── useSaffronData.ts
│ │ ├── useAssetsMap.ts
│ │ ├── useAuthedCallback.ts
│ │ ├── useBorrowLimit.ts
│ │ ├── useFusePoolData.ts
│ │ ├── useIsSemiSmallScreen.tsx
│ │ ├── useIsSmallScreen.tsx
│ │ ├── useIsUpgradable.ts
│ │ ├── useMaxWithdraw.ts
│ │ ├── useMaybeResponsiveProp.ts
│ │ ├── useNoSlippageCurrencies.ts
│ │ ├── usePoolAPY.ts
│ │ ├── usePoolBalance.ts
│ │ ├── usePoolInfo.ts
│ │ ├── usePoolInterest.ts
│ │ ├── useRSS.ts
│ │ ├── useTVL.ts
│ │ ├── useTokenBalance.ts
│ │ └── useTokenData.ts
│ ├── index.css
│ ├── index.tsx
│ ├── locales/
│ │ ├── en.json
│ │ ├── zh-CN.json
│ │ └── zh-TW.json
│ ├── rari-sdk/
│ │ ├── 0x.js
│ │ ├── abi/
│ │ │ └── ERC20.json
│ │ ├── cache.js
│ │ ├── docs/
│ │ │ ├── governance.md
│ │ │ └── pools/
│ │ │ ├── ethereum.md
│ │ │ ├── stable.md
│ │ │ └── yield.md
│ │ ├── governance/
│ │ │ └── abi/
│ │ │ ├── RariGovernanceToken.json
│ │ │ ├── RariGovernanceTokenDistributor.json
│ │ │ ├── RariGovernanceTokenUniswapDistributor.json
│ │ │ └── RariGovernanceTokenVesting.json
│ │ ├── governance.js
│ │ ├── index.js
│ │ ├── package.json
│ │ ├── pools/
│ │ │ ├── dai/
│ │ │ │ └── abi/
│ │ │ │ └── legacy/
│ │ │ │ └── v1.0.0/
│ │ │ │ ├── RariFundController.json
│ │ │ │ └── RariFundProxy.json
│ │ │ ├── dai.js
│ │ │ ├── ethereum/
│ │ │ │ └── abi/
│ │ │ │ ├── RariFundController.json
│ │ │ │ ├── RariFundManager.json
│ │ │ │ ├── RariFundProxy.json
│ │ │ │ ├── RariFundToken.json
│ │ │ │ └── legacy/
│ │ │ │ └── v1.0.0/
│ │ │ │ └── RariFundController.json
│ │ │ ├── ethereum.js
│ │ │ ├── stable/
│ │ │ │ └── abi/
│ │ │ │ ├── RariFundController.json
│ │ │ │ ├── RariFundManager.json
│ │ │ │ ├── RariFundPriceConsumer.json
│ │ │ │ ├── RariFundProxy.json
│ │ │ │ ├── RariFundToken.json
│ │ │ │ └── legacy/
│ │ │ │ ├── v1.0.0/
│ │ │ │ │ ├── RariFundManager.json
│ │ │ │ │ ├── RariFundProxy.json
│ │ │ │ │ └── RariFundToken.json
│ │ │ │ ├── v1.1.0/
│ │ │ │ │ ├── RariFundController.json
│ │ │ │ │ ├── RariFundManager.json
│ │ │ │ │ └── RariFundProxy.json
│ │ │ │ ├── v1.2.0/
│ │ │ │ │ └── RariFundProxy.json
│ │ │ │ ├── v2.0.0/
│ │ │ │ │ ├── RariFundController.json
│ │ │ │ │ ├── RariFundManager.json
│ │ │ │ │ └── RariFundProxy.json
│ │ │ │ ├── v2.2.0/
│ │ │ │ │ └── RariFundProxy.json
│ │ │ │ ├── v2.4.0/
│ │ │ │ │ └── RariFundProxy.json
│ │ │ │ └── v2.5.0/
│ │ │ │ └── RariFundController.json
│ │ │ ├── stable.js
│ │ │ ├── yield/
│ │ │ │ └── abi/
│ │ │ │ └── legacy/
│ │ │ │ ├── v1.0.0/
│ │ │ │ │ ├── RariFundController.json
│ │ │ │ │ └── RariFundProxy.json
│ │ │ │ └── v1.1.0/
│ │ │ │ └── RariFundProxy.json
│ │ │ └── yield.js
│ │ └── subpools/
│ │ ├── aave.js
│ │ ├── alpha/
│ │ │ └── abi/
│ │ │ ├── Bank.json
│ │ │ └── ConfigurableInterestBankConfig.json
│ │ ├── alpha.js
│ │ ├── compound.js
│ │ ├── dydx.js
│ │ ├── fuse/
│ │ │ └── abi/
│ │ │ └── CErc20Delegate.json
│ │ ├── fuse.js
│ │ ├── keeperdao.js
│ │ ├── mstable/
│ │ │ └── abi/
│ │ │ ├── Masset.json
│ │ │ └── MassetValidationHelper.json
│ │ ├── mstable.js
│ │ └── yvault.js
│ ├── rari-sdk.d.ts
│ ├── react-app-env.d.ts
│ ├── setupTests.ts
│ ├── static/
│ │ └── compiled/
│ │ ├── info.txt
│ │ └── tokens.json
│ └── utils/
│ ├── apyUtils.ts
│ ├── bigUtils.ts
│ ├── chakraUtils.tsx
│ ├── chartOptions.ts
│ ├── createComptroller.ts
│ ├── errorHandling.ts
│ ├── fetchFusePoolData.ts
│ ├── fetchPoolAPY.ts
│ ├── fetchPoolInterest.ts
│ ├── fetchTVL.ts
│ ├── format.ts
│ ├── homepage.ts
│ ├── i18n.ts
│ ├── multicall.ts
│ ├── poolIconUtils.ts
│ ├── poolUtils.ts
│ ├── rewards.ts
│ ├── shortAddress.ts
│ ├── stringUtils.ts
│ ├── symbolUtils.ts
│ ├── tokenUtils.ts
│ └── web3Providers.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .eslintignore
================================================
src/rari-sdk/**.*
================================================
FILE: .github/workflows/tests.yml
================================================
name: Tests
on: [push, pull_request]
jobs:
e2e-and-unit:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
persist-credentials: false
- name: Reconfigure git to use HTTP authentication
run: >
git config --global url."https://github.com/".insteadOf
ssh://git@github.com/
- name: Run our Cypress E2E tests
uses: cypress-io/github-action@v2
with:
# Passing environment variables here will pass them as Cypress Environment Variables (https://docs.cypress.io/guides/guides/environment-variables.html), and will not be accessible to the start script
# env: DATABASE_URL=${{ secrets.DATABASE_URL }}
start: npm start
wait-on: "http://localhost:3000"
wait-on-timeout: 120
record: ${{ contains(github.event_name, 'push') }}
env:
# These environment variables will be picked up by the start script
CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
REACT_APP_PORTIS_ID: ${{ secrets.REACT_APP_PORTIS_ID }}
REACT_APP_FORTMATIC_KEY: ${{ secrets.REACT_APP_FORTMATIC_KEY }}
- name: Run unit tests with coverage
run: npm run unit-test
env:
CI: true
- name: Merge our test reports
run: npx merge-cypress-jest-coverage
- name: Upload coverage report to Coveralls
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }} # This is passed by Github, don't worry about setting this.
- name: Report the bundle size of this build
uses: sarthak-saxena/JSBundleSize@master
with:
build_command: npm run build
dist_path: "build"
token: ${{ secrets.GITHUB_TOKEN }}
env:
CI: false
================================================
FILE: .github/workflows/translations.yml
================================================
name: Translations
on: [push]
jobs:
check-translations:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Check all text has been translated
run: npm run check-translations
================================================
FILE: .gitignore
================================================
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
**/node_modules
/.pnp
.pnp.js
# testing
/coverage
/jest-coverage
/cypress-coverage
/.nyc_output
/reports
/src/static/contracts/compiled/*.ts
# production
/build
# misc
.DS_Store
npm-debug.log*
yarn-debug.log*
yarn-error.log*
cypress/screenshots
cypress/videos
cypress.env.json
.next
.now
.vercel
.env
.eslintcache
================================================
FILE: .nycrc.json
================================================
{
"report-dir": "cypress-coverage"
}
================================================
FILE: .prettierrc
================================================
{
"printWidth": 80,
"tabWidth": 2,
"semicolons": true,
"singleQuote": false,
"jsxBracketSameLine": false
}
================================================
FILE: .vscode/launch.json
================================================
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}"
}
]
}
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
================================================
FILE: README.md
================================================
# Rari dApp ·  · [](https://coveralls.io/github/Rari-Capital/rari-dApp?branch=master)
Rari Capital's Web3 Portal.
## Requirements
- node: `v14.17.0`
- npm: `v7.21.0`
## Notes:
<details>
<summary>What are the "compiled" folders in src/static?</summary>
- The `src/static/compiled` folder has misc. files that are auto generated from scripts like: [rari-tokens-generator](https://github.com/Rari-Capital/rari-tokens-generator)
- You can generate these files using `npm install`.
- These files are gitignored so do not worry about trying to commit them!
</details>
================================================
FILE: api/rss.ts
================================================
import { NowRequest, NowResponse } from "@vercel/node";
import { variance, median } from "mathjs";
import fetch from "node-fetch";
import { fetchFusePoolData } from "../src/utils/fetchFusePoolData";
import { initFuseWithProviders, alchemyURL } from "../src/utils/web3Providers";
function clamp(num, min, max) {
return num <= min ? min : num >= max ? max : num;
}
type ThenArg<T> = T extends PromiseLike<infer U> ? U : T;
const weightedCalculation = async (
calculation: () => Promise<number>,
weight: number
) => {
return clamp((await calculation()) ?? 0, 0, 1) * weight;
};
const fuse = initFuseWithProviders(alchemyURL);
async function computeAssetRSS(address: string): Promise<{
liquidityUSD: number;
mcap: number;
volatility: number;
liquidity: number;
swapCount: number;
coingeckoMetadata: number;
exchanges: number;
transfers: number;
totalScore: number;
}> {
address = address.toLowerCase();
// swap sOHM to OHM with a penalty.
if (address === "0x04f2694c8fcee23e8fd0dfea1d4f5bb8c352111f") {
let OHM_RSS = await computeAssetRSS(
"0x383518188c0c6d7730d91b2c03a03c837814a899"
);
// 10% smart contract risk penalty.
OHM_RSS.totalScore *= 0.9;
return OHM_RSS;
}
// max score for ETH.
if (address === "0x0000000000000000000000000000000000000000") {
return {
liquidityUSD: 4_000_000_000,
mcap: 33,
volatility: 20,
liquidity: 32,
swapCount: 7,
coingeckoMetadata: 2,
exchanges: 3,
transfers: 3,
totalScore: 100,
};
}
try {
// Fetch all the data in parallel
const [
{
market_data: {
market_cap: { usd: asset_market_cap },
current_price: { usd: price_usd },
},
tickers,
community_data: { twitter_followers },
},
uniData,
sushiData,
defiCoins,
assetVariation,
ethVariation,
] = await Promise.all([
fetch(
`https://api.coingecko.com/api/v3/coins/ethereum/contract/${address}`
).then((res) => res.json()),
fetch("https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2", {
method: "post",
body: JSON.stringify({
query: `{
token(id: "${address}") {
totalLiquidity
txCount
}
}`,
}),
headers: { "Content-Type": "application/json" },
}).then((res) => res.json()),
fetch(
"https://api.thegraph.com/subgraphs/name/zippoxer/sushiswap-subgraph-fork",
{
method: "post",
body: JSON.stringify({
query: `{
token(id: "${address}") {
totalLiquidity
txCount
}
}`,
}),
headers: { "Content-Type": "application/json" },
}
).then((res) => res.json()),
fetch(
`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&category=decentralized_finance_defi&order=market_cap_desc&per_page=10&page=1&sparkline=false`
)
.then((res) => res.json())
.then((array) => array.slice(0, 30)),
fetch(
`https://api.coingecko.com/api/v3/coins/ethereum/contract/${address}/market_chart/?vs_currency=usd&days=30`
)
.then((res) => res.json())
.then((data) => data.prices.map(([, price]) => price))
.then((prices) => variance(prices)),
fetch(
`https://api.coingecko.com/api/v3/coins/ethereum/market_chart/?vs_currency=usd&days=30`
)
.then((res) => res.json())
.then((data) => data.prices.map(([, price]) => price))
.then((prices) => variance(prices)),
]);
const mcap = await weightedCalculation(async () => {
const medianDefiCoinMcap = median(
defiCoins.map((coin) => coin.market_cap)
);
// Make exception for WETH
if (address === "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2") {
return 1;
}
if (asset_market_cap < 1_000_000) {
return 0;
} else {
return asset_market_cap / medianDefiCoinMcap;
}
}, 33);
let liquidityUSD = 0;
const liquidity = await weightedCalculation(async () => {
const uniLiquidity = parseFloat(
uniData.data.token?.totalLiquidity ?? "0"
);
const sushiLiquidity = parseFloat(
sushiData.data.token?.totalLiquidity ?? "0"
);
const totalLiquidity = uniLiquidity + sushiLiquidity * price_usd;
liquidityUSD = totalLiquidity;
return totalLiquidity / 220_000_000;
}, 32);
const volatility = await weightedCalculation(async () => {
const peak = ethVariation * 3;
return 1 - assetVariation / peak;
}, 20);
const swapCount = await weightedCalculation(async () => {
const uniTxCount = parseFloat(uniData.data.token?.txCount ?? "0");
const sushiTxCount = parseFloat(sushiData.data.token?.txCount ?? "0");
const totalTxCount = uniTxCount + sushiTxCount;
return totalTxCount >= 10_000 ? 1 : 0;
}, 7);
const exchanges = await weightedCalculation(async () => {
let reputableExchanges: any[] = [];
for (const exchange of tickers) {
const name = exchange.market.identifier;
if (
!reputableExchanges.includes(name) &&
name !== "uniswap" &&
exchange.trust_score === "green"
) {
reputableExchanges.push(name);
}
}
return reputableExchanges.length >= 3 ? 1 : 0;
}, 3);
const transfers = await weightedCalculation(async () => {
return 1;
}, 3);
const coingeckoMetadata = await weightedCalculation(async () => {
// USDC needs an exception because Circle twitter is not listed on Coingecko.
if (address === "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48") {
return 1;
}
return twitter_followers >= 1000 ? 1 : 0;
}, 2);
return {
liquidityUSD,
mcap,
volatility,
liquidity,
swapCount,
coingeckoMetadata,
exchanges,
transfers,
totalScore:
mcap +
volatility +
liquidity +
swapCount +
coingeckoMetadata +
exchanges +
transfers || 0,
};
} catch (e) {
console.log(e);
return {
liquidityUSD: 0,
mcap: 0,
volatility: 0,
liquidity: 0,
swapCount: 0,
coingeckoMetadata: 0,
exchanges: 0,
transfers: 0,
totalScore: 0,
};
}
}
export default async (request: NowRequest, response: NowResponse) => {
const { address, poolID } = request.query as { [key: string]: string };
response.setHeader("Access-Control-Allow-Origin", "*");
let lastUpdated = new Date().toLocaleString("en-US", {
timeZone: "America/Los_Angeles",
});
try {
if (address) {
response.setHeader("Cache-Control", "s-maxage=3600");
response.json({ ...(await computeAssetRSS(address)), lastUpdated });
} else if (poolID) {
console.time("poolData");
const { assets, totalLiquidityUSD, comptroller } = (await fetchFusePoolData(
poolID,
"0x0000000000000000000000000000000000000000",
fuse
))!;
console.timeEnd("poolData");
const liquidity = await weightedCalculation(async () => {
return totalLiquidityUSD > 50_000 ? totalLiquidityUSD / 2_000_000 : 0;
}, 25);
const collateralFactor = await weightedCalculation(async () => {
// @ts-ignore
const avgCollatFactor = assets.reduce(
(a, b, _, { length }) => a + b.collateralFactor / 1e16 / length,
0
);
// Returns a percentage in the range of 45% -> 90% (where 90% is 0% and 45% is 100%)
return -1 * (1 / 45) * avgCollatFactor + 2;
}, 10);
const reserveFactor = await weightedCalculation(async () => {
// @ts-ignore
const avgReserveFactor = assets.reduce(
(a, b, _, { length }) => a + b.reserveFactor / 1e16 / length,
0
);
return avgReserveFactor <= 2 ? 0 : avgReserveFactor / 13;
}, 10);
const utilization = await weightedCalculation(async () => {
for (let i = 0; i < assets.length; i++) {
const asset = assets[i];
// If this asset has more than 75% utilization, fail
if (
// @ts-ignore
asset.totalSupply === "0"
? false
: asset.totalBorrow / asset.totalSupply >= 0.75
) {
return 0;
}
}
return 1;
}, 10);
let assetsRSS: ThenArg<ReturnType<typeof computeAssetRSS>>[] = [];
let totalRSS = 0;
let promises: Promise<any>[] = [];
for (let i = 0; i < assets.length; i++) {
const asset = assets[i];
console.time(asset.underlyingSymbol);
promises.push(
fetch(
`http://${process.env.VERCEL_URL}/api/rss?address=` +
asset.underlyingToken
)
.then((res) => res.json())
.then((rss) => {
assetsRSS[i] = rss;
totalRSS += rss.totalScore;
console.timeEnd(asset.underlyingSymbol);
})
);
}
await Promise.all(promises);
const averageRSS = await weightedCalculation(async () => {
return totalRSS / assets.length / 100;
}, 15);
const upgradeable = await weightedCalculation(async () => {
try {
const { 0: admin, 1: upgradeable } =
await fuse.contracts.FusePoolLens.methods
.getPoolOwnership(comptroller)
.call({ gas: 1e18 });
// These addresses MUST be ALL LOWERCASE!
const rariMultisigs = [
"0xa731585ab05fc9f83555cf9bff8f58ee94e18f85",
"0x5ea4a9a7592683bf0bc187d6da706c6c4770976f",
"0x7d7ec1c9b40f8d4125d2ee524e16b65b3ee83e8f",
"0x7b502f1aa0f48b83ca6349e1f42cacd8150307a6",
"0x521cf3d673f4b2025be0bdb03d6410b111cd17d5",
"0x49529a7ccbd9f8cabbfa36c65feb39ae08bdea0f",
"0x639572471f2f318464dc01066a56867130e45e25",
"0x7b34e07da62c716ab79390d37e09182b48f1936d",
"0x0cf30dc0d48604a301df8010cdc028c055336b2e",
];
if (rariMultisigs.includes(admin.toLowerCase())) {
return 1;
}
return upgradeable ? 0 : 1;
} catch (e) {
// Assume upgradeable.
return 0;
}
}, 10);
const mustPass = await weightedCalculation(async () => {
const comptrollerContract = new fuse.web3.eth.Contract(
JSON.parse(
fuse.compoundContracts["contracts/Comptroller.sol:Comptroller"].abi
),
comptroller
);
// Ex: 8
const liquidationIncentive =
(await comptrollerContract.methods
.liquidationIncentiveMantissa()
.call()) /
1e16 -
100;
for (let i = 0; i < assetsRSS.length; i++) {
const rss = assetsRSS[i];
const asset = assets[i];
// Ex: 75
const collateralFactor = asset.collateralFactor / 1e16;
// If the AMM liquidity is less than 2x the $ amount supplied, fail
if (rss.liquidityUSD < 2 * asset.totalSupplyUSD) {
return 0;
}
// If any of the RSS asset scores are less than 60, fail
if (rss.totalScore < 60) {
return 0;
}
// If the collateral factor and liquidation incentive do not have at least a 5% safety margin, fail
if (collateralFactor + liquidationIncentive > 95) {
/*
See this tweet for why: https://twitter.com/transmissions11/status/1378862288266960898
TLDR: If CF and LI add up to be greater than 100 then any liquidation will result in instant insolvency. 95 has been determined to be the highest sum that could be considered "safe".
*/
return 0;
}
// If the liquidation incentive is less than or equal to 1/10th of the collateral factor, fail
if (liquidationIncentive <= collateralFactor / 10) {
return 0;
}
}
return 1;
}, 20);
response.setHeader("Cache-Control", "s-maxage=3600");
response.json({
liquidity,
collateralFactor,
reserveFactor,
utilization,
averageRSS,
upgradeable,
mustPass,
totalScore:
liquidity +
collateralFactor +
reserveFactor +
utilization +
averageRSS +
upgradeable +
mustPass || 0,
lastUpdated,
});
console.log("done!");
} else {
return response.status(404).send("Specify address or poolID!");
}
} catch (err) {
return response.status(500).send("Error fetching RSS.");
}
};
================================================
FILE: api/stats.ts
================================================
import { NowRequest, NowResponse } from "@vercel/node";
import Rari from "../src/rari-sdk/index";
import { alchemyURL, initFuseWithProviders } from "../src/utils/web3Providers";
import { perPoolTVL } from "../src/utils/fetchTVL";
import {
fetchDAIPoolAPY,
fetchPoolAPY,
fetchRGTAPR,
} from "../src/utils/fetchPoolAPY";
import { Pool } from "../src/utils/poolUtils";
const rari = new Rari(alchemyURL);
const fuse = initFuseWithProviders();
const mantissaToFloat = (BN: any) => {
return parseFloat(rari.web3.utils.fromWei(BN));
};
export default async (request: NowRequest, response: NowResponse) => {
const [
tvls,
rawStablePoolAPY,
rawYieldPoolAPY,
rawEthPoolAPY,
rawDaiPoolAPY,
rawRgtAPR,
] = await Promise.all([
perPoolTVL(rari, fuse),
fetchPoolAPY(rari, Pool.USDC),
fetchPoolAPY(rari, Pool.YIELD),
fetchPoolAPY(rari, Pool.ETH),
fetchDAIPoolAPY(rari),
fetchRGTAPR(rari),
]);
const stablePoolAPY = parseFloat(rawStablePoolAPY!);
const yieldPoolAPY = parseFloat(rawYieldPoolAPY!);
const ethPoolAPY = parseFloat(rawEthPoolAPY!);
const daiPoolAPY = parseFloat(rawDaiPoolAPY!);
const rgtAPR = parseFloat(rawRgtAPR);
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Cache-Control", "s-maxage=600");
response.json({
tvl: mantissaToFloat(
tvls.stableTVL
.add(tvls.yieldTVL)
.add(tvls.ethTVL)
.add(tvls.daiTVL)
.add(tvls.stakedTVL)
.add(tvls.fuseTVL)
),
stableTVL: mantissaToFloat(tvls.stableTVL),
yieldTVL: mantissaToFloat(tvls.yieldTVL),
ethTVL: mantissaToFloat(tvls.ethTVL),
daiTVL: mantissaToFloat(tvls.daiTVL),
stakedTVL: mantissaToFloat(tvls.stakedTVL),
fuseTVL: mantissaToFloat(tvls.fuseTVL),
///////////
rgtAPR,
stablePoolAPY,
ethPoolAPY,
yieldPoolAPY,
daiPoolAPY,
});
};
================================================
FILE: api/tokenData.ts
================================================
import Vibrant from "node-vibrant";
import { Palette } from "node-vibrant/lib/color";
import fetch from "node-fetch";
import Web3 from "web3";
import ERC20ABI from "../src/rari-sdk/abi/ERC20.json";
import { TokenDataOverrides } from "../src/constants/tokenData";
import {
ChainID,
isSupportedChainId,
coingeckoNetworkPath,
networkData,
} from "../src/constants/networks";
import { VercelRequest, VercelResponse } from "@vercel/node";
import axios from "axios";
type TokenData = {
color;
overlayTextColor;
address;
chainId;
};
/**
* Ok so coingecko has minimal data on tokens not on Ethereum
* For L2, we must rely on projects maintaining L2 tokenLists
*
*/
// params: address (required), chainId (optional) (default 1)
let method: "RARI" | "COINGECKO" | "CONTRACT";
export default async (request: VercelRequest, response: VercelResponse) => {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Cache-Control", "max-age=3600, s-maxage=3600");
const { address: _address, chainId: _chainId = "1" } = request.query;
let chainId: number;
// Validate ChainID
try {
chainId = parseInt(_chainId as string);
if (!isSupportedChainId(chainId)) {
throw "Unsupported ChainID";
}
} catch {
return response.status(500).send(`Unsupported Chain ID: ${_chainId}`);
}
// Try to get networkdata
const netData = networkData[chainId];
if (!netData) {
return response
.status(500)
.send(
`Network supported but Could not find network data for chain ID: ${chainId}`
);
}
// Instiantate variables
let name: string;
let symbol: string;
let logoURL: string =
"https://raw.githubusercontent.com/feathericons/feather/master/icons/help-circle.svg";
// Instantiate Token Contract on proper chain
const web3 = new Web3(netData.rpc);
const address = web3.utils.toChecksumAddress(_address as string);
const tokenContract = new web3.eth.Contract(ERC20ABI as any, address);
// L1/L2 URLS
const rariURL = `https://raw.githubusercontent.com/sharad-s/rari-token-list/main/tokens/${chainId}/${address}/info.json`;
const coingeckoURL = `https://api.coingecko.com/api/v3/coins/${coingeckoNetworkPath[chainId]}/contract/${address}`;
// L1 URLS
const trustWalletURL = `https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/${address}/logo.png`;
const yearnLogoURL = `https://raw.githubusercontent.com/yearn/yearn-assets/master/icons/tokens/${address}/logo-128.png`;
let decimals = 18;
let rariTokenData;
// Get decimals, return 404 if cant
try {
decimals = await tokenContract.methods.decimals().call();
} catch {
return response
.status(404)
.send(`Invalid Token ${address} on chain ${chainId}`);
}
// Rari Token Data
try {
// Fetch data from rari token data first
const { data } = await axios.get(rariURL);
rariTokenData = data;
} catch (err) {
console.log(`Could not find Rari Token Data at url ${rariURL}}`);
} finally {
console.log({ rariTokenData, rariURL });
}
//1.) Try Rari Token list 2.) Try Coingecko 3.) Try contracts
if (!!rariTokenData) {
// We got data from rari token list
let { symbol: _symbol, name: _name, logoURI } = rariTokenData;
symbol =
_symbol == !!_symbol?.toLowerCase() ? _symbol.toUpperCase() : _symbol;
name = _name;
logoURL = logoURI;
method = "RARI";
} else {
// We could not get data from rari token list. Try Coingecko
const { data: coingeckoData } = await axios.get(coingeckoURL);
if (!!coingeckoData) {
// We got data from Coingecko
let {
symbol: _symbol,
name: _name,
image: { small },
} = coingeckoData;
symbol =
_symbol == !!_symbol?.toLowerCase() ? _symbol?.toUpperCase() : _symbol;
name = _name;
// Prefer the logo from trustwallet if possible!
const trustWalletLogoResponse = await fetch(trustWalletURL);
if (trustWalletLogoResponse.ok) {
logoURL = trustWalletURL;
} else {
logoURL = small;
}
method = "COINGECKO";
} else {
// We could not get data from coingecko. Use the contract data
try {
name = await tokenContract.methods.name().call();
symbol = await tokenContract.methods.symbol().call();
} catch (err) {
return response
.status(404)
.send(
`Could not get name and symbol for token ${address} on chain ${chainId}`
);
}
// We can't get the logo data from literally anywhere else so try one last time from yearn
const yearnLogoResponse = await fetch(yearnLogoURL);
if (yearnLogoResponse.ok) {
// A lot of the yearn tokens are curve tokens with long names,
// so we flatten them here and just remove the Curve part
symbol = symbol.replace("Curve-", "");
logoURL = yearnLogoURL;
}
method = "CONTRACT";
}
}
// Assign any overides if any specified
let overrides = {};
if (!!TokenDataOverrides[chainId]) {
overrides = TokenDataOverrides[chainId][address] ?? {};
}
const basicTokenInfo = Object.assign(
{},
{
symbol,
name,
decimals,
logoURL,
},
overrides
);
console.log({ overrides, basicTokenInfo, address });
// Get the color
let color: Palette;
try {
if (basicTokenInfo.logoURL === undefined) {
// If we have no logo no need to try to get the color
// just go to the catch block and return the default logo.
throw "Go to the catch block";
}
color = await Vibrant.from(basicTokenInfo.logoURL).getPalette();
} catch (error) {
return response.json({
...basicTokenInfo,
color: "#FFFFFF",
overlayTextColor: "#000",
address,
});
}
if (!color.Vibrant) {
response.json({
...basicTokenInfo,
color: "#FFFFFF",
overlayTextColor: "#000",
address,
});
return;
}
response.json({
...basicTokenInfo,
color: color.Vibrant.getHex(),
overlayTextColor: color.Vibrant.getTitleTextColor(),
address,
});
};
================================================
FILE: api/tsconfig.json
================================================
{
"compilerOptions": {
"target": "es5",
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"noImplicitAny": false,
"noFallthroughCasesInSwitch": true
},
"include": ["."]
}
================================================
FILE: cypress/README.md
================================================
# Cypress.io end-to-end tests
[Cypress.io](https://www.cypress.io) is an open source, MIT licensed end-to-end test runner
## Folder structure
These folders hold end-to-end tests and supporting files for the Cypress Test Runner.
- [fixtures](fixtures) holds optional JSON data for mocking, [read more](https://on.cypress.io/fixture)
- [e2e](integration) holds the actual test files, [read more](https://on.cypress.io/writing-and-organizing-tests)
- [plugins](plugins) allow you to customize how tests are loaded, [read more](https://on.cypress.io/plugins)
- [support](support) file runs before all tests and is a great place to write or load additional custom commands, [read more](https://on.cypress.io/writing-and-organizing-tests#Support-file)
## `cypress.json` file
You can configure project options in the [../cypress.json](../cypress.json) file, see [Cypress configuration doc](https://on.cypress.io/configuration).
## More information
- [https://github.com/cypress.io/cypress](https://github.com/cypress.io/cypress)
- [https://docs.cypress.io/](https://docs.cypress.io/)
- [Writing your first Cypress test](http://on.cypress.io/intro)
================================================
FILE: cypress/e2e/E2E.spec.js
================================================
// type definitions for Cypress object "cy"
/// <reference types="cypress" />
describe("E2E", function () {
before(() => {
cy.visit("/");
});
it("renders the pool page", () => {
cy.findByText(/Latest Rari News/i).should("be.visible");
});
});
================================================
FILE: cypress/fixtures/example.json
================================================
{
"name": "Using fixtures to represent data",
"email": "hello@cypress.io",
"body": "Fixtures are a great way to mock data for responses to routes"
}
================================================
FILE: cypress/plugins/index.js
================================================
// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************
// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
require("@cypress/code-coverage/task")(on, config);
return config;
};
================================================
FILE: cypress/support/commands.js
================================================
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add("login", (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })
import "@testing-library/cypress/add-commands";
================================================
FILE: cypress/support/index.js
================================================
// ***********************************************************
// This example support/index.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************
// Import commands.js using ES2015 syntax:
import "./commands";
// Import cypress/code-coverage/support for code coverage
import "@cypress/code-coverage/support";
// Alternatively you can use CommonJS syntax:
// require('./commands')
================================================
FILE: cypress.json
================================================
{
"baseUrl": "http://localhost:3000",
"integrationFolder": "cypress/e2e",
"projectId": "s8v41s"
}
================================================
FILE: hardhat.config.js
================================================
/**
* @type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.7.3",
networks: {
hardhat: {
forking: {
url: "https://eth-mainnet.alchemyapi.io/v2/2Mt-6brbJvTA4w9cpiDtnbTo6qOoySnN"
},
blockGasLimit: 12500000,
initialBaseFeePerGas: "0",
allowUnlimitedContractSize: true,
}
}
};
================================================
FILE: i18next-scanner.config.js
================================================
module.exports = {
input: ["./src/**/*.{ts,tsx}"],
output: "./",
options: {
debug: true,
removeUnusedKeys: true,
func: {
list: ["t"],
extensions: [".ts", ".tsx"],
},
lngs: ["en", "zh-CN", "zh-TW"],
defaultLng: "en",
ns: ["translation"],
defaultNs: "translation",
defaultValue: function (lng, ns, key) {
if (lng === "en") {
// Return key as the default value for English language
return key;
}
// Return the string '__NOT_TRANSLATED__' for other languages
return "__NOT_TRANSLATED__";
},
resource: {
loadPath: "./src/locales/{{lng}}.json",
savePath: "./src/locales/{{lng}}.json",
},
nsSeparator: false,
keySeparator: false,
},
};
================================================
FILE: package.json
================================================
{
"name": "rari-dapp",
"version": "3.0.0",
"private": true,
"dependencies": {
"@aave/protocol-v2": "^1.0.1",
"@brainhubeu/react-carousel": "^2.0.3",
"@chakra-ui/icons": "^1.0.0",
"@chakra-ui/react": "^1.3.4",
"@cypress/code-coverage": "^3.8.1",
"@cypress/instrument-cra": "^1.4.0",
"@emotion/react": "^11.0.0",
"@emotion/styled": "^11.0.0",
"@loadable/component": "^5.13.2",
"@sushiswap/default-token-list": "^20.11.0",
"@testing-library/cypress": "^7.0.1",
"@testing-library/jest-dom": "^5.11.2",
"@testing-library/react": "^11.0.4",
"@testing-library/user-event": "^12.1.6",
"@types/jest": "^26.0.13",
"@types/loadable__component": "^5.13.1",
"@types/mathjs": "^6.0.11",
"@types/node": "^14.11.7",
"@types/node-fetch": "^2.5.8",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"@types/react-virtualized-auto-sizer": "^1.0.0",
"@types/react-window": "^1.8.2",
"@walletconnect/web3-provider": "^1.7.1",
"apexcharts": "3.20.2",
"axios": "^0.20.0",
"bad-words": "^3.0.4",
"bignumber.js": "^9.0.1",
"buttered-chakra": "^4.3.0",
"chakra-ui-steps": "^1.3.0",
"cypress": "^5.3.0",
"focus-visible": "^5.2.0",
"framer-motion": "^4.1.11",
"fuse.js": "^6.4.6",
"history": "^5.0.0",
"i18next": "^19.7.0",
"istanbul-lib-coverage": "^3.0.0",
"logrocket": "^1.0.14",
"mathjs": "^9.0.0",
"node-fetch": "^2.6.1",
"node-vibrant": "^3.1.6",
"nyc": "^15.1.0",
"rari-tokens-generator": "^2.0.0",
"react": "^16.13.1",
"react-apexcharts": "1.3.7",
"react-awesome-reveal": "^3.3.1",
"react-dom": "^16.13.1",
"react-double-marquee": "^1.0.6",
"react-error-boundary": "^3.0.2",
"react-fast-marquee": "^1.1.3",
"react-i18next": "^11.7.3",
"react-icons": "^3.11.0",
"react-ios-pwa-prompt": "^1.8.1",
"react-jazzicon": "^0.1.3",
"react-query": "^3.13.10",
"react-responsive-carousel": "^3.2.18",
"react-router-dom": "^6.0.0-beta.0",
"react-scripts": "4.0.1",
"react-spinners": "^0.9.0",
"react-virtualized-auto-sizer": "^1.0.2",
"react-window": "^1.8.5",
"typescript": "^4.0.3",
"walletlink": "^2.4.3",
"web3": "^1.2.11",
"web3modal": "^1.9.5",
"window-table": "^1.0.0-alpha.11"
},
"scripts": {
"typecheck": "tsc --skipLibCheck -p ./tsconfig.json",
"start": "react-scripts -r @cypress/instrument-cra start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"unit-test": "react-scripts test --coverage --watchAll=false --coverageDirectory='jest-coverage'",
"e2e-test": "cypress run",
"test-all-with-coverage": "npm run unit-test && npm run e2e-test && npx merge-cypress-jest-coverage",
"translate": "npx i18next-scanner@2.11.0",
"check-translations": "npm run translate && if grep -q \"__NOT_TRANSLATED__\" src/locales/*.json; then echo \"Translations missing!\"; exit 1; else echo \"All translations present!\"; fi",
"compile-tokens": "node ./src/utils/compileTokenData.js"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.25%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@nomiclabs/hardhat-ethers": "^2.0.2",
"@nomiclabs/hardhat-waffle": "^2.0.1",
"@types/react-query": "^1.1.2",
"@types/react-slick": "^0.23.4",
"@vercel/node": "^1.8.3",
"chai": "^4.3.4",
"ethereum-waffle": "^3.4.0",
"ethers": "^5.4.7",
"hardhat": "^2.6.5"
}
}
================================================
FILE: public/index.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Easily access the Rari Protocol through the Portal’s simple interface."
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Rari Portal</title>
</head>
<body>
<noscript> aHR0cHM6Ly9wYXN0ZWJpbi5jb20vcmF3L1oxN3hocXFE </noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
<!--
This font is only used for displaying APY and a header about the fund.
We only load the alphabet, the numbers, and the % symbol.
-->
<link
href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@700&display=fallback&text=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv1234567890%"
rel="stylesheet"
/>
</html>
================================================
FILE: public/manifest.json
================================================
{
"short_name": "Rari",
"name": "Rari",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
================================================
FILE: public/robots.txt
================================================
# https://www.robotstxt.org/robotstxt.html
User-agent: *
================================================
FILE: src/components/App.tsx
================================================
import { Navigate, Outlet, Route, Routes } from "react-router-dom";
import { Heading } from "@chakra-ui/react";
import loadable from "@loadable/component";
import FullPageSpinner from "./shared/FullPageSpinner";
import { Pool } from "../utils/poolUtils";
import Layout from "./shared/Layout";
import { memo } from "react";
const MultiPoolPortal = loadable(
() => import(/* webpackPrefetch: true */ "./pages/MultiPoolPortal"),
{
fallback: <FullPageSpinner />,
}
);
const PoolPortal = loadable(
() => import(/* webpackPrefetch: true */ "./pages/PoolPortal"),
{
fallback: <FullPageSpinner />,
}
);
const TranchesPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Tranches/TranchesPage"),
{
fallback: <FullPageSpinner />,
}
);
const FusePoolsPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Fuse/FusePoolsPage"),
{
fallback: <FullPageSpinner />,
}
);
const FusePoolPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Fuse/FusePoolPage"),
{
fallback: <FullPageSpinner />,
}
);
const FusePoolInfoPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Fuse/FusePoolInfoPage"),
{
fallback: <FullPageSpinner />,
}
);
const FusePoolEditPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Fuse/FusePoolEditPage"),
{
fallback: <FullPageSpinner />,
}
);
const FusePoolCreatePage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Fuse/FusePoolCreatePage"),
{
fallback: <FullPageSpinner />,
}
);
const FuseLiquidationsPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Fuse/FuseLiquidationsPage"),
{
fallback: <FullPageSpinner />,
}
);
const Pool2Page = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Pool2/Pool2Page"),
{
fallback: <FullPageSpinner />,
}
);
const StatsPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Stats"),
{
fallback: <FullPageSpinner />,
}
);
const InterestRatesPage = loadable(
() =>
import(/* webpackPrefetch: true */ "./pages/InterestRates/InterestRates"),
{
fallback: <FullPageSpinner />,
}
);
const PageNotFound = memo(() => {
return (
<Heading
color="#FFF"
style={{
position: "fixed",
left: "50%",
top: "50%",
marginTop: "-15px",
marginLeft: "-114px",
}}
>
404: Not Found
</Heading>
);
});
const App = memo(() => {
return (
<Layout>
<Routes>
<Route path="/pools" element={<Outlet />}>
{Object.values(Pool).map((pool) => {
return (
<Route
key={pool}
path={pool}
element={<PoolPortal pool={pool} />}
/>
);
})}
</Route>
<Route path="/tranches" element={<TranchesPage />} />
<Route path="/pool2" element={<Pool2Page />} />
<Route path="/fuse" element={<FusePoolsPage />} />
<Route path="/fuse/liquidations" element={<FuseLiquidationsPage />} />
<Route path="/fuse/new-pool" element={<FusePoolCreatePage />} />
<Route path="/fuse/pool/:poolId" element={<FusePoolPage />} />
<Route path="/fuse/pool/:poolId/info" element={<FusePoolInfoPage />} />
<Route path="/fuse/pool/:poolId/edit" element={<FusePoolEditPage />} />
<Route path="/utils" element={<Navigate to="/" replace={true} />} />
<Route path="/utils/interest-rates" element={<InterestRatesPage />} />
<Route path="/utils/positions" element={<StatsPage />} />
{/* Backwards Compatibility Routes */}
<Route
path="/interest_rates"
element={<Navigate to="/utils/interest-rates" replace={true} />}
/>
<Route
path="/interest-rates"
element={<Navigate to="/utils/interest-rates" replace={true} />}
/>
<Route
path="/positions"
element={<Navigate to="/utils/positions" replace={true} />}
/>
{/* Backwards Compatibility Routes */}
<Route path="/" element={<MultiPoolPortal />} />
<Route path="*" element={<PageNotFound />} />
</Routes>
</Layout>
);
});
export default App;
================================================
FILE: src/components/pages/ErrorPage.tsx
================================================
/* istanbul ignore file */
import { Code, Box, Heading, Text, Link } from "@chakra-ui/react";
import { useTranslation } from "react-i18next";
import { ExternalLinkIcon } from "@chakra-ui/icons";
import { FallbackProps } from "react-error-boundary";
const ErrorPage: React.FC<FallbackProps> = ({ error }) => {
const { t } = useTranslation();
return (
<Box color="white">
<Box bg="red.600" width="100%" p={4}>
<Heading>{t("Whoops! Looks like something went wrong!")}</Heading>
<Text>
{t(
"You can either reload the page, or report this error to us on our"
)}{" "}
<Link isExternal href="https://github.com/Rari-Capital/rari-dApp">
<u>GitHub</u>
<ExternalLinkIcon mx="2px" />
</Link>
</Text>
</Box>
<Code colorScheme="red">{error.toString()}</Code>
</Box>
);
};
export default ErrorPage;
================================================
FILE: src/components/pages/Fuse/FuseLiquidationsPage.tsx
================================================
import { Box, Link, Spinner, Text } from "@chakra-ui/react";
import { Column, Row, RowOrColumn, useIsMobile } from "utils/chakraUtils";
import { useTranslation } from "react-i18next";
import { useRari } from "context/RariContext";
import { useIsSmallScreen } from "hooks/useIsSmallScreen";
import { smallUsdFormatter } from "utils/bigUtils";
import DashboardBox from "../../shared/DashboardBox";
import { Header } from "../../shared/Header";
import { ModalDivider } from "../../shared/Modal";
import FuseStatsBar from "./FuseStatsBar";
import FuseTabBar from "./FuseTabBar";
import { filterOnlyObjectProperties, FuseAsset } from "utils/fetchFusePoolData";
import Footer from "components/shared/Footer";
import { memo, useState } from "react";
// @ts-ignore
import Jazzicon, { jsNumberForAddress } from "react-jazzicon";
import { CTokenIcon } from "components/shared/CTokenIcon";
import { useQuery } from "react-query";
export type LiquidatablePosition = {
account: string;
totalBorrow: number;
totalCollateral: number;
totalSupplied: number;
health: number;
assets: FuseAsset[];
poolID: number;
};
export type LiquidationEvent = {
borrower: string;
cTokenBorrowed: string;
cTokenCollateral: string;
borrowedTokenAddress: string;
suppliedTokenAddress: string;
liquidator: string;
borrowedTokenUnderlyingDecimals: number;
borrowedTokenUnderlyingSymbol: string;
repayAmount: number;
seizeTokens: number;
blockNumber: number;
timestamp: number;
transactionHash: string;
transactionIndex: number;
poolID: number;
};
const FuseLiquidationsPage = memo(() => {
const isMobile = useIsSmallScreen();
const { fuse, isAuthed } = useRari();
const { data: liquidations } = useQuery("liquidations", async () => {
const pools = await fuse.contracts.FusePoolDirectory.methods
.getAllPools()
.call();
let liquidationEvents: LiquidationEvent[] = [];
let poolFetches: Promise<any>[] = [];
for (let poolID = 0; poolID < pools.length; poolID++) {
const pool = pools[poolID];
console.log(pool.comptroller, poolID);
if (poolID === 4) {
// Pool 4 is broken, we'll just skip it for now.
continue;
}
poolFetches.push(
fuse.contracts.FusePoolLens.methods
.getPoolAssetsWithData(pool.comptroller)
.call()
.then(async (assets: FuseAsset[]) => {
let eventFetches: Promise<any>[] = [];
for (const asset of assets) {
// If the asset has no borrowers, just skip it.
if (parseInt(asset.totalBorrow as any) === 0) {
continue;
}
const cToken = new fuse.web3.eth.Contract(
JSON.parse(
fuse.compoundContracts[
"contracts/CEtherDelegate.sol:CEtherDelegate"
].abi
),
asset.cToken
);
eventFetches.push(
cToken
.getPastEvents("LiquidateBorrow", {
fromBlock: 12060000,
toBlock: "latest",
})
.then(async (events) => {
let promises: Promise<any>[] = [];
for (const event of events) {
const suppliedToken = assets.find((a) => {
return (
a.cToken.toLowerCase() ===
event.returnValues.cTokenCollateral.toLowerCase()
);
})!;
promises.push(
fuse.web3.eth
.getBlock(event.blockNumber)
.then((blockInfo) => {
liquidationEvents.push({
...filterOnlyObjectProperties(event.returnValues),
cTokenBorrowed: asset.cToken,
borrowedTokenAddress: asset.underlyingToken,
suppliedTokenAddress:
suppliedToken.underlyingToken,
borrowedTokenUnderlyingDecimals:
asset.underlyingDecimals,
borrowedTokenUnderlyingSymbol:
asset.underlyingSymbol,
poolID,
blockNumber: event.blockNumber,
timestamp: blockInfo.timestamp,
transactionHash: event.transactionHash,
transactionIndex: event.transactionIndex,
});
})
);
}
await Promise.all(promises);
})
);
}
await Promise.all(eventFetches);
})
);
}
await Promise.all(poolFetches);
return liquidationEvents.sort((a, b) => {
if (b.blockNumber !== a.blockNumber) {
return b.blockNumber - a.blockNumber;
} else {
return b.transactionIndex - a.transactionIndex;
}
});
});
const [liquidationsToShow, setLiquidationsToShow] = useState(10);
const limitedLiquidations = liquidations?.slice(0, liquidationsToShow);
return (
<>
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
color="#FFFFFF"
mx="auto"
width={isMobile ? "100%" : "1000px"}
height="100%"
px={isMobile ? 4 : 0}
>
<Header isAuthed={isAuthed} isFuse />
<FuseStatsBar />
<FuseTabBar />
<RowOrColumn
isRow={!isMobile}
mt={4}
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
width="100%"
height={isMobile ? "400px" : "200px"}
>
<DashboardBox
height="100%"
width="100%"
overflow="hidden"
bg="#141619"
>
<iframe
src="https://metrics.rari.capital/d-solo/NlUs6DwGk/fuse-overview?orgId=1&refresh=5m&panelId=19"
height="100%"
width="100%"
title="Liquidation Count"
/>
</DashboardBox>
</RowOrColumn>
<DashboardBox width="100%" mt={4}>
<LiquidationEventsList
liquidations={limitedLiquidations}
totalLiquidations={liquidations?.length ?? 0}
setLiquidationsToShow={setLiquidationsToShow}
/>
</DashboardBox>
<Footer />
</Column>
</>
);
});
export default FuseLiquidationsPage;
const LiquidationEventsList = ({
liquidations,
totalLiquidations,
setLiquidationsToShow,
}: {
liquidations?: LiquidationEvent[];
totalLiquidations: number;
setLiquidationsToShow: React.Dispatch<React.SetStateAction<number>>;
}) => {
const { t } = useTranslation();
const isMobile = useIsMobile();
return (
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
expand
>
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
height="45px"
width="100%"
flexShrink={0}
pl={4}
pr={1}
>
<Text fontWeight="bold" width={isMobile ? "100%" : "30%"}>
{t("Recent Liquidations")}
</Text>
{isMobile ? null : (
<>
<Text fontWeight="bold" textAlign="center" width="23%">
{t("Collateral Seized")}
</Text>
<Text fontWeight="bold" textAlign="center" width="23%">
{t("Borrow Repaid")}
</Text>
<Text fontWeight="bold" textAlign="center" width="25%">
{t("Timestamp")}
</Text>
</>
)}
</Row>
<ModalDivider />
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
width="100%"
>
{liquidations ? (
<>
{liquidations.map((liquidation, index) => {
return (
<LiquidationRow
key={liquidation.transactionHash}
liquidation={liquidation}
noBottomDivider={index === liquidations.length - 1}
/>
);
})}
<RowsControl
totalAmount={totalLiquidations}
setAmountToShow={setLiquidationsToShow}
/>
</>
) : (
<Spinner my={8} />
)}
</Column>
</Column>
);
};
const LiquidationRow = ({
noBottomDivider,
liquidation,
}: {
noBottomDivider?: boolean;
liquidation: LiquidationEvent;
}) => {
const isMobile = useIsMobile();
const { t } = useTranslation();
const date = new Date(liquidation.timestamp * 1000);
return (
<>
<Link
isExternal
width="100%"
className="no-underline"
href={"https://etherscan.io/tx/" + liquidation.transactionHash}
>
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
width="100%"
height="100px"
className="hover-row"
pl={4}
pr={1}
>
<Column
width={isMobile ? "100%" : "30%"}
height="100%"
mainAxisAlignment="center"
crossAxisAlignment="flex-start"
>
<Row mainAxisAlignment="flex-start" crossAxisAlignment="center">
<Box boxSize="23px">
<Jazzicon
diameter={23}
seed={jsNumberForAddress(liquidation.liquidator)}
/>
</Box>
<Text ml={2} mr={2} fontWeight="bold">
<Text as="span" color="#EE1E45">
{" → "}
</Text>
{t("Liquidated")}
<Text as="span" color="#73BF69">
{" → "}
</Text>
</Text>
<Box boxSize="23px">
<Jazzicon
diameter={23}
seed={jsNumberForAddress(liquidation.borrower)}
/>
</Box>
<Text ml={3} mr={2} fontWeight="bold">
(Pool #{liquidation.poolID})
</Text>
</Row>
<Text mt={2} fontSize="11px" color="#EE1E45">
{liquidation.liquidator}
</Text>
<Text mt={1} fontSize="11px" color="#73BF69">
{liquidation.borrower}
</Text>
</Column>
{isMobile ? null : (
<>
<Column
mainAxisAlignment="center"
crossAxisAlignment="center"
height="100%"
width="23%"
>
<CTokenIcon
size="md"
mb={2}
address={liquidation.suppliedTokenAddress}
/>
</Column>
<Column
mainAxisAlignment="center"
crossAxisAlignment="center"
height="100%"
width="23%"
fontWeight="bold"
>
<CTokenIcon
size="sm"
mb={2}
address={liquidation.borrowedTokenAddress}
/>
{smallUsdFormatter(
liquidation.repayAmount /
10 ** liquidation.borrowedTokenUnderlyingDecimals
).replace("$", "")}{" "}
{liquidation.borrowedTokenUnderlyingSymbol}
</Column>
<Column
mainAxisAlignment="center"
crossAxisAlignment="center"
height="100%"
width="25%"
>
<Text fontWeight="bold">{date.toLocaleTimeString()}</Text>
<Text mt={1}>{date.toLocaleDateString()}</Text>
</Column>
</>
)}
</Row>
</Link>
{noBottomDivider ? null : <ModalDivider />}
</>
);
};
const RowsControl = ({
setAmountToShow,
totalAmount,
}: {
totalAmount: number;
setAmountToShow: React.Dispatch<React.SetStateAction<number>>;
}) => {
const { t } = useTranslation();
return (
<Row
mainAxisAlignment="center"
crossAxisAlignment="center"
width="100%"
my={4}
px={4}
>
<DashboardBox
fontWeight="bold"
as="button"
px={2}
py={1}
onClick={() =>
setAmountToShow((past) =>
Math.min(
past === 0 ? 1 : past === -1 ? totalAmount : past + 5,
totalAmount
)
)
}
>
{t("View More")}
</DashboardBox>
<DashboardBox
fontWeight="bold"
as="button"
ml={4}
px={2}
py={1}
onClick={() => setAmountToShow((past) => Math.max(past - 5, 0))}
>
{t("View Less")}
</DashboardBox>
<DashboardBox
as="button"
ml={4}
px={2}
py={1}
onClick={() => setAmountToShow(totalAmount)}
>
{t("View All")}
</DashboardBox>
<DashboardBox
as="button"
ml={4}
px={2}
py={1}
onClick={() => setAmountToShow(0)}
>
{t("Collapse All")}
</DashboardBox>
</Row>
);
};
================================================
FILE: src/components/pages/Fuse/FusePoolCreatePage.tsx
================================================
// Chakra and UI
import {
Heading,
Text,
Switch,
Input,
Spinner,
IconButton,
useToast,
useDisclosure,
Box,
Button,
CloseButton,
Checkbox
} from "@chakra-ui/react";
import { Column, Center, Row } from "utils/chakraUtils";
import DashboardBox from "../../shared/DashboardBox";
import { ModalDivider, MODAL_PROPS } from "../../shared/Modal";
import { SliderWithLabel } from "../../shared/SliderWithLabel";
import { AddIcon, QuestionIcon } from "@chakra-ui/icons";
import { SimpleTooltip } from "../../shared/SimpleTooltip";
import { Header } from "components/shared/Header";
import { Modal, ModalContent, ModalOverlay } from "@chakra-ui/modal";
// React
import { memo, ReactNode, useState } from "react";
// Rari
import { useRari } from "../../../context/RariContext";
// Hooks
import { useIsSemiSmallScreen } from "../../../hooks/useIsSemiSmallScreen";
import { useAuthedCallback } from "hooks/useAuthedCallback";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import BigNumber from "bignumber.js";
import LogRocket from "logrocket";
// Utils
import { handleGenericError } from "../../../utils/errorHandling";
// Components
import FuseStatsBar from "./FuseStatsBar";
import FuseTabBar from "./FuseTabBar";
import Fuse from "fuse-sdk";
import TransactionStepper from "components/shared/TransactionStepper";
const formatPercentage = (value: number) => value.toFixed(0) + "%";
const FusePoolCreatePage = memo(() => {
const isMobile = useIsSemiSmallScreen();
const { isAuthed } = useRari();
return (
<>
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
color="#FFFFFF"
mx="auto"
width={isMobile ? "100%" : "1150px"}
px={isMobile ? 4 : 0}
>
<Header isAuthed={isAuthed} isFuse />
<FuseStatsBar />
<FuseTabBar />
<PoolConfiguration />
</Column>
</>
);
});
export default FusePoolCreatePage;
const PoolConfiguration = () => {
const { t } = useTranslation();
const toast = useToast();
const { fuse, address } = useRari();
const navigate = useNavigate();
const { isOpen, onOpen, onClose } = useDisclosure();
const [name, setName] = useState("");
const [isWhitelisted, setIsWhitelisted] = useState(false);
const [whitelist, setWhitelist] = useState<string[]>([]);
const [closeFactor, setCloseFactor] = useState(50);
const [liquidationIncentive, setLiquidationIncentive] = useState(8);
const [isUsingMPO, setIsUsingMPO] = useState(true)
const [customOracleAddress, setCustomOracleAddress] = useState('')
const [isCreating, setIsCreating] = useState(false);
const [activeStep, setActiveStep] = useState<number>(0);
const increaseActiveStep = (step: string) => {
setActiveStep(steps.indexOf(step));
};
const [needsRetry, setNeedsRetry] = useState<boolean>(false);
const [retryFlag, setRetryFlag] = useState<number>(1);
const [deployedPriceOracle, setDeployedPriceOracle] = useState<string>("");
const postDeploymentHandle = (priceOracle: string) => {
setDeployedPriceOracle(priceOracle);
};
const deployPool = async (
bigCloseFactor: string,
bigLiquidationIncentive: string,
options: any,
priceOracle: string
) => {
const [poolAddress] = await fuse.deployPool(
name,
isWhitelisted,
bigCloseFactor,
bigLiquidationIncentive,
priceOracle,
{},
options,
isWhitelisted ? whitelist : null
);
return poolAddress;
};
const onDeploy = async () => {
let priceOracle = deployedPriceOracle;
if (name === "") {
toast({
title: "Error!",
description: "You must specify a name for your Fuse pool!",
status: "error",
duration: 2000,
isClosable: true,
position: "top-right",
});
return;
}
if (isWhitelisted && whitelist.length < 2 ) {
toast({
title: "Error!",
description: "You must add an address to your whitelist!",
status:"error",
duration: 2000,
isClosable: true,
position: "top-right",
})
return
}
if (!isUsingMPO && !fuse.web3.utils.isAddress(customOracleAddress)) {
toast({
title: "Error!",
description: "You must add an address for your oracle or use the default oracle.",
status:"error",
duration: 2000,
isClosable: true,
position: "top-right",
})
return
}
setIsCreating(true);
onOpen();
// 50% -> 0.5 * 1e18
const bigCloseFactor = new BigNumber(closeFactor)
.dividedBy(100)
.multipliedBy(1e18)
.toFixed(0);
// 8% -> 1.08 * 1e8
const bigLiquidationIncentive = new BigNumber(liquidationIncentive)
.dividedBy(100)
.plus(1)
.multipliedBy(1e18)
.toFixed(0);
let _retryFlag = retryFlag;
try {
const options = { from: address };
setNeedsRetry(false);
if (!isUsingMPO && _retryFlag === 1) {
_retryFlag = 2;
priceOracle = customOracleAddress
}
if (_retryFlag === 1) {
priceOracle = await fuse.deployPriceOracle(
"MasterPriceOracle",
{
underlyings: [],
oracles: [],
canAdminOverwrite: true,
defaultOracle:
Fuse.PUBLIC_PRICE_ORACLE_CONTRACT_ADDRESSES.MasterPriceOracle, // We give the MasterPriceOracle a default "fallback" oracle of the Rari MasterPriceOracle
},
options
);
postDeploymentHandle(priceOracle);
increaseActiveStep("Deploying Pool!");
_retryFlag = 2;
}
let poolAddress: string;
if (_retryFlag === 2) {
poolAddress = await deployPool(
bigCloseFactor,
bigLiquidationIncentive,
options,
priceOracle
);
const event = (
await fuse.contracts.FusePoolDirectory.getPastEvents(
"PoolRegistered",
{
fromBlock: (await fuse.web3.eth.getBlockNumber()) - 10,
toBlock: "latest",
}
)
).filter(
(event) =>
event.returnValues.pool.comptroller.toLowerCase() ===
poolAddress.toLowerCase()
)[0];
LogRocket.track("Fuse-CreatePool");
toast({
title: "Your pool has been deployed!",
description: "You may now add assets to it.",
status: "success",
duration: 2000,
isClosable: true,
position: "top-right",
});
let id = event.returnValues.index;
onClose();
navigate(`/fuse/pool/${id}/edit`);
}
} catch (e) {
handleGenericError(e, toast);
setRetryFlag(_retryFlag);
setNeedsRetry(true);
}
};
return (
<>
<TransactionStepperModal
handleRetry={onDeploy}
needsRetry={needsRetry}
activeStep={activeStep}
isOpen={isOpen}
onClose={onClose}
/>
<DashboardBox width="100%" mt={4}>
<Column mainAxisAlignment="flex-start" crossAxisAlignment="flex-start">
<Heading size="sm" px={4} py={4}>
{t("Create Pool")}
</Heading>
<ModalDivider />
<OptionRow>
<Text fontWeight="bold" mr={4}>
{t("Name")}
</Text>
<Input
width="20%"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</OptionRow>
<ModalDivider />
<ModalDivider />
<OptionRow>
<SimpleTooltip
label={t(
"If enabled you will be able to limit the ability to supply to the pool to a select group of addresses. The pool will not show up on the 'all pools' list."
)}
>
<Text fontWeight="bold">
{t("Whitelisted")} <QuestionIcon ml={1} mb="4px" />
</Text>
</SimpleTooltip>
<Switch
h="20px"
isChecked={isWhitelisted}
onChange={() => {
setIsWhitelisted((past) => !past);
// Add the user to the whitelist by default
if (whitelist.length === 0) {
setWhitelist([address]);
}
}}
className="black-switch"
colorScheme="#121212"
/>
</OptionRow>
{isWhitelisted ? (
<WhitelistInfo
whitelist={whitelist}
addToWhitelist={(user) => {
setWhitelist((past) => [...past, user]);
}}
removeFromWhitelist={(user) => {
setWhitelist((past) =>
past.filter(function (item) {
return item !== user;
})
);
}}
/>
) : null}
<ModalDivider />
<OptionRow>
<SimpleTooltip
label={t(
"The percent, ranging from 0% to 100%, of a liquidatable account's borrow that can be repaid in a single liquidate transaction. If a user has multiple borrowed assets, the closeFactor applies to any single borrowed asset, not the aggregated value of a user’s outstanding borrowing. Compound's close factor is 50%."
)}
>
<Text fontWeight="bold">
{t("Close Factor")} <QuestionIcon ml={1} mb="4px" />
</Text>
</SimpleTooltip>
<SliderWithLabel
value={closeFactor}
setValue={setCloseFactor}
formatValue={formatPercentage}
min={5}
max={90}
/>
</OptionRow>
<ModalDivider />
<OptionRow>
<SimpleTooltip
label={t(
"The additional collateral given to liquidators as an incentive to perform liquidation of underwater accounts. For example, if the liquidation incentive is 10%, liquidators receive an extra 10% of the borrowers collateral for every unit they close. Compound's liquidation incentive is 8%."
)}
>
<Text fontWeight="bold">
{t("Liquidation Incentive")} <QuestionIcon ml={1} mb="4px" />
</Text>
</SimpleTooltip>
<SliderWithLabel
value={liquidationIncentive}
setValue={setLiquidationIncentive}
formatValue={formatPercentage}
min={0}
max={50}
/>
</OptionRow>
<ModalDivider />
<OptionRow>
<SimpleTooltip
label={t(
"We will deploy a price oracle for your pool. This price oracle will contain price feeds for popular ERC20 tokens."
)}
>
<Text fontWeight="bold">
{isUsingMPO ? t("Default Price Oracle") : t("Custom Price Oracle")} <QuestionIcon ml={1} mb="4px" />
</Text>
</SimpleTooltip>
<Box display="flex" alignItems='flex-end' flexDirection="column">
<Checkbox
isChecked={isUsingMPO}
onChange={(e) => setIsUsingMPO(!isUsingMPO)}
marginBottom={3}
/>
{
!isUsingMPO ? (
<>
<Input
value={customOracleAddress}
onChange={(e) => setCustomOracleAddress(e.target.value)}
/>
<Text mt={3} opacity="0.6" fontSize="sm">
Please make sure you know what you're doing.
</Text>
</>
)
: null
}
</Box>
</OptionRow>
</Column>
</DashboardBox>
<DashboardBox
width="100%"
height="60px"
mt={4}
py={3}
fontSize="xl"
as="button"
onClick={useAuthedCallback(onDeploy)}
>
<Center expand fontWeight="bold">
{isCreating ? <Spinner /> : t("Create")}
</Center>
</DashboardBox>
</>
);
};
const steps = ["Deploying Oracle", "Deploying Pool!"];
const TransactionStepperModal = ({
isOpen,
onClose,
activeStep,
needsRetry,
handleRetry,
}: {
isOpen: boolean;
onClose: () => void;
activeStep: number;
needsRetry: boolean;
handleRetry: () => void;
}) => {
return (
<Modal isOpen={isOpen} onClose={onClose} closeOnOverlayClick={false}>
<ModalOverlay>
<ModalContent
{...MODAL_PROPS}
display="flex"
alignSelf="center"
alignItems="center"
justifyContent="center"
height="25%"
width="25%"
>
<Row
mb={6}
mainAxisAlignment="center"
crossAxisAlignment="center"
w="100%"
px={4}
>
<Box mx="auto">
<Text textAlign="center" fontSize="20px">
{steps[activeStep]}
</Text>
{steps[activeStep] === "Deploying Pool!" ? (
<Text fontSize="13px" opacity="0.8">
Will take two transactions, please wait.
</Text>
) : null}
</Box>
</Row>
<TransactionStepper
steps={steps}
activeStep={activeStep}
tokenData={{ color: "#21C35E" }}
/>
{needsRetry ? (
<Button onClick={() => handleRetry()} mx={3} bg="#21C35E">
{" "}
Retry{" "}
</Button>
) : null}
</ModalContent>
</ModalOverlay>
</Modal>
);
};
const OptionRow = ({
children,
...others
}: {
children: ReactNode;
[key: string]: any;
}) => {
return (
<Row
mainAxisAlignment="space-between"
crossAxisAlignment="center"
width="100%"
my={4}
px={4}
overflowX="auto"
{...others}
>
{children}
</Row>
);
};
export const WhitelistInfo = ({
whitelist,
addToWhitelist,
removeFromWhitelist,
}: {
whitelist: string[];
addToWhitelist: (user: string) => any;
removeFromWhitelist: (user: string) => any;
}) => {
const [_whitelistInput, _setWhitelistInput] = useState("");
const { t } = useTranslation();
const { fuse } = useRari();
const toast = useToast();
return (
<>
<OptionRow my={0} mb={4}>
<Input
width="100%"
value={_whitelistInput}
onChange={(event) => _setWhitelistInput(event.target.value)}
placeholder="0x0000000000000000000000000000000000000000"
_placeholder={{ color: "#FFF" }}
/>
<IconButton
flexShrink={0}
aria-label="add"
icon={<AddIcon />}
width="35px"
ml={2}
bg="#282727"
color="#FFF"
borderWidth="1px"
backgroundColor="transparent"
onClick={() => {
if (
fuse.web3.utils.isAddress(_whitelistInput) &&
!whitelist.includes(_whitelistInput)
) {
addToWhitelist(_whitelistInput);
_setWhitelistInput("");
} else {
toast({
title: "Error!",
description:
"This is not a valid ethereum address (or you have already entered this address)",
status: "error",
duration: 2000,
isClosable: true,
position: "top-right",
});
}
}}
_hover={{}}
_active={{}}
/>
</OptionRow>
{whitelist.length > 0 ? (
<Text mb={4} ml={4} width="100%">
<b>{t("Already added:")} </b>
{whitelist.map((user, index, array) => (
<Text
key={user}
className="underline-on-hover"
as="button"
onClick={() => removeFromWhitelist(user)}
>
{user}
{array.length - 1 === index ? null : <>, </>}
</Text>
))}
</Text>
) : null}
</>
);
};
================================================
FILE: src/components/pages/Fuse/FusePoolEditPage.tsx
================================================
// Chakra and UI
import {
Box,
Badge,
Heading,
Text,
useDisclosure,
Spinner,
// Table
Image,
HStack,
Th,
Thead,
Table,
Tbody,
Tr,
Td,
} from "@chakra-ui/react";
import { Column, RowOrColumn, Center, Row } from "utils/chakraUtils";
import DashboardBox from "../../shared/DashboardBox";
// Components
import { Header } from "../../shared/Header";
import FuseStatsBar from "./FuseStatsBar";
import FuseTabBar from "./FuseTabBar";
import AddAssetModal from "./Modals/AddAssetModal/AddAssetModal";
// React
import { memo, ReactNode, useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { useQuery } from "react-query";
// Rari
import { useRari } from "../../../context/RariContext";
// Hooks
import { useIsSemiSmallScreen } from "../../../hooks/useIsSemiSmallScreen";
import { useFusePoolData } from "../../../hooks/useFusePoolData";
import { useTokenData } from "../../../hooks/useTokenData";
// Utils
import { CTokenAvatarGroup } from "components/shared/CTokenIcon";
import { createComptroller } from "../../../utils/createComptroller";
// Libraries
import LogRocket from "logrocket";
import { useIsComptrollerAdmin } from "./FusePoolPage";
import { AdminAlert } from "components/shared/AdminAlert";
import { useAuthedCallback } from "hooks/useAuthedCallback";
import {
useCTokensUnderlying,
usePoolIncentives,
} from "hooks/rewards/usePoolIncentives";
import { useRewardsDistributorsForPool } from "hooks/rewards/useRewardsDistributorsForPool";
import { RewardsDistributor } from "hooks/rewards/useRewardsDistributorsForPool";
import { useTokenBalance } from "hooks/useTokenBalance";
import AddRewardsDistributorModal from "./Modals/AddRewardsDistributorModal";
import EditRewardsDistributorModal from "./Modals/EditRewardsDistributorModal";
import AssetConfiguration, {
AddAssetButton,
} from "./Modals/Edit/AssetConfiguration";
import PoolConfiguration from "./Modals/Edit/PoolConfiguration";
import { ModalDivider } from "components/shared/Modal";
export enum ComptrollerErrorCodes {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY,
SUPPLIER_NOT_WHITELISTED,
BORROW_BELOW_MIN,
SUPPLY_ABOVE_MAX,
NONZERO_TOTAL_SUPPLY,
}
export const useIsUpgradeable = (comptrollerAddress: string) => {
const { fuse } = useRari();
const { data } = useQuery(comptrollerAddress + " isUpgradeable", async () => {
const comptroller = createComptroller(comptrollerAddress, fuse);
const isUpgradeable: boolean = await comptroller.methods
.adminHasRights()
.call();
return isUpgradeable;
});
return data;
};
export async function testForComptrollerErrorAndSend(
txObject: any,
caller: string,
failMessage: string
) {
let response = await txObject.call({ from: caller });
// For some reason `response` will be `["0"]` if no error but otherwise it will return a string number.
if (response[0] !== "0") {
const err = new Error(
failMessage + " Code: " + (ComptrollerErrorCodes[response] ?? response)
);
LogRocket.captureException(err);
throw err;
}
return txObject.send({ from: caller });
}
const FusePoolEditPage = memo(() => {
const { isAuthed } = useRari();
const isMobile = useIsSemiSmallScreen();
const {
isOpen: isAddAssetModalOpen,
onOpen: openAddAssetModal,
onClose: closeAddAssetModal,
} = useDisclosure();
const {
isOpen: isAddRewardsDistributorModalOpen,
onOpen: openAddRewardsDistributorModal,
onClose: closeAddRewardsDistributorModal,
} = useDisclosure();
const {
isOpen: isEditRewardsDistributorModalOpen,
onOpen: openEditRewardsDistributorModal,
onClose: closeEditRewardsDistributorModal,
} = useDisclosure();
const authedOpenModal = useAuthedCallback(openAddAssetModal);
const { t } = useTranslation();
const { poolId } = useParams();
const data = useFusePoolData(poolId);
const isAdmin = useIsComptrollerAdmin(data?.comptroller);
// RewardsDistributor stuff
const poolIncentives = usePoolIncentives(data?.comptroller);
const rewardsDistributors = useRewardsDistributorsForPool(data?.comptroller);
const [rewardsDistributor, setRewardsDistributor] = useState<
RewardsDistributor | undefined
>();
console.log({ rewardsDistributors, poolIncentives });
const handleRewardsRowClick = useCallback(
(rD: RewardsDistributor) => {
setRewardsDistributor(rD);
openEditRewardsDistributorModal();
},
[setRewardsDistributor, openEditRewardsDistributorModal]
);
return (
<>
{data ? (
<AddAssetModal
comptrollerAddress={data.comptroller}
poolOracleAddress={data.oracle}
oracleModel={data.oracleModel}
existingAssets={data.assets}
poolName={data.name}
poolID={poolId!}
isOpen={isAddAssetModalOpen}
onClose={closeAddAssetModal}
/>
) : null}
{data ? (
<AddRewardsDistributorModal
comptrollerAddress={data.comptroller}
poolName={data.name}
poolID={poolId!}
isOpen={isAddRewardsDistributorModalOpen}
onClose={closeAddRewardsDistributorModal}
/>
) : null}
{data && !!rewardsDistributor ? (
<EditRewardsDistributorModal
rewardsDistributor={rewardsDistributor}
pool={data}
isOpen={isEditRewardsDistributorModalOpen}
onClose={closeEditRewardsDistributorModal}
/>
) : null}
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
color="#FFFFFF"
mx="auto"
width={isMobile ? "100%" : "1150px"}
px={isMobile ? 4 : 0}
>
<Header isAuthed={isAuthed} isFuse />
<FuseStatsBar data={data} />
<FuseTabBar />
{!!data && (
<AdminAlert
isAdmin={isAdmin}
isAdminText="You are the admin of this Fuse Pool!"
isNotAdminText="You are not the admin of this Fuse Pool!"
/>
)}
<RowOrColumn
width="100%"
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
isRow={!isMobile}
>
<DashboardBox
width={isMobile ? "100%" : "50%"}
height={isMobile ? "auto" : "560px"}
mt={4}
>
{data ? (
<PoolConfiguration
assets={data.assets}
comptrollerAddress={data.comptroller}
oracleAddress={data.oracle}
/>
) : (
<Center expand>
<Spinner my={8} />
</Center>
)}
</DashboardBox>
<Box pl={isMobile ? 0 : 4} width={isMobile ? "100%" : "50%"}>
<DashboardBox
width="100%"
mt={4}
height={isMobile ? "auto" : "560px"}
>
{data ? (
data.assets.length > 0 ? (
<AssetConfiguration
openAddAssetModal={authedOpenModal}
assets={data.assets}
poolOracleAddress={data.oracle}
oracleModel={data.oracleModel}
comptrollerAddress={data.comptroller}
poolID={poolId!}
poolName={data.name}
/>
) : (
<Column
expand
mainAxisAlignment="center"
crossAxisAlignment="center"
py={4}
>
<Text mb={4}>{t("There are no assets in this pool.")}</Text>
<AddAssetButton
comptrollerAddress={data.comptroller}
openAddAssetModal={authedOpenModal}
/>
</Column>
)
) : (
<Center expand>
<Spinner my={8} />
</Center>
)}
</DashboardBox>
</Box>
</RowOrColumn>
{/* Rewards Distributors */}
<DashboardBox w="100%" h="100%" my={4}>
<Row
mainAxisAlignment="space-between"
crossAxisAlignment="center"
p={3}
>
<Heading size="md">Rewards Distributors </Heading>
<AddRewardsDistributorButton
openAddRewardsDistributorModal={openAddRewardsDistributorModal}
comptrollerAddress={data?.comptroller}
/>
</Row>
{!!data && !rewardsDistributors.length && (
<Column
w="100%"
h="100%"
mainAxisAlignment="center"
crossAxisAlignment="center"
p={4}
>
<Text mb={4}>
{t("There are no RewardsDistributors for this pool.")}
</Text>
<AddRewardsDistributorButton
openAddRewardsDistributorModal={openAddRewardsDistributorModal}
comptrollerAddress={data?.comptroller}
/>
</Column>
)}
{!data && (
<Column
w="100%"
h="100%"
mainAxisAlignment="center"
crossAxisAlignment="center"
p={4}
>
<Spinner />
</Column>
)}
{!!data && !!rewardsDistributors.length && (
<Table>
<Thead>
<Tr>
<Th color="white" size="sm">
{t("Reward Token:")}
</Th>
<Th color="white">{t("Active CTokens:")}</Th>
<Th color="white">{t("Balance:")}</Th>
<Th color="white">{t("Admin?")}</Th>
</Tr>
</Thead>
<Tbody minHeight="50px">
{!data && !rewardsDistributors.length ? (
<Spinner />
) : (
rewardsDistributors.map((rD, i) => {
return (
<RewardsDistributorRow
key={rD.address}
rewardsDistributor={rD}
handleRowClick={handleRewardsRowClick}
hideModalDivider={i === rewardsDistributors.length - 1}
activeCTokens={
poolIncentives.rewardsDistributorCtokens[rD.address]
}
/>
);
})
)}
</Tbody>
</Table>
)}
<ModalDivider />
</DashboardBox>
</Column>
</>
);
});
export default FusePoolEditPage;
export const SaveButton = ({
onClick,
altText,
...others
}: {
onClick: () => any;
altText?: string;
[key: string]: any;
}) => {
const { t } = useTranslation();
return (
<DashboardBox
flexShrink={0}
ml={2}
px={2}
height="35px"
as="button"
fontWeight="bold"
onClick={onClick}
{...others}
>
<Center expand>{altText ?? t("Save")}</Center>
</DashboardBox>
);
};
export const ConfigRow = ({
children,
...others
}: {
children: ReactNode;
[key: string]: any;
}) => {
return (
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
width="100%"
my={4}
px={4}
overflowX="auto"
flexShrink={0}
{...others}
>
{children}
</Row>
);
};
const AddRewardsDistributorButton = ({
openAddRewardsDistributorModal,
comptrollerAddress,
}: {
openAddRewardsDistributorModal: () => any;
comptrollerAddress: string;
}) => {
const { t } = useTranslation();
const isUpgradeable = useIsUpgradeable(comptrollerAddress);
return isUpgradeable ? (
<DashboardBox
onClick={openAddRewardsDistributorModal}
as="button"
py={1}
px={2}
fontWeight="bold"
>
{t("Add Rewards Distributor")}
</DashboardBox>
) : null;
};
const RewardsDistributorRow = ({
rewardsDistributor,
handleRowClick,
hideModalDivider,
activeCTokens,
}: {
rewardsDistributor: RewardsDistributor;
handleRowClick: (rD: RewardsDistributor) => void;
hideModalDivider: boolean;
activeCTokens: string[];
}) => {
const { address, fuse } = useRari();
const isAdmin = address === rewardsDistributor.admin;
const tokenData = useTokenData(rewardsDistributor.rewardToken);
// Balances
const { data: rDBalance } = useTokenBalance(
rewardsDistributor.rewardToken,
rewardsDistributor.address
);
const underlyingsMap = useCTokensUnderlying(activeCTokens);
const underlyings = Object.values(underlyingsMap);
return (
<>
<Tr
_hover={{ background: "grey", cursor: "pointer" }}
h="30px"
p={5}
flexDir="row"
onClick={() => handleRowClick(rewardsDistributor)}
>
<Td>
<HStack>
{tokenData?.logoURL ? (
<Image
src={tokenData.logoURL}
boxSize="30px"
borderRadius="50%"
/>
) : null}
<Heading fontSize="22px" color={tokenData?.color ?? "#FFF"} ml={2}>
{tokenData
? tokenData.symbol ?? "Invalid Address!"
: "Loading..."}
</Heading>
</HStack>
</Td>
<Td>
{!!underlyings.length ? (
<CTokenAvatarGroup tokenAddresses={underlyings} popOnHover={true} />
) : (
<Badge colorScheme="red">Inactive</Badge>
)}
</Td>
<Td>
{(
parseFloat(rDBalance?.toString() ?? "0") /
10 ** (tokenData?.decimals ?? 18)
).toFixed(3)}{" "}
{tokenData?.symbol}
</Td>
<Td>
<Badge colorScheme={isAdmin ? "green" : "red"}>
{isAdmin ? "Is Admin" : "Not Admin"}
</Badge>
</Td>
</Tr>
{/* {!hideModalDivider && <ModalDivider />} */}
</>
);
};
================================================
FILE: src/components/pages/Fuse/FusePoolInfoPage.tsx
================================================
import {
AvatarGroup,
Box,
Heading,
Link,
Select,
Spinner,
Text,
useClipboard,
VStack,
} from "@chakra-ui/react";
import {
Column,
RowOnDesktopColumnOnMobile,
RowOrColumn,
Center,
Row,
useIsMobile,
} from "utils/chakraUtils";
import { memo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { useRari } from "../../../context/RariContext";
import { useIsSemiSmallScreen } from "../../../hooks/useIsSemiSmallScreen";
import { shortUsdFormatter } from "../../../utils/bigUtils";
import { FuseUtilizationChartOptions } from "../../../utils/chartOptions";
import DashboardBox, { DASHBOARD_BOX_PROPS } from "../../shared/DashboardBox";
import { Header } from "../../shared/Header";
import { ModalDivider } from "../../shared/Modal";
import { Link as RouterLink } from "react-router-dom";
import Chart from "react-apexcharts";
import FuseStatsBar from "./FuseStatsBar";
import FuseTabBar from "./FuseTabBar";
import { useQuery } from "react-query";
import { useFusePoolData } from "../../../hooks/useFusePoolData";
import { ETH_TOKEN_DATA, useTokenData } from "hooks/useTokenData";
import { CTokenIcon } from "components/shared/CTokenIcon";
import { shortAddress } from "../../../utils/shortAddress";
import { USDPricedFuseAsset } from "../../../utils/fetchFusePoolData";
import {
createComptroller,
createOracle,
} from "../../../utils/createComptroller";
import Fuse from "../../../fuse-sdk";
import CaptionedStat from "../../shared/CaptionedStat";
import Footer from "components/shared/Footer";
import { useIdentifyOracle } from "hooks/fuse/useOracleData";
import { truncate } from "utils/stringUtils";
import { SimpleTooltip } from "components/shared/SimpleTooltip";
export const useExtraPoolInfo = (
comptrollerAddress: string,
oracleAddress: string
) => {
const { fuse, address } = useRari();
const { data } = useQuery(comptrollerAddress + " extraPoolInfo", async () => {
const comptroller = createComptroller(comptrollerAddress, fuse);
const poolOracle = createOracle(oracleAddress, fuse, "MasterPriceOracle");
let defaultOracle = undefined;
try {
defaultOracle = await poolOracle.methods.defaultOracle().call();
} catch (err) {
console.error("Error querying for defaultOracle");
}
const [
{ 0: admin, 1: upgradeable },
closeFactor,
liquidationIncentive,
enforceWhitelist,
whitelist,
adminHasRights,
pendingAdmin,
] = await Promise.all([
fuse.contracts.FusePoolLensSecondary.methods
.getPoolOwnership(comptrollerAddress)
.call({ gas: 1e18 }),
comptroller.methods.closeFactorMantissa().call(),
comptroller.methods.liquidationIncentiveMantissa().call(),
(() => {
try {
return comptroller.methods.enforceWhitelist().call();
} catch (e) {
return false;
}
})(),
(() => {
try {
return comptroller.methods.getWhitelist().call();
} catch (_) {
return [];
}
})(),
comptroller.methods.adminHasRights().call(),
comptroller.methods.pendingAdmin().call(),
]);
return {
admin,
upgradeable,
enforceWhitelist,
whitelist: whitelist as string[],
isPowerfulAdmin:
admin.toLowerCase() === address.toLowerCase() && upgradeable,
closeFactor,
liquidationIncentive,
adminHasRights,
pendingAdmin,
defaultOracle,
};
});
return data;
};
const FusePoolInfoPage = memo(() => {
const { isAuthed } = useRari();
const isMobile = useIsSemiSmallScreen();
const { t } = useTranslation();
let { poolId } = useParams();
const data = useFusePoolData(poolId);
return (
<>
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
color="#FFFFFF"
mx="auto"
width={isMobile ? "100%" : "1150px"}
height="100%"
px={isMobile ? 4 : 0}
>
<Header isAuthed={isAuthed} isFuse />
<FuseStatsBar data={data} />
<FuseTabBar />
<RowOrColumn
width="100%"
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
isRow={!isMobile}
>
<DashboardBox
width={isMobile ? "100%" : "50%"}
mt={4}
height={isMobile ? "auto" : "450px"}
>
{data ? (
<OracleAndInterestRates
assets={data.assets}
name={data.name}
totalSuppliedUSD={data.totalSuppliedUSD}
totalBorrowedUSD={data.totalBorrowedUSD}
totalLiquidityUSD={data.totalLiquidityUSD}
comptrollerAddress={data.comptroller}
oracleAddress={data.oracle}
oracleModel={data.oracleModel}
/>
) : (
<Center expand>
<Spinner my={8} />
</Center>
)}
</DashboardBox>
<DashboardBox
ml={isMobile ? 0 : 4}
width={isMobile ? "100%" : "50%"}
mt={4}
height={isMobile ? "500px" : "450px"}
>
{data ? (
data.assets.length > 0 ? (
<AssetAndOtherInfo
assets={data.assets}
poolOracle={data.oracle}
/>
) : (
<Center expand>{t("There are no assets in this pool.")}</Center>
)
) : (
<Center expand>
<Spinner my={8} />
</Center>
)}
</DashboardBox>
</RowOrColumn>
<Footer />
</Column>
</>
);
});
export default FusePoolInfoPage;
const OracleAndInterestRates = ({
assets,
name,
totalSuppliedUSD,
totalBorrowedUSD,
totalLiquidityUSD,
comptrollerAddress,
oracleAddress,
oracleModel,
}: {
assets: USDPricedFuseAsset[];
name: string;
totalSuppliedUSD: number;
totalBorrowedUSD: number;
totalLiquidityUSD: number;
comptrollerAddress: string;
oracleAddress: string;
oracleModel: string | undefined;
}) => {
let { poolId } = useParams();
const { t } = useTranslation();
const data = useExtraPoolInfo(comptrollerAddress, oracleAddress);
const defaultOracleIdentity = useIdentifyOracle(data?.defaultOracle);
console.log(data?.defaultOracle, { defaultOracleIdentity });
const { hasCopied, onCopy } = useClipboard(data?.admin ?? "");
return (
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
height="100%"
width="100%"
>
<Row
mainAxisAlignment="space-between"
crossAxisAlignment="center"
width="100%"
px={4}
height="60px"
flexShrink={0}
>
<Heading size="sm">
{t("Pool {{num}} Info", { num: poolId, name })}
</Heading>
<Link
className="no-underline"
isExternal
ml="auto"
href={`https://metrics.rari.capital/d/HChNahwGk/fuse-pool-details?orgId=1&refresh=10s&var-poolID=${poolId}`}
>
<DashboardBox height="35px">
<Center expand px={2} fontWeight="bold">
{t("Metrics")}
</Center>
</DashboardBox>
</Link>
{data?.isPowerfulAdmin ? (
<Link
/* @ts-ignore */
as={RouterLink}
className="no-underline"
to="../edit"
ml={2}
>
<DashboardBox height="35px">
<Center expand px={2} fontWeight="bold">
{t("Edit")}
</Center>
</DashboardBox>
</Link>
) : null}
</Row>
<ModalDivider />
<Column
mainAxisAlignment="center"
crossAxisAlignment="center"
width="100%"
my={4}
px={4}
>
{assets.length > 0 ? (
<>
<AvatarGroup mt={1} size="xs" max={30}>
{assets.map(({ underlyingToken, cToken }) => {
return <CTokenIcon key={cToken} address={underlyingToken} />;
})}
</AvatarGroup>
<Text mt={3} lineHeight={1} textAlign="center">
{name} (
{assets.map(({ underlyingSymbol }, index, array) => {
return (
underlyingSymbol + (index !== array.length - 1 ? " / " : "")
);
})}
)
</Text>
</>
) : (
<Text>{name}</Text>
)}
</Column>
<ModalDivider />
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
my={5}
px={4}
width="100%"
>
<StatRow
statATitle={t("Total Supplied")}
statA={shortUsdFormatter(totalSuppliedUSD)}
statBTitle={t("Total Borrowed")}
statB={shortUsdFormatter(totalBorrowedUSD)}
/>
<StatRow
statATitle={t("Available Liquidity")}
statA={shortUsdFormatter(totalLiquidityUSD)}
statBTitle={t("Pool Utilization")}
statB={
totalSuppliedUSD.toString() === "0"
? "0%"
: ((totalBorrowedUSD / totalSuppliedUSD) * 100).toFixed(2) + "%"
}
/>
<StatRow
statATitle={t("Upgradeable")}
statA={data ? (data.upgradeable ? "Yes" : "No") : "?"}
statBTitle={
hasCopied ? t("Admin (copied!)") : t("Admin (click to copy)")
}
statB={data?.admin ? shortAddress(data.admin) : "?"}
onClick={onCopy}
/>
<StatRow
statATitle={t("Platform Fee")}
statA={assets.length > 0 ? assets[0].fuseFee / 1e16 + "%" : "10%"}
statBTitle={t("Average Admin Fee")}
statB={
assets
.reduce(
(a, b, _, { length }) => a + b.adminFee / 1e16 / length,
0
)
.toFixed(1) + "%"
}
/>
<StatRow
statATitle={t("Close Factor")}
statA={
data?.closeFactor
? (data.closeFactor / 1e16).toFixed(2) + "%"
: "?%"
}
statBTitle={t("Liquidation Incentive")}
statB={
data?.liquidationIncentive
? data.liquidationIncentive / 1e16 - 100 + "%"
: "?%"
}
/>
<StatRow
statATitle={t("Oracle")}
statA={data ? oracleModel ?? t("Unrecognized Oracle") : "?"}
statBTitle={t("Whitelist")}
statB={data ? (data.enforceWhitelist ? "Yes" : "No") : "?"}
/>
</Column>
</Column>
);
};
const StatRow = ({
statATitle,
statA,
statBTitle,
statB,
...other
}: {
statATitle: string;
statA: string;
statBTitle?: string;
statB?: string;
[key: string]: any;
}) => {
return (
<RowOnDesktopColumnOnMobile
mainAxisAlignment="center"
crossAxisAlignment="center"
width="100%"
mb={4}
{...other}
>
<Text width="50%" textAlign="center">
{statATitle}: <b>{statA}</b>
</Text>
{statBTitle && statB && (
<Text width="50%" textAlign="center">
{statBTitle}: <b>{statB}</b>
</Text>
)}
</RowOnDesktopColumnOnMobile>
);
};
const AssetAndOtherInfo = ({
assets,
poolOracle,
}: {
assets: USDPricedFuseAsset[];
poolOracle: string;
}) => {
let { poolId } = useParams();
const { fuse } = useRari();
const { t } = useTranslation();
const [selectedAsset, setSelectedAsset] = useState(
assets.length > 3 ? assets[2] : assets[0]
);
const selectedTokenData = useTokenData(selectedAsset.underlyingToken);
const selectedAssetUtilization =
// @ts-ignore
selectedAsset.totalSupply === "0"
? 0
: parseFloat(
// Use Max.min() to cap util at 100%
Math.min(
(selectedAsset.totalBorrow / selectedAsset.totalSupply) * 100,
100
).toFixed(0)
);
const { data: curveData } = useQuery(
selectedAsset.cToken + " curves",
async () => {
const interestRateModel = await fuse.getInterestRateModel(
selectedAsset.cToken
);
if (interestRateModel === null) {
return { borrowerRates: null, supplierRates: null };
}
const IRMidentity = await fuse.identifyInterestRateModelName(
interestRateModel
);
const curve = convertIRMtoCurve(interestRateModel, fuse);
return { curve, IRMidentity };
}
);
const { curve: data, IRMidentity } = curveData ?? {};
console.log({ data, IRMidentity });
const isMobile = useIsMobile();
const oracleIdentity = useIdentifyOracle(
selectedAsset.oracle,
selectedAsset.underlyingToken
);
// Link to MPO if asset is ETH
const oracleAddress =
selectedAsset.underlyingToken === ETH_TOKEN_DATA.address
? poolOracle
: selectedAsset.oracle;
return (
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
width="100%"
height="100%"
>
<Row
mainAxisAlignment="space-between"
crossAxisAlignment="center"
height="60px"
width="100%"
px={4}
flexShrink={0}
>
<Heading size="sm" py={3}>
{t("Pool {{num}}'s {{token}} Stats", {
num: poolId,
token: selectedAsset.underlyingSymbol,
})}
</Heading>
<Select
{...DASHBOARD_BOX_PROPS}
borderRadius="7px"
fontWeight="bold"
width="130px"
_focus={{ outline: "none" }}
color={selectedTokenData?.color ?? "#FFF"}
onChange={(event) =>
setSelectedAsset(
assets.find((asset) => asset.cToken === event.target.value)!
)
}
value={selectedAsset.cToken}
>
{assets.map((asset) => (
<option
className="black-bg-option"
value={asset.cToken}
key={asset.cToken}
>
{asset.underlyingSymbol}
</option>
))}
</Select>
</Row>
<ModalDivider />
<Box
height="200px"
width="100%"
color="#000000"
overflow="hidden"
px={3}
className="hide-bottom-tooltip"
flexShrink={0}
// bg="red"
>
{data ? (
data.supplierRates === null ? (
<Center expand color="#FFFFFF">
<Text>
{t("No graph is available for this asset's interest curves.")}
</Text>
</Center>
) : (
<>
<Chart
options={
{
...FuseUtilizationChartOptions,
annotations: {
points: [
{
x: selectedAssetUtilization,
y: data.borrowerRates[selectedAssetUtilization].y,
marker: {
size: 6,
fillColor: "#FFF",
strokeColor: "#DDDCDC",
},
},
{
x: selectedAssetUtilization,
y: data.supplierRates[selectedAssetUtilization].y,
marker: {
size: 6,
fillColor: selectedTokenData?.color ?? "#A6A6A6",
strokeColor: "#FFF",
},
},
],
xaxis: [
{
x: selectedAssetUtilization,
label: {
text: t("Current Utilization"),
orientation: "horizontal",
style: {
background: "#121212",
color: "#FFF",
},
},
},
],
},
colors: ["#FFFFFF", selectedTokenData?.color ?? "#A6A6A6"],
} as any
}
type="line"
width="100%"
height="100%"
series={[
{
name: "Borrow Rate",
data: data.borrowerRates,
},
{
name: "Deposit Rate",
data: data.supplierRates,
},
]}
/>
<Text
position="absolute"
zIndex={4}
top={4}
left={4}
color="white"
>
{" "}
{IRMidentity?.replace("_", " ") ?? ""}
</Text>
</>
)
) : (
<Center expand color="#FFFFFF">
<Spinner />
</Center>
)}
</Box>
<ModalDivider />
<Row
mainAxisAlignment="space-around"
crossAxisAlignment="center"
height="100%"
width="100%"
pt={4}
px={4}
pb={2}
>
<CaptionedStat
stat={(selectedAsset.collateralFactor / 1e16).toFixed(0) + "%"}
statSize="lg"
captionSize="xs"
caption={t("Collateral Factor")}
crossAxisAlignment="center"
captionFirst={true}
/>
<SimpleTooltip label={oracleIdentity}>
<Link
href={`https://etherscan.io/address/${oracleAddress}`}
isExternal
_hover={{ pointer: "cursor", color: "#21C35E" }}
>
<CaptionedStat
stat={truncate(oracleIdentity, 20)}
statSize="md"
captionSize="xs"
caption={t("Oracle")}
crossAxisAlignment="center"
captionFirst={true}
/>
</Link>
</SimpleTooltip>
<CaptionedStat
stat={(selectedAsset.reserveFactor / 1e16).toFixed(0) + "%"}
statSize="lg"
captionSize="xs"
caption={t("Reserve Factor")}
crossAxisAlignment="center"
captionFirst={true}
/>
</Row>
<ModalDivider />
<Row
mainAxisAlignment="space-around"
crossAxisAlignment="center"
height="100%"
width="100%"
p={4}
mt={3}
>
<SimpleTooltip label={`${selectedAsset.totalSupply} ${selectedAsset.underlyingSymbol}`}>
<CaptionedStat
stat={(selectedAsset.totalSupply / (10 ** selectedAsset.underlyingDecimals)).toFixed(2) + ` (${shortUsdFormatter(selectedAsset.totalSupplyUSD)})`}
statSize="lg"
captionSize="xs"
caption={t("Total Supplied")}
crossAxisAlignment="center"
captionFirst={true}
/>
</SimpleTooltip>
{isMobile ? null : (
<CaptionedStat
stat={
selectedAsset.totalSupplyUSD.toString() === "0"
? "0%"
: (
(selectedAsset.totalBorrowUSD /
selectedAsset.totalSupplyUSD) *
100
).toFixed(0) + "%"
}
statSize="lg"
captionSize="xs"
caption={t("Utilization")}
crossAxisAlignment="center"
captionFirst={true}
/>
)}
<CaptionedStat
stat={shortUsdFormatter(selectedAsset.totalBorrowUSD)}
statSize="lg"
captionSize="xs"
caption={t("Total Borrowed")}
crossAxisAlignment="center"
captionFirst={true}
/>
</Row>
<ModalDivider />
</Column>
);
};
export const convertIRMtoCurve = (interestRateModel: any, fuse: Fuse) => {
let borrowerRates = [];
let supplierRates = [];
for (var i = 0; i <= 100; i++) {
const supplyLevel =
(Math.pow(
(interestRateModel.getSupplyRate(
fuse.web3.utils.toBN((i * 1e16).toString())
) /
1e18) *
(4 * 60 * 24) +
1,
365
) -
1) *
100;
const borrowLevel =
(Math.pow(
(interestRateModel.getBorrowRate(
fuse.web3.utils.toBN((i * 1e16).toString())
) /
1e18) *
(4 * 60 * 24) +
1,
365
) -
1) *
100;
supplierRates.push({ x: i, y: supplyLevel });
borrowerRates.push({ x: i, y: borrowLevel });
}
return { borrowerRates, supplierRates };
};
================================================
FILE: src/components/pages/Fuse/FusePoolPage.tsx
================================================
import { memo, useEffect, useMemo, useState } from "react";
import {
Avatar,
AvatarGroup,
Box,
Button,
Heading,
Link,
Progress,
Spinner,
Switch,
Text,
useDisclosure,
useToast,
HStack,
} from "@chakra-ui/react";
import { Alert, AlertIcon } from "@chakra-ui/alert";
import {
Column,
Center,
Row,
RowOrColumn,
useIsMobile,
} from "utils/chakraUtils";
import { FusePoolData } from "utils/fetchFusePoolData";
// Hooks
import { useTranslation } from "react-i18next";
import { useQuery, useQueryClient } from "react-query";
import { useParams, Link as RouterLink } from "react-router-dom";
import { useRari } from "context/RariContext";
import { useBorrowLimit } from "hooks/useBorrowLimit";
import { useFusePoolData } from "hooks/useFusePoolData";
import { useIsSemiSmallScreen } from "hooks/useIsSemiSmallScreen";
import {
ETH_TOKEN_DATA,
TokensDataMap,
useTokenData,
useTokensData,
} from "hooks/useTokenData";
import { useAuthedCallback } from "hooks/useAuthedCallback";
// Utils
import { convertMantissaToAPY } from "utils/apyUtils";
import { shortUsdFormatter, smallUsdFormatter } from "utils/bigUtils";
import { createComptroller, createUnitroller } from "utils/createComptroller";
import { USDPricedFuseAsset } from "utils/fetchFusePoolData";
// Components
import DashboardBox from "components/shared/DashboardBox";
import { Header } from "components/shared/Header";
import { ModalDivider } from "components/shared/Modal";
import { SimpleTooltip } from "components/shared/SimpleTooltip";
import { SwitchCSS } from "components/shared/SwitchCSS";
import FuseStatsBar from "./FuseStatsBar";
import FuseTabBar from "./FuseTabBar";
import PoolModal, { Mode } from "./Modals/PoolModal";
import LogRocket from "logrocket";
import Footer from "components/shared/Footer";
import {
CTokenRewardsDistributorIncentives,
IncentivesData,
usePoolIncentives,
} from "hooks/rewards/usePoolIncentives";
import { CTokenAvatarGroup, CTokenIcon } from "components/shared/CTokenIcon";
import { motion } from "framer-motion";
import { GlowingBox } from "components/shared/GlowingButton";
import { AdminAlert } from "components/shared/AdminAlert";
import { EditIcon } from "@chakra-ui/icons";
import { testForComptrollerErrorAndSend } from "./FusePoolEditPage";
import { handleGenericError } from "utils/errorHandling";
import { CTokenRewardsDistributorIncentivesWithRates } from "hooks/rewards/useRewardAPY";
import { getSymbol } from "utils/symbolUtils";
export const useIsComptrollerAdmin = (comptrollerAddress?: string): boolean => {
const { fuse, address } = useRari();
const { data } = useQuery(comptrollerAddress + " admin", async () => {
if (!comptrollerAddress) return undefined;
const comptroller = createComptroller(comptrollerAddress, fuse);
const admin = await comptroller.methods.admin().call();
return admin;
});
return address === data;
};
export const useIsComptrollerPendingAdmin = (
comptrollerAddress?: string
): boolean => {
const { fuse, address, isAuthed } = useRari();
const { data } = useQuery(comptrollerAddress + " pending admin", async () => {
if (!comptrollerAddress) return undefined;
const comptroller = createComptroller(comptrollerAddress, fuse);
const pendingAdmin = await comptroller.methods.pendingAdmin().call();
return pendingAdmin;
});
if (!isAuthed) return false;
return address === data;
};
const PendingAdminAlert = ({ comptroller }: { comptroller?: string }) => {
const { address, fuse } = useRari();
const toast = useToast();
const queryClient = useQueryClient();
const [isAccepting, setIsAccepting] = useState(false);
const isPendingAdmin = useIsComptrollerPendingAdmin(comptroller);
const acceptAdmin = async () => {
if (!comptroller) return;
const unitroller = createUnitroller(comptroller, fuse);
setIsAccepting(true);
try {
await testForComptrollerErrorAndSend(
unitroller.methods._acceptAdmin(),
address,
""
);
LogRocket.track("Fuse-AcceptAdmin");
queryClient.refetchQueries();
setIsAccepting(false);
} catch (e) {
setIsAccepting(false);
handleGenericError(e, toast);
}
};
return (
<>
{isPendingAdmin && (
<AdminAlert
isAdmin={isPendingAdmin}
isAdminText="You are the pending admin of this Fuse Pool! Click to Accept Admin"
rightAdornment={
<Button
h="100%"
p={3}
ml="auto"
color="black"
onClick={acceptAdmin}
disabled={isAccepting}
>
<HStack>
<Text fontWeight="bold">
{isAccepting} ? Accepting... : Accept Admin{" "}
</Text>
</HStack>
</Button>
}
/>
)}
</>
);
};
const RiskyPoolAlert = () => {
return (
<Alert colorScheme={"red"} borderRadius={5} mt="5">
<AlertIcon />
<Text color="black">
Do not use this pool. This pool has risks due to a weak oracle.
</Text>
</Alert>
);
};
const FusePoolPage = memo(() => {
const { isAuthed } = useRari();
const isMobile = useIsSemiSmallScreen();
let { poolId } = useParams();
const data = useFusePoolData(poolId);
const isRiskyPool = poolId == "90" ?? false
const incentivesData: IncentivesData = usePoolIncentives(data?.comptroller);
const { hasIncentives } = incentivesData;
const isAdmin = useIsComptrollerAdmin(data?.comptroller);
return (
<>
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
color="#FFFFFF"
mx="auto"
width={isMobile ? "100%" : "1150px"}
px={isMobile ? 4 : 0}
>
<Header isAuthed={isAuthed} isFuse />
<FuseStatsBar data={data} />
<FuseTabBar />
{
/* If they have some asset enabled as collateral, show the collateral ratio bar */
data && data.assets.some((asset) => asset.membership) ? (
<CollateralRatioBar
assets={data.assets}
borrowUSD={data.totalBorrowBalanceUSD}
/>
) : null
}
{!!data && isAdmin && (
<AdminAlert
isAdmin={isAdmin}
isAdminText="You are the admin of this Fuse Pool!"
rightAdornment={
<Box h="100%" ml="auto" color="black">
<Link
/* @ts-ignore */
as={RouterLink}
to="./edit"
>
<HStack>
<Text fontWeight="bold">Edit </Text>
<EditIcon />
</HStack>
</Link>
</Box>
}
/>
)}
{!!data && isAuthed && (
<PendingAdminAlert comptroller={data?.comptroller} />
)}
{!!isRiskyPool && <RiskyPoolAlert />}
{hasIncentives && (
<motion.div
initial={{ opacity: 0, y: 40 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0 }}
style={{ width: "100%" }}
>
<GlowingBox w="100%" h="50px" mt={4}>
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
h="100%"
w="100"
p={3}
>
<Heading fontSize="md" ml={2}>
{" "}
🎉 This pool is offering rewards
</Heading>
<CTokenAvatarGroup
tokenAddresses={Object.keys(incentivesData.rewardTokensData)}
ml={2}
mr={2}
popOnHover={true}
/>
</Row>
</GlowingBox>
</motion.div>
)}
<RowOrColumn
width="100%"
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
mt={4}
isRow={!isMobile}
>
<DashboardBox width={isMobile ? "100%" : "50%"}>
{data ? (
<SupplyList
assets={data.assets}
comptrollerAddress={data.comptroller}
supplyBalanceUSD={data.totalSupplyBalanceUSD}
incentivesData={incentivesData}
/>
) : (
<Center height="200px">
<Spinner />
</Center>
)}
</DashboardBox>
<DashboardBox
ml={isMobile ? 0 : 4}
mt={isMobile ? 4 : 0}
width={isMobile ? "100%" : "50%"}
>
{data ? (
<BorrowList
comptrollerAddress={data.comptroller}
assets={data.assets}
borrowBalanceUSD={data.totalBorrowBalanceUSD}
incentivesData={incentivesData}
/>
) : (
<Center height="200px">
<Spinner />
</Center>
)}
</DashboardBox>
</RowOrColumn>
<Footer />
</Column>
</>
);
});
export default FusePoolPage;
const CollateralRatioBar = ({
assets,
borrowUSD,
}: {
assets: USDPricedFuseAsset[];
borrowUSD: number;
}) => {
const { t } = useTranslation();
const maxBorrow = useBorrowLimit(assets);
const borrowPercent = borrowUSD / maxBorrow;
const ratio = isNaN(borrowPercent) ? 0 : borrowPercent * 100;
useEffect(() => {
if (ratio > 95) {
LogRocket.track("Fuse-AtRiskOfLiquidation");
}
}, [ratio]);
return (
<DashboardBox width="100%" height="65px" mt={4} p={4}>
<Row mainAxisAlignment="flex-start" crossAxisAlignment="center" expand>
<SimpleTooltip
label={t("Keep this bar from filling up to avoid being liquidated!")}
>
<Text flexShrink={0} mr={4}>
{t("Borrow Limit")}
</Text>
</SimpleTooltip>
<SimpleTooltip label={t("This is how much you have borrowed.")}>
<Text flexShrink={0} mt="2px" mr={3} fontSize="10px">
{smallUsdFormatter(borrowUSD)}
</Text>
</SimpleTooltip>
<SimpleTooltip
label={`You're using ${ratio.toFixed(1)}% of your ${smallUsdFormatter(
maxBorrow
)} borrow limit.`}
>
<Box width="100%">
<Progress
size="xs"
width="100%"
colorScheme={
ratio <= 40
? "whatsapp"
: ratio <= 60
? "yellow"
: ratio <= 80
? "orange"
: "red"
}
borderRadius="10px"
value={ratio}
/>
</Box>
</SimpleTooltip>
<SimpleTooltip
label={t(
"If your borrow amount reaches this value, you will be liquidated."
)}
>
<Text flexShrink={0} mt="2px" ml={3} fontSize="10px">
{smallUsdFormatter(maxBorrow)}
</Text>
</SimpleTooltip>
</Row>
</DashboardBox>
);
};
const SupplyList = ({
assets,
supplyBalanceUSD,
comptrollerAddress,
incentivesData,
}: {
assets: USDPricedFuseAsset[];
supplyBalanceUSD: number;
comptrollerAddress: string;
incentivesData: IncentivesData;
}) => {
const { t } = useTranslation();
const suppliedAssets = assets.filter((asset) => asset.supplyBalanceUSD > 1);
const nonSuppliedAssets = assets.filter(
(asset) => asset.supplyBalanceUSD < 1
);
const isMobile = useIsMobile();
return (
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
height="100%"
pb={1}
>
<Heading size="md" px={4} py={3}>
{t("Supply Balance:")} {smallUsdFormatter(supplyBalanceUSD)}
</Heading>
<ModalDivider />
{assets.length > 0 ? (
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
width="100%"
px={4}
mt={4}
>
<Text width="27%" fontWeight="bold" pl={1}>
{t("Asset")}
</Text>
{isMobile ? null : (
<Text width="27%" fontWeight="bold" textAlign="right">
{t("APY/LTV")}
</Text>
)}
<Text
width={isMobile ? "40%" : "27%"}
fontWeight="bold"
textAlign="right"
>
{t("Balance")}
</Text>
<Text
width={isMobile ? "34%" : "20%"}
fontWeight="bold"
textAlign="right"
>
{t("Collateral")}
</Text>
</Row>
) : null}
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
expand
mt={1}
>
{assets.length > 0 ? (
<>
{suppliedAssets.map((asset, index) => {
const supplyIncentivesForAsset = (
incentivesData?.incentives?.[asset.cToken] ?? []
).filter(({ supplySpeed }) => !!supplySpeed);
return (
<AssetSupplyRow
comptrollerAddress={comptrollerAddress}
key={asset.underlyingToken}
assets={suppliedAssets}
index={index}
supplyIncentives={supplyIncentivesForAsset}
rewardTokensData={incentivesData.rewardTokensData}
isPaused={asset.isPaused}
/>
);
})}
{suppliedAssets.length > 0 ? <ModalDivider my={2} /> : null}
{nonSuppliedAssets.map((asset, index) => {
const supplyIncentivesForAsset = (
incentivesData?.incentives?.[asset.cToken] ?? []
).filter(({ supplySpeed }) => !!supplySpeed);
return (
<AssetSupplyRow
comptrollerAddress={comptrollerAddress}
key={asset.underlyingToken}
assets={nonSuppliedAssets}
index={index}
supplyIncentives={supplyIncentivesForAsset}
rewardTokensData={incentivesData.rewardTokensData}
isPaused={asset.isPaused}
/>
);
})}
</>
) : (
<Center expand my={8}>
{t("There are no assets in this pool.")}
</Center>
)}
</Column>
</Column>
);
};
const AssetSupplyRow = ({
assets,
index,
comptrollerAddress,
supplyIncentives,
rewardTokensData,
isPaused,
}: {
assets: USDPricedFuseAsset[];
index: number;
comptrollerAddress: string;
supplyIncentives: CTokenRewardsDistributorIncentivesWithRates[];
rewardTokensData: TokensDataMap;
isPaused: boolean;
}) => {
const {
isOpen: isModalOpen,
onOpen: openModal,
onClose: closeModal,
} = useDisclosure();
const authedOpenModal = useAuthedCallback(openModal);
const asset = assets[index];
const { fuse, address } = useRari();
const tokenData = useTokenData(asset.underlyingToken);
const supplyAPY = convertMantissaToAPY(asset.supplyRatePerBlock, 365);
const queryClient = useQueryClient();
const toast = useToast();
const onToggleCollateral = async () => {
const comptroller = createComptroller(comptrollerAddress, fuse);
let call;
if (asset.membership) {
call = comptroller.methods.exitMarket(asset.cToken);
} else {
call = comptroller.methods.enterMarkets([asset.cToken]);
}
let response = await call.call({ from: address });
// For some reason `response` will be `["0"]` if no error but otherwise it will return a string number.
if (response[0] !== "0") {
if (asset.membership) {
toast({
title: "Error! Code: " + response,
description:
"You cannot disable this asset as collateral as you would not have enough collateral posted to keep your borrow. Try adding more collateral of another type or paying back some of your debt.",
status: "error",
duration: 9000,
isClosable: true,
position: "top-right",
});
} else {
toast({
title: "Error! Code: " + response,
description:
"You cannot enable this asset as collateral at this time.",
status: "error",
duration: 9000,
isClosable: true,
position: "top-right",
});
}
return;
}
await call.send({ from: address });
LogRocket.track("Fuse-ToggleCollateral");
queryClient.refetchQueries();
};
const isStakedOHM =
asset.underlyingToken.toLowerCase() ===
"0x04F2694C8fcee23e8Fd0dfEA1d4f5Bb8c352111F".toLowerCase();
const { data: stakedOHMApyData } = useQuery("sOHM_APY", async () => {
const data = (
await fetch("https://api.rari.capital/fuse/pools/18/apy")
).json();
return data as Promise<{ supplyApy: number; supplyWpy: number }>;
});
const isMobile = useIsMobile();
const { t } = useTranslation();
const hasSupplyIncentives = !!supplyIncentives.length;
const totalSupplyAPR =
supplyIncentives?.reduce((prev, incentive) => {
const apr = incentive.supplyAPR;
return prev + apr;
}, 0) ?? 0;
const [hovered, setHovered] = useState<number>(-1);
const handleMouseEnter = (index: number) => setHovered(index);
const handleMouseLeave = () => setHovered(-1);
const displayedSupplyAPR =
hovered >= 0 ? supplyIncentives[hovered].supplyAPR : totalSupplyAPR;
const displayedSupplyAPRLabel =
hovered >= 0
? `${supplyIncentives[hovered].supplyAPR.toFixed(2)} % APR in ${
rewardTokensData[supplyIncentives[hovered].rewardToken].symbol
} distributions.`
: `${displayedSupplyAPR.toFixed(
2
)}% total APR distributed in ${supplyIncentives
.map((incentive) => rewardTokensData[incentive.rewardToken].symbol)
.join(", ")}
`;
const _hovered = hovered > 0 ? hovered : 0;
const color =
rewardTokensData[supplyIncentives?.[_hovered]?.rewardToken]?.color ??
"white";
const symbol = getSymbol(tokenData, asset);
return (
<>
<PoolModal
defaultMode={Mode.SUPPLY}
comptrollerAddress={comptrollerAddress}
assets={assets}
index={index}
isOpen={isModalOpen}
onClose={closeModal}
isBorrowPaused={asset.isPaused}
/>
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
width="100%"
px={4}
py={1.5}
className="hover-row"
>
{/* Underlying Token Data */}
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
width="27%"
>
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
width="100%"
as="button"
onClick={authedOpenModal}
>
<Avatar
bg="#FFF"
boxSize="37px"
name={symbol}
src={
tokenData?.logoURL ??
"https://raw.githubusercontent.com/feathericons/feather/master/icons/help-circle.svg"
}
/>
<Text fontWeight="bold" fontSize="lg" ml={2} flexShrink={0}>
{symbol}
</Text>
</Row>
{/* <Row
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
width="100%"
>
<Text fontSize="sm" ml={2} flexShrink={0}>
{shortUsdFormatter(asset.liquidityUSD)}
</Text>
</Row> */}
</Column>
{/* APY */}
{isMobile ? null : (
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-end"
width="27%"
as="button"
onClick={authedOpenModal}
>
<Text
color={tokenData?.color ?? "#FF"}
fontWeight="bold"
fontSize="17px"
>
{isStakedOHM
? stakedOHMApyData
? (stakedOHMApyData.supplyApy * 100).toFixed(2)
: "?"
: supplyAPY.toFixed(2)}
%
</Text>
{/* Demo Supply Incentives */}
{hasSupplyIncentives && (
<Row
// ml={1}
// mb={.5}
crossAxisAlignment="center"
mainAxisAlignment="flex-end"
py={2}
>
<Text fontWeight="bold" mr={1}>
+
</Text>
<AvatarGroup size="xs" max={30} ml={2} mr={1} spacing={1}>
{supplyIncentives?.map((supplyIncentive, i) => {
return (
<SimpleTooltip label={displayedSupplyAPRLabel}>
<CTokenIcon
address={supplyIncentive.rewardToken}
boxSize="20px"
onMouseEnter={() => handleMouseEnter(i)}
onMouseLeave={() => handleMouseLeave()}
_hover={{
zIndex: 9,
border: ".5px solid white",
transform: "scale(1.3);",
}}
/>
</SimpleTooltip>
);
})}
</AvatarGroup>
<SimpleTooltip label={displayedSupplyAPRLabel}>
<Text color={color} fontWeight="bold" pl={1} fontSize="sm">
{/* {(supplyIncentive.supplySpeed / 1e18).toString()}% */}
{displayedSupplyAPR.toFixed(2)}% APR
</Text>
</SimpleTooltip>
</Row>
)}
{/* Incentives */}
{/* {hasSupplyIncentives && (
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-end"
py={1}
>
{supplyIncentives?.map((supplyIncentive) => {
return (
<Row
ml={1}
py={0.5}
// mb={.5}
crossAxisAlignment="center"
mainAxisAlignment="flex-end"
>
<Text fontWeight="bold" mr={2}>
+
</Text>
<CTokenIcon
address={supplyIncentive.rewardToken}
boxSize="20px"
/>
<Text fontWeight="bold" mr={2}></Text>
<Text
color={
rewardTokensData[supplyIncentive.rewardToken].color ??
"white"
}
fontWeight="bold"
>
{(supplyIncentive.supplySpeed / 1e18).toString()}%
</Text>
</Row>
);
})}
</Column>
)} */}
<SimpleTooltip
label={t(
"The Collateral Factor (CF) ratio defines the maximum amount of tokens in the pool that can be borrowed with a specific collateral. It’s expressed in percentage: if in a pool ETH has 75% LTV, for every 1 ETH worth of collateral, borrowers will be able to borrow 0.75 ETH worth of other tokens in the pool."
)}
>
<Text fontSize="sm">{asset.collateralFactor / 1e16}% CF</Text>
</SimpleTooltip>
{/* Incentives under APY
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-end"
my={1}
>
{supplyIncentives?.map((supplyIncentive) => {
return (
<Row
mainAxisAlignment="space-between"
crossAxisAlignment="center"
w="100%"
>
<Avatar
src={
rewardTokensData[supplyIncentive.rewardToken].logoURL ?? ""
}
boxSize="20px"
/>
<Text
ml={2}
fontWeight="bold"
color={
rewardTokensData[supplyIncentive.rewardToken].color ?? ""
}
>
{(supplyIncentive.supplySpeed / 1e18).toString()}%
</Text>
</Row>
);
})}
</Column>
*/}
</Column>
)}
{/* Incentives */}
{/* <Column mainAxisAlignment="flex-start" crossAxisAlignment="flex-start">
{supplyIncentives?.map((supplyIncentive) => {
return (
<Row mainAxisAlignment="flex-start" crossAxisAlignment="center">
<Avatar
src={rewardTokensData[supplyIncentive.rewardToken].logoURL}
boxSize="15px"
/>
<Box>
{(supplyIncentive.supplySpeed / 1e18).toString()}% APY
</Box>
</Row>
);
})}
</Column> */}
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-end"
width={isMobile ? "40%" : "27%"}
as="button"
onClick={authedOpenModal}
>
<Text
color={tokenData?.color ?? "#FFF"}
fontWeight="bold"
fontSize="17px"
>
{smallUsdFormatter(asset.supplyBalanceUSD)}
</Text>
<Text fontSize="sm">
{smallUsdFormatter(
asset.supplyBalance / 10 ** asset.underlyingDecimals
).replace("$", "")}{" "}
{symbol}
</Text>
</Column>
{/* Set As Collateral */}
<Row
width={isMobile ? "34%" : "20%"}
mainAxisAlignment="flex-end"
crossAxisAlignment="center"
>
<SwitchCSS symbol={symbol} color={tokenData?.color} />
<Switch
isChecked={asset.membership}
className={symbol + "-switch"}
onChange={onToggleCollateral}
size="md"
mt={1}
mr={5}
/>
</Row>
</Row>
</>
);
};
const BorrowList = ({
assets,
borrowBalanceUSD,
comptrollerAddress,
incentivesData,
}: {
assets: USDPricedFuseAsset[];
borrowBalanceUSD: number;
comptrollerAddress: string;
incentivesData: IncentivesData;
}) => {
const { t } = useTranslation();
const borrowedAssets = assets.filter((asset) => asset.borrowBalanceUSD > 1);
const nonBorrowedAssets = assets.filter(
(asset) => asset.borrowBalanceUSD < 1
);
const isMobile = useIsMobile();
return (
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
height="100%"
pb={1}
>
<Heading size="md" px={4} py={3}>
{t("Borrow Balance:")} {smallUsdFormatter(borrowBalanceUSD)}
</Heading>
<ModalDivider />
{assets.length > 0 ? (
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
width="100%"
px={4}
mt={4}
>
<Text width="27%" fontWeight="bold" pl={1}>
{t("Asset")}
</Text>
{isMobile ? null : (
<Text width="27%" fontWeight="bold" textAlign="right">
{t("APY/TVL")}
</Text>
)}
<Text
fontWeight="bold"
textAlign="right"
width={isMobile ? "40%" : "27%"}
>
{t("Balance")}
</Text>
<Text
fontWeight="bold"
textAlign="right"
width={isMobile ? "34%" : "20%"}
>
{t("Liquidity")}
</Text>
</Row>
) : null}
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
expand
mt={1}
>
{assets.length > 0 ? (
<>
{borrowedAssets.map((asset, index) => {
// Don't show paused assets.
// if (asset.isPaused) {
// return null;
// }
const incentivesForAsset = (
incentivesData?.incentives?.[asset.cToken] ?? []
).filter(({ borrowSpeed }) => !!borrowSpeed);
return (
<AssetBorrowRow
comptrollerAddress={comptrollerAddress}
key={asset.underlyingToken}
assets={borrowedAssets}
index={index}
borrowIncentives={incentivesForAsset}
rewardTokensData={incentivesData.rewardTokensData}
isPaused={asset.isPaused}
/>
);
})}
{borrowedAssets.length > 0 ? <ModalDivider my={2} /> : null}
{nonBorrowedAssets.map((asset, index) => {
// Don't show paused assets.
if (asset.isPaused) {
return null;
}
const incentivesForAsset = (
incentivesData?.incentives?.[asset.cToken] ?? []
).filter(({ borrowSpeed }) => !!borrowSpeed);
return (
<AssetBorrowRow
comptrollerAddress={comptrollerAddress}
key={asset.underlyingToken}
assets={nonBorrowedAssets}
index={index}
borrowIncentives={incentivesForAsset}
rewardTokensData={incentivesData.rewardTokensData}
isPaused={asset.isPaused}
/>
);
})}
</>
) : (
<Center expand my={8}>
{t("There are no assets in this pool.")}
</Center>
)}
</Column>
</Column>
);
};
const AssetBorrowRow = ({
assets,
index,
comptrollerAddress,
borrowIncentives,
rewardTokensData,
isPaused,
}: {
assets: USDPricedFuseAsset[];
index: number;
comptrollerAddress: string;
borrowIncentives: CTokenRewardsDistributorIncentives[];
rewardTokensData: TokensDataMap;
isPaused: boolean;
}) => {
const asset = assets[index];
const {
isOpen: isModalOpen,
onOpen: openModal,
onClose: closeModal,
} = useDisclosure();
const authedOpenModal = useAuthedCallback(openModal);
const tokenData = useTokenData(asset.underlyingToken);
const borrowAPY = convertMantissaToAPY(asset.borrowRatePerBlock, 365);
const { t } = useTranslation();
const isMobile = useIsMobile();
const hasBorrowIncentives = !!borrowIncentives.length;
const totalBorrowAPY =
borrowIncentives?.reduce((prev, incentive) => {
const apy = incentive.borrowSpeed / 1e18;
return prev + apy;
}, 0) ?? 0;
const [hovered, setHovered] = useState<number>(-1);
const handleMouseEnter = (index: number) => setHovered(index);
const handleMouseLeave = () => setHovered(-1);
const displayedBorrowAPY =
hovered >= 0
? borrowIncentives[hovered].borrowSpeed / 1e18
: totalBorrowAPY;
const symbol = getSymbol(tokenData, asset);
return (
<>
<PoolModal
comptrollerAddress={comptrollerAddress}
defaultMode={Mode.BORROW}
assets={assets}
index={index}
isOpen={isModalOpen}
onClose={closeModal}
isBorrowPaused={isPaused}
/>
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
width="100%"
px={4}
py={1.5}
className="hover-row"
as="button"
onClick={authedOpenModal}
>
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
width="27%"
>
<Avatar
bg="#FFF"
boxSize="37px"
name={symbol}
src={
tokenData?.logoURL ??
"https://raw.githubusercontent.com/feathericons/feather/master/icons/help-circle.svg"
}
/>
<Text fontWeight="bold" fontSize="lg" ml={2} flexShrink={0}>
{symbol}
</Text>
</Row>
{isMobile ? null : (
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-end"
width="27%"
>
<Text
color={tokenData?.color ?? "#FF"}
fontWeight="bold"
fontSize="17px"
>
{borrowAPY.toFixed(2)}%
</Text>
{/* Demo Borrow Incentives */}
{hasBorrowIncentives && (
<Row
// ml={1}
// mb={.5}
crossAxisAlignment="center"
mainAxisAlignment="flex-end"
py={1}
>
<Text fontWeight="bold" mr={1}>
+
</Text>
<AvatarGroup size="xs" max={30} ml={2} mr={2} spacing={1}>
{borrowIncentives?.map((borrowIncentive, i) => {
return (
<CTokenIcon
address={borrowIncentive.rewardToken}
boxSize="20px"
_hover={{
zIndex: 9,
border: ".5px solid white",
transform: "scale(1.3);",
}}
onMouseEnter={() => handleMouseEnter(i)}
onMouseLeave={handleMouseLeave}
/>
);
})}
</AvatarGroup>
<Text
color={
rewardTokensData[borrowIncentives?.[hovered]?.rewardToken]
?.color ?? "white"
}
pl={1}
fontWeight="bold"
>
{/* {(supplyIncentive.supplySpeed / 1e18).toString()}% */}
{displayedBorrowAPY}%
</Text>
</Row>
)}
{/* Borrow Incentives */}
{/* {hasBorrowIncentives && (
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-end"
py={1}
>
{borrowIncentives?.map((borrowIncentive) => {
return (
<Row
ml={1}
// mb={.5}
crossAxisAlignment="center"
mainAxisAlignment="flex-end"
>
<Text fontWeight="bold" mr={2}>
+
</Text>
<CTokenIcon
address={borrowIncentive.rewardToken}
boxSize="20px"
/>
<Text fontWeight="bold" mr={2}></Text>
<Text
color={
rewardTokensData[borrowIncentive.rewardToken].color ??
"white"
}
fontWeight="bold"
>
{(borrowIncentive.borrowSpeed / 1e18).toString()}%
</Text>
</Row>
);
})}
</Column>
)} */}
<SimpleTooltip
label={t(
"Total Value Lent (TVL) measures how much of this asset has been supplied in total. TVL does not account for how much of the lent assets have been borrowed, use 'liquidity' to determine the total unborrowed assets lent."
)}
>
<Text fontSize="sm">
{shortUsdFormatter(asset.totalSupplyUSD)} TVL
</Text>
</SimpleTooltip>
{/* Borrow Incentives under APY */}
{/* <Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-end"
my={1}
>
{borrowIncentives?.map((borrowIncentive) => {
return (
<Row
mainAxisAlignment="space-between"
crossAxisAlignment="center"
w="100%"
>
<Avatar
src={
rewardTokensData[borrowIncentive.rewardToken].logoURL ??
""
}
boxSize="20px"
/>
<Text
ml={2}
fontWeight="bold"
color={
rewardTokensData[borrowIncentive.rewardToken].color ??
""
}
>
{(borrowIncentive.borrowSpeed / 1e18).toString()}%
</Text>
</Row>
);
})}
</Column> */}
</Column>
)}
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-end"
width={isMobile ? "40%" : "27%"}
>
<Text
color={tokenData?.color ?? "#FFF"}
fontWeight="bold"
fontSize="17px"
>
{smallUsdFormatter(asset.borrowBalanceUSD)}
</Text>
<Text fontSize="sm">
{smallUsdFormatter(
asset.borrowBalance / 10 ** asset.underlyingDecimals
).replace("$", "")}{" "}
{symbol}
</Text>
</Column>
<SimpleTooltip
label={t(
"Liquidity is the amount of this asset that is available to borrow (unborrowed). To see how much has been supplied and borrowed in total, navigate to the Pool Info tab."
)}
placement="top-end"
>
<Box width={isMobile ? "34%" : "20%"}>
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-end"
>
<Text
color={tokenData?.color ?? "#FFF"}
fontWeight="bold"
fontSize="17px"
>
{shortUsdFormatter(asset.liquidityUSD)}
</Text>
<Text fontSize="sm">
{shortUsdFormatter(
asset.liquidity / 10 ** asset.underlyingDecimals
).replace("$", "")}{" "}
{symbol}
</Text>
</Column>
</Box>
</SimpleTooltip>
</Row>
</>
);
};
================================================
FILE: src/components/pages/Fuse/FusePoolsPage.tsx
================================================
import {
Avatar,
AvatarGroup,
Link,
Spinner,
Text,
Box,
} from "@chakra-ui/react";
import { Center, Column, Row, useIsMobile } from "utils/chakraUtils";
import { useTranslation } from "react-i18next";
import { useRari } from "context/RariContext";
import { useIsSmallScreen } from "hooks/useIsSmallScreen";
import { smallUsdFormatter } from "utils/bigUtils";
import DashboardBox from "../../shared/DashboardBox";
import { Header } from "../../shared/Header";
import { ModalDivider } from "../../shared/Modal";
import { Link as RouterLink } from "react-router-dom";
import FuseStatsBar, { WhitelistedIcon } from "./FuseStatsBar";
import FuseTabBar, { useFilter } from "./FuseTabBar";
import { useTokenData } from "hooks/useTokenData";
import { filterPoolName } from "utils/fetchFusePoolData";
import { letterScore, usePoolRSS } from "hooks/useRSS";
import { SimpleTooltip } from "components/shared/SimpleTooltip";
import { useFusePools } from "hooks/fuse/useFusePools";
import Footer from "components/shared/Footer";
import { memo } from "react";
import { CTokenIcon } from "components/shared/CTokenIcon";
import { usePoolIncentives } from "hooks/rewards/usePoolIncentives";
export const useHasCreatedPools = () => {
const { filteredPools } = useFusePools("created-pools");
return !!filteredPools.length;
};
const FusePoolsPage = memo(() => {
const { isAuthed } = useRari();
const isMobile = useIsSmallScreen();
return (
<>
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
color="#FFFFFF"
mx="auto"
width={isMobile ? "100%" : "1000px"}
height="100%"
px={isMobile ? 4 : 0}
>
<Header isAuthed={isAuthed} isFuse />
<FuseStatsBar />
<FuseTabBar />
<DashboardBox width="100%" mt={4}>
<PoolList />
</DashboardBox>
<Footer />
</Column>
</>
);
});
export default FusePoolsPage;
const PoolList = () => {
const filter = useFilter();
const { t } = useTranslation();
const { filteredPools } = useFusePools(filter);
const isMobile = useIsMobile();
return (
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
expand
>
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
height="45px"
width="100%"
flexShrink={0}
pl={4}
pr={1}
>
<Text fontWeight="bold" width={isMobile ? "100%" : "40%"}>
{!isMobile ? t("Pool Assets") : t("Pool Directory")}
</Text>
{isMobile ? null : (
<>
<Text fontWeight="bold" textAlign="center" width="13%">
{t("Pool Number")}
</Text>
<Text fontWeight="bold" textAlign="center" width="16%">
{t("Total Supplied")}
</Text>
<Text fontWeight="bold" textAlign="center" width="16%">
{t("Total Borrowed")}
</Text>
<Text fontWeight="bold" textAlign="center" width="15%">
{t("Pool Risk Score")}
</Text>
</>
)}
</Row>
<ModalDivider />
<Column
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
width="100%"
minHeight="100px"
>
{filteredPools && filteredPools.length ? (
filteredPools.map((pool, index) => {
return (
<PoolRow
key={pool.id}
poolNumber={pool.id}
name={filterPoolName(pool.name)}
tvl={pool.suppliedUSD}
borrowed={pool.borrowedUSD}
tokens={pool.underlyingTokens.map((address, index) => ({
symbol: pool.underlyingSymbols[index],
address,
}))}
noBottomDivider={index === filteredPools.length - 1}
isWhitelisted={pool.whitelistedAdmin}
comptroller={pool.comptroller}
/>
);
})
) : (
<Center h="100%" w="100%" bg="transparent">
<Spinner my={8} />
</Center>
)}
</Column>
</Column>
);
};
const PoolRow = ({
tokens,
poolNumber,
tvl,
borrowed,
name,
noBottomDivider,
isWhitelisted,
comptroller,
}: {
tokens: { symbol: string; address: string }[];
poolNumber: number;
tvl: number;
borrowed: number;
name: string;
noBottomDivider?: boolean;
isWhitelisted: boolean;
comptroller: string;
}) => {
const isEmpty = tokens.length === 0;
const rss = usePoolRSS(poolNumber);
const rssScore = rss ? letterScore(rss.totalScore) : "?";
const isMobile = useIsMobile();
const poolIncentives = usePoolIncentives(comptroller);
const { hasIncentives } = poolIncentives;
if (hasIncentives) {
console.log({ poolNumber, poolIncentives });
}
return (
<>
<Link
/* @ts-ignore */
as={RouterLink}
width="100%"
className="no-underline"
to={"/fuse/pool/" + poolNumber}
>
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
width="100%"
height="90px"
className="hover-row"
pl={4}
pr={1}
>
<Column
pt={2}
width={isMobile ? "100%" : "40%"}
height="100%"
mainAxisAlignment="center"
crossAxisAlignment="flex-start"
>
{isEmpty ? null : (
<SimpleTooltip label={tokens.map((t) => t.symbol).join(" / ")}>
<AvatarGroup size="xs" max={30} mr={2}>
{tokens.map(({ address }) => {
return <CTokenIcon key={address} address={address} />;
})}
</AvatarGroup>
</SimpleTooltip>
)}
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
mt={isEmpty ? 0 : 2}
>
<WhitelistedIcon
isWhitelisted={isWhitelisted}
mr={2}
boxSize={"15px"}
mb="2px"
/>
<Text>{name}</Text>
</Row>
</Column>
{isMobile ? null : (
<>
<Center height="100%" width="13%">
<b>{poolNumber}</b>
</Center>
<Center height="100%" width="16%">
<b>{smallUsdFormatter(tvl)}</b>
</Center>
<Center height="100%" width="16%">
<b>{smallUsdFormatter(borrowed)}</b>
</Center>
<Center height="100%" width="15%">
<SimpleTooltip
label={
"Underlying RSS: " +
(rss ? rss.totalScore.toFixed(2) : "?") +
"%"
}
>
<b>{rssScore}</b>
</SimpleTooltip>
</Center>
</>
)}
</Row>
</Link>
{noBottomDivider ? null : <ModalDivider />}
</>
);
};
================================================
FILE: src/components/pages/Fuse/FuseStatsBar.tsx
================================================
import { Heading, Text } from "@chakra-ui/react";
import { RowOrColumn, Column, Center, Row } from "utils/chakraUtils";
import { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { useRari } from "context/RariContext";
import { useIsSmallScreen } from "hooks/useIsSmallScreen";
import { smallUsdFormatter } from "utils/bigUtils";
import CaptionedStat from "components/shared/CaptionedStat";
import DashboardBox from "components/shared/DashboardBox";
import { fetchFuseNumberTVL } from "hooks/fuse/useFuseTVL";
import { useFuseTotalBorrowAndSupply } from "hooks/fuse/useFuseTotalBorrowAndSupply";
import { APYWithRefreshMovingStat } from "components/shared/MovingStat";
import { FusePoolData } from "utils/fetchFusePoolData";
import { CheckCircleIcon, WarningTwoIcon } from "@chakra-ui/icons";
import { SimpleTooltip } from "components/shared/SimpleTooltip";
const FuseStatsBar = ({ data }: { data?: FusePoolData }) => {
const isMobile = useIsSmallScreen();
const { t } = useTranslation();
const { isAuthed, fuse, rari } = useRari();
const { data: totalBorrowAndSupply } = useFuseTotalBorrowAndSupply();
return (
<RowOrColumn
width="100%"
isRow={!isMobile}
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
height={isMobile ? "auto" : "125px"}
>
<DashboardBox
width={isMobile ? "100%" : "50%"}
height={isMobile ? "auto" : "100%"}
>
<Column
expand
mainAxisAlignment="center"
crossAxisAlignment={isMobile ? "center" : "flex-start"}
textAlign={isMobile ? "center" : "left"}
p={4}
fontSize="sm"
>
<Row
mainAxisAlignment="flex-start"
crossAxisAlignment="center"
mb="2px"
>
{/* Title */}
{!!data ? (
<WhitelistedIcon isWhitelisted={data.isAdminWhitelisted} mb={1} />
) : null}
<Heading size="lg" isTruncated>
{data?.name ?? "Fuse"}
</Heading>
</Row>
{/* Description */}
{!!data ? (
<Text>
This pool has{" "}
<span style={{ fontWeight: "bold" }}>
{smallUsdFormatter(data.totalSuppliedUSD)} supplied{" "}
</span>{" "}
across{" "}
<span style={{ fontWeight: "bold" }}>
{data.assets.length} assets.
</span>{" "}
Fuse is a truly open interest rate protocol. Lend, borrow,
and create isolated lending pools with extreme flexibility.
</Text>
) : (
<Text>
Fuse is a truly open interest rate protocol. Lend, borrow,
and create isolated lending pools with extreme flexibility.
</Text>
)}
</Column>
</DashboardBox>
<RowOrColumn
isRow={!isMobile}
mainAxisAlignment="flex-start"
crossAxisAlignment="flex-start"
height="100%"
width={isMobile ? "100%" : "50%"}
>
{isAuthed &&
totalBorrowAndSupply &&
totalBorrowAndSupply.totalSuppliedUSD > 0 ? (
<>
<StatBox width={isMobile ? "100%" : "50%"}>
<CaptionedStat
crossAxisAlignment="center"
captionFirst={false}
statSize="3xl"
captionSize="sm"
stat={
totalBorrowAndSupply
? smallUsdFormatter(totalBorrowAndSupply.totalSuppliedUSD)
: "$?"
}
caption={t("Your Supply Balance")}
/>
</StatBox>
<StatBox width={isMobile ? "100%" : "50%"}>
<CaptionedStat
crossAxisAlignment="center"
captionFirst={false}
statSize="3xl"
captionSize="sm"
stat={
totalBorrowAndSupply
? smallUsdFormatter(totalBorrowAndSupply.totalBorrowedUSD)
: "$?"
}
caption={t("Your Borrow Balance")}
/>
</StatBox>
</>
) : (
<StatBox width="100%">
<APYWithRefreshMovingStat
formatStat={smallUsdFormatter}
fetchInterval={40000}
loadingPlaceholder="$?"
apyInterval={100}
fetch={() => fetchFuseNumberTVL(rari, fuse)}
queryKey={"fuseTVL"}
apy={0.15}
statSize="3xl"
captionSize="xs"
caption={t("Total Value Supplied Across Fuse")}
crossAxisAlignment="center"
captionFirst={false}
/>
</StatBox>
)}
</RowOrColumn>
</RowOrColumn>
);
};
export default FuseStatsBar;
const StatBox = ({
children,
...others
}: {
children: ReactNode;
[key: string]: any;
}) => {
const isMobile = useIsSmallScreen();
return (
<DashboardBox
height={isMobile ? "auto" : "100%"}
mt={isMobile ? 4 : 0}
ml={isMobile ? 0 : 4}
{...others}
>
<Center expand p={4}>
{children}
</Center>
</DashboardBox>
);
};
export const WhitelistedIcon = ({
isWhitelisted,
...boxProps
}: {
isWhitelisted: boolean;
[x: string]: any;
}) => {
return (
<>
<SimpleTooltip
label={
isWhitelisted
? "This pool is from a Whitelisted Admin"
: "This pool is not from a whitelisted admin. Use with caution!"
}
placement="bottom-end"
>
{isWhitelisted ? (
<CheckCircleIcon boxSize="20px" mr={3} {...boxProps} />
) : (
<WarningTwoIcon
boxSize="20px"
mr={3}
color="orange.300"
{...boxProps}
/>
)}
</SimpleTooltip>
</>
);
};
================================================
FILE: src/components/pages/Fuse/FuseTabBar.tsx
================================================
import { DeleteIcon, SmallAddIcon } from "@chakra-ui/icons";
import { ButtonGroup, Input, Link, Text } from "@chakra-ui/react";
import { RowOrColumn, Row, Center, useWindowSize } from "utils/chakraUtils";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { useIsSmallScreen } from "../../../hooks/useIsSmallScreen";
import DashboardBox from "../../shared/DashboardBox";
imp
gitextract_warb6kwy/ ├── .eslintignore ├── .github/ │ └── workflows/ │ ├── tests.yml │ └── translations.yml ├── .gitignore ├── .nycrc.json ├── .prettierrc ├── .vscode/ │ └── launch.json ├── LICENSE ├── README.md ├── api/ │ ├── rss.ts │ ├── stats.ts │ ├── tokenData.ts │ └── tsconfig.json ├── cypress/ │ ├── README.md │ ├── e2e/ │ │ └── E2E.spec.js │ ├── fixtures/ │ │ └── example.json │ ├── plugins/ │ │ └── index.js │ └── support/ │ ├── commands.js │ └── index.js ├── cypress.json ├── hardhat.config.js ├── i18next-scanner.config.js ├── package.json ├── public/ │ ├── index.html │ ├── manifest.json │ └── robots.txt ├── src/ │ ├── components/ │ │ ├── App.tsx │ │ ├── pages/ │ │ │ ├── ErrorPage.tsx │ │ │ ├── Fuse/ │ │ │ │ ├── FuseLiquidationsPage.tsx │ │ │ │ ├── FusePoolCreatePage.tsx │ │ │ │ ├── FusePoolEditPage.tsx │ │ │ │ ├── FusePoolInfoPage.tsx │ │ │ │ ├── FusePoolPage.tsx │ │ │ │ ├── FusePoolsPage.tsx │ │ │ │ ├── FuseStatsBar.tsx │ │ │ │ ├── FuseTabBar.tsx │ │ │ │ └── Modals/ │ │ │ │ ├── AddAssetModal/ │ │ │ │ │ ├── AddAssetModal.tsx │ │ │ │ │ ├── AssetConfig.tsx │ │ │ │ │ ├── AssetSettings.tsx │ │ │ │ │ ├── DeployButton.tsx │ │ │ │ │ ├── IRMChart.tsx │ │ │ │ │ ├── OracleConfig/ │ │ │ │ │ │ ├── BaseTokenOracleConfig.tsx │ │ │ │ │ │ ├── OracleConfig.tsx │ │ │ │ │ │ ├── UniswapV2OrSushiPriceOracleConfigurator.tsx │ │ │ │ │ │ └── UniswapV3PriceOracleConfigurator.tsx │ │ │ │ │ └── Screens/ │ │ │ │ │ ├── Screen1.tsx │ │ │ │ │ ├── Screen2.tsx │ │ │ │ │ └── Screen3.tsx │ │ │ │ ├── AddAssetModal.tsx │ │ │ │ ├── AddRewardsDistributorModal.tsx │ │ │ │ ├── Edit/ │ │ │ │ │ ├── AssetConfiguration.tsx │ │ │ │ │ ├── MarketCapConfigurator.tsx │ │ │ │ │ ├── OraclesTable.tsx │ │ │ │ │ └── PoolConfiguration.tsx │ │ │ │ ├── EditRewardsDistributorModal.tsx │ │ │ │ └── PoolModal/ │ │ │ │ ├── AmountSelect.tsx │ │ │ │ └── index.tsx │ │ │ ├── InterestRates/ │ │ │ │ ├── InterestRates.tsx │ │ │ │ ├── InterestRatesTable.tsx │ │ │ │ ├── InterestRatesView.tsx │ │ │ │ ├── MultiPicker.tsx │ │ │ │ └── TokenSearch.tsx │ │ │ ├── MultiPoolPortal.tsx │ │ │ ├── Pool2/ │ │ │ │ ├── Pool2Modal/ │ │ │ │ │ ├── AmountSelect.tsx │ │ │ │ │ ├── OptionsMenu.tsx │ │ │ │ │ └── index.tsx │ │ │ │ └── Pool2Page.tsx │ │ │ ├── PoolPortal.tsx │ │ │ ├── RariDepositModal/ │ │ │ │ ├── AmountSelect.tsx │ │ │ │ ├── OptionsMenu.tsx │ │ │ │ ├── TokenSelect.tsx │ │ │ │ └── index.tsx │ │ │ ├── Stats/ │ │ │ │ ├── StatsEarnSection.tsx │ │ │ │ ├── StatsFuseSection.tsx │ │ │ │ ├── StatsPage.tsx │ │ │ │ ├── StatsPool2Section.tsx │ │ │ │ ├── StatsSubNav.tsx │ │ │ │ ├── StatsTranchesSection.tsx │ │ │ │ ├── Totals/ │ │ │ │ │ ├── EarnRow.tsx │ │ │ │ │ ├── FuseRow.tsx │ │ │ │ │ ├── Pool2Row.tsx │ │ │ │ │ ├── StatsTotalSection.tsx │ │ │ │ │ └── TranchesRow.tsx │ │ │ │ └── index.ts │ │ │ └── Tranches/ │ │ │ ├── SaffronContext.tsx │ │ │ ├── SaffronDepositModal/ │ │ │ │ ├── AmountSelect.tsx │ │ │ │ └── index.tsx │ │ │ ├── SaffronPoolABI.json │ │ │ ├── SaffronStrategyABI.json │ │ │ └── TranchesPage.tsx │ │ └── shared/ │ │ ├── AccountButton.tsx │ │ ├── AdminAlert.tsx │ │ ├── CTokenIcon.tsx │ │ ├── CaptionedStat.tsx │ │ ├── ClaimRGTModal.tsx │ │ ├── CopyrightSpacer.tsx │ │ ├── CountdownBanner.tsx │ │ ├── DashboardBox.tsx │ │ ├── Footer.tsx │ │ ├── FullPageSpinner.test.tsx │ │ ├── FullPageSpinner.tsx │ │ ├── GlowingButton.tsx │ │ ├── Header.tsx │ │ ├── Layout.tsx │ │ ├── Logos.tsx │ │ ├── Modal.tsx │ │ ├── MovingStat.tsx │ │ ├── PoolsPerformance.tsx │ │ ├── ProgressBar.tsx │ │ ├── SimpleTooltip.tsx │ │ ├── SliderWithLabel.tsx │ │ ├── SwitchCSS.tsx │ │ ├── TransactionStepper.tsx │ │ └── TranslateButton.tsx │ ├── constants/ │ │ ├── homepage.ts │ │ ├── networks.ts │ │ ├── pools.ts │ │ ├── saffron.ts │ │ └── tokenData.ts │ ├── context/ │ │ ├── AddAssetContext.tsx │ │ ├── PoolContext.tsx │ │ └── RariContext.tsx │ ├── fuse-sdk/ │ │ ├── .browserslistrc │ │ ├── .gitattributes │ │ ├── .gitignore │ │ ├── LICENSE │ │ ├── README.md │ │ ├── package.json │ │ ├── scripts/ │ │ │ └── minify-contracts.js │ │ ├── src/ │ │ │ ├── abi/ │ │ │ │ ├── FuseFeeDistributor.json │ │ │ │ ├── FusePoolDirectory.json │ │ │ │ ├── FusePoolLens.json │ │ │ │ ├── FusePoolLensSecondary.json │ │ │ │ ├── FuseSafeLiquidator.json │ │ │ │ ├── InitializableClones.json │ │ │ │ └── UniswapV3Pool.slim.json │ │ │ ├── contracts/ │ │ │ │ ├── compound-protocol.json │ │ │ │ ├── compound-protocol.min.json │ │ │ │ ├── open-oracle.json │ │ │ │ ├── open-oracle.min.json │ │ │ │ ├── oracles/ │ │ │ │ │ ├── AlphaHomoraV1PriceOracle.json │ │ │ │ │ ├── BalancerLpTokenPriceOracle.json │ │ │ │ │ ├── ChainlinkPriceOracle.json │ │ │ │ │ ├── CurveLpTokenPriceOracle.json │ │ │ │ │ ├── Keep3rPriceOracle.json │ │ │ │ │ ├── MasterPriceOracle.json │ │ │ │ │ ├── PreferredPriceOracle.json │ │ │ │ │ ├── RecursivePriceOracle.json │ │ │ │ │ ├── SynthetixPriceOracle.json │ │ │ │ │ ├── UniswapLpTokenPriceOracle.json │ │ │ │ │ ├── UniswapTwapPriceOracleV2Factory.json │ │ │ │ │ ├── UniswapV3TwapPriceOracleV2Factory.json │ │ │ │ │ ├── YVaultV1PriceOracle.json │ │ │ │ │ └── YVaultV2PriceOracle.json │ │ │ │ └── oracles.min.json │ │ │ ├── index.js │ │ │ └── irm/ │ │ │ ├── DAIInterestRateModelV2.js │ │ │ ├── JumpRateModel.js │ │ │ ├── JumpRateModelV2.js │ │ │ └── WhitePaperInterestRateModel.js │ │ ├── test/ │ │ │ ├── launch-pools.js │ │ │ ├── live-price-oracle.js │ │ │ ├── oracles.js │ │ │ ├── public-contracts.js │ │ │ ├── safe-liquidator.js │ │ │ └── update-interest-rate-models-v2.js │ │ └── webpack.config.js │ ├── hooks/ │ │ ├── fuse/ │ │ │ ├── useCTokenData.ts │ │ │ ├── useFusePools.ts │ │ │ ├── useFuseTVL.ts │ │ │ ├── useFuseTotalBorrowAndSupply.ts │ │ │ ├── useIRMCurves.ts │ │ │ ├── useLiquidationIncentive.ts │ │ │ ├── useOracleData.ts │ │ │ └── useOraclesForPool.ts │ │ ├── homepage/ │ │ │ └── useOpportunitySubtitle.ts │ │ ├── interestRates/ │ │ │ ├── aave/ │ │ │ │ ├── LendingPool.ts │ │ │ │ └── useReserves.ts │ │ │ ├── compound/ │ │ │ │ ├── CErc20.ts │ │ │ │ ├── contracts/ │ │ │ │ │ └── CErc20.json │ │ │ │ └── useCompoundMarkets.ts │ │ │ ├── fuse/ │ │ │ │ └── useFuseMarkets.ts │ │ │ └── types.ts │ │ ├── pool2/ │ │ │ ├── usePool2APR.ts │ │ │ ├── usePool2Balance.ts │ │ │ ├── usePool2TotalStaked.ts │ │ │ ├── usePool2UnclaimedRGT.ts │ │ │ └── useSushiswapRewards.ts │ │ ├── rewards/ │ │ │ ├── useClaimable.ts │ │ │ ├── usePoolIncentives.ts │ │ │ ├── useRewardAPY.ts │ │ │ ├── useRewardsDistributorsForPool.ts │ │ │ ├── useUnclaimedFuseRewards.ts │ │ │ └── useUnclaimedRGT.ts │ │ ├── tranches/ │ │ │ ├── useSFIDistributions.ts │ │ │ ├── useSFIEarnings.ts │ │ │ └── useSaffronData.ts │ │ ├── useAssetsMap.ts │ │ ├── useAuthedCallback.ts │ │ ├── useBorrowLimit.ts │ │ ├── useFusePoolData.ts │ │ ├── useIsSemiSmallScreen.tsx │ │ ├── useIsSmallScreen.tsx │ │ ├── useIsUpgradable.ts │ │ ├── useMaxWithdraw.ts │ │ ├── useMaybeResponsiveProp.ts │ │ ├── useNoSlippageCurrencies.ts │ │ ├── usePoolAPY.ts │ │ ├── usePoolBalance.ts │ │ ├── usePoolInfo.ts │ │ ├── usePoolInterest.ts │ │ ├── useRSS.ts │ │ ├── useTVL.ts │ │ ├── useTokenBalance.ts │ │ └── useTokenData.ts │ ├── index.css │ ├── index.tsx │ ├── locales/ │ │ ├── en.json │ │ ├── zh-CN.json │ │ └── zh-TW.json │ ├── rari-sdk/ │ │ ├── 0x.js │ │ ├── abi/ │ │ │ └── ERC20.json │ │ ├── cache.js │ │ ├── docs/ │ │ │ ├── governance.md │ │ │ └── pools/ │ │ │ ├── ethereum.md │ │ │ ├── stable.md │ │ │ └── yield.md │ │ ├── governance/ │ │ │ └── abi/ │ │ │ ├── RariGovernanceToken.json │ │ │ ├── RariGovernanceTokenDistributor.json │ │ │ ├── RariGovernanceTokenUniswapDistributor.json │ │ │ └── RariGovernanceTokenVesting.json │ │ ├── governance.js │ │ ├── index.js │ │ ├── package.json │ │ ├── pools/ │ │ │ ├── dai/ │ │ │ │ └── abi/ │ │ │ │ └── legacy/ │ │ │ │ └── v1.0.0/ │ │ │ │ ├── RariFundController.json │ │ │ │ └── RariFundProxy.json │ │ │ ├── dai.js │ │ │ ├── ethereum/ │ │ │ │ └── abi/ │ │ │ │ ├── RariFundController.json │ │ │ │ ├── RariFundManager.json │ │ │ │ ├── RariFundProxy.json │ │ │ │ ├── RariFundToken.json │ │ │ │ └── legacy/ │ │ │ │ └── v1.0.0/ │ │ │ │ └── RariFundController.json │ │ │ ├── ethereum.js │ │ │ ├── stable/ │ │ │ │ └── abi/ │ │ │ │ ├── RariFundController.json │ │ │ │ ├── RariFundManager.json │ │ │ │ ├── RariFundPriceConsumer.json │ │ │ │ ├── RariFundProxy.json │ │ │ │ ├── RariFundToken.json │ │ │ │ └── legacy/ │ │ │ │ ├── v1.0.0/ │ │ │ │ │ ├── RariFundManager.json │ │ │ │ │ ├── RariFundProxy.json │ │ │ │ │ └── RariFundToken.json │ │ │ │ ├── v1.1.0/ │ │ │ │ │ ├── RariFundController.json │ │ │ │ │ ├── RariFundManager.json │ │ │ │ │ └── RariFundProxy.json │ │ │ │ ├── v1.2.0/ │ │ │ │ │ └── RariFundProxy.json │ │ │ │ ├── v2.0.0/ │ │ │ │ │ ├── RariFundController.json │ │ │ │ │ ├── RariFundManager.json │ │ │ │ │ └── RariFundProxy.json │ │ │ │ ├── v2.2.0/ │ │ │ │ │ └── RariFundProxy.json │ │ │ │ ├── v2.4.0/ │ │ │ │ │ └── RariFundProxy.json │ │ │ │ └── v2.5.0/ │ │ │ │ └── RariFundController.json │ │ │ ├── stable.js │ │ │ ├── yield/ │ │ │ │ └── abi/ │ │ │ │ └── legacy/ │ │ │ │ ├── v1.0.0/ │ │ │ │ │ ├── RariFundController.json │ │ │ │ │ └── RariFundProxy.json │ │ │ │ └── v1.1.0/ │ │ │ │ └── RariFundProxy.json │ │ │ └── yield.js │ │ └── subpools/ │ │ ├── aave.js │ │ ├── alpha/ │ │ │ └── abi/ │ │ │ ├── Bank.json │ │ │ └── ConfigurableInterestBankConfig.json │ │ ├── alpha.js │ │ ├── compound.js │ │ ├── dydx.js │ │ ├── fuse/ │ │ │ └── abi/ │ │ │ └── CErc20Delegate.json │ │ ├── fuse.js │ │ ├── keeperdao.js │ │ ├── mstable/ │ │ │ └── abi/ │ │ │ ├── Masset.json │ │ │ └── MassetValidationHelper.json │ │ ├── mstable.js │ │ └── yvault.js │ ├── rari-sdk.d.ts │ ├── react-app-env.d.ts │ ├── setupTests.ts │ ├── static/ │ │ └── compiled/ │ │ ├── info.txt │ │ └── tokens.json │ └── utils/ │ ├── apyUtils.ts │ ├── bigUtils.ts │ ├── chakraUtils.tsx │ ├── chartOptions.ts │ ├── createComptroller.ts │ ├── errorHandling.ts │ ├── fetchFusePoolData.ts │ ├── fetchPoolAPY.ts │ ├── fetchPoolInterest.ts │ ├── fetchTVL.ts │ ├── format.ts │ ├── homepage.ts │ ├── i18n.ts │ ├── multicall.ts │ ├── poolIconUtils.ts │ ├── poolUtils.ts │ ├── rewards.ts │ ├── shortAddress.ts │ ├── stringUtils.ts │ ├── symbolUtils.ts │ ├── tokenUtils.ts │ └── web3Providers.ts └── tsconfig.json
SYMBOL INDEX (303 symbols across 92 files)
FILE: api/rss.ts
function clamp (line 9) | function clamp(num, min, max) {
type ThenArg (line 13) | type ThenArg<T> = T extends PromiseLike<infer U> ? U : T;
function computeAssetRSS (line 24) | async function computeAssetRSS(address: string): Promise<{
FILE: api/tokenData.ts
type TokenData (line 18) | type TokenData = {
FILE: src/components/pages/Fuse/FuseLiquidationsPage.tsx
type LiquidatablePosition (line 25) | type LiquidatablePosition = {
type LiquidationEvent (line 35) | type LiquidationEvent = {
FILE: src/components/pages/Fuse/FusePoolEditPage.tsx
type ComptrollerErrorCodes (line 68) | enum ComptrollerErrorCodes {
function testForComptrollerErrorAndSend (line 109) | async function testForComptrollerErrorAndSend(
FILE: src/components/pages/Fuse/FuseTabBar.tsx
function useFilter (line 15) | function useFilter() {
function useIsMediumScreen (line 19) | function useIsMediumScreen() {
FILE: src/components/pages/Fuse/Modals/AddAssetModal/AssetSettings.tsx
type RETRY_FLAG (line 56) | type RETRY_FLAG = 1 | 2 | 3 | 4 | 5;
FILE: src/components/pages/Fuse/Modals/AddRewardsDistributorModal.tsx
type Nav (line 344) | enum Nav {
FILE: src/components/pages/Fuse/Modals/PoolModal/AmountSelect.tsx
type UserAction (line 53) | enum UserAction {
type CTokenErrorCodes (line 58) | enum CTokenErrorCodes {
function testForCTokenErrorAndSend (line 79) | async function testForCTokenErrorAndSend(
function fetchMaxAmount (line 151) | async function fetchMaxAmount(
FILE: src/components/pages/Fuse/Modals/PoolModal/index.tsx
type Props (line 9) | interface Props {
type Mode (line 19) | enum Mode {
FILE: src/components/pages/InterestRates/InterestRates.tsx
function InterestRates (line 12) | function InterestRates() {
FILE: src/components/pages/InterestRates/InterestRatesTable.tsx
constant DEFAULT_COLUMNS (line 20) | const DEFAULT_COLUMNS: any = [
function InterestRatesTable (line 41) | function InterestRatesTable() {
function TableCell (line 147) | function TableCell({ children, column, ...props }: any) {
function TableRow (line 160) | function TableRow({ children, row, ...props }: any) {
function HeaderCell (line 175) | function HeaderCell({ children, column, ...props }: any) {
function AssetTitle (line 215) | function AssetTitle({ row, column }: any) {
function PercentageComponent (line 255) | function PercentageComponent({ row, column }: any) {
FILE: src/components/pages/InterestRates/InterestRatesView.tsx
type InterestRatesTableOptions (line 22) | enum InterestRatesTableOptions {
type FuseMarket (line 27) | type FuseMarket = {
type InterestRatesContextType (line 31) | type InterestRatesContextType = {
function InterestRatesView (line 54) | function InterestRatesView() {
function fetchTokenDataWithCache (line 201) | async function fetchTokenDataWithCache(address: string) {
FILE: src/components/pages/InterestRates/MultiPicker.tsx
function MultiPicker (line 7) | function MultiPicker({
function MultiPickerButton (line 38) | function MultiPickerButton({
FILE: src/components/pages/InterestRates/TokenSearch.tsx
function TokenSearch (line 15) | function TokenSearch({
FILE: src/components/pages/Pool2/Pool2Modal/AmountSelect.tsx
type Props (line 40) | interface Props {
type UserAction (line 46) | enum UserAction {
FILE: src/components/pages/Pool2/Pool2Modal/index.tsx
type Props (line 8) | interface Props {
type CurrentScreen (line 13) | enum CurrentScreen {
type Mode (line 18) | enum Mode {
FILE: src/components/pages/RariDepositModal/AmountSelect.tsx
type Props (line 51) | interface Props {
type UserAction (line 59) | enum UserAction {
FILE: src/components/pages/RariDepositModal/index.tsx
type CurrentScreen (line 11) | enum CurrentScreen {
type Mode (line 17) | enum Mode {
type Props (line 22) | interface Props {
FILE: src/components/pages/Stats/StatsFuseSection.tsx
type AssetContainerType (line 31) | enum AssetContainerType {
FILE: src/components/pages/Stats/StatsPage.tsx
type StatsSubNav (line 29) | enum StatsSubNav {
FILE: src/components/pages/Tranches/SaffronContext.tsx
type SaffronContextType (line 8) | interface SaffronContextType {
FILE: src/components/pages/Tranches/SaffronDepositModal/AmountSelect.tsx
function noop (line 45) | function noop() {}
type Props (line 58) | interface Props {
type UserAction (line 65) | enum UserAction {
FILE: src/components/pages/Tranches/SaffronDepositModal/index.tsx
type Props (line 7) | interface Props {
FILE: src/components/shared/CaptionedStat.tsx
type CaptionedStatProps (line 5) | interface CaptionedStatProps {
FILE: src/components/shared/ClaimRGTModal.tsx
type ClaimMode (line 41) | type ClaimMode = "pool2" | "private" | "yieldagg" | "fuse";
constant RGT (line 43) | const RGT = "0xd291e7a03283640fdc51b121ac401383a46cc623";
FILE: src/components/shared/DashboardBox.tsx
constant DASHBOARD_BOX_SPACING (line 5) | const DASHBOARD_BOX_SPACING = new PixelMeasurement(15);
constant DASHBOARD_BOX_PROPS (line 7) | const DASHBOARD_BOX_PROPS = {
type ExtendedBoxProps (line 14) | type ExtendedBoxProps = BoxProps & { glow?: boolean };
FILE: src/components/shared/Modal.tsx
constant MODAL_PROPS (line 5) | const MODAL_PROPS = {
FILE: src/components/shared/MovingStat.tsx
function useInterval (line 7) | function useInterval(callback: () => any, delay: number) {
type RefetchMovingStatProps (line 25) | type RefetchMovingStatProps = Omit<CaptionedStatProps, "stat"> & {
type APYMovingStatProps (line 49) | type APYMovingStatProps = Omit<CaptionedStatProps, "stat"> & {
type APYWithRefreshMovingProps (line 93) | type APYWithRefreshMovingProps = Omit<
FILE: src/components/shared/ProgressBar.tsx
type Props (line 3) | interface Props {
FILE: src/constants/homepage.ts
type HomepageFusePool (line 7) | interface HomepageFusePool {
constant HOMEPAGE_FUSE_POOLS (line 13) | const HOMEPAGE_FUSE_POOLS: HomepageFusePool[] = [
type HomepageOpportunityType (line 59) | enum HomepageOpportunityType {
type HomepageOpportunity (line 68) | interface HomepageOpportunity {
constant HOMEPAGE_OPPORTUNIES (line 80) | const HOMEPAGE_OPPORTUNIES: HomepageOpportunity[] = [
constant HOMEPAGE_EARN_VAULTS (line 145) | const HOMEPAGE_EARN_VAULTS: HomepageOpportunity[] = [
constant ABILLY (line 220) | const ABILLY = 1e9;
FILE: src/constants/networks.ts
type ChainID (line 1) | enum ChainID {
FILE: src/constants/pools.ts
type PoolInterface (line 8) | interface PoolInterface {
FILE: src/constants/tokenData.ts
type TokenDataOverride (line 3) | interface TokenDataOverride {
FILE: src/context/AddAssetContext.tsx
type AddAssetContextData (line 7) | type AddAssetContextData = {
function useAddAssetContext (line 97) | function useAddAssetContext() {
FILE: src/context/RariContext.tsx
function launchModalLazy (line 28) | async function launchModalLazy(
type RariContextData (line 86) | interface RariContextData {
function useRari (line 259) | function useRari() {
FILE: src/fuse-sdk/src/index.js
class Fuse (line 29) | class Fuse {
method constructor (line 362) | constructor(web3Provider) {
FILE: src/fuse-sdk/src/irm/DAIInterestRateModelV2.js
class DAIInterestRateModelV2 (line 8) | class DAIInterestRateModelV2 extends JumpRateModel {
method init (line 20) | async init(web3, interestRateModelAddress, assetAddress) {
method _init (line 49) | async _init(
method __init (line 80) | async __init(
method getSupplyRate (line 104) | getSupplyRate(utilizationRate) {
FILE: src/fuse-sdk/src/irm/JumpRateModel.js
class JumpRateModel (line 6) | class JumpRateModel {
method init (line 21) | async init(web3, interestRateModelAddress, assetAddress) {
method _init (line 56) | async _init(
method __init (line 85) | async __init(
method getBorrowRate (line 106) | getBorrowRate(utilizationRate) {
method getSupplyRate (line 128) | getSupplyRate(utilizationRate) {
FILE: src/fuse-sdk/src/irm/JumpRateModelV2.js
class JumpRateModelV2 (line 6) | class JumpRateModelV2 {
method init (line 19) | async init(web3, interestRateModelAddress, assetAddress) {
method _init (line 54) | async _init(
method __init (line 83) | async __init(
method getBorrowRate (line 104) | getBorrowRate(utilizationRate) {
method getSupplyRate (line 126) | getSupplyRate(utilizationRate) {
FILE: src/fuse-sdk/src/irm/WhitePaperInterestRateModel.js
class WhitePaperInterestRateModel (line 6) | class WhitePaperInterestRateModel {
method init (line 17) | async init(web3, interestRateModelAddress, assetAddress) {
method _init (line 52) | async _init(
method __init (line 81) | async __init(
method getBorrowRate (line 98) | getBorrowRate(utilizationRate) {
method getSupplyRate (line 107) | getSupplyRate(utilizationRate) {
FILE: src/fuse-sdk/test/launch-pools.js
function deployPool (line 306) | async function deployPool(conf, options) {
function deployAsset (line 340) | async function deployAsset(conf, options, bypassPriceFeedCheck) {
function getTokenPrice (line 380) | async function getTokenPrice(tokenAddress) {
constant CHAINLINK_TOKENS (line 401) | const CHAINLINK_TOKENS = [
FILE: src/fuse-sdk/test/live-price-oracle.js
function getTokenPrice (line 9) | async function getTokenPrice(tokenAddress) {
FILE: src/fuse-sdk/test/oracles.js
function increaseTime (line 15) | function increaseTime(seconds) {
function impersonateAccount (line 32) | function impersonateAccount(account) {
function deployPool (line 48) | async function deployPool(conf, options) {
function deployAsset (line 60) | async function deployAsset(conf, collateralFactor, reserveFactor, adminF...
function getTokenPrice (line 73) | async function getTokenPrice(tokenAddress) {
function getYVaultPrice (line 469) | async function getYVaultPrice(yVault, v2) {
function getLpTokenPrice (line 584) | async function getLpTokenPrice(lpToken, sushiSwap) {
function getCurveLpTokenPrice (line 915) | async function getCurveLpTokenPrice(lpToken) {
function getBalancerLpTokenPrice (line 1001) | async function getBalancerLpTokenPrice(lpToken) {
function getCurveLpTokenPrice (line 1018) | async function getCurveLpTokenPrice(lpToken) {
function getCurveLiquidityGaugeV2Price (line 1112) | async function getCurveLiquidityGaugeV2Price(gauge) {
function getWSTEthTokenPrice (line 1585) | async function getWSTEthTokenPrice() {
FILE: src/fuse-sdk/test/safe-liquidator.js
function snapshot (line 18) | function snapshot() {
function revert (line 32) | function revert() {
function dryRun (line 48) | function dryRun(promise) {
function impersonateAccount (line 65) | function impersonateAccount(account) {
function deployPool (line 81) | async function deployPool(conf, options) {
function deployAsset (line 93) | async function deployAsset(conf, collateralFactor, reserveFactor, adminF...
constant LIQUIDATION_STRATEGIES (line 109) | const LIQUIDATION_STRATEGIES = {
constant UNISWAP_V2_PROTOCOLS (line 129) | const UNISWAP_V2_PROTOCOLS = {
function getUniswapV2RouterByBestWethLiquidity (line 141) | async function getUniswapV2RouterByBestWethLiquidity(token) {
function getLiquidationStrategyData (line 161) | async function getLiquidationStrategyData(token, strategy) {
function setupUnhealthyEthBorrowWithTokenCollateral (line 374) | async function setupUnhealthyEthBorrowWithTokenCollateral(tokenCollatera...
function setupUnhealthyTokenBorrowWithEthCollateral (line 397) | async function setupUnhealthyTokenBorrowWithEthCollateral() {
function setupUnhealthyTokenBorrowWithTokenCollateral (line 416) | async function setupUnhealthyTokenBorrowWithTokenCollateral(tokenCollate...
function setupAndLiquidateUnhealthyEthBorrowWithTokenCollateral (line 443) | async function setupAndLiquidateUnhealthyEthBorrowWithTokenCollateral(ex...
function setupAndLiquidateUnhealthyTokenBorrowWithEthCollateral (line 471) | async function setupAndLiquidateUnhealthyTokenBorrowWithEthCollateral(ex...
function setupAndLiquidateUnhealthyTokenBorrowWithTokenCollateral (line 494) | async function setupAndLiquidateUnhealthyTokenBorrowWithTokenCollateral(...
FILE: src/fuse-sdk/webpack.config.js
function createConfig (line 11) | function createConfig(libraryTarget, target) {
FILE: src/hooks/fuse/useCTokenData.ts
type CTokenData (line 6) | interface CTokenData {
FILE: src/hooks/fuse/useFusePools.ts
type FusePool (line 9) | interface FusePool {
type LensFusePool (line 16) | interface LensFusePool {
type LensFusePoolData (line 24) | interface LensFusePoolData {
type LensPoolsWithData (line 32) | type LensPoolsWithData = [
type MergedPool (line 39) | interface MergedPool extends LensFusePoolData, LensFusePool {
type UseFusePoolsReturn (line 122) | interface UseFusePoolsReturn {
FILE: src/hooks/fuse/useOracleData.ts
type OracleDataType (line 16) | type OracleDataType = {
FILE: src/hooks/interestRates/aave/useReserves.ts
constant WETH_TOKEN_ADDRESS (line 17) | const WETH_TOKEN_ADDRESS = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
function useReserves (line 19) | function useReserves() {
function fetchReserveData (line 86) | async function fetchReserveData(
FILE: src/hooks/interestRates/compound/useCompoundMarkets.ts
type CTokenData (line 15) | type CTokenData = {
constant CTOKEN_LIST (line 27) | const CTOKEN_LIST = [
function useCompoundMarkets (line 43) | function useCompoundMarkets() {
function convertRatePerBlockToAPY (line 115) | function convertRatePerBlockToAPY(rate: number) {
FILE: src/hooks/interestRates/fuse/useFuseMarkets.ts
type FuseMarket (line 14) | type FuseMarket = {
function useFuseMarkets (line 18) | function useFuseMarkets() {
FILE: src/hooks/interestRates/types.ts
type InterestRatesType (line 1) | type InterestRatesType = {
type MarketInfo (line 6) | type MarketInfo = {
FILE: src/hooks/rewards/useClaimable.ts
type ClaimMode (line 14) | type ClaimMode = "pool2" | "private" | "yieldagg" | "fuse";
type UseClaimableReturn (line 16) | interface UseClaimableReturn {
type GenericClaimableReward (line 26) | interface GenericClaimableReward {
type FuseReward (line 34) | type FuseReward = {
type CTokenUnclaimedForPool (line 40) | interface CTokenUnclaimedForPool {}
constant RGT (line 42) | const RGT = "0xd291e7a03283640fdc51b121ac401383a46cc623";
constant DUST_THRESHOLD (line 44) | const DUST_THRESHOLD = 0;
function useClaimable (line 50) | function useClaimable(showPrivate: boolean = false): UseClaimableReturn {
FILE: src/hooks/rewards/usePoolIncentives.ts
type CTokenRewardsDistributorIncentives (line 11) | interface CTokenRewardsDistributorIncentives {
type CTokenIncentivesMap (line 18) | interface CTokenIncentivesMap {
type RewardsDistributorCTokensMap (line 23) | interface RewardsDistributorCTokensMap {
type IncentivesData (line 27) | interface IncentivesData {
function usePoolIncentives (line 34) | function usePoolIncentives(comptroller?: string): IncentivesData {
type CTokensUnderlyingMap (line 142) | interface CTokensUnderlyingMap {
FILE: src/hooks/rewards/useRewardAPY.ts
type CTokenRewardsDistributorIncentivesWithRates (line 35) | interface CTokenRewardsDistributorIncentivesWithRates
type CTokenRewardsDistributorIncentivesWithRatesMap (line 43) | interface CTokenRewardsDistributorIncentivesWithRatesMap {
type RewardsDataForMantissa (line 47) | interface RewardsDataForMantissa {
type CTokensDataForRewardsMap (line 187) | interface CTokensDataForRewardsMap {
type CTokenDataForRewards (line 191) | type CTokenDataForRewards = Pick<
type TokenPricesMap (line 267) | interface TokenPricesMap {
type TokenPrices (line 274) | interface TokenPrices {
FILE: src/hooks/rewards/useRewardsDistributorsForPool.ts
type RewardsDistributor (line 5) | interface RewardsDistributor {
FILE: src/hooks/rewards/useUnclaimedFuseRewards.ts
type RewardsDistributorToPoolsMap (line 6) | interface RewardsDistributorToPoolsMap {
function useUnclaimedFuseRewards (line 18) | function useUnclaimedFuseRewards() {
type RewardsTokenMap (line 210) | type RewardsTokenMap = {
type RewardsDistributorUnclaimed (line 214) | interface RewardsDistributorUnclaimed {
type RewardsDistributorMap (line 222) | interface RewardsDistributorMap {
type UnclaimedReward (line 226) | interface UnclaimedReward {
FILE: src/hooks/rewards/useUnclaimedRGT.ts
function useUnclaimedRGT (line 5) | function useUnclaimedRGT() {
FILE: src/hooks/tranches/useSaffronData.ts
type TranchePool (line 8) | enum TranchePool {
type TrancheRating (line 13) | enum TrancheRating {
type SaffronData (line 20) | type SaffronData = {
type SaffronTranchePool (line 25) | interface SaffronTranchePool {
type SaffronTranches (line 31) | type SaffronTranches = {
type UseEstimatedSFIReturn (line 40) | interface UseEstimatedSFIReturn {
type SupportedTranchePool (line 50) | type SupportedTranchePool = {
constant SUPPORTED_TRANCHEPOOLS (line 55) | const SUPPORTED_TRANCHEPOOLS: SupportedTranchePool[] = [
FILE: src/hooks/useAssetsMap.ts
type AssetsMapWithTokenDataReturn (line 27) | type AssetsMapWithTokenDataReturn = {
FILE: src/hooks/useMaybeResponsiveProp.ts
function useMaybeResponsiveProp (line 3) | function useMaybeResponsiveProp<T, A>(
FILE: src/hooks/usePoolBalance.ts
type UseQueryResponse (line 10) | interface UseQueryResponse {
FILE: src/hooks/usePoolInfo.ts
type AggregatePoolInfo (line 53) | type AggregatePoolInfo = {
type PoolTotals (line 64) | type PoolTotals = {
type AggregatePoolsInfoReturn (line 72) | type AggregatePoolsInfoReturn = {
FILE: src/hooks/useTokenBalance.ts
function useTokenBalance (line 29) | function useTokenBalance(tokenAddress: string, customAddress?: string) {
FILE: src/hooks/useTokenData.ts
constant ETH_TOKEN_DATA (line 7) | const ETH_TOKEN_DATA = {
type TokenData (line 18) | interface TokenData {
type TokensDataMap (line 111) | interface TokensDataMap {
FILE: src/index.tsx
function ScrollToTop (line 56) | function ScrollToTop() {
FILE: src/rari-sdk/cache.js
class Cache (line 2) | class Cache {
method constructor (line 5) | constructor(timeouts) {
method getOrUpdate (line 10) | async getOrUpdate(key, asyncMethod) {
method update (line 41) | update(key, value) {
method clear (line 48) | clear(key) {
FILE: src/rari-sdk/governance.js
constant LP_TOKEN_CONTRACT (line 18) | const LP_TOKEN_CONTRACT = "0x18a797c7c70c1bf22fdee1c09062aba709cacf04";
class Governance (line 42) | class Governance {
method constructor (line 48) | constructor(web3) {
FILE: src/rari-sdk/index.js
class Rari (line 26) | class Rari {
method constructor (line 27) | constructor(web3Provider) {
FILE: src/rari-sdk/pools/dai.js
class DaiPool (line 41) | class DaiPool extends StablePool {
method constructor (line 50) | constructor(web3, subpools, getAllTokens) {
FILE: src/rari-sdk/pools/ethereum.js
class EthereumPool (line 61) | class EthereumPool extends StablePool {
method constructor (line 70) | constructor(web3, subpools, getAllTokens) {
FILE: src/rari-sdk/pools/stable.js
class StablePool (line 187) | class StablePool {
method constructor (line 242) | constructor(web3, subpools, getAllTokens) {
FILE: src/rari-sdk/pools/yield.js
class YieldPool (line 52) | class YieldPool extends StablePool {
method constructor (line 61) | constructor(web3, subpools, getAllTokens) {
FILE: src/rari-sdk/subpools/aave.js
class AaveSubpool (line 7) | class AaveSubpool {
method constructor (line 8) | constructor(web3) {
method getCurrencyApys (line 15) | async getCurrencyApys() {
FILE: src/rari-sdk/subpools/alpha.js
class AlphaSubpool (line 20) | class AlphaSubpool {
method constructor (line 24) | constructor(web3) {
method getCurrencyApys (line 38) | async getCurrencyApys() {
method getIBEthApyBN (line 42) | async getIBEthApyBN() {
FILE: src/rari-sdk/subpools/compound.js
class CompoundSubpool (line 7) | class CompoundSubpool {
method constructor (line 8) | constructor(web3) {
method getCurrencySupplierAndCompApys (line 15) | async getCurrencySupplierAndCompApys() {
method getCurrencyApys (line 41) | async getCurrencyApys() {
FILE: src/rari-sdk/subpools/dydx.js
class DydxSubpool (line 7) | class DydxSubpool {
method constructor (line 8) | constructor(web3) {
method getCurrencyApys (line 15) | async getCurrencyApys() {
FILE: src/rari-sdk/subpools/fuse.js
class FuseSubpool (line 6) | class FuseSubpool {
method constructor (line 7) | constructor(web3, cTokens) {
method getCurrencyApy (line 15) | async getCurrencyApy(cTokenAddress) {
method getCurrencyApys (line 26) | async getCurrencyApys() {
FILE: src/rari-sdk/subpools/keeperdao.js
class KeeperDAOSubpool (line 4) | class KeeperDAOSubpool {
method constructor (line 5) | constructor(web3) {
method getCurrencyApys (line 9) | getCurrencyApys() {
FILE: src/rari-sdk/subpools/mstable.js
class MStableSubpool (line 22) | class MStableSubpool {
method constructor (line 28) | constructor(web3) {
method getMUsdSavingsApy (line 43) | async getMUsdSavingsApy(includeIMUsdVaultApy) {
method getCurrencyApys (line 76) | async getCurrencyApys() {
method getMUsdSwapFeeBN (line 86) | async getMUsdSwapFeeBN() {
method getMtaUsdPrice (line 99) | async getMtaUsdPrice() {
method getIMUsdVaultWeeklyRoi (line 107) | async getIMUsdVaultWeeklyRoi(totalStakingRewards, stakingTokenPrice) {
method getIMUsdVaultApy (line 121) | async getIMUsdVaultApy(totalStakingRewards, stakingTokenPrice) {
FILE: src/rari-sdk/subpools/yvault.js
class YVaultSubpool (line 4) | class YVaultSubpool {
method constructor (line 5) | constructor(web3) {
method getCurrencyApys (line 9) | getCurrencyApys() {
FILE: src/utils/bigUtils.ts
function smallStringUsdFormatter (line 22) | function smallStringUsdFormatter(num: string | number) {
function stringUsdFormatter (line 27) | function stringUsdFormatter(num: string) {
function smallUsdFormatter (line 31) | function smallUsdFormatter(num: number) {
function usdFormatter (line 35) | function usdFormatter(num: number) {
function shortUsdFormatter (line 39) | function shortUsdFormatter(num: number) {
type BN (line 45) | type BN = ReturnType<typeof toBN>;
FILE: src/utils/chakraUtils.tsx
type MainAxisAlignmentStrings (line 5) | type MainAxisAlignmentStrings =
type MainAxisAlignment (line 12) | type MainAxisAlignment =
type CrossAxisAlignmentStrings (line 16) | type CrossAxisAlignmentStrings =
type CrossAxisAlignment (line 22) | type CrossAxisAlignment =
class PixelMeasurement (line 29) | class PixelMeasurement {
method constructor (line 32) | constructor(num: number) {
method asPxString (line 36) | asPxString(): string {
method toString (line 40) | toString(): string {
method asNumber (line 44) | asNumber(): number {
class PercentageSize (line 50) | class PercentageSize {
method constructor (line 53) | constructor(num: number) {
class PercentOnDesktopPixelOnMobileSize (line 62) | class PercentOnDesktopPixelOnMobileSize {
method constructor (line 66) | constructor({
class PixelSize (line 82) | class PixelSize {
method constructor (line 85) | constructor(num: number) {
class ResponsivePixelSize (line 90) | class ResponsivePixelSize {
method constructor (line 94) | constructor({ desktop, mobile }: { desktop: number; mobile: number }) {
type CenterProps (line 121) | type CenterProps = {
type ColumnProps (line 149) | type ColumnProps = {
type RowProps (line 190) | type RowProps = {
function handleResize (line 316) | function handleResize() {
function useLockedViewHeight (line 343) | function useLockedViewHeight({
function useIsMobile (line 375) | function useIsMobile() {
function useSpacedLayout (line 391) | function useSpacedLayout({
FILE: src/utils/fetchFusePoolData.ts
function filterOnlyObjectProperties (line 12) | function filterOnlyObjectProperties(obj: any) {
type FuseAsset (line 18) | interface FuseAsset {
type USDPricedFuseAsset (line 48) | interface USDPricedFuseAsset extends FuseAsset {
type USDPricedFuseAssetWithTokenData (line 60) | interface USDPricedFuseAssetWithTokenData extends USDPricedFuseAsset {
type FusePoolData (line 64) | interface FusePoolData {
type FusePoolMetric (line 81) | enum FusePoolMetric {
FILE: src/utils/fetchPoolInterest.ts
type PoolInterestEarned (line 41) | type PoolInterestEarned = {
FILE: src/utils/multicall.ts
constant MULTICALL_ADDRESS (line 30) | const MULTICALL_ADDRESS = "0xeefba1e63905ef1d7acba5a8513c70307c1ce441";
FILE: src/utils/poolUtils.ts
type Pool (line 8) | enum Pool {
function poolHasDivergenceRisk (line 45) | function poolHasDivergenceRisk(pool: Pool) {
FILE: src/utils/shortAddress.ts
function shortAddress (line 1) | function shortAddress(address: string) {
function mediumAddress (line 9) | function mediumAddress(address: string) {
FILE: src/utils/stringUtils.ts
function truncate (line 1) | function truncate(str: string, n: number) {
FILE: src/utils/symbolUtils.ts
function getSymbol (line 4) | function getSymbol(tokenData: TokenData | undefined, asset: FuseAsset) {
FILE: src/utils/tokenUtils.ts
type AssetHash (line 11) | interface AssetHash {
type AssetHashWithTokenData (line 15) | interface AssetHashWithTokenData {
type TokensDataHash (line 19) | interface TokensDataHash {
constant ETH_AND_WETH (line 24) | const ETH_AND_WETH = [
FILE: src/utils/web3Providers.ts
function chooseBestWeb3Provider (line 7) | function chooseBestWeb3Provider() {
Condensed preview — 307 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (9,509K chars).
[
{
"path": ".eslintignore",
"chars": 17,
"preview": "src/rari-sdk/**.*"
},
{
"path": ".github/workflows/tests.yml",
"chars": 1879,
"preview": "name: Tests\n\non: [push, pull_request]\n\njobs:\n e2e-and-unit:\n runs-on: ubuntu-latest\n\n steps:\n - name: Checko"
},
{
"path": ".github/workflows/translations.yml",
"chars": 223,
"preview": "name: Translations\n\non: [push]\n\njobs:\n check-translations:\n runs-on: ubuntu-latest\n\n steps:\n - uses: actions"
},
{
"path": ".gitignore",
"chars": 426,
"preview": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n**/node_modules\n/."
},
{
"path": ".nycrc.json",
"chars": 39,
"preview": "{\n \"report-dir\": \"cypress-coverage\"\n}\n"
},
{
"path": ".prettierrc",
"chars": 117,
"preview": "{\n \"printWidth\": 80,\n \"tabWidth\": 2,\n \"semicolons\": true,\n \"singleQuote\": false,\n \"jsxBracketSameLine\": false\n}\n"
},
{
"path": ".vscode/launch.json",
"chars": 435,
"preview": "{\n // Use IntelliSense to learn about possible attributes.\n // Hover to view descriptions of existing attributes.\n //"
},
{
"path": "LICENSE",
"chars": 34523,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "README.md",
"chars": 764,
"preview": "# Rari dApp ·  · [ is an open source, MIT licensed end-to-end test runn"
},
{
"path": "cypress/e2e/E2E.spec.js",
"chars": 261,
"preview": "// type definitions for Cypress object \"cy\"\n/// <reference types=\"cypress\" />\n\ndescribe(\"E2E\", function () {\n before(()"
},
{
"path": "cypress/fixtures/example.json",
"chars": 155,
"preview": "{\n \"name\": \"Using fixtures to represent data\",\n \"email\": \"hello@cypress.io\",\n \"body\": \"Fixtures are a great way to mo"
},
{
"path": "cypress/plugins/index.js",
"chars": 718,
"preview": "// ***********************************************************\n// This example plugins/index.js can be used to load plug"
},
{
"path": "cypress/support/commands.js",
"chars": 887,
"preview": "// ***********************************************\n// This example commands.js shows you how to\n// create various custom"
},
{
"path": "cypress/support/index.js",
"chars": 771,
"preview": "// ***********************************************************\n// This example support/index.js is processed and\n// load"
},
{
"path": "cypress.json",
"chars": 104,
"preview": "{\n \"baseUrl\": \"http://localhost:3000\",\n \"integrationFolder\": \"cypress/e2e\",\n \"projectId\": \"s8v41s\"\n}\n"
},
{
"path": "hardhat.config.js",
"chars": 384,
"preview": "/**\n * @type import('hardhat/config').HardhatUserConfig\n */\n module.exports = {\n solidity: \"0.7.3\",\n networks: {\n "
},
{
"path": "i18next-scanner.config.js",
"chars": 764,
"preview": "module.exports = {\n input: [\"./src/**/*.{ts,tsx}\"],\n output: \"./\",\n options: {\n debug: true,\n\n removeUnusedKeys"
},
{
"path": "package.json",
"chars": 3729,
"preview": "{\n \"name\": \"rari-dapp\",\n \"version\": \"3.0.0\",\n \"private\": true,\n \"dependencies\": {\n \"@aave/protocol-v2\": \"^1.0.1\","
},
{
"path": "public/index.html",
"chars": 2089,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.i"
},
{
"path": "public/manifest.json",
"chars": 468,
"preview": "{\n \"short_name\": \"Rari\",\n \"name\": \"Rari\",\n \"icons\": [\n {\n \"src\": \"favicon.ico\",\n \"sizes\": \"64x64 32x32 2"
},
{
"path": "public/robots.txt",
"chars": 57,
"preview": "# https://www.robotstxt.org/robotstxt.html\nUser-agent: *\n"
},
{
"path": "src/components/App.tsx",
"chars": 4277,
"preview": "import { Navigate, Outlet, Route, Routes } from \"react-router-dom\";\nimport { Heading } from \"@chakra-ui/react\";\nimport l"
},
{
"path": "src/components/pages/ErrorPage.tsx",
"chars": 924,
"preview": "/* istanbul ignore file */\n\nimport { Code, Box, Heading, Text, Link } from \"@chakra-ui/react\";\n\nimport { useTranslation "
},
{
"path": "src/components/pages/Fuse/FuseLiquidationsPage.tsx",
"chars": 13616,
"preview": "import { Box, Link, Spinner, Text } from \"@chakra-ui/react\";\nimport { Column, Row, RowOrColumn, useIsMobile } from \"util"
},
{
"path": "src/components/pages/Fuse/FusePoolCreatePage.tsx",
"chars": 16487,
"preview": "// Chakra and UI\nimport {\n Heading,\n Text,\n Switch,\n Input,\n Spinner,\n IconButton,\n useToast,\n useDisclosure,\n "
},
{
"path": "src/components/pages/Fuse/FusePoolEditPage.tsx",
"chars": 14594,
"preview": "// Chakra and UI\nimport {\n Box,\n Badge,\n Heading,\n Text,\n useDisclosure,\n Spinner,\n\n // Table\n Image,\n HStack,\n"
},
{
"path": "src/components/pages/Fuse/FusePoolInfoPage.tsx",
"chars": 21081,
"preview": "import {\n AvatarGroup,\n Box,\n Heading,\n Link,\n Select,\n Spinner,\n Text,\n useClipboard,\n VStack,\n} from \"@chakra"
},
{
"path": "src/components/pages/Fuse/FusePoolPage.tsx",
"chars": 39464,
"preview": "import { memo, useEffect, useMemo, useState } from \"react\";\nimport {\n Avatar,\n AvatarGroup,\n Box,\n Button,\n Heading"
},
{
"path": "src/components/pages/Fuse/FusePoolsPage.tsx",
"chars": 7211,
"preview": "import {\n Avatar,\n AvatarGroup,\n Link,\n Spinner,\n Text,\n Box,\n} from \"@chakra-ui/react\";\nimport { Center, Column, "
},
{
"path": "src/components/pages/Fuse/FuseStatsBar.tsx",
"chars": 6021,
"preview": "import { Heading, Text } from \"@chakra-ui/react\";\nimport { RowOrColumn, Column, Center, Row } from \"utils/chakraUtils\";\n"
},
{
"path": "src/components/pages/Fuse/FuseTabBar.tsx",
"chars": 6972,
"preview": "import { DeleteIcon, SmallAddIcon } from \"@chakra-ui/icons\";\nimport { ButtonGroup, Input, Link, Text } from \"@chakra-ui/"
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal/AddAssetModal.tsx",
"chars": 6226,
"preview": "// Chakra and UI\nimport { Modal, ModalContent, ModalOverlay } from \"@chakra-ui/modal\";\nimport { CloseButton } from \"@cha"
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal/AssetConfig.tsx",
"chars": 12509,
"preview": "// Chakra and UI\nimport { Text, Select, useToast } from \"@chakra-ui/react\";\nimport { Column } from \"utils/chakraUtils\";\n"
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal/AssetSettings.tsx",
"chars": 22899,
"preview": "// Chakra and UI\nimport { Heading, Spinner, useToast } from \"@chakra-ui/react\";\nimport { Column, Center, RowOrColumn, Ro"
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal/DeployButton.tsx",
"chars": 5218,
"preview": "// Chakra and UI\nimport { Button } from \"@chakra-ui/button\";\nimport { Center } from \"@chakra-ui/react\";\nimport { Box } f"
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal/IRMChart.tsx",
"chars": 1763,
"preview": "// Chakra and UI\nimport {\n Box,\n Text,\n Spinner,\n } from \"@chakra-ui/react\";\n import {\n Center,\n } from \""
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal/OracleConfig/BaseTokenOracleConfig.tsx",
"chars": 5826,
"preview": "// Chakra and UI\nimport { Input, Box, Text, Select, Alert, AlertIcon } from \"@chakra-ui/react\";\nimport { Column, Row } f"
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal/OracleConfig/OracleConfig.tsx",
"chars": 11576,
"preview": "// Chakra and UI\nimport { Input, Box, Text, Select, Spinner, useToast } from \"@chakra-ui/react\";\nimport { Center, Row } "
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal/OracleConfig/UniswapV2OrSushiPriceOracleConfigurator.tsx",
"chars": 5477,
"preview": "// Chakra and UI\nimport { Button, Text, Select, Checkbox } from \"@chakra-ui/react\";\nimport { Row } from \"utils/chakraUti"
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal/OracleConfig/UniswapV3PriceOracleConfigurator.tsx",
"chars": 8671,
"preview": "// Chakra and UI\nimport { Text, Select, Link, Alert, AlertIcon } from \"@chakra-ui/react\";\nimport { Column, Row } from \"u"
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal/Screens/Screen1.tsx",
"chars": 509,
"preview": "// Chakra and UI\nimport { Row } from \"utils/chakraUtils\";\n\n// Components\nimport AssetConfig from \"../AssetConfig\";\n\n\ncon"
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal/Screens/Screen2.tsx",
"chars": 5845,
"preview": "// Chakra and UI\nimport { Column, Row } from \"utils/chakraUtils\";\nimport { Alert, Text, AlertIcon } from \"@chakra-ui/rea"
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal/Screens/Screen3.tsx",
"chars": 3313,
"preview": "// Chakra and UI\nimport { Column } from \"utils/chakraUtils\";\nimport { Box, Text } from \"@chakra-ui/layout\";\nimport { Con"
},
{
"path": "src/components/pages/Fuse/Modals/AddAssetModal.tsx",
"chars": 20635,
"preview": "import {\n Heading,\n Modal,\n ModalContent,\n ModalOverlay,\n Input,\n Button,\n Box,\n Text,\n Image,\n Select,\n Spin"
},
{
"path": "src/components/pages/Fuse/Modals/AddRewardsDistributorModal.tsx",
"chars": 9312,
"preview": "import {\n Heading,\n Modal,\n ModalContent,\n ModalOverlay,\n Input,\n Button,\n Box,\n Text,\n Image,\n RadioGroup,\n "
},
{
"path": "src/components/pages/Fuse/Modals/Edit/AssetConfiguration.tsx",
"chars": 4434,
"preview": "import { Box, Center, Heading, Text } from \"@chakra-ui/layout\";\nimport { Spinner } from \"@chakra-ui/spinner\";\nimport Das"
},
{
"path": "src/components/pages/Fuse/Modals/Edit/MarketCapConfigurator.tsx",
"chars": 5604,
"preview": "// Charka and UI\nimport { ConfigRow, SaveButton } from \"../../FusePoolEditPage\";\nimport { SimpleTooltip } from \"componen"
},
{
"path": "src/components/pages/Fuse/Modals/Edit/OraclesTable.tsx",
"chars": 2062,
"preview": "// Chakra and UI\nimport {\n AvatarGroup,\n Text,\n Link,\n // Table\n Table,\n Thead,\n Tbody,\n Tr,\n Th,\n Td,\n} from "
},
{
"path": "src/components/pages/Fuse/Modals/Edit/PoolConfiguration.tsx",
"chars": 12236,
"preview": "import OraclesTable from \"./OraclesTable\";\n\nimport { Box, Center, Heading, Text } from \"@chakra-ui/layout\";\nimport { Spi"
},
{
"path": "src/components/pages/Fuse/Modals/EditRewardsDistributorModal.tsx",
"chars": 16265,
"preview": "import { useEffect, useState } from \"react\";\nimport {\n Heading,\n Modal,\n ModalContent,\n ModalOverlay,\n Input,\n But"
},
{
"path": "src/components/pages/Fuse/Modals/PoolModal/AmountSelect.tsx",
"chars": 35219,
"preview": "import { useState } from \"react\";\nimport { Row, Column, Center, useIsMobile } from \"utils/chakraUtils\";\n\nimport LogRocke"
},
{
"path": "src/components/pages/Fuse/Modals/PoolModal/index.tsx",
"chars": 1292,
"preview": "import { useEffect, useState } from \"react\";\nimport { Modal, ModalOverlay, ModalContent } from \"@chakra-ui/react\";\n\nimpo"
},
{
"path": "src/components/pages/InterestRates/InterestRates.tsx",
"chars": 1670,
"preview": "// Components\nimport { Alert, Link, AlertIcon } from \"@chakra-ui/react\";\nimport { Column } from \"utils/chakraUtils\";\nimp"
},
{
"path": "src/components/pages/InterestRates/InterestRatesTable.tsx",
"chars": 7462,
"preview": "import { useContext, useMemo, useState } from \"react\";\nimport { Link as RouterLink } from \"react-router-dom\";\n\n// Compon"
},
{
"path": "src/components/pages/InterestRates/InterestRatesView.tsx",
"chars": 6173,
"preview": "import { useEffect, useMemo, useState, createContext } from \"react\";\n\n// Components\nimport { Box, Center, Flex, Heading,"
},
{
"path": "src/components/pages/InterestRates/MultiPicker.tsx",
"chars": 1300,
"preview": "import { useState, useEffect, MouseEventHandler, ReactNode } from \"react\";\n\n// Components\nimport { Button, ButtonGroup }"
},
{
"path": "src/components/pages/InterestRates/TokenSearch.tsx",
"chars": 1490,
"preview": "import { useEffect } from \"react\";\nimport { useState } from \"react\";\n\n// Components\nimport { Box } from \"@chakra-ui/reac"
},
{
"path": "src/components/pages/MultiPoolPortal.tsx",
"chars": 17538,
"preview": "import { memo, ReactNode, useEffect, useState } from \"react\";\n\nimport {\n Center,\n Column,\n Row,\n RowOnDesktopColumnO"
},
{
"path": "src/components/pages/Pool2/Pool2Modal/AmountSelect.tsx",
"chars": 9548,
"preview": "import { useState } from \"react\";\nimport { Row, Column } from \"utils/chakraUtils\";\n\nimport {\n Heading,\n Box,\n Button,"
},
{
"path": "src/components/pages/Pool2/Pool2Modal/OptionsMenu.tsx",
"chars": 1108,
"preview": "import { Button } from \"@chakra-ui/react\";\n\nimport { Fade } from \"react-awesome-reveal\";\nimport { Column } from \"utils/c"
},
{
"path": "src/components/pages/Pool2/Pool2Modal/index.tsx",
"chars": 1248,
"preview": "import { useState } from \"react\";\nimport { Modal, ModalOverlay, ModalContent } from \"@chakra-ui/react\";\n\nimport AmountSe"
},
{
"path": "src/components/pages/Pool2/Pool2Page.tsx",
"chars": 9752,
"preview": "import { useState } from \"react\";\nimport {\n useInterval,\n useDisclosure,\n Heading,\n Link,\n Spinner,\n Text,\n Box,\n"
},
{
"path": "src/components/pages/PoolPortal.tsx",
"chars": 29769,
"preview": "import { memo, useState } from \"react\";\nimport {\n Box,\n Text,\n Heading,\n Spinner,\n Divider,\n Select,\n useDisclosu"
},
{
"path": "src/components/pages/RariDepositModal/AmountSelect.tsx",
"chars": 17055,
"preview": "import { useState } from \"react\";\nimport { Row, Column, Center } from \"utils/chakraUtils\";\nimport SmallWhiteCircle from "
},
{
"path": "src/components/pages/RariDepositModal/OptionsMenu.tsx",
"chars": 1105,
"preview": "import { Button } from \"@chakra-ui/react\";\n\nimport { Fade } from \"react-awesome-reveal\";\nimport { Column } from \"utils/c"
},
{
"path": "src/components/pages/RariDepositModal/TokenSelect.tsx",
"chars": 6329,
"preview": "import { memo, useState, CSSProperties, useCallback, useMemo } from \"react\";\nimport {\n Input,\n Image,\n InputGroup,\n "
},
{
"path": "src/components/pages/RariDepositModal/index.tsx",
"chars": 2332,
"preview": "import { useState, useEffect } from \"react\";\nimport { Modal, ModalOverlay, ModalContent } from \"@chakra-ui/react\";\n\nimpo"
},
{
"path": "src/components/pages/Stats/StatsEarnSection.tsx",
"chars": 2749,
"preview": "import { useMemo } from \"react\";\nimport {\n Table,\n Text,\n Thead,\n Tbody,\n Tr,\n Th,\n Td,\n Spinner,\n} from \"@chakr"
},
{
"path": "src/components/pages/Stats/StatsFuseSection.tsx",
"chars": 9429,
"preview": "import { useMemo } from \"react\";\nimport {\n Avatar,\n Box,\n Text,\n Table,\n Thead,\n Tbody,\n Tr,\n Th,\n Td,\n} from \""
},
{
"path": "src/components/pages/Stats/StatsPage.tsx",
"chars": 3978,
"preview": "import { useMemo, useState } from \"react\";\n\n// Components\nimport { Box, Heading } from \"@chakra-ui/react\";\nimport { Ques"
},
{
"path": "src/components/pages/Stats/StatsPool2Section.tsx",
"chars": 4855,
"preview": "import { useMemo } from \"react\";\nimport {\n Box,\n Table,\n Text,\n Thead,\n Tbody,\n Tr,\n Th,\n Td,\n Avatar,\n} from \""
},
{
"path": "src/components/pages/Stats/StatsSubNav.tsx",
"chars": 3430,
"preview": "import { Dispatch, SetStateAction } from \"react\";\n\n// Components\nimport { Column, Row } from \"utils/chakraUtils\";\nimport"
},
{
"path": "src/components/pages/Stats/StatsTranchesSection.tsx",
"chars": 5108,
"preview": "import { useMemo } from \"react\";\nimport { Box, Table, Text, Thead, Tbody, Tr, Th, Td } from \"@chakra-ui/react\";\nimport {"
},
{
"path": "src/components/pages/Stats/Totals/EarnRow.tsx",
"chars": 1885,
"preview": "import { Box, Td, Text } from \"@chakra-ui/react\";\nimport { motion } from \"framer-motion\";\n\nimport { SimpleTooltip } from"
},
{
"path": "src/components/pages/Stats/Totals/FuseRow.tsx",
"chars": 2027,
"preview": "import { useMemo } from \"react\";\nimport { Box, Td, Text } from \"@chakra-ui/react\";\nimport { motion } from \"framer-motion"
},
{
"path": "src/components/pages/Stats/Totals/Pool2Row.tsx",
"chars": 1123,
"preview": "import { Box, Td } from \"@chakra-ui/react\";\nimport { motion } from \"framer-motion\";\nimport { Pool2LogoPNGWhite } from \"c"
},
{
"path": "src/components/pages/Stats/Totals/StatsTotalSection.tsx",
"chars": 6380,
"preview": "import { useMemo, useEffect } from \"react\";\nimport { Table, Thead, Tbody, Tr, Th, Td, Text } from \"@chakra-ui/react\";\nim"
},
{
"path": "src/components/pages/Stats/Totals/TranchesRow.tsx",
"chars": 2445,
"preview": "import { Box, Td, Text } from \"@chakra-ui/react\";\nimport { motion } from \"framer-motion\";\nimport { Column } from \"utils/"
},
{
"path": "src/components/pages/Stats/index.ts",
"chars": 63,
"preview": "import StatsPage from \"./StatsPage\";\nexport default StatsPage;\n"
},
{
"path": "src/components/pages/Tranches/SaffronContext.tsx",
"chars": 1642,
"preview": "import { createContext, memo, useContext, useState, useEffect } from \"react\";\nimport { useRari } from \"../../../context/"
},
{
"path": "src/components/pages/Tranches/SaffronDepositModal/AmountSelect.tsx",
"chars": 14130,
"preview": "import { useState } from \"react\";\nimport { Row, Column } from \"utils/chakraUtils\";\nimport SmallWhiteCircle from \"../../."
},
{
"path": "src/components/pages/Tranches/SaffronDepositModal/index.tsx",
"chars": 1056,
"preview": "import { Modal, ModalOverlay, ModalContent } from \"@chakra-ui/react\";\n\nimport AmountSelect, { requiresSFIStaking } from "
},
{
"path": "src/components/pages/Tranches/SaffronPoolABI.json",
"chars": 19532,
"preview": "[\n {\n \"inputs\": [\n { \"internalType\": \"address\", \"name\": \"_strategy\", \"type\": \"address\" },\n { \"internalType"
},
{
"path": "src/components/pages/Tranches/SaffronStrategyABI.json",
"chars": 8455,
"preview": "[\n {\n \"inputs\": [\n { \"internalType\": \"address\", \"name\": \"_sfi_address\", \"type\": \"address\" },\n { \"internalT"
},
{
"path": "src/components/pages/Tranches/TranchesPage.tsx",
"chars": 14138,
"preview": "import { Center, Column, Row, RowOrColumn } from \"utils/chakraUtils\";\nimport { useRari } from \"../../../context/RariCont"
},
{
"path": "src/components/shared/AccountButton.tsx",
"chars": 7110,
"preview": "import { memo, useCallback } from \"react\";\nimport { useRari } from \"../../context/RariContext\";\nimport {\n useDisclosure"
},
{
"path": "src/components/shared/AdminAlert.tsx",
"chars": 906,
"preview": "import { Alert, AlertIcon } from \"@chakra-ui/alert\";\nimport { EditIcon } from \"@chakra-ui/icons\";\nimport { Box } from \"@"
},
{
"path": "src/components/shared/CTokenIcon.tsx",
"chars": 1099,
"preview": "import { Avatar, AvatarGroup } from \"@chakra-ui/avatar\";\nimport { useTokenData } from \"hooks/useTokenData\";\n\nexport cons"
},
{
"path": "src/components/shared/CaptionedStat.tsx",
"chars": 2112,
"preview": "import { Heading, Text } from \"@chakra-ui/react\";\nimport { CrossAxisAlignment, Column } from \"utils/chakraUtils\";\nimport"
},
{
"path": "src/components/shared/ClaimRGTModal.tsx",
"chars": 11663,
"preview": "import { motion } from \"framer-motion\";\nimport {\n Modal,\n ModalOverlay,\n ModalContent,\n Text,\n Heading,\n Image,\n "
},
{
"path": "src/components/shared/CopyrightSpacer.tsx",
"chars": 470,
"preview": "import { Text } from \"@chakra-ui/react\";\n\nconst CopyrightSpacer = ({ forceShow = false }: { forceShow?: boolean }) => {\n"
},
{
"path": "src/components/shared/CountdownBanner.tsx",
"chars": 3483,
"preview": "import { Flex, Text, Box, Image, Collapse, Link } from \"@chakra-ui/react\"\nimport ArbitrumLogo from \"../../static/arbitru"
},
{
"path": "src/components/shared/DashboardBox.tsx",
"chars": 797,
"preview": "import { Box, BoxProps } from \"@chakra-ui/react\";\nimport { PixelMeasurement } from \"utils/chakraUtils\";\nimport { DarkGlo"
},
{
"path": "src/components/shared/Footer.tsx",
"chars": 1528,
"preview": "import CopyrightSpacer from \"./CopyrightSpacer\";\nimport { Link, Text } from \"@chakra-ui/react\";\nimport { Row, Column } f"
},
{
"path": "src/components/shared/FullPageSpinner.test.tsx",
"chars": 357,
"preview": "import { ChakraProvider } from \"@chakra-ui/react\";\nimport { render, screen } from \"@testing-library/react\";\n\nimport Full"
},
{
"path": "src/components/shared/FullPageSpinner.tsx",
"chars": 1015,
"preview": "/* istanbul ignore file */\nimport { useEffect, useState } from \"react\";\nimport { Spinner, Text } from \"@chakra-ui/react\""
},
{
"path": "src/components/shared/GlowingButton.tsx",
"chars": 2859,
"preview": "import { Box, BoxProps, Button } from \"@chakra-ui/react\";\n\nimport { ReactElement } from \"react\";\n\nexport const GlowingBu"
},
{
"path": "src/components/shared/Header.tsx",
"chars": 5910,
"preview": "import { MouseEventHandler } from \"react\";\n\nimport {\n Box,\n Link,\n Text,\n Menu,\n MenuButton,\n MenuList,\n MenuItem"
},
{
"path": "src/components/shared/Layout.tsx",
"chars": 333,
"preview": "//@ts-nocheck\n\nimport { Column } from \"utils/chakraUtils\";\nimport CountdownBanner from \"./CountdownBanner\";\n// import Fo"
},
{
"path": "src/components/shared/Logos.tsx",
"chars": 4493,
"preview": "// @ts-ignore\n\nimport { Flip } from \"react-awesome-reveal\";\nimport { Box, Image } from \"@chakra-ui/react\";\n\n//PNGS\nimpor"
},
{
"path": "src/components/shared/Modal.tsx",
"chars": 1099,
"preview": "import { DASHBOARD_BOX_PROPS } from \"./DashboardBox\";\nimport { Box, Heading, CloseButton } from \"@chakra-ui/react\";\nimpo"
},
{
"path": "src/components/shared/MovingStat.tsx",
"chars": 4009,
"preview": "import { useEffect, useMemo, useState } from \"react\";\nimport * as React from \"react\";\nimport { useQuery } from \"react-qu"
},
{
"path": "src/components/shared/PoolsPerformance.tsx",
"chars": 5335,
"preview": "import { Box, Text } from \"@chakra-ui/react\";\nimport {\n useSpacedLayout,\n PixelSize,\n ResponsivePixelSize,\n Percenta"
},
{
"path": "src/components/shared/ProgressBar.tsx",
"chars": 457,
"preview": "import { BoxProps, Box } from \"@chakra-ui/react\";\n\ninterface Props {\n percentageFilled: number;\n}\n\nconst ProgressBar = "
},
{
"path": "src/components/shared/SimpleTooltip.tsx",
"chars": 710,
"preview": "import { Tooltip } from \"@chakra-ui/react\";\nimport { ReactNode } from \"react\";\n\nexport const SimpleTooltip = ({\n label,"
},
{
"path": "src/components/shared/SliderWithLabel.tsx",
"chars": 1027,
"preview": "import {\n Slider,\n SliderTrack,\n SliderFilledTrack,\n SliderThumb,\n Text,\n} from \"@chakra-ui/react\";\nimport { Row } "
},
{
"path": "src/components/shared/SwitchCSS.tsx",
"chars": 609,
"preview": "export const SwitchCSS = ({\n symbol,\n color,\n}: {\n symbol: string;\n color: string | undefined | null;\n}) => {\n retu"
},
{
"path": "src/components/shared/TransactionStepper.tsx",
"chars": 1167,
"preview": "// Chakra and UI\nimport { Box } from \"@chakra-ui/layout\";\nimport { Row } from \"utils/chakraUtils\";\nimport { Circle } fro"
},
{
"path": "src/components/shared/TranslateButton.tsx",
"chars": 757,
"preview": "import { Select, SelectProps } from \"@chakra-ui/react\";\n\nimport { useTranslation } from \"react-i18next\";\n\nexport const L"
},
{
"path": "src/constants/homepage.ts",
"chars": 4769,
"preview": "// Logos\nimport FuseLogo from \"static/fuseicon.png\";\nimport { FusePoolMetric } from \"utils/fetchFusePoolData\";\nimport { "
},
{
"path": "src/constants/networks.ts",
"chars": 1625,
"preview": "export enum ChainID {\n MAINNET = 1,\n ROPSTEN = 3,\n RINKEBY = 4,\n GOERLI = 5,\n KOVAN = 42,\n //\n ARBITRUM = 42161,\n"
},
{
"path": "src/constants/pools.ts",
"chars": 840,
"preview": "import { Pool } from \"utils/poolUtils\";\n\n// Icons\nimport EthIcon from \"static/ethicon.png\";\nimport StableIcon from \"stat"
},
{
"path": "src/constants/saffron.ts",
"chars": 166,
"preview": "export const SaffronStrategyAddress =\n \"0x75a154c5177a631f32771B4cAb9466bd777C3291\";\nexport const SaffronPoolAddress = "
},
{
"path": "src/constants/tokenData.ts",
"chars": 8325,
"preview": "import { ChainID } from \"./networks\";\n\ninterface TokenDataOverride {\n symbol?: string;\n name?: string;\n logoURL?: str"
},
{
"path": "src/context/AddAssetContext.tsx",
"chars": 2993,
"preview": "import { RETRY_FLAG } from \"components/pages/Fuse/Modals/AddAssetModal/AssetSettings\";\nimport { CTokenData } from \"hooks"
},
{
"path": "src/context/PoolContext.tsx",
"chars": 606,
"preview": "import { createContext, useContext, ReactNode } from \"react\";\nimport { Pool } from \"../utils/poolUtils\";\n\nexport const P"
},
{
"path": "src/context/RariContext.tsx",
"chars": 7226,
"preview": "import {\n createContext,\n useContext,\n useState,\n useCallback,\n useEffect,\n useMemo,\n ReactNode,\n} from \"react\";\n"
},
{
"path": "src/fuse-sdk/.browserslistrc",
"chars": 17,
"preview": "> 0.25%\nnot dead\n"
},
{
"path": "src/fuse-sdk/.gitattributes",
"chars": 66,
"preview": "# Auto detect text files and perform LF normalization\n* text=auto\n"
},
{
"path": "src/fuse-sdk/.gitignore",
"chars": 1610,
"preview": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# Diagnostic reports (https://nodejs."
},
{
"path": "src/fuse-sdk/LICENSE",
"chars": 289,
"preview": "COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.\n\nNo one is permitted to use the software for any purpose withou"
},
{
"path": "src/fuse-sdk/README.md",
"chars": 4455,
"preview": "# Rari Capital: Fuse JavaScript SDK\n\nCalling all DeFi developers: Rari Capital's SDK is now available for easy implement"
},
{
"path": "src/fuse-sdk/package.json",
"chars": 1490,
"preview": "{\n \"name\": \"fuse-sdk\",\n \"version\": \"1.2.0\",\n \"description\": \"JavaScript SDK for easy implementation of Fuse by Rari C"
},
{
"path": "src/fuse-sdk/scripts/minify-contracts.js",
"chars": 4141,
"preview": "const fs = require(\"fs\");\n\nvar compoundContracts = require(__dirname +\n \"/../src/contracts/compound-protocol.json\").con"
},
{
"path": "src/fuse-sdk/src/abi/FuseFeeDistributor.json",
"chars": 8167,
"preview": "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexe"
},
{
"path": "src/fuse-sdk/src/abi/FusePoolDirectory.json",
"chars": 7005,
"preview": "[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address[]\",\"name\":\"admins\",\"type\":\"address[]\"},{\"indexed\""
},
{
"path": "src/fuse-sdk/src/abi/FusePoolLens.json",
"chars": 17043,
"preview": "[{\"inputs\":[],\"name\":\"directory\",\"outputs\":[{\"internalType\":\"contract FusePoolDirectory\",\"name\":\"\",\"type\":\"address\"}],\"s"
},
{
"path": "src/fuse-sdk/src/abi/FusePoolLensSecondary.json",
"chars": 3662,
"preview": "[{\"inputs\":[],\"name\":\"directory\",\"outputs\":[{\"internalType\":\"contract FusePoolDirectory\",\"name\":\"\",\"type\":\"address\"}],\"s"
},
{
"path": "src/fuse-sdk/src/abi/FuseSafeLiquidator.json",
"chars": 4431,
"preview": "[{\"stateMutability\":\"payable\",\"type\":\"receive\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"borrower\",\"type\":\"address\"}"
},
{
"path": "src/fuse-sdk/src/abi/InitializableClones.json",
"chars": 416,
"preview": "[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"instance\",\"type\":\"address\"}],\"name\":\"Dep"
},
{
"path": "src/fuse-sdk/src/abi/UniswapV3Pool.slim.json",
"chars": 740,
"preview": "[{\"inputs\":[{\"internalType\":\"uint16\",\"name\":\"observationCardinalityNext\",\"type\":\"uint16\"}],\"name\":\"increaseObservationCa"
},
{
"path": "src/fuse-sdk/src/contracts/compound-protocol.min.json",
"chars": 147576,
"preview": "{\"contracts\":{\"contracts/Comptroller.sol:Comptroller\":{\"abi\":\"[{\\\"anonymous\\\":false,\\\"inputs\\\":[{\\\"indexed\\\":false,\\\"int"
},
{
"path": "src/fuse-sdk/src/contracts/open-oracle.json",
"chars": 704690,
"preview": "{\n \"contracts\": {\n \"contracts/OpenOracleData.sol:OpenOracleData\": {\n \"abi\": \"[{\\\"inputs\\\":[{\\\"internalType\\\":\\\""
},
{
"path": "src/fuse-sdk/src/contracts/open-oracle.min.json",
"chars": 95959,
"preview": "{\n \"contracts\": {\n \"contracts/Uniswap/UniswapAnchoredView.sol:UniswapAnchoredView\": {\n \"abi\": \"[{\\\"inputs\\\":[{\\"
},
{
"path": "src/fuse-sdk/src/contracts/oracles/AlphaHomoraV1PriceOracle.json",
"chars": 82171,
"preview": "{\n \"contractName\": \"AlphaHomoraV1PriceOracle\",\n \"abi\": [\n {\n \"inputs\": [],\n \"name\": \"IBETH\",\n \"outpu"
},
{
"path": "src/fuse-sdk/src/contracts/oracles/BalancerLpTokenPriceOracle.json",
"chars": 556545,
"preview": "{\n \"contractName\": \"BalancerLpTokenPriceOracle\",\n \"abi\": [\n {\n \"inputs\": [],\n \"name\": \"BONE\",\n \"outp"
},
{
"path": "src/fuse-sdk/src/contracts/oracles/ChainlinkPriceOracle.json",
"chars": 1746538,
"preview": "{\n \"contractName\": \"ChainlinkPriceOracle\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalType\": \"uint"
},
{
"path": "src/fuse-sdk/src/contracts/oracles/CurveLpTokenPriceOracle.json",
"chars": 364256,
"preview": "{\n \"contractName\": \"CurveLpTokenPriceOracle\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalType\": \"a"
},
{
"path": "src/fuse-sdk/src/contracts/oracles/Keep3rPriceOracle.json",
"chars": 683667,
"preview": "{\n \"contractName\": \"Keep3rPriceOracle\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalType\": \"bool\",\n"
},
{
"path": "src/fuse-sdk/src/contracts/oracles/MasterPriceOracle.json",
"chars": 536757,
"preview": "{\n \"contractName\": \"MasterPriceOracle\",\n \"abi\": [\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n "
},
{
"path": "src/fuse-sdk/src/contracts/oracles/PreferredPriceOracle.json",
"chars": 147800,
"preview": "{\n \"contractName\": \"PreferredPriceOracle\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalType\": \"cont"
},
{
"path": "src/fuse-sdk/src/contracts/oracles/RecursivePriceOracle.json",
"chars": 279983,
"preview": "{\n \"contractName\": \"RecursivePriceOracle\",\n \"abi\": [\n {\n \"inputs\": [],\n \"name\": \"COMPOUND_COMPTROLLER\",\n "
},
{
"path": "src/fuse-sdk/src/contracts/oracles/SynthetixPriceOracle.json",
"chars": 142050,
"preview": "{\n \"contractName\": \"SynthetixPriceOracle\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalType\": \"cont"
},
{
"path": "src/fuse-sdk/src/contracts/oracles/UniswapLpTokenPriceOracle.json",
"chars": 601048,
"preview": "{\n \"contractName\": \"UniswapLpTokenPriceOracle\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalType\": "
},
{
"path": "src/fuse-sdk/src/contracts/oracles/UniswapTwapPriceOracleV2Factory.json",
"chars": 187868,
"preview": "{\n \"contractName\": \"UniswapTwapPriceOracleV2Factory\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalT"
},
{
"path": "src/fuse-sdk/src/contracts/oracles/UniswapV3TwapPriceOracleV2Factory.json",
"chars": 179308,
"preview": "{\n \"contractName\": \"UniswapV3TwapPriceOracleV2Factory\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"interna"
},
{
"path": "src/fuse-sdk/src/contracts/oracles/YVaultV1PriceOracle.json",
"chars": 111935,
"preview": "{\n \"contractName\": \"YVaultV1PriceOracle\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalType\": \"contr"
},
{
"path": "src/fuse-sdk/src/contracts/oracles/YVaultV2PriceOracle.json",
"chars": 126560,
"preview": "{\n \"contractName\": \"YVaultV2PriceOracle\",\n \"abi\": [\n {\n \"inputs\": [\n {\n \"internalType\": \"contr"
},
{
"path": "src/fuse-sdk/src/contracts/oracles.min.json",
"chars": 15769,
"preview": "{\"contracts\":{\"AlphaHomoraV1PriceOracle\":{\"abi\":[{\"inputs\":[],\"name\":\"IBETH\",\"outputs\":[{\"internalType\":\"contract Bank\","
},
{
"path": "src/fuse-sdk/src/index.js",
"chars": 73009,
"preview": "/* eslint-disable */\nimport Web3 from \"web3\";\n\nimport JumpRateModel from \"./irm/JumpRateModel.js\";\nimport JumpRateModelV"
},
{
"path": "src/fuse-sdk/src/irm/DAIInterestRateModelV2.js",
"chars": 3082,
"preview": "import Web3 from \"web3\";\n\nimport JumpRateModel from \"./JumpRateModel.js\";\n\nvar contracts = require(__dirname + \"/../cont"
},
{
"path": "src/fuse-sdk/src/irm/JumpRateModel.js",
"chars": 4404,
"preview": "import Web3 from \"web3\";\n\nvar contracts = require(__dirname + \"/../contracts/compound-protocol.min.json\")\n .contracts;\n"
},
{
"path": "src/fuse-sdk/src/irm/JumpRateModelV2.js",
"chars": 4324,
"preview": "import Web3 from \"web3\";\n\nvar contracts = require(__dirname + \"/../contracts/compound-protocol.min.json\")\n .contracts;\n"
},
{
"path": "src/fuse-sdk/src/irm/WhitePaperInterestRateModel.js",
"chars": 3497,
"preview": "import Web3 from \"web3\";\n\nvar contracts = require(__dirname + \"/../contracts/compound-protocol.min.json\")\n .contracts;\n"
},
{
"path": "src/fuse-sdk/test/launch-pools.js",
"chars": 24099,
"preview": "var axios = require(\"axios\");\nvar Big = require(\"big.js\");\n\nconst Fuse = require(\"../dist/fuse.node.commonjs2.js\");\n\nvar"
},
{
"path": "src/fuse-sdk/test/live-price-oracle.js",
"chars": 3031,
"preview": "var axios = require('axios');\n\nconst Fuse = require(\"../dist/fuse.node.commonjs2.js\");\n\nvar fuse = new Fuse(process.env."
},
{
"path": "src/fuse-sdk/test/oracles.js",
"chars": 100874,
"preview": "var assert = require('assert');\nvar Big = require('big.js');\nvar axios = require('axios');\n\nconst Fuse = require(\"../dis"
},
{
"path": "src/fuse-sdk/test/public-contracts.js",
"chars": 2496,
"preview": "const Fuse = require(\"../dist/fuse.node.commonjs2.js\");\n\nvar fuse = new Fuse(process.env.TESTING_WEB3_PROVIDER_URL);\n\nco"
},
{
"path": "src/fuse-sdk/test/safe-liquidator.js",
"chars": 96383,
"preview": "var assert = require('assert');\nvar Big = require('big.js');\nvar hre = require('hardhat');\n\nconst Fuse = require(\"../dis"
},
{
"path": "src/fuse-sdk/test/update-interest-rate-models-v2.js",
"chars": 10302,
"preview": "const Fuse = require(\"../dist/fuse.node.commonjs2.js\");\n\nvar fuse = new Fuse(process.env.TESTING_WEB3_PROVIDER_URL);\n\n//"
},
{
"path": "src/fuse-sdk/webpack.config.js",
"chars": 2578,
"preview": "const webpack = require(\"webpack\");\nconst TerserPlugin = require(\"terser-webpack-plugin\");\nconst CompressionPlugin = req"
},
{
"path": "src/hooks/fuse/useCTokenData.ts",
"chars": 1498,
"preview": "import { useRari } from \"context/RariContext\";\nimport { useQuery } from \"react-query\";\n\nimport { createComptroller, crea"
},
{
"path": "src/hooks/fuse/useFusePools.ts",
"chars": 4301,
"preview": "import { useMemo } from \"react\";\nimport { useQuery } from \"react-query\";\nimport { useRari } from \"context/RariContext\";\n"
},
{
"path": "src/hooks/fuse/useFuseTVL.ts",
"chars": 640,
"preview": "import { useQuery } from \"react-query\";\nimport { useRari } from \"context/RariContext\";\nimport Rari from \"rari-sdk/index\""
},
{
"path": "src/hooks/fuse/useFuseTotalBorrowAndSupply.ts",
"chars": 970,
"preview": "import { useQuery } from \"react-query\";\nimport { useRari } from \"context/RariContext\";\nimport Rari from \"rari-sdk/index\""
},
{
"path": "src/hooks/fuse/useIRMCurves.ts",
"chars": 1049,
"preview": "\n// Rari\nimport { useRari } from \"context/RariContext\";\n\n// Hooks\nimport { useQuery } from \"react-query\";\n\n// Utils\nimpo"
},
{
"path": "src/hooks/fuse/useLiquidationIncentive.ts",
"chars": 562,
"preview": "// Rari\nimport { useRari } from \"context/RariContext\";\n\n// Hooks\nimport { useQuery } from \"react-query\";\nimport { create"
},
{
"path": "src/hooks/fuse/useOracleData.ts",
"chars": 12757,
"preview": "// Rari\nimport Fuse from \"../../fuse-sdk/src/index\";\n\n// Hooks\nimport { createOracle } from \"../../utils/createComptroll"
},
{
"path": "src/hooks/fuse/useOraclesForPool.ts",
"chars": 1797,
"preview": "import { useRari } from \"context/RariContext\";\nimport { string } from \"mathjs\";\nimport React, { useMemo } from \"react\";\n"
},
{
"path": "src/hooks/homepage/useOpportunitySubtitle.ts",
"chars": 3241,
"preview": "import { useMemo } from \"react\";\nimport {\n HomepageOpportunity,\n HomepageOpportunityType,\n} from \"constants/homepage\";"
},
{
"path": "src/hooks/interestRates/aave/LendingPool.ts",
"chars": 360,
"preview": "// Types\nimport { AbiItem } from \"web3-utils\";\n\n// LendingPool contract ABI\nconst abi: AbiItem[] =\n require(\"@aave/prot"
},
{
"path": "src/hooks/interestRates/aave/useReserves.ts",
"chars": 2930,
"preview": "import { useEffect, useRef, useState } from \"react\";\n\n// Hooks\nimport { useRari } from \"context/RariContext\";\n\n// ABIs\ni"
},
{
"path": "src/hooks/interestRates/compound/CErc20.ts",
"chars": 179,
"preview": "// Types\nimport { AbiItem } from \"web3-utils\";\n\n// CErc20 contract ABI\nconst abi: AbiItem[] = require(\"./contracts/CErc2"
},
{
"path": "src/hooks/interestRates/compound/contracts/CErc20.json",
"chars": 24389,
"preview": "[\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n "
},
{
"path": "src/hooks/interestRates/compound/useCompoundMarkets.ts",
"chars": 4009,
"preview": "import { useEffect, useState, useRef } from \"react\";\n\n// Hooks\nimport { useRari } from \"context/RariContext\";\n\n// ABIs\ni"
},
{
"path": "src/hooks/interestRates/fuse/useFuseMarkets.ts",
"chars": 1968,
"preview": "import { useEffect, useState } from \"react\";\n\n// Hooks\nimport { useRari } from \"context/RariContext\";\nimport { useFusePo"
},
{
"path": "src/hooks/interestRates/types.ts",
"chars": 160,
"preview": "export type InterestRatesType = {\n lending: number;\n borrowing: number;\n};\n\nexport type MarketInfo = {\n tokenAddress:"
},
{
"path": "src/hooks/pool2/usePool2APR.ts",
"chars": 608,
"preview": "import { useQuery } from \"react-query\";\nimport { useRari } from \"context/RariContext\";\n\nexport const usePool2APR = () =>"
},
{
"path": "src/hooks/pool2/usePool2Balance.ts",
"chars": 1160,
"preview": "import { useQuery } from \"react-query\";\nimport { useRari } from \"context/RariContext\";\nimport Rari from \"rari-sdk/index\""
},
{
"path": "src/hooks/pool2/usePool2TotalStaked.ts",
"chars": 412,
"preview": "import { useQuery } from \"react-query\";\nimport { useRari } from \"context/RariContext\";\n\nexport const usePool2TotalStaked"
},
{
"path": "src/hooks/pool2/usePool2UnclaimedRGT.ts",
"chars": 625,
"preview": "import { useQuery } from \"react-query\";\nimport { useRari } from \"context/RariContext\";\nimport Rari from \"rari-sdk/index\""
},
{
"path": "src/hooks/pool2/useSushiswapRewards.ts",
"chars": 503,
"preview": "import { useQuery } from \"react-query\";\nimport { useRari } from \"context/RariContext\";\n\nexport const useHasSushiswapRewa"
},
{
"path": "src/hooks/rewards/useClaimable.ts",
"chars": 3821,
"preview": "import { useMemo } from \"react\";\nimport {\n UnclaimedReward,\n useUnclaimedFuseRewards,\n} from \"./useUnclaimedFuseReward"
},
{
"path": "src/hooks/rewards/usePoolIncentives.ts",
"chars": 5927,
"preview": "import { createCToken } from \"utils/createComptroller\";\nimport { useRari } from \"context/RariContext\";\nimport { TokensDa"
},
{
"path": "src/hooks/rewards/useRewardAPY.ts",
"chars": 11481,
"preview": "// for supply-side rewards apy:\n// export const\n\nimport { useQuery } from \"react-query\";\nimport {\n ETH_TOKEN_DATA,\n To"
},
{
"path": "src/hooks/rewards/useRewardsDistributorsForPool.ts",
"chars": 1520,
"preview": "import { useRari } from \"context/RariContext\";\nimport { useQuery } from \"react-query\";\nimport { createComptroller } from"
},
{
"path": "src/hooks/rewards/useUnclaimedFuseRewards.ts",
"chars": 7189,
"preview": "import { useQuery } from \"react-query\";\nimport { useRari } from \"../../context/RariContext\";\nimport { createRewardsDistr"
},
{
"path": "src/hooks/rewards/useUnclaimedRGT.ts",
"chars": 1113,
"preview": "import { useMemo } from \"react\";\nimport { useQuery } from \"react-query\";\nimport { useRari } from \"../../context/RariCont"
},
{
"path": "src/hooks/tranches/useSFIDistributions.ts",
"chars": 795,
"preview": "import { useQuery } from \"react-query\";\nimport { useRari } from \"context/RariContext\";\nimport { useSaffronData } from \"."
},
{
"path": "src/hooks/tranches/useSFIEarnings.ts",
"chars": 421,
"preview": "import { useQuery } from \"react-query\";\nimport { useSaffronData } from \"./useSaffronData\";\n\nexport const useSFIEarnings "
},
{
"path": "src/hooks/tranches/useSaffronData.ts",
"chars": 8331,
"preview": "import { useQuery } from \"react-query\";\nimport { useRari } from \"context/RariContext\";\nimport { useSaffronContracts } fr"
},
{
"path": "src/hooks/useAssetsMap.ts",
"chars": 1770,
"preview": "import { useMemo } from \"react\";\n\n// Utils\nimport {\n createAssetsMap,\n AssetHash,\n createTokensDataMap,\n TokensDataH"
},
{
"path": "src/hooks/useAuthedCallback.ts",
"chars": 306,
"preview": "import { useRari } from \"../context/RariContext\";\n\nexport const useAuthedCallback = (callback: () => any) => {\n const {"
},
{
"path": "src/hooks/useBorrowLimit.ts",
"chars": 1291,
"preview": "import { useMemo } from \"react\";\nimport { USDPricedFuseAsset } from \"utils/fetchFusePoolData\";\n\nexport const useBorrowLi"
},
{
"path": "src/hooks/useFusePoolData.ts",
"chars": 2195,
"preview": "import { useMemo } from \"react\";\nimport { useQuery, useQueries } from \"react-query\";\n\nimport { useRari } from \"../contex"
}
]
// ... and 107 more files (download for full content)
About this extraction
This page contains the full source code of the Rari-Capital/rari-dApp GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 307 files (21.0 MB), approximately 2.2M tokens, and a symbol index with 303 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.