Skip to content

Commit

Permalink
fix: dApp new contracts
Browse files Browse the repository at this point in the history
  • Loading branch information
andyv09 committed Aug 12, 2024
1 parent d058181 commit 53f47e1
Show file tree
Hide file tree
Showing 11 changed files with 109 additions and 868 deletions.
34 changes: 26 additions & 8 deletions apps/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"@fuels/connectors": "^0.5.0",
"@fuels/react": "^0.20.0",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.3",
"@pythnetwork/pyth-fuel-js": "^1.0.1",
"@pythnetwork/pyth-fuel-js": "^1.0.3",
"@svgr/webpack": "^6.5.1",
"@tanstack/react-query": "^5.51.11",
"@tanstack/react-query-devtools": "^5.51.11",
Expand Down Expand Up @@ -109,21 +109,37 @@
"node": ">=20.15.0"
},
"eslintConfig": {
"extends": ["react-app", "react-app/jest"]
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [">0.2%", "not dead", "not op_mini all"],
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"jest": {
"roots": ["<rootDir>/src"],
"collectCoverageFrom": ["src/**/*.{js,jsx,ts,tsx}", "!src/**/*.d.ts"],
"setupFiles": ["react-app-polyfill/jsdom"],
"setupFilesAfterEnv": ["<rootDir>/src/setupTests.ts"],
"roots": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
],
"setupFiles": [
"react-app-polyfill/jsdom"
],
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.ts"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
Expand Down Expand Up @@ -162,7 +178,9 @@
"resetMocks": true
},
"babel": {
"presets": ["react-app"]
"presets": [
"react-app"
]
},
"devDependencies": {
"@types/lodash": "^4.14.191",
Expand Down
14 changes: 13 additions & 1 deletion apps/frontend/src/hooks/useCollateralUtilization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,33 @@ export const useCollateralUtilization = (
rootStore.accountStore.addressInput?.value ?? ''
);

// console.log('collateralBalances', collateralBalances);
// console.log('assetsConfigs', assetsConfigs);
// console.log('userSupplyBorrow', userSupplyBorrow);

const trueCollateralsValue = useMemo(() => {
if (collateralBalances == null || assetsConfigs == null) return BN.ZERO;
return Object.entries(collateralBalances!).reduce((acc, [assetId, v]) => {
const token = TOKENS_BY_ASSET_ID[assetId];
const liquidationFactor = BN.formatUnits(
assetsConfigs![assetId].liquidate_collateral_factor.toString(),
4
18
);
const balance = BN.formatUnits(v, token.decimals);
const dollBalance = getTokenPrice(assetId).times(balance);
console.log('token', token.name);
console.log('dollBalance', dollBalance.toFixed(2));
console.log('liquidationFactor', liquidationFactor.toFixed(2));
console.log('balance', balance.toFixed(2));
console.log('liquidationFactor', liquidationFactor.toFixed(2));
const trueDollBalance = dollBalance.times(liquidationFactor);
console.log('trueDollBalance', trueDollBalance.toFixed(2));
return acc.plus(trueDollBalance);
}, BN.ZERO);
}, [collateralBalances, assetsConfigs]);

console.log('trueCollateralsValue', trueCollateralsValue.toFixed(2));

const borrowedBalance = useMemo(() => {
if (userSupplyBorrow == null) return BN.ZERO;
return userSupplyBorrow[1];
Expand Down
31 changes: 10 additions & 21 deletions apps/frontend/src/hooks/usePrice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,19 @@ const PRICE_FEEDS = {
symbol: 'Crypto.ETH/USD',
id: '0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace',
},
'0xb3a405892c0725ae9cfc117306752f623e3f357963b7489636b83d4842f96d62': {
'0x7d9d3e3df2900080f47b5e55c0501e153d21e67a2cdf86cb86ff5b717daab767': {
symbol: 'Crypto.BTC/USD',
id: '0x56a3121958b01f99fdc4e1fd01e81050602c7ace3a571918bb55c6a96657cca9',
id: '0xe62df6c8b4a85fe1a67db44dc12de5db330f7ac66b72dc658afedf0f4a415b43',
},
'0x403489ee55a733cce6deb3e46e16a0ded38f902ff70224df97e15c243319b6f3': {
'0x23e8c3a2fc7a10cfa612da898d1cb3c0f0bb2a94de29ec4fa742bd2f690d9a67': {
symbol: 'Crypto.USDC/USD',
id: '0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a',
},
};
'0x7a31611c81e974db193570a6b918d083cbf223ddfef0cce18e02746b21ea8964': {
symbol: 'Crypto.UNI/USD',
id: '0x78d185a741d07edb3412b09008b7c5cfb9bbbd7d568bf00ba737b456ba171501',
},
} as Record<string, any>;

export const usePrice = (assetIds: string[]) => {
const [wallet, setWallet] = useState<WalletUnlocked | null>(null);
Expand All @@ -33,32 +37,17 @@ export const usePrice = (assetIds: string[]) => {
}, []);

const oracleContract = new Contract(
PYTH_CONTRACT_ADDRESS_SEPOLIA,
'0x73591bf32f010ce4e83d86005c24e7833b397be38014ab670a73f6fde59ad607',
PYTH_CONTRACT_ABI,
wallet!
);

const fetchPrice = async (assetId: string) => {
if (
assetId ===
'0xb3a405892c0725ae9cfc117306752f623e3f357963b7489636b83d4842f96d62'
)
return new BN(66292.123);

if (
assetId !==
'0xf8f8b6283d7fa5b672b530cbb84fcccb4ff8dc40f8176ef4544ddb1f1952ad07' &&
assetId !==
'0xb3a405892c0725ae9cfc117306752f623e3f357963b7489636b83d4842f96d62' &&
assetId !==
'0x403489ee55a733cce6deb3e46e16a0ded38f902ff70224df97e15c243319b6f3'
)
throw new Error('Invalid assetId');
const { value } = await oracleContract.functions
.price_unsafe(PRICE_FEEDS[assetId].id)
.get();
if (!value) throw new Error('Failed to fetch price');

if (!value) throw new Error('Failed to fetch price');
const previousPrice = value.price.toNumber() * 10 ** -value.exponent;

return new BN(previousPrice.toString());
Expand Down
11 changes: 6 additions & 5 deletions apps/frontend/src/screens/Dashboard/ActionTab/ActionTab.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Button from '@components/Button';
import SizedBox from '@components/SizedBox';
import styled from '@emotion/styled';
import { PYTH_CONTRACT_ABI } from '@pythnetwork/pyth-fuel-js';
import InputCard from '@screens/Dashboard/ActionTab/InputCard';
import useCollapse from '@src/components/Collapse';
import { Row } from '@src/components/Flex';
Expand All @@ -11,7 +12,7 @@ import { ACTION_TYPE } from '@src/stores/DashboardStore';
import { getMarketContract, getOracleContract } from '@src/utils/readContracts';
import { initProvider, walletToRead } from '@src/utils/walletToRead';
import { useStores } from '@stores';
import type { Provider, WalletUnlocked } from 'fuels';
import { Contract, type Provider, type WalletUnlocked } from 'fuels';
import { observer } from 'mobx-react-lite';
import type React from 'react';
import { useEffect, useState } from 'react';
Expand All @@ -38,10 +39,10 @@ const ActionTab: React.FC<IProps> = () => {
wallet!,
settingsStore.currentVersionConfig
);
const oracleContract = getOracleContract(
wallet!,
provider!,
settingsStore.currentVersionConfig
const oracleContract = new Contract(
'0x73591bf32f010ce4e83d86005c24e7833b397be38014ab670a73f6fde59ad607',
PYTH_CONTRACT_ABI,
wallet!
);
const { data: userSupplyBorrow, isSuccess: isSuccessUserSupplyBorrow } =
useUserSupplyBorrow(marketContract, accountStore.addressInput?.value ?? '');
Expand Down
11 changes: 6 additions & 5 deletions apps/frontend/src/screens/Dashboard/ActionTab/InputCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import useCollapse from '@components/Collapse';
import Notification from '@components/Notification';
import SizedBox from '@components/SizedBox';
import TokenInput from '@components/TokenInput/TokenInput';
import { PYTH_CONTRACT_ABI } from '@pythnetwork/pyth-fuel-js';
import SummaryCard from '@screens/Dashboard/SummaryCard';
import Card from '@src/components/Card';
import { Row } from '@src/components/Flex';
Expand All @@ -29,7 +30,7 @@ import {
import { getMarketContract, getOracleContract } from '@src/utils/readContracts';
import { initProvider, walletToRead } from '@src/utils/walletToRead';
import { useStores } from '@stores';
import type { Provider, WalletUnlocked } from 'fuels';
import { Contract, type Provider, type WalletUnlocked } from 'fuels';
import { observer } from 'mobx-react-lite';
import type React from 'react';
import { useEffect, useState } from 'react';
Expand All @@ -51,10 +52,10 @@ const InputCard: React.FC<IProps> = () => {
wallet!,
settingsStore.currentVersionConfig
);
const oracleContract = getOracleContract(
wallet!,
provider!,
settingsStore.currentVersionConfig
const oracleContract = new Contract(
'0x73591bf32f010ce4e83d86005c24e7833b397be38014ab670a73f6fde59ad607',
PYTH_CONTRACT_ABI,
wallet!
);

const {
Expand Down
15 changes: 8 additions & 7 deletions apps/frontend/src/screens/Dashboard/SummaryCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Divider from '@components/Divider';
import { Row } from '@components/Flex';
import SizedBox from '@components/SizedBox';
import Text from '@components/Text';
import { PYTH_CONTRACT_ABI } from '@pythnetwork/pyth-fuel-js';
import { TOKENS_BY_ASSET_ID } from '@src/constants';
import { useAvailableToBorrow } from '@src/hooks/useAvailableToBorrow';
import { useBalanceOf } from '@src/hooks/useBalanceOf';
Expand All @@ -22,7 +23,7 @@ import {
} from '@src/utils/dashboardUtils';
import { getMarketContract, getOracleContract } from '@src/utils/readContracts';
import { initProvider, walletToRead } from '@src/utils/walletToRead';
import type { Provider, WalletUnlocked } from 'fuels';
import { Contract, type Provider, type WalletUnlocked } from 'fuels';
import { observer } from 'mobx-react-lite';
import type React from 'react';
import { useEffect, useMemo, useState } from 'react';
Expand Down Expand Up @@ -50,17 +51,17 @@ const SummaryCard: React.FC<IProps> = () => {
walletToRead().then((w) => setWallet(w));
initProvider().then((p) => setProvider(p));
}, []);

const oracleContract = getOracleContract(
wallet!,
provider!,
settingsStore.currentVersionConfig
);
const marketContract = getMarketContract(
wallet!,
settingsStore.currentVersionConfig
);

const oracleContract = new Contract(
'0x73591bf32f010ce4e83d86005c24e7833b397be38014ab670a73f6fde59ad607',
PYTH_CONTRACT_ABI,
wallet!
);

const { data: maxBorrowAmount } = useAvailableToBorrow(
marketContract,
oracleContract,
Expand Down
56 changes: 28 additions & 28 deletions apps/frontend/src/stores/PricesStore.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { type IToken, TOKENS_LIST } from '@src/constants';
import { OracleAbi__factory } from '@src/contract-types';
import { PYTH_CONTRACT_ABI } from '@pythnetwork/pyth-fuel-js';
import BN from '@src/utils/BN';
import type RootStore from '@stores/RootStore';
import { makeAutoObservable, reaction } from 'mobx';
Expand Down Expand Up @@ -43,35 +43,35 @@ class PricesStore {
updateTokenPrices = async () => {
const { settingsStore, accountStore } = this.rootStore;
const { priceOracle } = settingsStore.currentVersionConfig;
try {
const wallet = accountStore.walletToRead;
if (wallet == null) return;
const oracleContract = OracleAbi__factory.connect(priceOracle, wallet);
// try {
// const wallet = accountStore.walletToRead;
// if (wallet == null) return;
// const oracleContract = OracleAbi__factory.connect(priceOracle, wallet);

const response = await Promise.all(
TOKENS_LIST.map((token) =>
oracleContract.functions.get_price(token.assetId).dryRun()
)
);
console.log(response);
// const response = await Promise.all(
// TOKENS_LIST.map((token) =>
// oracleContract.functions.get_price(token.assetId).dryRun()
// )
// );
// console.log(response);

// TODO[old] change to locked wallet
// console.log("response", response);
if (response.length > 0) {
const v = response.reduce(
(acc, { value }) => ({
// biome-ignore lint/performance/noAccumulatingSpread: <explanation>
...acc,
[value.asset_id]: BN.formatUnits(value.price.toString(), 9),
}),
{}
);
this.setTokensPrices(v);
}
} catch (e) {
console.log('updateTokenPrices error');
console.log(e);
}
// // TODO[old] change to locked wallet
// // console.log("response", response);
// if (response.length > 0) {
// const v = response.reduce(
// (acc, { value }) => ({
// // biome-ignore lint/performance/noAccumulatingSpread: <explanation>
// ...acc,
// [value.asset_id]: BN.formatUnits(value.price.toString(), 9),
// }),
// {}
// );
// this.setTokensPrices(v);
// }
// } catch (e) {
// console.log('updateTokenPrices error');
// console.log(e);
// }
};
}

Expand Down
2 changes: 1 addition & 1 deletion apps/frontend/src/utils/dashboardUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export function getTrueTotalCollateralBalance(
const token = TOKENS_BY_ASSET_ID[assetId];
const liquidationFactor = BN.formatUnits(
assetsConfigs[assetId].liquidate_collateral_factor.toString(),
4
18
);
const balance = BN.formatUnits(v, token.decimals);
const dollBalance = getTokenPrice(assetId).times(balance);
Expand Down
7 changes: 4 additions & 3 deletions apps/frontend/src/utils/marketUtils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { type MarketAbi, OracleAbi__factory } from '@src/contract-types';
import type { MarketAbi } from '@src/contract-types';
import { PYTH_CONTRACT_ABI } from '@pythnetwork/pyth-fuel-js';
import type { AccountStore, DashboardStore, SettingsStore } from '@src/stores';
import { Contract } from 'fuels';
import type BN from './BN';
Expand Down Expand Up @@ -69,7 +70,7 @@ export const withdrawCollateral = async (
if (accountStore.provider == null) return;
const oracle = new Contract(
priceOracle,
OracleAbi__factory.abi,
PYTH_CONTRACT_ABI,
accountStore.provider
);

Expand Down Expand Up @@ -99,7 +100,7 @@ export const borrowBase = async (
if (accountStore.provider == null) return;
const oracle = new Contract(
priceOracle,
OracleAbi__factory.abi,
PYTH_CONTRACT_ABI,
accountStore.provider
);
return market.functions
Expand Down
5 changes: 3 additions & 2 deletions apps/frontend/src/utils/readContracts.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { IContractsConfig } from '@src/constants';
import { MarketAbi__factory, OracleAbi__factory } from '@src/contract-types';
import { MarketAbi__factory } from '@src/contract-types';
import { PYTH_CONTRACT_ABI } from '@pythnetwork/pyth-fuel-js';
import { Contract, type Provider, type WalletUnlocked } from 'fuels';

export const getMarketContract = (
Expand All @@ -16,5 +17,5 @@ export const getOracleContract = (
currentVersionConfig: IContractsConfig
) => {
const { priceOracle } = currentVersionConfig;
return new Contract(priceOracle, OracleAbi__factory.abi, provider);
return new Contract(priceOracle, PYTH_CONTRACT_ABI, provider);
};
Loading

0 comments on commit 53f47e1

Please sign in to comment.