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.
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.
Copyright (C)
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 .
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
.
================================================
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:
What are the "compiled" folders in src/static?
- 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!
================================================
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 extends PromiseLike ? U : T;
const weightedCalculation = async (
calculation: () => Promise,
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>[] = [];
let totalRSS = 0;
let promises: Promise[] = [];
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"
///
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
================================================
Rari Portal
================================================
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: ,
}
);
const PoolPortal = loadable(
() => import(/* webpackPrefetch: true */ "./pages/PoolPortal"),
{
fallback: ,
}
);
const TranchesPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Tranches/TranchesPage"),
{
fallback: ,
}
);
const FusePoolsPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Fuse/FusePoolsPage"),
{
fallback: ,
}
);
const FusePoolPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Fuse/FusePoolPage"),
{
fallback: ,
}
);
const FusePoolInfoPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Fuse/FusePoolInfoPage"),
{
fallback: ,
}
);
const FusePoolEditPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Fuse/FusePoolEditPage"),
{
fallback: ,
}
);
const FusePoolCreatePage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Fuse/FusePoolCreatePage"),
{
fallback: ,
}
);
const FuseLiquidationsPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Fuse/FuseLiquidationsPage"),
{
fallback: ,
}
);
const Pool2Page = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Pool2/Pool2Page"),
{
fallback: ,
}
);
const StatsPage = loadable(
() => import(/* webpackPrefetch: true */ "./pages/Stats"),
{
fallback: ,
}
);
const InterestRatesPage = loadable(
() =>
import(/* webpackPrefetch: true */ "./pages/InterestRates/InterestRates"),
{
fallback: ,
}
);
const PageNotFound = memo(() => {
return (
404: Not Found
);
});
const App = memo(() => {
return (
}>
{Object.values(Pool).map((pool) => {
return (
}
/>
);
})}
} />
} />
} />
} />
} />
} />
} />
} />
} />
} />
} />
{/* Backwards Compatibility Routes */}
}
/>
}
/>
}
/>
{/* Backwards Compatibility Routes */}
} />
} />
);
});
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 = ({ error }) => {
const { t } = useTranslation();
return (
{t("Whoops! Looks like something went wrong!")}
{t(
"You can either reload the page, or report this error to us on our"
)}{" "}
GitHub{error.toString()}
);
};
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[] = [];
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[] = [];
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[] = [];
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 (
<>
>
);
});
export default FuseLiquidationsPage;
const LiquidationEventsList = ({
liquidations,
totalLiquidations,
setLiquidationsToShow,
}: {
liquidations?: LiquidationEvent[];
totalLiquidations: number;
setLiquidationsToShow: React.Dispatch>;
}) => {
const { t } = useTranslation();
const isMobile = useIsMobile();
return (
{t("Recent Liquidations")}
{isMobile ? null : (
<>
{t("Collateral Seized")}
{t("Borrow Repaid")}
{t("Timestamp")}
>
)}
{liquidations ? (
<>
{liquidations.map((liquidation, index) => {
return (
);
})}
>
) : (
)}
);
};
const LiquidationRow = ({
noBottomDivider,
liquidation,
}: {
noBottomDivider?: boolean;
liquidation: LiquidationEvent;
}) => {
const isMobile = useIsMobile();
const { t } = useTranslation();
const date = new Date(liquidation.timestamp * 1000);
return (
<>
{" → "}
{t("Liquidated")}
{" → "}
(Pool #{liquidation.poolID})
{liquidation.liquidator}
{liquidation.borrower}
{isMobile ? null : (
<>
{smallUsdFormatter(
liquidation.repayAmount /
10 ** liquidation.borrowedTokenUnderlyingDecimals
).replace("$", "")}{" "}
{liquidation.borrowedTokenUnderlyingSymbol}
{date.toLocaleTimeString()}{date.toLocaleDateString()}
>
)}
{noBottomDivider ? null : }
>
);
};
const RowsControl = ({
setAmountToShow,
totalAmount,
}: {
totalAmount: number;
setAmountToShow: React.Dispatch>;
}) => {
const { t } = useTranslation();
return (
setAmountToShow((past) =>
Math.min(
past === 0 ? 1 : past === -1 ? totalAmount : past + 5,
totalAmount
)
)
}
>
{t("View More")}
setAmountToShow((past) => Math.max(past - 5, 0))}
>
{t("View Less")}
setAmountToShow(totalAmount)}
>
{t("View All")}
setAmountToShow(0)}
>
{t("Collapse All")}
);
};
================================================
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 (
<>
>
);
});
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([]);
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(0);
const increaseActiveStep = (step: string) => {
setActiveStep(steps.indexOf(step));
};
const [needsRetry, setNeedsRetry] = useState(false);
const [retryFlag, setRetryFlag] = useState(1);
const [deployedPriceOracle, setDeployedPriceOracle] = useState("");
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 (
<>
{t("Create Pool")}
{t("Name")}
setName(event.target.value)}
/>
{t("Whitelisted")} {
setIsWhitelisted((past) => !past);
// Add the user to the whitelist by default
if (whitelist.length === 0) {
setWhitelist([address]);
}
}}
className="black-switch"
colorScheme="#121212"
/>
{isWhitelisted ? (
{
setWhitelist((past) => [...past, user]);
}}
removeFromWhitelist={(user) => {
setWhitelist((past) =>
past.filter(function (item) {
return item !== user;
})
);
}}
/>
) : null}
{t("Close Factor")}
{t("Liquidation Incentive")}
{isUsingMPO ? t("Default Price Oracle") : t("Custom Price Oracle")} setIsUsingMPO(!isUsingMPO)}
marginBottom={3}
/>
{
!isUsingMPO ? (
<>
setCustomOracleAddress(e.target.value)}
/>
Please make sure you know what you're doing.
>
)
: null
}
{tokenData?.symbol ? (
<>
>
) : null}
);
};
export default AddAssetModal;
================================================
FILE: src/components/pages/Fuse/Modals/AddAssetModal/AssetConfig.tsx
================================================
// Chakra and UI
import { Text, Select, useToast } from "@chakra-ui/react";
import { Column } from "utils/chakraUtils";
import { DASHBOARD_BOX_PROPS } from "../../../../shared/DashboardBox";
import { ModalDivider } from "../../../../shared/Modal";
import { SliderWithLabel } from "../../../../shared/SliderWithLabel";
import {
ConfigRow,
SaveButton,
testForComptrollerErrorAndSend,
} from "../../FusePoolEditPage";
import { QuestionIcon } from "@chakra-ui/icons";
import { SimpleTooltip } from "../../../../shared/SimpleTooltip";
// React
import { useTranslation } from "react-i18next";
import { useQueryClient } from "react-query";
// Rari
import { useRari } from "../../../../../context/RariContext";
import Fuse from "../../../../../fuse-sdk";
// Hooks
import useIRMCurves from "hooks/fuse/useIRMCurves";
import { createCToken } from "../../../../../utils/createComptroller";
import { useLiquidationIncentive } from "hooks/fuse/useLiquidationIncentive";
// Utils
import { handleGenericError } from "../../../../../utils/errorHandling";
import { createComptroller } from "../../../../../utils/createComptroller";
import { testForCTokenErrorAndSend } from "../PoolModal/AmountSelect";
import { isTokenETHOrWETH } from "utils/tokenUtils";
// Libraries
import BigNumber from "bignumber.js";
import LogRocket from "logrocket";
// Components
import IRMChart from "./IRMChart";
import OracleConfig from "./OracleConfig/OracleConfig";
import { useAddAssetContext } from "context/AddAssetContext";
import MarketCapConfigurator from "../Edit/MarketCapConfigurator";
const formatPercentage = (value: number) => value.toFixed(1) + "%";
const AssetConfig = () => {
const queryClient = useQueryClient();
const { fuse, address } = useRari();
const { t } = useTranslation();
const toast = useToast();
const {
cTokenData,
collateralFactor,
setCollateralFactor,
cTokenAddress,
isBorrowPaused,
adminFee,
setAdminFee,
activeOracleModel,
oracleData,
tokenAddress,
mode,
setInterestRateModel,
interestRateModel,
tokenData,
setReserveFactor,
reserveFactor,
comptrollerAddress,
} = useAddAssetContext();
const curves = useIRMCurves({ interestRateModel, adminFee, reserveFactor });
// Liquidation incentive. (This is configured at pool level)
const liquidationIncentiveMantissa =
useLiquidationIncentive(comptrollerAddress);
const scaleCollateralFactor = (_collateralFactor: number) => {
return _collateralFactor / 1e16;
};
const scaleReserveFactor = (_reserveFactor: number) => {
return _reserveFactor / 1e16;
};
const scaleAdminFee = (_adminFee: number) => {
return _adminFee / 1e16;
};
// Updates asset's Interest Rate Model.
const updateInterestRateModel = async () => {
const cToken = createCToken(fuse, cTokenAddress!);
try {
await testForCTokenErrorAndSend(
cToken.methods._setInterestRateModel(interestRateModel),
address,
""
);
LogRocket.track("Fuse-UpdateInterestRateModel");
queryClient.refetchQueries();
} catch (e) {
handleGenericError(e, toast);
}
};
// Determines if users can borrow an asset or not.
const togglePause = async () => {
const comptroller = createComptroller(comptrollerAddress, fuse);
try {
await comptroller.methods
._setBorrowPaused(cTokenAddress, !isBorrowPaused)
.send({ from: address });
LogRocket.track("Fuse-PauseToggle");
queryClient.refetchQueries();
} catch (e) {
handleGenericError(e, toast);
}
};
// Updates loan to Value ratio.
const updateCollateralFactor = async () => {
const comptroller = createComptroller(comptrollerAddress, fuse);
// 70% -> 0.7 * 1e18
const bigCollateralFactor = new BigNumber(collateralFactor)
.dividedBy(100)
.multipliedBy(1e18)
.toFixed(0);
try {
await testForComptrollerErrorAndSend(
comptroller.methods._setCollateralFactor(
cTokenAddress,
bigCollateralFactor
),
address,
""
);
LogRocket.track("Fuse-UpdateCollateralFactor");
queryClient.refetchQueries();
} catch (e) {
handleGenericError(e, toast);
}
};
// Updated portion of accrued reserves that goes into reserves.
const updateReserveFactor = async () => {
const cToken = createCToken(fuse, cTokenAddress!);
// 10% -> 0.1 * 1e18
const bigReserveFactor = new BigNumber(reserveFactor)
.dividedBy(100)
.multipliedBy(1e18)
.toFixed(0);
try {
await testForCTokenErrorAndSend(
cToken.methods._setReserveFactor(bigReserveFactor),
address,
""
);
LogRocket.track("Fuse-UpdateReserveFactor");
queryClient.refetchQueries();
} catch (e) {
handleGenericError(e, toast);
}
};
// Updates asset's admin fee.
const updateAdminFee = async () => {
const cToken = createCToken(fuse, cTokenAddress!);
// 5% -> 0.05 * 1e18
const bigAdminFee = new BigNumber(adminFee)
.dividedBy(100)
.multipliedBy(1e18)
.toFixed(0);
try {
await testForCTokenErrorAndSend(
cToken.methods._setAdminFee(bigAdminFee),
address,
""
);
LogRocket.track("Fuse-UpdateAdminFee");
queryClient.refetchQueries();
} catch (e) {
handleGenericError(e, toast);
}
};
return (
<>
{mode === "Editing" ? (
<>
>
) : null}
{t("Collateral Factor")}
{cTokenData !== undefined &&
mode === "Editing" &&
collateralFactor !==
scaleCollateralFactor(cTokenData?.collateralFactorMantissa) ? (
) : null}
{cTokenAddress ? (
{t("Pause Borrowing")}
) : null}
{t("Reserve Factor")}
{cTokenData &&
reserveFactor !==
scaleReserveFactor(cTokenData.reserveFactorMantissa) ? (
) : null}
{t("Admin Fee")}
{cTokenData &&
adminFee !== scaleAdminFee(cTokenData.adminFeeMantissa) ? (
) : null}
{(activeOracleModel === "MasterPriceOracleV2" ||
activeOracleModel === "MasterPriceOracleV3") &&
oracleData !== undefined &&
!isTokenETHOrWETH(tokenAddress) &&
mode === "Editing" && (
<>
>
)}
{t("Interest Model")}
{cTokenData &&
cTokenData.interestRateModelAddress.toLowerCase() !==
interestRateModel.toLowerCase() ? (
) : null}
{mode === "Editing" && (
)}
{mode === "Adding" ? (
{fuse
.identifyInterestRateModelName(interestRateModel)
.replace("_", " ")}
) : null}
>
);
};
export default AssetConfig;
================================================
FILE: src/components/pages/Fuse/Modals/AddAssetModal/AssetSettings.tsx
================================================
// Chakra and UI
import { Heading, Spinner, useToast } from "@chakra-ui/react";
import { Column, Center, RowOrColumn, Row } from "utils/chakraUtils";
import { Fade } from "@chakra-ui/react";
// React
import { useEffect, useState, useMemo, createContext, useContext } from "react";
// React Query
import { useQueryClient } from "react-query";
// Rari
import Fuse from "../../../../../fuse-sdk";
import { useRari } from "../../../../../context/RariContext";
// Hooks
import { ETH_TOKEN_DATA, TokenData } from "../../../../../hooks/useTokenData";
import { createOracle } from "../../../../../utils/createComptroller";
import { CTokenData, useCTokenData } from "hooks/fuse/useCTokenData";
import { OracleDataType } from "hooks/fuse/useOracleData";
import useIRMCurves from "hooks/fuse/useIRMCurves";
// Utils
import { handleGenericError } from "../../../../../utils/errorHandling";
import { USDPricedFuseAsset } from "../../../../../utils/fetchFusePoolData";
import { isTokenETHOrWETH } from "utils/tokenUtils";
// Libraries
import BigNumber from "bignumber.js";
import LogRocket from "logrocket";
import { useIsMediumScreen } from "../../FuseTabBar";
// Components
import DeployButton from "./DeployButton";
import AssetConfig from "./AssetConfig";
import Screen1 from "./Screens/Screen1";
import Screen2 from "./Screens/Screen2";
import Screen3 from "./Screens/Screen3";
import { AddAssetContextData, AddAssetContext } from "context/AddAssetContext";
const SimpleDeployment = [
"Configuring your Fuse pool's Master Price Oracle",
"Configuring your Fuse pool to support new asset market",
"All Done!",
];
const UniSwapV3DeploymentSimple = [
"Checking for pair's cardinality",
"Increasing Uniswap V3 pair cardinality",
"Deploying Uniswap V3 Twap Oracle",
"Configuring your Fuse pool's Master Price Oracle",
"Configuring your Fuse pool to support new asset market",
"All Done!",
];
export type RETRY_FLAG = 1 | 2 | 3 | 4 | 5;
const AssetSettings = ({
mode,
poolID,
poolName,
tokenData,
closeModal,
oracleData,
oracleModel,
tokenAddress,
cTokenAddress,
existingAssets,
poolOracleAddress,
comptrollerAddress,
}: {
comptrollerAddress: string; // Fuse pool's comptroller address
poolOracleAddress: string; // Fuse pool's oracle address
tokenAddress: string; // Underlying token's addres. i.e. USDC, DAI, etc.
oracleModel: string | undefined; // Fuse pool's oracle model name. i.e MasterPrice, Chainlink, etc.
oracleData: OracleDataType | undefined; // Fuse pool's oracle contract, admin, overwriting permissions.
tokenData: TokenData; // Token's data i.e. symbol, logo, css color, etc.
poolName: string; // Fuse pool's name.
poolID: string; // Fuse pool's ID.
// Only for editing mode
cTokenAddress?: string; // CToken for Underlying token. i.e f-USDC-4
// Only for add asset modal
existingAssets?: USDPricedFuseAsset[]; // A list of assets in the pool
// Modal config
closeModal: () => any;
mode: "Editing" | "Adding";
}) => {
const toast = useToast();
const { fuse, address } = useRari();
const queryClient = useQueryClient();
const isMobile = useIsMediumScreen();
// Component state
const [isDeploying, setIsDeploying] = useState(false);
// Asset's general configurations.
const [adminFee, setAdminFee] = useState(0);
const [reserveFactor, setReserveFactor] = useState(10);
const [isBorrowPaused, setIsBorrowPaused] = useState(false);
const [collateralFactor, setCollateralFactor] = useState(50);
const [interestRateModel, setInterestRateModel] = useState(
Fuse.PUBLIC_INTEREST_RATE_MODEL_CONTRACT_ADDRESSES
.JumpRateModel_Cream_Stables_Majors
);
const curves = useIRMCurves({ interestRateModel, adminFee, reserveFactor });
// Asset's Oracle Configuration
const [oracleTouched, setOracleTouched] = useState(false);
const [activeOracleModel, setActiveOracleModel] = useState(""); // Will store the oracle's model selected for this asset. i.e. Rari Master Price Oracle, Custome Oracle, etc.
const [oracleAddress, setOracleAddress] = useState(""); // Will store the actual address of the oracle.
// Uniswap V3 base token oracle config - these following lines are used only
// if you choose Uniswap V3 Twap Oracle as the asset's oracle.
const [feeTier, setFeeTier] = useState(0);
const [uniV3BaseTokenAddress, setUniV3BaseTokenAddress] =
useState(""); // This will store the pair's base token.
const [uniV3BaseTokenOracle, setUniV3BaseTokenOracle] = useState(""); // This will store the oracle chosen for the uniV3BaseTokenAddress.
const [baseTokenActiveOracleName, setBaseTokenActiveOracleName] =
useState("");
const [uniV3BaseTokenHasOracle, setUniV3BaseTokenHasOracle] =
useState(false); // Will let us know if fuse pool's oracle has a price feed for the pair's base token.
// This will be used to index whitelistPools array (fetched from the graph.)
// It also helps us know if user has selected anything or not. If they have, detail fields are shown.
const [activeUniSwapPair, setActiveUniSwapPair] = useState("");
// If uniV3BaseTokenAddress doesn't have an oracle in the fuse pool's oracle, then show the form
// Or if the baseToken is weth then dont show form because we already have a hardcoded oracle for it
const shouldShowUniV3BaseTokenOracleForm = useMemo(
() =>
!!uniV3BaseTokenAddress &&
!uniV3BaseTokenHasOracle &&
!isTokenETHOrWETH(uniV3BaseTokenAddress) &&
(activeOracleModel === "Uniswap_V3_Oracle" ||
activeOracleModel === "Uniswap_V2_Oracle" ||
activeOracleModel === "SushiSwap_Oracle"),
[uniV3BaseTokenHasOracle, uniV3BaseTokenAddress, activeOracleModel]
);
// If you choose a UniV3 Pool as the oracle, check if fuse pool's oracle can get a price for uniV3BaseTokenAddress
useEffect(() => {
if (
!!uniV3BaseTokenAddress &&
!isTokenETHOrWETH(uniV3BaseTokenAddress) &&
!!oracleData &&
typeof oracleData !== "string"
) {
oracleData.oracleContract.methods
.price(uniV3BaseTokenAddress)
.call()
.then((price: string) => {
// if you're able to get a price for this asset then
return parseFloat(price) > 0
? setUniV3BaseTokenHasOracle(true)
: setUniV3BaseTokenHasOracle(false);
})
.catch((err: any) => {
console.log("Could not fetch price using pool's oracle");
setUniV3BaseTokenHasOracle(false);
});
}
}, [uniV3BaseTokenAddress, oracleData, setUniV3BaseTokenHasOracle]);
// Sharad: New stuff - to skip oracle step if possible
const [defaultOracle, setDefaultOracle] = useState(
ETH_TOKEN_DATA.address
);
const [customOracleForToken, setCustomOracleForToken] = useState(
ETH_TOKEN_DATA.address
);
const [priceForAsset, setPriceForAsset] = useState();
const hasDefaultOracle = useMemo(
() => defaultOracle !== ETH_TOKEN_DATA.address,
[defaultOracle]
);
const hasCustomOracleForToken = useMemo(
() => customOracleForToken !== ETH_TOKEN_DATA.address,
[customOracleForToken]
);
const hasPriceForAsset = useMemo(
() => !!priceForAsset && priceForAsset > 0,
[priceForAsset]
);
// For this asset, check for a defaultOracle, customOracle, and Pool MPO price for this token
useEffect(() => {
// If its a legacy oracle (type === string) then we cant create a MasterPriceOracle isntance for it and the user wont even be able to configure the oracle.
if (!!oracleData && typeof oracleData !== "string") {
const mpo = createOracle(poolOracleAddress, fuse, "MasterPriceOracle");
// 1. Check if it has a default oracle
mpo.methods
.defaultOracle()
.call()
.then((defaultOracle: string) => {
// const defaultOracle = createOracle(defaultOracle, fuse, "MasterPriceOracle");
setDefaultOracle(defaultOracle);
return mpo.methods.oracles(tokenAddress).call();
})
.then((oracleForToken: string) => {
// 2.) Check for Custom oracle
setCustomOracleForToken(oracleForToken);
return mpo.methods.price(tokenAddress).call();
})
.then((priceForAsset: string) => {
// 3.) Check for price
console.log({ priceForAsset });
setPriceForAsset(parseFloat(priceForAsset));
})
.catch((err: any) => {
console.error(err);
});
}
}, [oracleData, fuse, tokenAddress, poolOracleAddress]);
// Modal Pages
const [stage, setStage] = useState(1);
const handleSetStage = (incr: number) => {
const newStage = stage + incr;
// increment stage
if (incr > 0) {
if (isTokenETHOrWETH(tokenAddress) && newStage === 2) {
setStage(3);
} else setStage(newStage);
}
// decrement (previous page)
else if (incr < 0) {
if (isTokenETHOrWETH(tokenAddress) && newStage === 2) {
setStage(1);
} else setStage(newStage);
}
};
// Transaction Stepper
const [activeStep, setActiveStep] = useState(0);
// Retry Flag - start deploy function from here
const [retryFlag, setRetryFlag] = useState(1);
const [needsRetry, setNeedsRetry] = useState(false);
// Set transaction steps based on type of Oracle deployed
const steps: string[] =
activeOracleModel === "Rari_Default_Oracle" ||
activeOracleModel === "Chainlink_Oracle"
? SimpleDeployment
: activeOracleModel === "Uniswap_V3_Oracle"
? UniSwapV3DeploymentSimple
: SimpleDeployment;
const increaseActiveStep = (step: string) => {
setActiveStep(steps.indexOf(step));
};
const preDeployValidate = (oracleAddressToUse: string) => {
// If pool already contains this asset:
if (
existingAssets!.some(
(asset) => asset.underlyingToken === tokenData.address
)
) {
toast({
title: "Error!",
description: "You have already added this asset to this pool.",
status: "error",
duration: 2000,
isClosable: true,
position: "top-right",
});
throw new Error("You have already added this asset to this pool.");
}
// If you have not chosen an oracle
if (!isTokenETHOrWETH(tokenAddress)) {
if (oracleAddressToUse === "") {
toast({
title: "Error!",
description: "Please choose a valid oracle for this asset",
status: "error",
duration: 2000,
isClosable: true,
position: "top-right",
});
throw new Error("Please choose a valid oracle for this asset");
}
}
};
const checkUniV3Oracle = async () => {
// If this oracle is set in the optional form (only if u have a univ3pair and the base token isnt in the oracle)
// Then u have to deploy the base token )
// Check for observation cardinality and fix if necessary
const shouldPrime = await fuse.checkCardinality(oracleAddress);
if (shouldPrime) {
increaseActiveStep("Increasing Uniswap V3 pair cardinality");
await fuse.primeUniswapV3Oracle(oracleAddress, { from: address });
}
};
const deployUniV3Oracle = async () => {
increaseActiveStep("Deploying Uniswap V3 Twap Oracle");
// alert("deploying univ3twapOracle");
console.log("deployUniV3Oracle", {
feeTier,
uniV3BaseTokenAddress,
address,
deployPriceOracle: fuse.deployPriceOracle,
});
// Deploy UniV3 oracle
const oracleAddressToUse = await fuse.deployPriceOracle(
"UniswapV3TwapPriceOracleV2",
{ feeTier, baseToken: uniV3BaseTokenAddress },
{ from: address }
);
// alert("finished univ3twapOracle " + oracleAddressToUse);
console.log({ oracleAddressToUse });
return oracleAddressToUse;
};
// Deploy Oracle
const deployUniV2Oracle = async () =>
await fuse.deployPriceOracle(
"UniswapTwapPriceOracleV2",
{ baseToken: uniV3BaseTokenAddress },
{ from: address }
);
const addOraclesToMasterPriceOracle = async (oracleAddressToUse: string) => {
/** Configure the pool's MasterPriceOracle **/
increaseActiveStep("Configuring your Fuse pool's Master Price Oracle");
// Instantiate Fuse Pool's Oracle contract (Always "MasterPriceOracle")
const poolOracleContract = createOracle(
poolOracleAddress,
fuse,
"MasterPriceOracle"
);
const tokenArray = shouldShowUniV3BaseTokenOracleForm
? [tokenAddress, uniV3BaseTokenAddress] // univ3 only
: [tokenAddress];
const oracleAddress = shouldShowUniV3BaseTokenOracleForm
? [oracleAddressToUse, uniV3BaseTokenOracle] // univ3 only
: [oracleAddressToUse];
const hasOracles = await Promise.all(
tokenArray.map(async (tokenAddr) => {
const address: string = await poolOracleContract.methods
.oracles(tokenAddr)
.call();
// if address is EmptyAddress then there is no oracle for this token
return !(address === "0x0000000000000000000000000000000000000000");
})
);
const tokenHasOraclesInPool = hasOracles.some((x) => !!x);
console.log({
hasOracles,
tokenArray,
oracleAddress,
tokenHasOraclesInPool,
});
if (!!tokenHasOraclesInPool) return;
const tx = await poolOracleContract.methods
.add(tokenArray, oracleAddress)
.send({ from: address });
toast({
title: "You have successfully configured the oracle for this asset!",
description:
"Oracle will now point to the new selected address. Now, lets add you asset to the pool.",
status: "success",
duration: 2000,
isClosable: true,
position: "top-right",
});
};
const deployAssetToPool = async () => {
increaseActiveStep(
"Configuring your Fuse pool to support new asset market"
);
// 50% -> 0.5 * 1e18
const bigCollateralFactor = new BigNumber(collateralFactor)
.dividedBy(100)
.multipliedBy(1e18)
.toFixed(0);
// 10% -> 0.1 * 1e18
const bigReserveFactor = new BigNumber(reserveFactor)
.dividedBy(100)
.multipliedBy(1e18)
.toFixed(0);
// 5% -> 0.05 * 1e18
const bigAdminFee = new BigNumber(adminFee)
.dividedBy(100)
.multipliedBy(1e18)
.toFixed(0);
const conf: any = {
underlying: tokenData.address,
comptroller: comptrollerAddress,
interestRateModel,
initialExchangeRateMantissa: fuse.web3.utils.toBN(1e18),
// Ex: BOGGED USDC
name: poolName + " " + tokenData.name,
// Ex: fUSDC-456
symbol: "f" + tokenData.symbol + "-" + poolID,
decimals: 8,
};
console.log({
conf,
bigCollateralFactor,
bigReserveFactor,
bigAdminFee,
address,
});
await fuse.deployAsset(
conf,
bigCollateralFactor,
bigReserveFactor,
bigAdminFee,
{ from: address },
// TODO: Disable this. This bypasses the price feed check. Only using now because only trusted partners are deploying assets.
true
);
increaseActiveStep("All Done!");
};
// Deploy Asset!
const deploy = async () => {
let oracleAddressToUse = oracleAddress;
try {
preDeployValidate(oracleAddressToUse);
} catch (err) {
return;
}
setIsDeploying(true);
let _retryFlag = retryFlag;
try {
// It should be 1 if we haven't had to retry anything
/** IF UNISWAP V3 ORACLE **/
if (_retryFlag === 1) {
setNeedsRetry(false);
if (activeOracleModel === "Uniswap_V3_Oracle") {
console.log("preCheck");
await checkUniV3Oracle();
console.log("postCheck");
}
_retryFlag = 2; // set it to two after we fall through step 1
}
/** IF UNISWAP V3 ORACLE **/
if (_retryFlag === 2) {
setNeedsRetry(false);
if (activeOracleModel === "Uniswap_V3_Oracle") {
console.log("predeploy");
oracleAddressToUse = await deployUniV3Oracle();
console.log("postDeploy", { oracleAddressToUse });
}
_retryFlag = 3;
}
/** IF UNISWAP V2 ORACLE **/
if (_retryFlag === 3) {
setNeedsRetry(false);
if (activeOracleModel === "Uniswap_V2_Oracle") {
oracleAddressToUse = await deployUniV2Oracle();
}
_retryFlag = 4;
}
/** CONFIGURE MASTERPRICEORACLE **/
// You dont need to configure if your asset is ETH / WETH
// You dont need to configure if a default oracle is available and you have chosen it
if (_retryFlag === 4) {
setNeedsRetry(false);
if (
!isTokenETHOrWETH(tokenAddress) &&
(oracleModel === "MasterPriceOracleV3" ||
oracleModel === "MasterPriceOracleV2") &&
oracleAddress !== defaultOracle // If you have not selected the default oracle you will have to configure.
) {
// alert("addOraclesToMasterPriceOracle");
await addOraclesToMasterPriceOracle(oracleAddressToUse);
}
_retryFlag = 5;
}
/** DEPLOY ASSET **/
if (_retryFlag === 5) {
setNeedsRetry(false);
await deployAssetToPool();
LogRocket.track("Fuse-DeployAsset");
queryClient.refetchQueries();
// Wait 2 seconds for refetch and then close modal.
// We do this instead of waiting the refetch because some refetches take a while or error out and we want to close now.
await new Promise((resolve) => setTimeout(resolve, 2000));
toast({
title: "You have successfully added an asset to this pool!",
description: "You may now lend and borrow with this asset.",
status: "success",
duration: 2000,
isClosable: true,
position: "top-right",
});
}
closeModal();
} catch (e) {
handleGenericError(e, toast);
setRetryFlag(_retryFlag);
console.log({ _retryFlag });
setNeedsRetry(true);
}
};
// Update values on refetch!
const cTokenData = useCTokenData(comptrollerAddress, cTokenAddress);
useEffect(() => {
if (cTokenData) {
setIsBorrowPaused(cTokenData.isPaused);
setAdminFee(cTokenData.adminFeeMantissa / 1e16);
setReserveFactor(cTokenData.reserveFactorMantissa / 1e16);
setInterestRateModel(cTokenData.interestRateModelAddress);
setCollateralFactor(cTokenData.collateralFactorMantissa / 1e16);
}
}, [cTokenData]);
const args2: AddAssetContextData = {
mode,
isDeploying,
setIsDeploying,
adminFee,
setAdminFee,
reserveFactor,
setReserveFactor,
isBorrowPaused,
setIsBorrowPaused,
collateralFactor,
setCollateralFactor,
interestRateModel,
setInterestRateModel,
curves,
oracleTouched,
setOracleTouched,
activeOracleModel,
setActiveOracleModel,
oracleAddress,
setOracleAddress,
feeTier,
setFeeTier,
uniV3BaseTokenAddress,
setUniV3BaseTokenAddress: setUniV3BaseTokenAddress,
uniV3BaseTokenOracle,
setUniV3BaseTokenOracle,
baseTokenActiveOracleName,
setBaseTokenActiveOracleName,
uniV3BaseTokenHasOracle,
setUniV3BaseTokenHasOracle,
activeUniSwapPair,
setActiveUniSwapPair,
shouldShowUniV3BaseTokenOracleForm,
defaultOracle,
setDefaultOracle,
customOracleForToken,
setCustomOracleForToken,
priceForAsset,
setPriceForAsset,
hasDefaultOracle,
hasCustomOracleForToken,
hasPriceForAsset,
stage,
setStage,
handleSetStage,
activeStep,
setActiveStep,
increaseActiveStep,
retryFlag,
setRetryFlag,
needsRetry,
setNeedsRetry,
cTokenData,
cTokenAddress,
oracleData,
poolOracleAddress,
poolOracleModel: oracleModel,
tokenData,
tokenAddress,
comptrollerAddress,
};
if (mode === "Editing")
return (
);
return (
cTokenAddress ? cTokenData?.cTokenAddress === cTokenAddress : true
) ? (
{stage === 1 ? (
) : stage === 2 ? (
) : (
// SCREEN3
)}
{/* {needsRetry && } */}
) : (
);
};
export default AssetSettings;
const Title = ({ stage }: { stage: number }) => {
return (
<>
Configure Interest Rate Model Configure Oracle Asset Config Summary
>
);
};
================================================
FILE: src/components/pages/Fuse/Modals/AddAssetModal/DeployButton.tsx
================================================
// Chakra and UI
import { Button } from "@chakra-ui/button";
import { Center } from "@chakra-ui/react";
import { Box } from "@chakra-ui/layout";
// Rari
import { useRari } from "../../../../../context/RariContext";
// Hooks
import { useTranslation } from "react-i18next";
// Components
import TransactionStepper from "components/shared/TransactionStepper";
import { Column } from "utils/chakraUtils";
import { useIsMediumScreen } from "../../FuseTabBar";
import { useAddAssetContext } from "context/AddAssetContext";
const DeployButton = ({ steps, deploy }: { deploy: any; steps: any }) => {
const { t } = useTranslation();
const { fuse } = useRari();
const {
mode,
stage,
tokenData,
activeStep,
isDeploying,
oracleAddress,
handleSetStage,
uniV3BaseTokenOracle,
shouldShowUniV3BaseTokenOracleForm,
needsRetry,
// New stuff
hasPriceForAsset,
hasDefaultOracle,
defaultOracle,
} = useAddAssetContext();
// If user hasnt edited the form and we have a default oracle price for this asset
const hasDefaultOraclePriceAndHasntEdited =
hasDefaultOracle && hasPriceForAsset && oracleAddress === defaultOracle;
// This checks whether the user can proceed in the Oracle Configuration step.
const checkUserOracleConfigurationState = (
oracleAddress: string,
shouldShowUniV3BaseTokenOracleForm: boolean,
uniV3BaseTokenOracle: string
) => {
// If the user needs to configure a BaseToken Oracle for their Univ3 Pair, then disable until its set
if (shouldShowUniV3BaseTokenOracleForm) {
return fuse.web3.utils.isAddress(uniV3BaseTokenOracle);
}
// NEW: If this Fuse pool has a default oracle and price
// AND if the oracle is not set yet in the UI, let them continue
console.log("checkUserOracleConfigurationState", {
hasDefaultOracle,
hasPriceForAsset,
oracleAddress,
hasDefaultOraclePriceAndHasntEdited,
});
if (hasDefaultOraclePriceAndHasntEdited) return true;
// If the oracle address is not set at all, then disable until it is set.
return fuse.web3.utils.isAddress(oracleAddress);
};
const shouldNextButtonBeDisabled = !checkUserOracleConfigurationState(
oracleAddress,
shouldShowUniV3BaseTokenOracleForm,
uniV3BaseTokenOracle
);
return (
{isDeploying ? (
) : null}
);
};
export default DeployButton;
================================================
FILE: src/components/pages/Fuse/Modals/AddAssetModal/IRMChart.tsx
================================================
// Chakra and UI
import {
Box,
Text,
Spinner,
} from "@chakra-ui/react";
import {
Center,
} from "utils/chakraUtils";
// React
import { useTranslation } from "react-i18next";
// Hooks
import { TokenData } from "../../../../../hooks/useTokenData";
// Utils
import { FuseIRMDemoChartOptions } from "../../../../../utils/chartOptions";
// Libraries
import Chart from "react-apexcharts";
const IRMChart = ({
curves,
tokenData,
modal
}: {
curves: any;
tokenData: TokenData;
modal?: boolean;
}) => {
const { t } = useTranslation();
return (
{curves ? (
) : curves === undefined ? (
) : (
{t("No graph is available for this asset's interest curves.")}
)}
);
};
export default IRMChart
================================================
FILE: src/components/pages/Fuse/Modals/AddAssetModal/OracleConfig/BaseTokenOracleConfig.tsx
================================================
// Chakra and UI
import { Input, Box, Text, Select, Alert, AlertIcon } from "@chakra-ui/react";
import { Column, Row } from "utils/chakraUtils";
import { DASHBOARD_BOX_PROPS } from "components/shared/DashboardBox";
import { QuestionIcon } from "@chakra-ui/icons";
import { SimpleTooltip } from "components/shared/SimpleTooltip";
// Components
import { CTokenIcon } from "components/shared/CTokenIcon";
// React
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
// Rari
import { useRari } from "context/RariContext";
// Hooks
import { OracleDataType, useGetOracleOptions } from "hooks/fuse/useOracleData";
import { useAddAssetContext } from "context/AddAssetContext";
const BaseTokenOracleConfig = () => {
const { t } = useTranslation();
const { address } = useRari();
const {
mode,
oracleData,
uniV3BaseTokenAddress,
uniV3BaseTokenOracle,
setUniV3BaseTokenOracle,
baseTokenActiveOracleName,
setBaseTokenActiveOracleName,
} = useAddAssetContext();
const isUserAdmin = address === oracleData?.admin ?? false;
// We get all oracle options.
const options = useGetOracleOptions(oracleData, uniV3BaseTokenAddress);
console.log("helo there", { options });
// If we're editing the asset, show master price oracle as a default.
// Should run only once, when component renders.
useEffect(() => {
if (
mode === "Editing" &&
baseTokenActiveOracleName === "" &&
options &&
options["Current_Price_Oracle"]
)
setBaseTokenActiveOracleName("Current_Price_Oracle");
}, [mode, baseTokenActiveOracleName, options, setBaseTokenActiveOracleName]);
// This will update the oracle address, after user chooses which options they want to use.
// If option is Custom_Oracle oracle address is typed in by user, so we dont trigger this.
useEffect(() => {
if (
!!baseTokenActiveOracleName &&
baseTokenActiveOracleName !== "Custom_Oracle" &&
options
)
setUniV3BaseTokenOracle(options[baseTokenActiveOracleName]);
}, [baseTokenActiveOracleName, options, setUniV3BaseTokenOracle]);
return (
<>
{"This Uniswap V3 TWAP Oracle needs an oracle for the BaseToken."}
{t("BaseToken Price Oracle")}
{options ? (
{baseTokenActiveOracleName.length > 0 ? (
{
const address = event.target.value;
setUniV3BaseTokenOracle(address);
}}
disabled={
baseTokenActiveOracleName === "Custom_Oracle" ? false : true
}
{...DASHBOARD_BOX_PROPS}
_placeholder={{ color: "#e0e0e0" }}
_focus={{ bg: "#121212" }}
_hover={{ bg: "#282727" }}
bg="#282727"
/>
) : null}
) : null}
>
);
};
export default BaseTokenOracleConfig;
================================================
FILE: src/components/pages/Fuse/Modals/AddAssetModal/OracleConfig/OracleConfig.tsx
================================================
// Chakra and UI
import { Input, Box, Text, Select, Spinner, useToast } from "@chakra-ui/react";
import { Center, Row } from "utils/chakraUtils";
import { DASHBOARD_BOX_PROPS } from "../../../../../shared/DashboardBox";
import { SaveButton } from "../../../FusePoolEditPage";
import { QuestionIcon } from "@chakra-ui/icons";
import { SimpleTooltip } from "../../../../../shared/SimpleTooltip";
// React
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "react-query";
// Rari
import { useRari } from "../../../../../../context/RariContext";
// Hooks
import {
useGetOracleOptions,
useIdentifyOracle,
} from "hooks/fuse/useOracleData";
import { createOracle } from "../../../../../../utils/createComptroller";
// Utils
import { handleGenericError } from "../../../../../../utils/errorHandling";
import { isTokenETHOrWETH } from "utils/tokenUtils";
// Components
import UniswapV3PriceOracleConfigurator from "./UniswapV3PriceOracleConfigurator";
import UniswapV2OrSushiPriceOracleConfigurator from "./UniswapV2OrSushiPriceOracleConfigurator";
import BaseTokenOracleConfig from "./BaseTokenOracleConfig";
import { useAddAssetContext } from "context/AddAssetContext";
// const useOraclesLoading = (options: any) => {
// const [isLoading, setIsLoading] = useState(false)
// Object.keys(options).filter((option) => {
// })
// };
const OracleConfig = () => {
const toast = useToast();
const { t } = useTranslation();
const queryClient = useQueryClient();
const { fuse, address } = useRari();
const {
mode,
feeTier,
oracleData,
activeOracleModel,
tokenAddress,
oracleAddress,
oracleTouched,
uniV3BaseTokenAddress,
setOracleTouched,
activeUniSwapPair,
setActiveOracleModel,
setOracleAddress,
poolOracleAddress,
uniV3BaseTokenOracle,
baseTokenActiveOracleName,
shouldShowUniV3BaseTokenOracleForm,
} = useAddAssetContext();
const isUserAdmin = !!oracleData ? address === oracleData.admin : false;
// Available oracle options for asset
const options = useGetOracleOptions(oracleData, tokenAddress);
// Identify token oracle address
const oracleIdentity = useIdentifyOracle(oracleAddress);
const [inputTouched, setInputTouched] = useState(false);
// If user's editing the asset's properties, show the Ctoken's active Oracle
useEffect(() => {
// Map oracleIdentity to whatever the type of `activeOracle` can be
// "Current_Price_Oracle" would only be avialable if you are editing
if (
mode === "Editing" &&
options &&
options["Current_Price_Oracle"] &&
!oracleTouched
) {
setActiveOracleModel("Current_Price_Oracle");
}
// if avaiable, set to "Default_Price_Oracle" if you are adding
if (
mode === "Adding" &&
options &&
!!options["Default_Price_Oracle"] &&
!oracleTouched
) {
setActiveOracleModel("Default_Price_Oracle");
}
// if avaiable, set to "Default_Price_Oracle" if you are adding
if (
mode === "Adding" &&
options &&
!!options["Current_Price_Oracle"] &&
!oracleTouched
) {
setActiveOracleModel("Current_Price_Oracle");
}
}, [
mode,
activeOracleModel,
options,
setActiveOracleModel,
oracleIdentity,
oracleTouched,
]);
// Update the oracle address, after user chooses which option they want to use.
// If option is Custom_Oracle or Uniswap_V3_Oracle, oracle address is changed differently so we dont trigger this.
useEffect(() => {
if (
activeOracleModel.length > 0 &&
activeOracleModel !== "Custom_Oracle" &&
activeOracleModel !== "Uniswap_V3_Oracle" &&
activeOracleModel !== "Uniswap_V2_Oracle" &&
activeOracleModel !== "SushiSwap_Oracle" &&
options
)
setOracleAddress(options[activeOracleModel]);
if (
activeUniSwapPair === "" &&
(activeOracleModel === "Custom_Oracle" ||
activeOracleModel === "Uniswap_V3_Oracle" ||
activeOracleModel === "Uniswap_V2_Oracle" ||
activeOracleModel === "SushiSwap_Oracle") &&
!inputTouched
)
setOracleAddress("");
}, [activeOracleModel, options, setOracleAddress, activeUniSwapPair]);
// Will update oracle for the asset. This is used only if user is editing asset.
const updateOracle = async () => {
const poolOracleContract = createOracle(
poolOracleAddress,
fuse,
"MasterPriceOracle"
);
// This variable will change if we deploy an oracle. (i.e TWAP Oracles)
// If we're using an option that has been deployed it stays the same.
let oracleAddressToUse = oracleAddress;
try {
if (options === null) return null;
// If activeOracle if a TWAP Oracle
if (activeOracleModel === "Uniswap_V3_Oracle") {
// Check for observation cardinality and fix if necessary
await fuse.primeUniswapV3Oracle(oracleAddressToUse, { from: address });
// Deploy oracle
oracleAddressToUse = await fuse.deployPriceOracle(
"UniswapV3TwapPriceOracleV2",
{
feeTier,
baseToken: uniV3BaseTokenAddress,
},
{ from: address }
);
}
const tokenArray =
shouldShowUniV3BaseTokenOracleForm &&
!isTokenETHOrWETH(uniV3BaseTokenAddress)
? [tokenAddress, uniV3BaseTokenAddress]
: [tokenAddress];
const oracleAddressArray =
shouldShowUniV3BaseTokenOracleForm &&
!isTokenETHOrWETH(uniV3BaseTokenAddress)
? [oracleAddressToUse, uniV3BaseTokenOracle]
: [oracleAddressToUse];
console.log({ tokenArray, oracleAddressArray });
// Add oracle to Master Price Oracle
await poolOracleContract.methods
.add(tokenArray, oracleAddressArray)
.send({ from: address });
queryClient.refetchQueries();
// Wait 2 seconds for refetch and then close modal.
// We do this instead of waiting the refetch because some refetches take a while or error out and we want to close now.
await new Promise((resolve) => setTimeout(resolve, 2000));
toast({
title: "You have successfully updated the oracle to this asset!",
description: "Oracle will now point to the new selected address.",
status: "success",
duration: 2000,
isClosable: true,
position: "top-right",
});
setActiveOracleModel("Current_Price_Oracle");
setOracleAddress(options["Current_Price_Oracle"]);
} catch (e) {
handleGenericError(e, toast);
}
};
if (!options)
return (
);
return (
<>
{t("Price Oracle")}
{/* Oracles */}
{activeOracleModel.length > 0 ? (
{
const address = event.target.value;
setInputTouched(true);
setOracleAddress(address);
}}
{...DASHBOARD_BOX_PROPS}
_focus={{ bg: "#121212" }}
_hover={{ bg: "#282727" }}
_placeholder={{ color: "#e0e0e0" }}
disabled={activeOracleModel === "Custom_Oracle" ? false : true}
/>
) : null}
{oracleIdentity}
{activeOracleModel === "Custom_Oracle" && (
Make sure you know what you are doing!
)}
{activeOracleModel === "Uniswap_V3_Oracle" ? (
) : null}
{activeOracleModel === "Uniswap_V2_Oracle" ? (
) : null}
{activeOracleModel === "SushiSwap_Oracle" ? (
) : null}
{shouldShowUniV3BaseTokenOracleForm && mode === "Editing" ? (
) : null}
{activeOracleModel !== "Current_Price_Oracle" && mode === "Editing" ? (
) : null}
>
);
};
export default OracleConfig;
================================================
FILE: src/components/pages/Fuse/Modals/AddAssetModal/OracleConfig/UniswapV2OrSushiPriceOracleConfigurator.tsx
================================================
// Chakra and UI
import { Button, Text, Select, Checkbox } from "@chakra-ui/react";
import { Row } from "utils/chakraUtils";
import { DASHBOARD_BOX_PROPS } from "../../../../../shared/DashboardBox";
import { QuestionIcon } from "@chakra-ui/icons";
import { SimpleTooltip } from "../../../../../shared/SimpleTooltip";
// React
import { useState } from "react";
import { useTranslation } from "react-i18next";
// Hooks
import { useSushiOrUniswapV2Pairs } from "hooks/fuse/useOracleData";
import { useAddAssetContext } from "context/AddAssetContext";
// Utils
import { smallUsdFormatter, shortUsdFormatter } from "utils/bigUtils";
const UniswapV2OrSushiPriceOracleConfigurator = ({
type,
}: {
// Asset's Address. i.e DAI, USDC
// Either SushiSwap or Uniswap V2
type: string;
}) => {
const { t } = useTranslation();
// This will be used to index whitelistPools array (fetched from the graph.)
// It also helps us know if user has selected anything or not. If they have, detail fields are shown.
const [activePool, setActivePair] = useState("");
// Checks if user has started the TWAP bot.
const [checked, setChecked] = useState(false);
// Will store oracle response. This helps us know if its safe to add it to Master Price Oracle
const [checkedStepTwo, setCheckedStepTwo] = useState(false);
const { tokenAddress, setOracleAddress, setUniV3BaseTokenAddress } =
useAddAssetContext();
// Get pair options from sushiswap and uniswap
const { SushiPairs, SushiError, UniV2Pairs, univ2Error } =
useSushiOrUniswapV2Pairs(tokenAddress);
// This is where we conditionally store data depending on type.
// Uniswap V2 or SushiSwap
const Pairs = type === "UniswapV2" ? UniV2Pairs : SushiPairs;
const Error = type === "UniswapV2" ? univ2Error : SushiError;
// Will update active pair, set oracle address and base token.
const updateInfo = (value: string) => {
const pair = Pairs[value];
setActivePair(value);
setOracleAddress(pair.id);
setUniV3BaseTokenAddress(
pair.token1.id === tokenAddress ? pair.token0.id : pair.token1.id
);
};
// If pairs are still being fetched, if theres and error or if there are none, return nothing.
if (Pairs === undefined || Error || Pairs === null) return null;
return (
<>
setChecked(!checked)}>
Using this type of oracle requires you to run a TWAP bot.
{checked ? (
After deploying your oracle, you have to wait about 15 - 25 minutes
for the oracle to be set.
) : null}
{true ? (
{t("Pool:")}
) : null}
{activePool.length > 0 ? (
{t("Liquidity:")}
) : null}
>
);
};
export default UniswapV2OrSushiPriceOracleConfigurator;
================================================
FILE: src/components/pages/Fuse/Modals/AddAssetModal/OracleConfig/UniswapV3PriceOracleConfigurator.tsx
================================================
// Chakra and UI
import { Text, Select, Link, Alert, AlertIcon } from "@chakra-ui/react";
import { Column, Row } from "utils/chakraUtils";
import { DASHBOARD_BOX_PROPS } from "../../../../../shared/DashboardBox";
import { QuestionIcon } from "@chakra-ui/icons";
import { SimpleTooltip } from "../../../../../shared/SimpleTooltip";
// React
import { useTranslation } from "react-i18next";
import { useQuery } from "react-query";
// Axios
import axios from "axios";
// Utils
import { shortUsdFormatter } from "utils/bigUtils";
import { useAddAssetContext } from "context/AddAssetContext";
import { useMemo } from "react";
const UniswapV3PriceOracleConfigurator = () => {
const { t } = useTranslation();
const {
setFeeTier,
tokenAddress,
setOracleAddress,
setUniV3BaseTokenAddress,
activeUniSwapPair,
setActiveUniSwapPair,
} = useAddAssetContext();
// We get a list of whitelistedPools from uniswap-v3's the graph.
const { data: liquidity, error } = useQuery(
"UniswapV3 pool liquidity for " + tokenAddress,
async () =>
(
await axios.post(
"https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3",
{
query: `{
token(id:"${tokenAddress.toLowerCase()}") {
whitelistPools {
id,
feeTier,
volumeUSD,
totalValueLockedUSD,
token0 {
symbol,
id,
name
},
token1 {
symbol,
id,
name
}
}
}
}`,
}
)
).data,
{ refetchOnMount: false }
);
// When user selects an option this function will be called.
// Active pool, fee Tier, and base token are updated and we set the oracle address to the address of the pool we chose.
const updateBoth = (value: string) => {
const uniPool = liquidity.data.token.whitelistPools[value];
const baseToken: string =
uniPool.token0.id.toLowerCase() === tokenAddress.toLocaleLowerCase()
? uniPool.token1.id
: uniPool.token0.id;
setActiveUniSwapPair(value);
setFeeTier(uniPool.feeTier);
setOracleAddress(uniPool.id);
setUniV3BaseTokenAddress(baseToken);
};
// If liquidity is undefined, theres an error or theres no token found return nothing.
if (liquidity === undefined || liquidity.data === undefined)
return null;
// Sort whitelisted pools by TVL. Greatest to smallest. Greater TVL is safer for users so we show it first.
// Filter out pools where volume is less than $100,000
const liquiditySorted = liquidity.data.token.whitelistPools.sort(
(a: any, b: any): any =>
parseInt(a.totalValueLockedUSD) > parseInt(b.totalValueLockedUSD) ? -1 : 1
);
// .filter((pool: any) => pool.volumeUSD >= 100000);
const selectedOracle = liquidity.data.token.whitelistPools[activeUniSwapPair];
console.log({ selectedOracle });
// const warning = useMemo(() => {
// if (selectedOracle.liquidityProviderCount <=100)
// }, [selectedOracle]);
return (
<>
{t("Pool:")}
{activeUniSwapPair !== "" ? (
{
"Make sure this Uniswap V3 Pool has full-range liquidity. If not, your pool could be compromised."
}
{t("Liquidity:")}