From b1b2bc2963ef393bcbc3d1df765967c0d1a3360c Mon Sep 17 00:00:00 2001 From: bojan07 Date: Mon, 2 Oct 2023 02:01:59 -0700 Subject: [PATCH 01/19] feat: apply diamond to home page --- .../dapp/components/redeem/lib/use-prices.ts | 22 +++++++++++-------- packages/dapp/pages/index.tsx | 10 ++++----- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/packages/dapp/components/redeem/lib/use-prices.ts b/packages/dapp/components/redeem/lib/use-prices.ts index cf4df037d..fb15312dd 100644 --- a/packages/dapp/components/redeem/lib/use-prices.ts +++ b/packages/dapp/components/redeem/lib/use-prices.ts @@ -1,20 +1,24 @@ -import useDeployedContracts from "@/components/lib/hooks/contracts/use-deployed-contracts"; -import useManagerManaged from "@/components/lib/hooks/contracts/use-manager-managed"; +import { getIMetaPoolContract } from "@/components/utils/contracts"; +import useProtocolContracts from "@/components/lib/hooks/contracts/use-protocol-contracts"; +import useWeb3 from "@/components/lib/hooks/use-web-3"; import { BigNumber, utils } from "ethers"; import { useEffect, useState } from "react"; const usePrices = (): [BigNumber | null, BigNumber | null, () => Promise] => { - const deployedContracts = useDeployedContracts(); - const managedContracts = useManagerManaged(); + const protocolContracts = useProtocolContracts(); + const { provider } = useWeb3(); const [twapPrice, setTwapPrice] = useState(null); const [spotPrice, setSpotPrice] = useState(null); async function refreshPrices() { - if (managedContracts && deployedContracts) { - const dollarTokenAddress = await deployedContracts.manager.dollarTokenAddress(); - const newTwapPrice = await managedContracts.dollarTwapOracle.consult(dollarTokenAddress); - const newSpotPrice = await managedContracts.dollarMetapool["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); + if (protocolContracts && provider) { + const dollarTokenAddress = protocolContracts.managerFacet && await protocolContracts.managerFacet.dollarTokenAddress(); + const newTwapPrice = protocolContracts.twapOracleDollar3poolFacet && await protocolContracts.twapOracleDollar3poolFacet.consult(dollarTokenAddress); + + const dollar3poolMarket = protocolContracts.managerFacet && await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); + const dollarMetapool = getIMetaPoolContract(dollar3poolMarket, provider) + const newSpotPrice = await dollarMetapool["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); setTwapPrice(newTwapPrice); setSpotPrice(newSpotPrice); } @@ -22,7 +26,7 @@ const usePrices = (): [BigNumber | null, BigNumber | null, () => Promise] useEffect(() => { refreshPrices(); - }, [managedContracts, deployedContracts]); + }, [protocolContracts, provider]); return [twapPrice, spotPrice, refreshPrices]; }; diff --git a/packages/dapp/pages/index.tsx b/packages/dapp/pages/index.tsx index 7dd1f428f..6003cdfbc 100644 --- a/packages/dapp/pages/index.tsx +++ b/packages/dapp/pages/index.tsx @@ -2,7 +2,7 @@ import { ethers } from "ethers"; import { FC, useState } from "react"; import "@uniswap/widgets/fonts.css"; -import useManagerManaged from "@/components/lib/hooks/contracts/use-manager-managed"; +import useProtocolContracts from "@/components/lib/hooks/contracts/use-protocol-contracts"; import useEffectAsync from "@/components/lib/hooks/use-effect-async"; import DollarPrice from "@/components/redeem/dollar-price"; import { fetchData } from "@/components/utils/local-data"; @@ -12,10 +12,10 @@ const WalletConnectionWall = dynamic(() => import("@/components/ui/wallet-connec const index: FC = (): JSX.Element => { const [twapPrice, setTwapPrice] = useState(null); - const managedContracts = useManagerManaged(); + const protocolContracts = useProtocolContracts(); useEffectAsync(async () => { - if (managedContracts != null) { + if (protocolContracts != null) { try { console.log(twapPrice, "priced in "); } catch (error) { @@ -23,10 +23,10 @@ const index: FC = (): JSX.Element => { setTwapPrice(null); } } else { - console.log("managedContracts is null"); + console.log("protocolContracts is null"); setTwapPrice(null); } - }, [managedContracts]); + }, [protocolContracts]); if (process.env.DEBUG === "true") { fetchData(); From dd22fa0d1887b89953293a705a544250fcb6583a Mon Sep 17 00:00:00 2001 From: bojan07 Date: Tue, 3 Oct 2023 05:39:24 -0400 Subject: [PATCH 02/19] fix: added debug option to refreshPrices function --- packages/dapp/components/redeem/lib/use-prices.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/dapp/components/redeem/lib/use-prices.ts b/packages/dapp/components/redeem/lib/use-prices.ts index fb15312dd..4fb336373 100644 --- a/packages/dapp/components/redeem/lib/use-prices.ts +++ b/packages/dapp/components/redeem/lib/use-prices.ts @@ -12,7 +12,11 @@ const usePrices = (): [BigNumber | null, BigNumber | null, () => Promise] const [spotPrice, setSpotPrice] = useState(null); async function refreshPrices() { - if (protocolContracts && provider) { + try { + if(!protocolContracts || !provider) { + return; + } + const dollarTokenAddress = protocolContracts.managerFacet && await protocolContracts.managerFacet.dollarTokenAddress(); const newTwapPrice = protocolContracts.twapOracleDollar3poolFacet && await protocolContracts.twapOracleDollar3poolFacet.consult(dollarTokenAddress); @@ -21,6 +25,8 @@ const usePrices = (): [BigNumber | null, BigNumber | null, () => Promise] const newSpotPrice = await dollarMetapool["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); setTwapPrice(newTwapPrice); setSpotPrice(newSpotPrice); + } catch (error) { + console.log("Error in refreshPrices: ", error) } } From b2bbdcab4a8dda5434cad9cb4f3ab933e8fd1987 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Tue, 3 Oct 2023 07:51:03 -0400 Subject: [PATCH 03/19] fix: make code clean in use-prices --- .../dapp/components/redeem/lib/use-prices.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/dapp/components/redeem/lib/use-prices.ts b/packages/dapp/components/redeem/lib/use-prices.ts index 4fb336373..9b22d050e 100644 --- a/packages/dapp/components/redeem/lib/use-prices.ts +++ b/packages/dapp/components/redeem/lib/use-prices.ts @@ -17,14 +17,16 @@ const usePrices = (): [BigNumber | null, BigNumber | null, () => Promise] return; } - const dollarTokenAddress = protocolContracts.managerFacet && await protocolContracts.managerFacet.dollarTokenAddress(); - const newTwapPrice = protocolContracts.twapOracleDollar3poolFacet && await protocolContracts.twapOracleDollar3poolFacet.consult(dollarTokenAddress); - - const dollar3poolMarket = protocolContracts.managerFacet && await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); - const dollarMetapool = getIMetaPoolContract(dollar3poolMarket, provider) - const newSpotPrice = await dollarMetapool["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); - setTwapPrice(newTwapPrice); - setSpotPrice(newSpotPrice); + if(protocolContracts.managerFacet && protocolContracts.twapOracleDollar3poolFacet) { + const dollarTokenAddress = await protocolContracts.managerFacet.dollarTokenAddress(); + const newTwapPrice = await protocolContracts.twapOracleDollar3poolFacet.consult(dollarTokenAddress); + const dollar3poolMarket = await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); + const dollarMetapool = getIMetaPoolContract(dollar3poolMarket, provider) + const newSpotPrice = await dollarMetapool["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); + setTwapPrice(newTwapPrice); + setSpotPrice(newSpotPrice); + } + } catch (error) { console.log("Error in refreshPrices: ", error) } From 8da767d25ee05a3055c0b64b7f9c524623e05868 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Tue, 3 Oct 2023 16:54:31 -0400 Subject: [PATCH 04/19] feat: used protocol-contracts in use-balances and use-named-contracts --- .../hooks/contracts/use-named-contracts.tsx | 12 +------- .../components/lib/hooks/use-balances.tsx | 30 ++++++++++++------- packages/dapp/components/lib/utils.ts | 6 ++-- 3 files changed, 23 insertions(+), 25 deletions(-) diff --git a/packages/dapp/components/lib/hooks/contracts/use-named-contracts.tsx b/packages/dapp/components/lib/hooks/contracts/use-named-contracts.tsx index 61723bd0f..d8ce7d7dd 100644 --- a/packages/dapp/components/lib/hooks/contracts/use-named-contracts.tsx +++ b/packages/dapp/components/lib/hooks/contracts/use-named-contracts.tsx @@ -1,16 +1,7 @@ import useWeb3, { PossibleProviders } from "../use-web-3"; -import Deployed_Contracts from "@ubiquity/contracts/deployments.json"; import NAMED_ACCOUNTS from "../../../config/named-accounts.json"; -import { getCurveFactoryContract, getDebtCouponManagerContract, getERC20Contract, getIJarContract, getYieldProxyContract } from "@/components/utils/contracts"; - -const getDebtCouponManagerAddress = () => { - const contractDeployments: Record = Deployed_Contracts; - const record = contractDeployments["1"] ?? {}; - const contract = record?.contracts ? record?.contracts["DebtCouponManager"] : undefined; - return contract ? contract.address : undefined; -}; -export const DEBT_COUPON_MANAGER_ADDRESS = getDebtCouponManagerAddress(); +import { getCurveFactoryContract, getERC20Contract, getIJarContract, getYieldProxyContract } from "@/components/utils/contracts"; export type NamedContracts = ReturnType | null; export function connectedContracts(provider: NonNullable) { @@ -20,7 +11,6 @@ export function connectedContracts(provider: NonNullable) { usdc: getERC20Contract(NAMED_ACCOUNTS.USDC, provider), dai: getERC20Contract(NAMED_ACCOUNTS.DAI, provider), usdt: getERC20Contract(NAMED_ACCOUNTS.USDT, provider), - debtCouponManager: getDebtCouponManagerContract(DEBT_COUPON_MANAGER_ADDRESS, provider), jarUsdc: getIJarContract(NAMED_ACCOUNTS.jarUSDCAddr, provider), }; } diff --git a/packages/dapp/components/lib/hooks/use-balances.tsx b/packages/dapp/components/lib/hooks/use-balances.tsx index 6eaf6c53a..6fbb3c07e 100644 --- a/packages/dapp/components/lib/hooks/use-balances.tsx +++ b/packages/dapp/components/lib/hooks/use-balances.tsx @@ -1,10 +1,12 @@ import { erc1155BalanceOf } from "@/lib/utils"; import { BigNumber, Contract } from "ethers"; import { createContext, useContext, useEffect, useState } from "react"; -import useManagerManaged from "./contracts/use-manager-managed"; import useNamedContracts from "./contracts/use-named-contracts"; import useWalletAddress from "./use-wallet-address"; import { ChildrenShim } from "./children-shim-d"; +import useProtocolContracts from "@/components/lib/hooks/contracts/use-protocol-contracts"; +import { getERC20Contract, getIMetaPoolContract } from "@/components/utils/contracts"; +import useWeb3 from "@/components/lib/hooks/use-web-3"; export interface Balances { uad: BigNumber; @@ -26,19 +28,25 @@ export const BalancesContext = createContext<[Balances | null, RefreshBalances]> export const BalancesContextProvider: React.FC = ({ children }) => { const [balances, setBalances] = useState(null); const [walletAddress] = useWalletAddress(); - const managedContracts = useManagerManaged(); const namedContracts = useNamedContracts(); + const protocolContracts = useProtocolContracts(); + const { provider } = useWeb3(); async function refreshBalances() { - if (walletAddress && managedContracts && namedContracts) { + if (walletAddress && namedContracts && protocolContracts && provider) { + const _3crvToken = protocolContracts.managerFacet && await protocolContracts.managerFacet.curve3PoolTokenAddress(); + const dollar3poolMarket = protocolContracts.managerFacet && await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); + const _3crvTokenContract = getERC20Contract(_3crvToken, provider); + const dollarMetapool = getIMetaPoolContract(dollar3poolMarket, provider); + const [uad, _3crv, uad3crv, ucr, ubq, ucrNft, stakingShares, usdc, dai, usdt] = await Promise.all([ - managedContracts.dollarToken.balanceOf(walletAddress), - managedContracts._3crvToken.balanceOf(walletAddress), - managedContracts.dollarMetapool.balanceOf(walletAddress), - managedContracts.creditToken.balanceOf(walletAddress), - managedContracts.governanceToken.balanceOf(walletAddress), - erc1155BalanceOf(walletAddress, managedContracts.creditNft), - erc1155BalanceOf(walletAddress, managedContracts.stakingToken), + protocolContracts.dollarToken && protocolContracts.dollarToken.balanceOf(walletAddress), + _3crvTokenContract.balanceOf(walletAddress), + dollarMetapool.balanceOf(walletAddress), + protocolContracts.creditToken && protocolContracts.creditToken.balanceOf(walletAddress), + protocolContracts.governanceToken && protocolContracts.governanceToken.balanceOf(walletAddress), + erc1155BalanceOf(walletAddress, protocolContracts.creditNft), + erc1155BalanceOf(walletAddress, protocolContracts.stakingShare), namedContracts.usdc.balanceOf(walletAddress), namedContracts.dai.balanceOf(walletAddress), namedContracts.usdt.balanceOf(walletAddress), @@ -61,7 +69,7 @@ export const BalancesContextProvider: React.FC = ({ children }) => useEffect(() => { refreshBalances(); - }, [walletAddress, managedContracts]); + }, [walletAddress, protocolContracts]); return {children}; }; diff --git a/packages/dapp/components/lib/utils.ts b/packages/dapp/components/lib/utils.ts index 2caf22cb1..65854ba7f 100644 --- a/packages/dapp/components/lib/utils.ts +++ b/packages/dapp/components/lib/utils.ts @@ -30,11 +30,11 @@ export async function performTransaction(transaction: Promise { - const treasuryIds = await erc1155UbiquityCtr.holderTokens(addr); +export async function erc1155BalanceOf(addr: string, erc1155UbiquityCtr: Contract | null): Promise { + const treasuryIds = erc1155UbiquityCtr && await erc1155UbiquityCtr.holderTokens(addr); const balanceOfs = treasuryIds.map((id: string) => { - return erc1155UbiquityCtr.balanceOf(addr, id); + return erc1155UbiquityCtr && erc1155UbiquityCtr.balanceOf(addr, id); }); const balances = await Promise.all(balanceOfs); let fullBalance = BigNumber.from(0); From b3a3856e64961f83d0f67b69dbf4f3bec6581580 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Tue, 3 Oct 2023 19:15:54 -0400 Subject: [PATCH 05/19] feat: applied protocol-contracts to child components of staking page --- .../hooks/contracts/use-protocol-contracts.ts | 1 + .../components/lib/with-loaded-context.tsx | 15 +++----- .../staking/bonding-shares-explorer.tsx | 22 ++++++++---- .../dapp/components/staking/deposit-share.tsx | 35 +++++++++++++------ 4 files changed, 46 insertions(+), 27 deletions(-) diff --git a/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts b/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts index a36d68409..14feeee61 100644 --- a/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts +++ b/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts @@ -52,6 +52,7 @@ import UbiquityPoolFacetArtifact from "@ubiquity/contracts/out/UbiquityPoolFacet * Contracts on hold (i.e. obsolete) until we find a better utility for them: * - https://github.com/ubiquity/ubiquity-dollar/tree/development/packages/contracts/src/ubiquistick */ +export type ProtocolContracts = ReturnType | null; const useProtocolContracts = () => { // get current web3 provider const { provider } = useWeb3(); diff --git a/packages/dapp/components/lib/with-loaded-context.tsx b/packages/dapp/components/lib/with-loaded-context.tsx index 53ce24cd2..690575c4f 100644 --- a/packages/dapp/components/lib/with-loaded-context.tsx +++ b/packages/dapp/components/lib/with-loaded-context.tsx @@ -1,13 +1,10 @@ import { ethers } from "ethers"; -import useDeployedContracts, { DeployedContracts } from "./hooks/contracts/use-deployed-contracts"; -import { ManagedContracts } from "./hooks/contracts/use-manager-managed"; +import useProtocolContracts, { ProtocolContracts } from "./hooks/contracts/use-protocol-contracts"; import useNamedContracts, { NamedContracts } from "./hooks/contracts/use-named-contracts"; import useWeb3, { PossibleProviders } from "./hooks/use-web-3"; -import useManagerManaged from "@/components/lib/hooks/contracts/use-manager-managed"; export type LoadedContext = { - managedContracts: NonNullable; - deployedContracts: NonNullable; + protocolContracts: NonNullable; namedContracts: NonNullable; web3Provider: NonNullable; walletAddress: string; @@ -17,19 +14,17 @@ export type LoadedContext = { export default function withLoadedContext(El: (params: LoadedContext & T) => JSX.Element, ElNull?: () => JSX.Element) { return (otherParams: T) => { const { walletAddress, signer, provider } = useWeb3(); - const managedContracts = useManagerManaged(); - const deployedContracts = useDeployedContracts(); const namedContracts = useNamedContracts(); + const protocolContracts = useProtocolContracts(); - if (provider && walletAddress && signer && managedContracts && deployedContracts && namedContracts) { + if (provider && walletAddress && signer && protocolContracts && namedContracts) { return ( ); diff --git a/packages/dapp/components/staking/bonding-shares-explorer.tsx b/packages/dapp/components/staking/bonding-shares-explorer.tsx index 014420123..2958d1453 100644 --- a/packages/dapp/components/staking/bonding-shares-explorer.tsx +++ b/packages/dapp/components/staking/bonding-shares-explorer.tsx @@ -4,6 +4,7 @@ import { memo, useCallback, useState } from "react"; import { formatEther } from "@/lib/format"; import { performTransaction, useAsyncInit } from "@/lib/utils"; import withLoadedContext, { LoadedContext } from "@/lib/with-loaded-context"; +import { getIMetaPoolContract } from "@/components/utils/contracts"; import DepositShare from "./deposit-share"; import useBalances from "../lib/hooks/use-balances"; @@ -44,12 +45,15 @@ type Actions = { const USD_TO_LP = 0.7460387929; const LP_TO_USD = 1 / USD_TO_LP; -export const BondingSharesExplorerContainer = ({ managedContracts, web3Provider, walletAddress, signer }: LoadedContext) => { +export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider, walletAddress, signer }: LoadedContext) => { + if (!protocolContracts.chefFacet || !protocolContracts.stakingFacet || !protocolContracts.stakingShare || !protocolContracts.managerFacet) { + return <>; + } const [model, setModel] = useState(null); const [, doTransaction] = useTransactionLogger(); const [, refreshBalances] = useBalances(); // cspell: disable-next-line - const { staking: bonding, masterChef, stakingToken: bondingToken, dollarMetapool: metaPool } = managedContracts; + const { stakingFacet: bonding, chefFacet, stakingShare: bondingToken, managerFacet } = protocolContracts; useAsyncInit(fetchSharesInformation); async function fetchSharesInformation(processedShareId?: ShareData["id"]) { @@ -57,9 +61,12 @@ export const BondingSharesExplorerContainer = ({ managedContracts, web3Provider, const currentBlock = await web3Provider.getBlockNumber(); // cspell: disable-next-line const blockCountInAWeek = +(await bonding.blockCountInAWeek()).toString(); - const totalShares = await masterChef.totalShares(); + const totalShares = await chefFacet.totalShares(); // cspell: disable-next-line const bondingShareIds = await bondingToken.holderTokens(walletAddress); + + const dollar3poolMarket = await managerFacet.stableSwapMetaPoolAddress(); + const metaPool = getIMetaPoolContract(dollar3poolMarket, web3Provider); const walletLpBalance = await metaPool.balanceOf(walletAddress); const shares: ShareData[] = []; @@ -69,10 +76,10 @@ export const BondingSharesExplorerContainer = ({ managedContracts, web3Provider, // cspell: disable-next-line const [ugov, bond, bondingShareInfo, tokenBalance] = await Promise.all([ // cspell: disable-next-line - masterChef.pendingGovernance(id), + chefFacet.pendingGovernance(id), // cspell: disable-next-line bondingToken.getStake(id), - masterChef.getStakingShareInfo(id), + chefFacet.getStakingShareInfo(id), // cspell: disable-next-line bondingToken.balanceOf(walletAddress, id), ]); @@ -149,7 +156,7 @@ export const BondingSharesExplorerContainer = ({ managedContracts, web3Provider, setModel((prevModel) => (prevModel ? { ...prevModel, processing: [...prevModel.processing, id] } : null)); doTransaction("Claiming Ubiquity Governance tokens...", async () => { try { - await performTransaction(masterChef.connect(signer).getRewards(BigNumber.from(id))); + await performTransaction(chefFacet.connect(signer).getRewards(BigNumber.from(id))); } catch (error) { console.log(`Claiming Ubiquity Governance token rewards from ${id} failed:`, error); // throws exception to update the transaction log @@ -168,6 +175,9 @@ export const BondingSharesExplorerContainer = ({ managedContracts, web3Provider, if (!model || model.processing.length) return; console.log(`Staking ${amount} for ${weeks} weeks`); doTransaction("Staking...", async () => {}); + + const dollar3poolMarket = await managerFacet.stableSwapMetaPoolAddress(); + const metaPool = getIMetaPoolContract(dollar3poolMarket, web3Provider); // cspell: disable-next-line const allowance = await metaPool.allowance(walletAddress, bonding.address); console.log("allowance", ethers.utils.formatEther(allowance)); diff --git a/packages/dapp/components/staking/deposit-share.tsx b/packages/dapp/components/staking/deposit-share.tsx index 7f8463280..8ad8e47e6 100644 --- a/packages/dapp/components/staking/deposit-share.tsx +++ b/packages/dapp/components/staking/deposit-share.tsx @@ -1,11 +1,13 @@ import { BigNumber, ethers } from "ethers"; import { useEffect, useState } from "react"; -import { ManagedContracts } from "@/lib/hooks/contracts/use-manager-managed"; +import { ProtocolContracts } from "@/components/lib/hooks/contracts/use-protocol-contracts"; +import { getSushiSwapPoolContract, getUniswapV2PairContract } from "@/components/utils/contracts"; import { constrainNumber } from "@/lib/utils"; import withLoadedContext, { LoadedContext } from "@/lib/with-loaded-context"; import Button from "../ui/button"; import PositiveNumberInput from "../ui/positive-number-input"; +import useWeb3 from "@/lib/hooks/use-web-3"; const toEtherNum = (n: BigNumber) => +n.toString() / 1e18; const toNum = (n: BigNumber) => +n.toString(); @@ -15,24 +17,35 @@ const MAX_WEEKS = 208; // cspell: disable-next-line type PrefetchedConstants = { totalShares: number; usdPerWeek: number; bondingDiscountMultiplier: BigNumber }; -async function prefetchConstants(contracts: NonNullable): Promise { - const reserves = await contracts.governanceMarket.getReserves(); +async function prefetchConstants(contracts: NonNullable): Promise { + const { provider } = useWeb3(); + + if (!contracts.managerFacet || !contracts.chefFacet || !contracts.stakingFacet || !provider) { + return { totalShares: 0, usdPerWeek: 0, bondingDiscountMultiplier: new BigNumber(0, "0x") }; + } + const sushiSwapPool = await contracts.managerFacet.sushiSwapPoolAddress(); + const sushiSwapPoolContract = getSushiSwapPoolContract(sushiSwapPool, provider); + const governanceMarket = getUniswapV2PairContract(await sushiSwapPoolContract.pair(), provider); + const reserves = await governanceMarket.getReserves(); const ubqPrice = +reserves[0].toString() / +reserves[1].toString(); - const ubqPerBlock = await contracts.masterChef.governancePerBlock(); - const ubqMultiplier = await contracts.masterChef.governanceMultiplier(); + const ubqPerBlock = await contracts.chefFacet.governancePerBlock(); + const ubqMultiplier = await contracts.chefFacet.governanceMultiplier(); const actualUbqPerBlock = toEtherNum(ubqPerBlock.mul(ubqMultiplier).div(`${1e18}`)); - const blockCountInAWeek = toNum(await contracts.staking.blockCountInAWeek()); + const blockCountInAWeek = toNum(await contracts.stakingFacet.blockCountInAWeek()); const ubqPerWeek = actualUbqPerBlock * blockCountInAWeek; - const totalShares = toEtherNum(await contracts.masterChef.totalShares()); + const totalShares = toEtherNum(await contracts.chefFacet.totalShares()); const usdPerWeek = ubqPerWeek * ubqPrice; // cspell: disable-next-line - const bondingDiscountMultiplier = await contracts.staking.stakingDiscountMultiplier(); + const bondingDiscountMultiplier = await contracts.stakingFacet.stakingDiscountMultiplier(); // cspell: disable-next-line return { totalShares, usdPerWeek, bondingDiscountMultiplier }; } -async function calculateApyForWeeks(contracts: NonNullable, prefetch: PrefetchedConstants, weeksNum: number): Promise { +async function calculateApyForWeeks(contracts: NonNullable, prefetch: PrefetchedConstants, weeksNum: number): Promise { + if (!contracts.stakingFormulasFacet) { + return 0; + } // cspell: disable-next-line const { totalShares, usdPerWeek, bondingDiscountMultiplier } = prefetch; const DAYS_IN_A_YEAR = 365.2422; @@ -40,7 +53,7 @@ async function calculateApyForWeeks(contracts: NonNullable, pr const bigNumberOneUsdAsLp = ethers.utils.parseEther(usdAsLp.toString()); const weeks = BigNumber.from(weeksNum.toString()); // cspell: disable-next-line - const shares = toEtherNum(await contracts.ubiquityFormulas.durationMultiply(bigNumberOneUsdAsLp, weeks, bondingDiscountMultiplier)); + const shares = toEtherNum(await contracts.stakingFormulasFacet.durationMultiply(bigNumberOneUsdAsLp, weeks, bondingDiscountMultiplier)); const rewardsPerWeek = (shares / totalShares) * usdPerWeek; const yearlyYield = (rewardsPerWeek / 7) * DAYS_IN_A_YEAR * 100; return Math.round(yearlyYield * 100) / 100; @@ -52,7 +65,7 @@ type DepositShareProps = { maxLp: BigNumber; } & LoadedContext; -const DepositShare = ({ onStake, disabled, maxLp, managedContracts: contracts }: DepositShareProps) => { +const DepositShare = ({ onStake, disabled, maxLp, protocolContracts: contracts }: DepositShareProps) => { const [amount, setAmount] = useState(""); const [weeks, setWeeks] = useState(""); const [currentApy, setCurrentApy] = useState(null); From 5e1a0717974be91e4c6bf1d578bfce165db37498 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Tue, 3 Oct 2023 19:53:42 -0400 Subject: [PATCH 06/19] fix: fixed build error and made code clean in use-balances --- .../components/lib/hooks/use-balances.tsx | 20 +++++++++++-------- packages/dapp/components/lib/utils.ts | 6 +++--- .../dapp/components/redeem/debt-coupon.tsx | 2 +- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/packages/dapp/components/lib/hooks/use-balances.tsx b/packages/dapp/components/lib/hooks/use-balances.tsx index 6fbb3c07e..73189074e 100644 --- a/packages/dapp/components/lib/hooks/use-balances.tsx +++ b/packages/dapp/components/lib/hooks/use-balances.tsx @@ -1,5 +1,5 @@ import { erc1155BalanceOf } from "@/lib/utils"; -import { BigNumber, Contract } from "ethers"; +import { BigNumber } from "ethers"; import { createContext, useContext, useEffect, useState } from "react"; import useNamedContracts from "./contracts/use-named-contracts"; import useWalletAddress from "./use-wallet-address"; @@ -33,25 +33,29 @@ export const BalancesContextProvider: React.FC = ({ children }) => const { provider } = useWeb3(); async function refreshBalances() { - if (walletAddress && namedContracts && protocolContracts && provider) { - const _3crvToken = protocolContracts.managerFacet && await protocolContracts.managerFacet.curve3PoolTokenAddress(); - const dollar3poolMarket = protocolContracts.managerFacet && await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); + if (!walletAddress || !namedContracts || !protocolContracts || !provider) { + return; + } + + if(protocolContracts.managerFacet && protocolContracts.dollarToken && protocolContracts.creditToken && protocolContracts.governanceToken && protocolContracts.creditNft && protocolContracts.stakingShare) { + const _3crvToken = await protocolContracts.managerFacet.curve3PoolTokenAddress(); + const dollar3poolMarket = await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); const _3crvTokenContract = getERC20Contract(_3crvToken, provider); const dollarMetapool = getIMetaPoolContract(dollar3poolMarket, provider); const [uad, _3crv, uad3crv, ucr, ubq, ucrNft, stakingShares, usdc, dai, usdt] = await Promise.all([ - protocolContracts.dollarToken && protocolContracts.dollarToken.balanceOf(walletAddress), + protocolContracts.dollarToken.balanceOf(walletAddress), _3crvTokenContract.balanceOf(walletAddress), dollarMetapool.balanceOf(walletAddress), - protocolContracts.creditToken && protocolContracts.creditToken.balanceOf(walletAddress), - protocolContracts.governanceToken && protocolContracts.governanceToken.balanceOf(walletAddress), + protocolContracts.creditToken.balanceOf(walletAddress), + protocolContracts.governanceToken.balanceOf(walletAddress), erc1155BalanceOf(walletAddress, protocolContracts.creditNft), erc1155BalanceOf(walletAddress, protocolContracts.stakingShare), namedContracts.usdc.balanceOf(walletAddress), namedContracts.dai.balanceOf(walletAddress), namedContracts.usdt.balanceOf(walletAddress), ]); - + setBalances({ uad, _3crv, diff --git a/packages/dapp/components/lib/utils.ts b/packages/dapp/components/lib/utils.ts index 65854ba7f..2caf22cb1 100644 --- a/packages/dapp/components/lib/utils.ts +++ b/packages/dapp/components/lib/utils.ts @@ -30,11 +30,11 @@ export async function performTransaction(transaction: Promise { - const treasuryIds = erc1155UbiquityCtr && await erc1155UbiquityCtr.holderTokens(addr); +export async function erc1155BalanceOf(addr: string, erc1155UbiquityCtr: Contract): Promise { + const treasuryIds = await erc1155UbiquityCtr.holderTokens(addr); const balanceOfs = treasuryIds.map((id: string) => { - return erc1155UbiquityCtr && erc1155UbiquityCtr.balanceOf(addr, id); + return erc1155UbiquityCtr.balanceOf(addr, id); }); const balances = await Promise.all(balanceOfs); let fullBalance = BigNumber.from(0); diff --git a/packages/dapp/components/redeem/debt-coupon.tsx b/packages/dapp/components/redeem/debt-coupon.tsx index 73682758b..cf18ba7c9 100644 --- a/packages/dapp/components/redeem/debt-coupon.tsx +++ b/packages/dapp/components/redeem/debt-coupon.tsx @@ -33,7 +33,7 @@ const uDEBT = "uDEBT"; const uAR = "uAR"; // eslint-disable-next-line @typescript-eslint/no-unused-vars -export const DebtCouponContainer = ({ managedContracts, deployedContracts, web3Provider, walletAddress, signer }: LoadedContext) => { +export const DebtCouponContainer = ({ protocolContracts, web3Provider, walletAddress, signer }: LoadedContext) => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const [balances, refreshBalances] = useBalances(); const [, doTransaction] = useTransactionLogger(); From f5ac79bfff63716646d4bb7a63e8031431a9fdc7 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Wed, 4 Oct 2023 03:09:33 -0400 Subject: [PATCH 07/19] fix: used non-null assertion operator for object null checking --- .../components/lib/hooks/use-balances.tsx | 60 +++++++++---------- .../dapp/components/redeem/lib/use-prices.ts | 16 +++-- .../staking/bonding-shares-explorer.tsx | 37 ++++++------ .../dapp/components/staking/deposit-share.tsx | 24 +++----- 4 files changed, 62 insertions(+), 75 deletions(-) diff --git a/packages/dapp/components/lib/hooks/use-balances.tsx b/packages/dapp/components/lib/hooks/use-balances.tsx index 73189074e..4f9488c88 100644 --- a/packages/dapp/components/lib/hooks/use-balances.tsx +++ b/packages/dapp/components/lib/hooks/use-balances.tsx @@ -36,39 +36,37 @@ export const BalancesContextProvider: React.FC = ({ children }) => if (!walletAddress || !namedContracts || !protocolContracts || !provider) { return; } + + const _3crvToken = await protocolContracts.managerFacet!.curve3PoolTokenAddress(); + const dollar3poolMarket = await protocolContracts.managerFacet!.stableSwapMetaPoolAddress(); + const _3crvTokenContract = getERC20Contract(_3crvToken, provider); + const dollarMetapool = getIMetaPoolContract(dollar3poolMarket, provider); - if(protocolContracts.managerFacet && protocolContracts.dollarToken && protocolContracts.creditToken && protocolContracts.governanceToken && protocolContracts.creditNft && protocolContracts.stakingShare) { - const _3crvToken = await protocolContracts.managerFacet.curve3PoolTokenAddress(); - const dollar3poolMarket = await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); - const _3crvTokenContract = getERC20Contract(_3crvToken, provider); - const dollarMetapool = getIMetaPoolContract(dollar3poolMarket, provider); + const [uad, _3crv, uad3crv, ucr, ubq, ucrNft, stakingShares, usdc, dai, usdt] = await Promise.all([ + protocolContracts.dollarToken!.balanceOf(walletAddress), + _3crvTokenContract.balanceOf(walletAddress), + dollarMetapool.balanceOf(walletAddress), + protocolContracts.creditToken!.balanceOf(walletAddress), + protocolContracts.governanceToken!.balanceOf(walletAddress), + erc1155BalanceOf(walletAddress, protocolContracts.creditNft!), + erc1155BalanceOf(walletAddress, protocolContracts.stakingShare!), + namedContracts.usdc.balanceOf(walletAddress), + namedContracts.dai.balanceOf(walletAddress), + namedContracts.usdt.balanceOf(walletAddress), + ]); - const [uad, _3crv, uad3crv, ucr, ubq, ucrNft, stakingShares, usdc, dai, usdt] = await Promise.all([ - protocolContracts.dollarToken.balanceOf(walletAddress), - _3crvTokenContract.balanceOf(walletAddress), - dollarMetapool.balanceOf(walletAddress), - protocolContracts.creditToken.balanceOf(walletAddress), - protocolContracts.governanceToken.balanceOf(walletAddress), - erc1155BalanceOf(walletAddress, protocolContracts.creditNft), - erc1155BalanceOf(walletAddress, protocolContracts.stakingShare), - namedContracts.usdc.balanceOf(walletAddress), - namedContracts.dai.balanceOf(walletAddress), - namedContracts.usdt.balanceOf(walletAddress), - ]); - - setBalances({ - uad, - _3crv, - uad3crv, - ucr, - ucrNft, - ubq, - stakingShares, - usdc, - dai, - usdt, - }); - } + setBalances({ + uad, + _3crv, + uad3crv, + ucr, + ucrNft, + ubq, + stakingShares, + usdc, + dai, + usdt, + }); } useEffect(() => { diff --git a/packages/dapp/components/redeem/lib/use-prices.ts b/packages/dapp/components/redeem/lib/use-prices.ts index 9b22d050e..815bab58c 100644 --- a/packages/dapp/components/redeem/lib/use-prices.ts +++ b/packages/dapp/components/redeem/lib/use-prices.ts @@ -17,15 +17,13 @@ const usePrices = (): [BigNumber | null, BigNumber | null, () => Promise] return; } - if(protocolContracts.managerFacet && protocolContracts.twapOracleDollar3poolFacet) { - const dollarTokenAddress = await protocolContracts.managerFacet.dollarTokenAddress(); - const newTwapPrice = await protocolContracts.twapOracleDollar3poolFacet.consult(dollarTokenAddress); - const dollar3poolMarket = await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); - const dollarMetapool = getIMetaPoolContract(dollar3poolMarket, provider) - const newSpotPrice = await dollarMetapool["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); - setTwapPrice(newTwapPrice); - setSpotPrice(newSpotPrice); - } + const dollarTokenAddress = await protocolContracts.managerFacet!.dollarTokenAddress(); + const newTwapPrice = await protocolContracts.twapOracleDollar3poolFacet!.consult(dollarTokenAddress); + const dollar3poolMarket = await protocolContracts.managerFacet!.stableSwapMetaPoolAddress(); + const dollarMetapool = getIMetaPoolContract(dollar3poolMarket, provider) + const newSpotPrice = await dollarMetapool["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); + setTwapPrice(newTwapPrice); + setSpotPrice(newSpotPrice); } catch (error) { console.log("Error in refreshPrices: ", error) diff --git a/packages/dapp/components/staking/bonding-shares-explorer.tsx b/packages/dapp/components/staking/bonding-shares-explorer.tsx index 2958d1453..35299b823 100644 --- a/packages/dapp/components/staking/bonding-shares-explorer.tsx +++ b/packages/dapp/components/staking/bonding-shares-explorer.tsx @@ -46,9 +46,6 @@ const USD_TO_LP = 0.7460387929; const LP_TO_USD = 1 / USD_TO_LP; export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider, walletAddress, signer }: LoadedContext) => { - if (!protocolContracts.chefFacet || !protocolContracts.stakingFacet || !protocolContracts.stakingShare || !protocolContracts.managerFacet) { - return <>; - } const [model, setModel] = useState(null); const [, doTransaction] = useTransactionLogger(); const [, refreshBalances] = useBalances(); @@ -60,12 +57,12 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider console.time("BondingShareExplorerContainer contract loading"); const currentBlock = await web3Provider.getBlockNumber(); // cspell: disable-next-line - const blockCountInAWeek = +(await bonding.blockCountInAWeek()).toString(); - const totalShares = await chefFacet.totalShares(); + const blockCountInAWeek = +(await bonding!.blockCountInAWeek()).toString(); + const totalShares = await chefFacet!.totalShares(); // cspell: disable-next-line - const bondingShareIds = await bondingToken.holderTokens(walletAddress); + const bondingShareIds = await bondingToken!.holderTokens(walletAddress); - const dollar3poolMarket = await managerFacet.stableSwapMetaPoolAddress(); + const dollar3poolMarket = await managerFacet!.stableSwapMetaPoolAddress(); const metaPool = getIMetaPoolContract(dollar3poolMarket, web3Provider); const walletLpBalance = await metaPool.balanceOf(walletAddress); @@ -76,12 +73,12 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider // cspell: disable-next-line const [ugov, bond, bondingShareInfo, tokenBalance] = await Promise.all([ // cspell: disable-next-line - chefFacet.pendingGovernance(id), + chefFacet!.pendingGovernance(id), // cspell: disable-next-line - bondingToken.getStake(id), - chefFacet.getStakingShareInfo(id), + bondingToken!.getStake(id), + chefFacet!.getStakingShareInfo(id), // cspell: disable-next-line - bondingToken.balanceOf(walletAddress, id), + bondingToken!.balanceOf(walletAddress, id), ]); const endBlock = +bond.endBlock.toString(); @@ -123,19 +120,19 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider doTransaction("Withdrawing LP...", async () => { try { // cspell: disable-next-line - const isAllowed = await bondingToken.isApprovedForAll(walletAddress, bonding.address); + const isAllowed = await bondingToken!.isApprovedForAll(walletAddress, bonding!.address); if (!isAllowed) { // cspell: disable-next-line // Allow bonding contract to control account share // cspell: disable-next-line - if (!(await performTransaction(bondingToken.connect(signer).setApprovalForAll(bonding.address, true)))) { + if (!(await performTransaction(bondingToken!.connect(signer).setApprovalForAll(bonding!.address, true)))) { return; // TODO: Show transaction errors to user } } const bigNumberAmount = amount ? ethers.utils.parseEther(amount.toString()) : allLpAmount(id); // cspell: disable-next-line - await performTransaction(bonding.connect(signer).removeLiquidity(bigNumberAmount, BigNumber.from(id))); + await performTransaction(bonding!.connect(signer).removeLiquidity(bigNumberAmount, BigNumber.from(id))); } catch (error) { console.log(`Withdrawing LP from ${id} failed:`, error); // throws exception to update the transaction log @@ -156,7 +153,7 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider setModel((prevModel) => (prevModel ? { ...prevModel, processing: [...prevModel.processing, id] } : null)); doTransaction("Claiming Ubiquity Governance tokens...", async () => { try { - await performTransaction(chefFacet.connect(signer).getRewards(BigNumber.from(id))); + await performTransaction(chefFacet!.connect(signer).getRewards(BigNumber.from(id))); } catch (error) { console.log(`Claiming Ubiquity Governance token rewards from ${id} failed:`, error); // throws exception to update the transaction log @@ -176,21 +173,21 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider console.log(`Staking ${amount} for ${weeks} weeks`); doTransaction("Staking...", async () => {}); - const dollar3poolMarket = await managerFacet.stableSwapMetaPoolAddress(); + const dollar3poolMarket = await managerFacet!.stableSwapMetaPoolAddress(); const metaPool = getIMetaPoolContract(dollar3poolMarket, web3Provider); // cspell: disable-next-line - const allowance = await metaPool.allowance(walletAddress, bonding.address); + const allowance = await metaPool.allowance(walletAddress, bonding!.address); console.log("allowance", ethers.utils.formatEther(allowance)); console.log("lpsAmount", ethers.utils.formatEther(amount)); if (allowance.lt(amount)) { // cspell: disable-next-line - await performTransaction(metaPool.connect(signer).approve(bonding.address, amount)); + await performTransaction(metaPool.connect(signer).approve(bonding!.address, amount)); // cspell: disable-next-line - const allowance2 = await metaPool.allowance(walletAddress, bonding.address); + const allowance2 = await metaPool.allowance(walletAddress, bonding!.address); console.log("allowance2", ethers.utils.formatEther(allowance2)); } // cspell: disable-next-line - await performTransaction(bonding.connect(signer).deposit(amount, weeks)); + await performTransaction(bonding!.connect(signer).deposit(amount, weeks)); fetchSharesInformation(); refreshBalances(); diff --git a/packages/dapp/components/staking/deposit-share.tsx b/packages/dapp/components/staking/deposit-share.tsx index 8ad8e47e6..8de44ad5d 100644 --- a/packages/dapp/components/staking/deposit-share.tsx +++ b/packages/dapp/components/staking/deposit-share.tsx @@ -20,32 +20,26 @@ type PrefetchedConstants = { totalShares: number; usdPerWeek: number; bondingDis async function prefetchConstants(contracts: NonNullable): Promise { const { provider } = useWeb3(); - if (!contracts.managerFacet || !contracts.chefFacet || !contracts.stakingFacet || !provider) { - return { totalShares: 0, usdPerWeek: 0, bondingDiscountMultiplier: new BigNumber(0, "0x") }; - } - const sushiSwapPool = await contracts.managerFacet.sushiSwapPoolAddress(); - const sushiSwapPoolContract = getSushiSwapPoolContract(sushiSwapPool, provider); - const governanceMarket = getUniswapV2PairContract(await sushiSwapPoolContract.pair(), provider); + const sushiSwapPool = await contracts.managerFacet!.sushiSwapPoolAddress(); + const sushiSwapPoolContract = getSushiSwapPoolContract(sushiSwapPool, provider!); + const governanceMarket = getUniswapV2PairContract(await sushiSwapPoolContract.pair(), provider!); const reserves = await governanceMarket.getReserves(); const ubqPrice = +reserves[0].toString() / +reserves[1].toString(); - const ubqPerBlock = await contracts.chefFacet.governancePerBlock(); - const ubqMultiplier = await contracts.chefFacet.governanceMultiplier(); + const ubqPerBlock = await contracts.chefFacet!.governancePerBlock(); + const ubqMultiplier = await contracts.chefFacet!.governanceMultiplier(); const actualUbqPerBlock = toEtherNum(ubqPerBlock.mul(ubqMultiplier).div(`${1e18}`)); - const blockCountInAWeek = toNum(await contracts.stakingFacet.blockCountInAWeek()); + const blockCountInAWeek = toNum(await contracts.stakingFacet!.blockCountInAWeek()); const ubqPerWeek = actualUbqPerBlock * blockCountInAWeek; - const totalShares = toEtherNum(await contracts.chefFacet.totalShares()); + const totalShares = toEtherNum(await contracts.chefFacet!.totalShares()); const usdPerWeek = ubqPerWeek * ubqPrice; // cspell: disable-next-line - const bondingDiscountMultiplier = await contracts.stakingFacet.stakingDiscountMultiplier(); + const bondingDiscountMultiplier = await contracts.stakingFacet!.stakingDiscountMultiplier(); // cspell: disable-next-line return { totalShares, usdPerWeek, bondingDiscountMultiplier }; } async function calculateApyForWeeks(contracts: NonNullable, prefetch: PrefetchedConstants, weeksNum: number): Promise { - if (!contracts.stakingFormulasFacet) { - return 0; - } // cspell: disable-next-line const { totalShares, usdPerWeek, bondingDiscountMultiplier } = prefetch; const DAYS_IN_A_YEAR = 365.2422; @@ -53,7 +47,7 @@ async function calculateApyForWeeks(contracts: NonNullable, p const bigNumberOneUsdAsLp = ethers.utils.parseEther(usdAsLp.toString()); const weeks = BigNumber.from(weeksNum.toString()); // cspell: disable-next-line - const shares = toEtherNum(await contracts.stakingFormulasFacet.durationMultiply(bigNumberOneUsdAsLp, weeks, bondingDiscountMultiplier)); + const shares = toEtherNum(await contracts.stakingFormulasFacet!.durationMultiply(bigNumberOneUsdAsLp, weeks, bondingDiscountMultiplier)); const rewardsPerWeek = (shares / totalShares) * usdPerWeek; const yearlyYield = (rewardsPerWeek / 7) * DAYS_IN_A_YEAR * 100; return Math.round(yearlyYield * 100) / 100; From 18ee55635c1c7a91f62192e5f45a41366aba3b65 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Wed, 4 Oct 2023 08:00:48 -0700 Subject: [PATCH 08/19] fix: added metapool and governancemarket contract to protocol-contracts to avoid invalid hook call --- .../hooks/contracts/use-protocol-contracts.ts | 50 ++++++++++++++++++- .../components/lib/hooks/use-balances.tsx | 16 +++--- .../dapp/components/redeem/lib/use-prices.ts | 11 ++-- .../staking/bonding-shares-explorer.tsx | 20 ++++---- .../dapp/components/staking/deposit-share.tsx | 24 ++++----- 5 files changed, 81 insertions(+), 40 deletions(-) diff --git a/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts b/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts index 14feeee61..3839ae91f 100644 --- a/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts +++ b/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts @@ -27,6 +27,12 @@ import StakingFacetArtifact from "@ubiquity/contracts/out/StakingFacet.sol/Staki import StakingFormulasFacetArtifact from "@ubiquity/contracts/out/StakingFormulasFacet.sol/StakingFormulasFacet.json"; import TWAPOracleDollar3poolFacetArtifact from "@ubiquity/contracts/out/TWAPOracleDollar3poolFacet.sol/TWAPOracleDollar3poolFacet.json"; import UbiquityPoolFacetArtifact from "@ubiquity/contracts/out/UbiquityPoolFacet.sol/UbiquityPoolFacet.json"; +// other related contracts +import { + getSushiSwapPoolContract, + getUniswapV2PairContract, + getIMetaPoolContract +} from "@/components/utils/contracts"; /** * Returns all of the available protocol contracts. @@ -53,9 +59,35 @@ import UbiquityPoolFacetArtifact from "@ubiquity/contracts/out/UbiquityPoolFacet * - https://github.com/ubiquity/ubiquity-dollar/tree/development/packages/contracts/src/ubiquistick */ export type ProtocolContracts = ReturnType | null; -const useProtocolContracts = () => { +const useProtocolContracts = async () => { // get current web3 provider const { provider } = useWeb3(); + if(!provider) { + return { + creditNft: null, + creditToken: null, + dollarToken: null, + governanceToken: null, + stakingShare: null, + accessControlFacet: null, + chefFacet: null, + collectableDustFacet: null, + creditNftManagerFacet: null, + creditNftRedemptionCalculatorFacet: null, + creditRedemptionCalculatorFacet: null, + curveDollarIncentiveFacet: null, + dollarMintCalculatorFacet: null, + dollarMintExcessFacet: null, + managerFacet: null, + ownershipFacet: null, + stakingFacet: null, + stakingFormulasFacet: null, + twapOracleDollar3poolFacet: null, + ubiquityPoolFacet: null, + governanceMarket: null, + metaPool: null, + }; + } // all protocol contracts const protocolContracts: { @@ -81,6 +113,9 @@ const useProtocolContracts = () => { stakingFormulasFacet: Contract | null, twapOracleDollar3poolFacet: Contract | null, ubiquityPoolFacet: Contract | null, + // related contracts + governanceMarket: Contract | null, + metaPool: Contract | null, } = { // separately deployed contracts (i.e. not part of the diamond) creditNft: null, @@ -104,6 +139,9 @@ const useProtocolContracts = () => { stakingFormulasFacet: null, twapOracleDollar3poolFacet: null, ubiquityPoolFacet: null, + // related contracts + governanceMarket: null, + metaPool: null, }; let diamondAddress = ''; @@ -149,6 +187,16 @@ const useProtocolContracts = () => { protocolContracts.twapOracleDollar3poolFacet = new ethers.Contract(diamondAddress, TWAPOracleDollar3poolFacetArtifact.abi, provider); protocolContracts.ubiquityPoolFacet = new ethers.Contract(diamondAddress, UbiquityPoolFacetArtifact.abi, provider); + // other related contracts + const sushiSwapPool = await protocolContracts.managerFacet.sushiSwapPoolAddress(); + const sushiSwapPoolContract = getSushiSwapPoolContract(sushiSwapPool, provider); + const governanceMarket = getUniswapV2PairContract(await sushiSwapPoolContract.pair(), provider); + protocolContracts.governanceMarket = governanceMarket; + + const dollar3poolMarket = await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); + const metaPool = getIMetaPoolContract(dollar3poolMarket, provider); + protocolContracts.metaPool = metaPool + return protocolContracts; }; diff --git a/packages/dapp/components/lib/hooks/use-balances.tsx b/packages/dapp/components/lib/hooks/use-balances.tsx index 4f9488c88..46eb99216 100644 --- a/packages/dapp/components/lib/hooks/use-balances.tsx +++ b/packages/dapp/components/lib/hooks/use-balances.tsx @@ -36,20 +36,22 @@ export const BalancesContextProvider: React.FC = ({ children }) => if (!walletAddress || !namedContracts || !protocolContracts || !provider) { return; } + + const contracts = await protocolContracts; - const _3crvToken = await protocolContracts.managerFacet!.curve3PoolTokenAddress(); - const dollar3poolMarket = await protocolContracts.managerFacet!.stableSwapMetaPoolAddress(); + const _3crvToken = await contracts.managerFacet!.curve3PoolTokenAddress(); + const dollar3poolMarket = await contracts.managerFacet!.stableSwapMetaPoolAddress(); const _3crvTokenContract = getERC20Contract(_3crvToken, provider); const dollarMetapool = getIMetaPoolContract(dollar3poolMarket, provider); const [uad, _3crv, uad3crv, ucr, ubq, ucrNft, stakingShares, usdc, dai, usdt] = await Promise.all([ - protocolContracts.dollarToken!.balanceOf(walletAddress), + contracts.dollarToken!.balanceOf(walletAddress), _3crvTokenContract.balanceOf(walletAddress), dollarMetapool.balanceOf(walletAddress), - protocolContracts.creditToken!.balanceOf(walletAddress), - protocolContracts.governanceToken!.balanceOf(walletAddress), - erc1155BalanceOf(walletAddress, protocolContracts.creditNft!), - erc1155BalanceOf(walletAddress, protocolContracts.stakingShare!), + contracts.creditToken!.balanceOf(walletAddress), + contracts.governanceToken!.balanceOf(walletAddress), + erc1155BalanceOf(walletAddress, contracts.creditNft!), + erc1155BalanceOf(walletAddress, contracts.stakingShare!), namedContracts.usdc.balanceOf(walletAddress), namedContracts.dai.balanceOf(walletAddress), namedContracts.usdt.balanceOf(walletAddress), diff --git a/packages/dapp/components/redeem/lib/use-prices.ts b/packages/dapp/components/redeem/lib/use-prices.ts index 815bab58c..e2e5ece62 100644 --- a/packages/dapp/components/redeem/lib/use-prices.ts +++ b/packages/dapp/components/redeem/lib/use-prices.ts @@ -1,4 +1,3 @@ -import { getIMetaPoolContract } from "@/components/utils/contracts"; import useProtocolContracts from "@/components/lib/hooks/contracts/use-protocol-contracts"; import useWeb3 from "@/components/lib/hooks/use-web-3"; import { BigNumber, utils } from "ethers"; @@ -17,11 +16,11 @@ const usePrices = (): [BigNumber | null, BigNumber | null, () => Promise] return; } - const dollarTokenAddress = await protocolContracts.managerFacet!.dollarTokenAddress(); - const newTwapPrice = await protocolContracts.twapOracleDollar3poolFacet!.consult(dollarTokenAddress); - const dollar3poolMarket = await protocolContracts.managerFacet!.stableSwapMetaPoolAddress(); - const dollarMetapool = getIMetaPoolContract(dollar3poolMarket, provider) - const newSpotPrice = await dollarMetapool["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); + const contracts = await protocolContracts; + + const dollarTokenAddress = await contracts.managerFacet!.dollarTokenAddress(); + const newTwapPrice = await contracts.twapOracleDollar3poolFacet!.consult(dollarTokenAddress); + const newSpotPrice = await contracts.metaPool!["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); setTwapPrice(newTwapPrice); setSpotPrice(newSpotPrice); diff --git a/packages/dapp/components/staking/bonding-shares-explorer.tsx b/packages/dapp/components/staking/bonding-shares-explorer.tsx index 35299b823..7b18a7df7 100644 --- a/packages/dapp/components/staking/bonding-shares-explorer.tsx +++ b/packages/dapp/components/staking/bonding-shares-explorer.tsx @@ -4,7 +4,6 @@ import { memo, useCallback, useState } from "react"; import { formatEther } from "@/lib/format"; import { performTransaction, useAsyncInit } from "@/lib/utils"; import withLoadedContext, { LoadedContext } from "@/lib/with-loaded-context"; -import { getIMetaPoolContract } from "@/components/utils/contracts"; import DepositShare from "./deposit-share"; import useBalances from "../lib/hooks/use-balances"; @@ -49,11 +48,11 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider const [model, setModel] = useState(null); const [, doTransaction] = useTransactionLogger(); const [, refreshBalances] = useBalances(); - // cspell: disable-next-line - const { stakingFacet: bonding, chefFacet, stakingShare: bondingToken, managerFacet } = protocolContracts; useAsyncInit(fetchSharesInformation); async function fetchSharesInformation(processedShareId?: ShareData["id"]) { + // cspell: disable-next-line + const { stakingFacet: bonding, chefFacet, stakingShare: bondingToken, metaPool } = await protocolContracts; console.time("BondingShareExplorerContainer contract loading"); const currentBlock = await web3Provider.getBlockNumber(); // cspell: disable-next-line @@ -62,9 +61,7 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider // cspell: disable-next-line const bondingShareIds = await bondingToken!.holderTokens(walletAddress); - const dollar3poolMarket = await managerFacet!.stableSwapMetaPoolAddress(); - const metaPool = getIMetaPoolContract(dollar3poolMarket, web3Provider); - const walletLpBalance = await metaPool.balanceOf(walletAddress); + const walletLpBalance = await metaPool!.balanceOf(walletAddress); const shares: ShareData[] = []; await Promise.all( @@ -114,6 +111,7 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider const actions: Actions = { onWithdrawLp: useCallback( async ({ id, amount }) => { + const { stakingFacet: bonding, stakingShare: bondingToken } = await protocolContracts; if (!model || model.processing.includes(id)) return; console.log(`Withdrawing ${amount ? amount : "ALL"} LP from ${id}`); setModel((prevModel) => (prevModel ? { ...prevModel, processing: [...prevModel.processing, id] } : null)); @@ -148,6 +146,7 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider onClaimUbq: useCallback( async (id) => { + const { chefFacet } = await protocolContracts; if (!model) return; console.log(`Claiming Ubiquity Governance token rewards from ${id}`); setModel((prevModel) => (prevModel ? { ...prevModel, processing: [...prevModel.processing, id] } : null)); @@ -169,21 +168,20 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider onStake: useCallback( async ({ amount, weeks }) => { + const { stakingFacet: bonding, metaPool } = await protocolContracts; if (!model || model.processing.length) return; console.log(`Staking ${amount} for ${weeks} weeks`); doTransaction("Staking...", async () => {}); - const dollar3poolMarket = await managerFacet!.stableSwapMetaPoolAddress(); - const metaPool = getIMetaPoolContract(dollar3poolMarket, web3Provider); // cspell: disable-next-line - const allowance = await metaPool.allowance(walletAddress, bonding!.address); + const allowance = await metaPool!.allowance(walletAddress, bonding!.address); console.log("allowance", ethers.utils.formatEther(allowance)); console.log("lpsAmount", ethers.utils.formatEther(amount)); if (allowance.lt(amount)) { // cspell: disable-next-line - await performTransaction(metaPool.connect(signer).approve(bonding!.address, amount)); + await performTransaction(metaPool!.connect(signer).approve(bonding!.address, amount)); // cspell: disable-next-line - const allowance2 = await metaPool.allowance(walletAddress, bonding!.address); + const allowance2 = await metaPool!.allowance(walletAddress, bonding!.address); console.log("allowance2", ethers.utils.formatEther(allowance2)); } // cspell: disable-next-line diff --git a/packages/dapp/components/staking/deposit-share.tsx b/packages/dapp/components/staking/deposit-share.tsx index 8de44ad5d..30dfbb113 100644 --- a/packages/dapp/components/staking/deposit-share.tsx +++ b/packages/dapp/components/staking/deposit-share.tsx @@ -2,12 +2,10 @@ import { BigNumber, ethers } from "ethers"; import { useEffect, useState } from "react"; import { ProtocolContracts } from "@/components/lib/hooks/contracts/use-protocol-contracts"; -import { getSushiSwapPoolContract, getUniswapV2PairContract } from "@/components/utils/contracts"; import { constrainNumber } from "@/lib/utils"; import withLoadedContext, { LoadedContext } from "@/lib/with-loaded-context"; import Button from "../ui/button"; import PositiveNumberInput from "../ui/positive-number-input"; -import useWeb3 from "@/lib/hooks/use-web-3"; const toEtherNum = (n: BigNumber) => +n.toString() / 1e18; const toNum = (n: BigNumber) => +n.toString(); @@ -18,28 +16,24 @@ const MAX_WEEKS = 208; // cspell: disable-next-line type PrefetchedConstants = { totalShares: number; usdPerWeek: number; bondingDiscountMultiplier: BigNumber }; async function prefetchConstants(contracts: NonNullable): Promise { - const { provider } = useWeb3(); - - const sushiSwapPool = await contracts.managerFacet!.sushiSwapPoolAddress(); - const sushiSwapPoolContract = getSushiSwapPoolContract(sushiSwapPool, provider!); - const governanceMarket = getUniswapV2PairContract(await sushiSwapPoolContract.pair(), provider!); - const reserves = await governanceMarket.getReserves(); - + const contract = await contracts; + const reserves = contract.governanceMarket!.getReserves(); const ubqPrice = +reserves[0].toString() / +reserves[1].toString(); - const ubqPerBlock = await contracts.chefFacet!.governancePerBlock(); - const ubqMultiplier = await contracts.chefFacet!.governanceMultiplier(); + const ubqPerBlock = contract.chefFacet!.governancePerBlock(); + const ubqMultiplier = contract.chefFacet!.governanceMultiplier(); const actualUbqPerBlock = toEtherNum(ubqPerBlock.mul(ubqMultiplier).div(`${1e18}`)); - const blockCountInAWeek = toNum(await contracts.stakingFacet!.blockCountInAWeek()); + const blockCountInAWeek = toNum(contract.stakingFacet!.blockCountInAWeek()); const ubqPerWeek = actualUbqPerBlock * blockCountInAWeek; - const totalShares = toEtherNum(await contracts.chefFacet!.totalShares()); + const totalShares = toEtherNum(contract.chefFacet!.totalShares()); const usdPerWeek = ubqPerWeek * ubqPrice; // cspell: disable-next-line - const bondingDiscountMultiplier = await contracts.stakingFacet!.stakingDiscountMultiplier(); + const bondingDiscountMultiplier = contract.stakingFacet!.stakingDiscountMultiplier(); // cspell: disable-next-line return { totalShares, usdPerWeek, bondingDiscountMultiplier }; } async function calculateApyForWeeks(contracts: NonNullable, prefetch: PrefetchedConstants, weeksNum: number): Promise { + const contract = await contracts; // cspell: disable-next-line const { totalShares, usdPerWeek, bondingDiscountMultiplier } = prefetch; const DAYS_IN_A_YEAR = 365.2422; @@ -47,7 +41,7 @@ async function calculateApyForWeeks(contracts: NonNullable, p const bigNumberOneUsdAsLp = ethers.utils.parseEther(usdAsLp.toString()); const weeks = BigNumber.from(weeksNum.toString()); // cspell: disable-next-line - const shares = toEtherNum(await contracts.stakingFormulasFacet!.durationMultiply(bigNumberOneUsdAsLp, weeks, bondingDiscountMultiplier)); + const shares = toEtherNum(contract.stakingFormulasFacet!.durationMultiply(bigNumberOneUsdAsLp, weeks, bondingDiscountMultiplier)); const rewardsPerWeek = (shares / totalShares) * usdPerWeek; const yearlyYield = (rewardsPerWeek / 7) * DAYS_IN_A_YEAR * 100; return Math.round(yearlyYield * 100) / 100; From 9ad50eeee3b5779e0588d009128221524022b966 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Wed, 4 Oct 2023 08:25:33 -0700 Subject: [PATCH 09/19] chore: cleamake use-protocol-contracts clean --- .../hooks/contracts/use-protocol-contracts.ts | 40 +++---------------- 1 file changed, 6 insertions(+), 34 deletions(-) diff --git a/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts b/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts index 3839ae91f..e82e1453e 100644 --- a/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts +++ b/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts @@ -28,11 +28,9 @@ import StakingFormulasFacetArtifact from "@ubiquity/contracts/out/StakingFormula import TWAPOracleDollar3poolFacetArtifact from "@ubiquity/contracts/out/TWAPOracleDollar3poolFacet.sol/TWAPOracleDollar3poolFacet.json"; import UbiquityPoolFacetArtifact from "@ubiquity/contracts/out/UbiquityPoolFacet.sol/UbiquityPoolFacet.json"; // other related contracts -import { - getSushiSwapPoolContract, - getUniswapV2PairContract, - getIMetaPoolContract -} from "@/components/utils/contracts"; +import SushiSwapPoolArtifact from "@ubiquity/contracts/out/SushiSwapPool.sol/SushiSwapPool.json"; +import IMetaPoolArtifact from "@ubiquity/contracts/out/IMetaPool.sol/IMetaPool.json"; +import UniswapV2PairABI from "@/components/config/abis/uniswap-v-2-pair.json"; /** * Returns all of the available protocol contracts. @@ -62,32 +60,6 @@ export type ProtocolContracts = ReturnType | null; const useProtocolContracts = async () => { // get current web3 provider const { provider } = useWeb3(); - if(!provider) { - return { - creditNft: null, - creditToken: null, - dollarToken: null, - governanceToken: null, - stakingShare: null, - accessControlFacet: null, - chefFacet: null, - collectableDustFacet: null, - creditNftManagerFacet: null, - creditNftRedemptionCalculatorFacet: null, - creditRedemptionCalculatorFacet: null, - curveDollarIncentiveFacet: null, - dollarMintCalculatorFacet: null, - dollarMintExcessFacet: null, - managerFacet: null, - ownershipFacet: null, - stakingFacet: null, - stakingFormulasFacet: null, - twapOracleDollar3poolFacet: null, - ubiquityPoolFacet: null, - governanceMarket: null, - metaPool: null, - }; - } // all protocol contracts const protocolContracts: { @@ -189,12 +161,12 @@ const useProtocolContracts = async () => { // other related contracts const sushiSwapPool = await protocolContracts.managerFacet.sushiSwapPoolAddress(); - const sushiSwapPoolContract = getSushiSwapPoolContract(sushiSwapPool, provider); - const governanceMarket = getUniswapV2PairContract(await sushiSwapPoolContract.pair(), provider); + const sushiSwapPoolContract = new ethers.Contract(sushiSwapPool, SushiSwapPoolArtifact.abi, provider); + const governanceMarket = new ethers.Contract(await sushiSwapPoolContract.pair(), UniswapV2PairABI, provider); protocolContracts.governanceMarket = governanceMarket; const dollar3poolMarket = await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); - const metaPool = getIMetaPoolContract(dollar3poolMarket, provider); + const metaPool = new ethers.Contract(dollar3poolMarket, IMetaPoolArtifact.abi, provider); protocolContracts.metaPool = metaPool return protocolContracts; From 1ce1d355bf32ee7e452ef5128ee968f5509b4cf7 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Thu, 5 Oct 2023 14:00:53 -0400 Subject: [PATCH 10/19] fix: applied new name convention --- .../hooks/contracts/use-protocol-contracts.ts | 16 ++++++++-------- .../dapp/components/redeem/lib/use-prices.ts | 2 +- .../staking/bonding-shares-explorer.tsx | 12 ++++++------ .../dapp/components/staking/deposit-share.tsx | 2 +- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts b/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts index e82e1453e..5e0d2b208 100644 --- a/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts +++ b/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts @@ -86,8 +86,8 @@ const useProtocolContracts = async () => { twapOracleDollar3poolFacet: Contract | null, ubiquityPoolFacet: Contract | null, // related contracts - governanceMarket: Contract | null, - metaPool: Contract | null, + sushiPoolGovernanceDollarLp: Contract | null, + curveMetaPoolDollarTriPoolLp: Contract | null, } = { // separately deployed contracts (i.e. not part of the diamond) creditNft: null, @@ -112,8 +112,8 @@ const useProtocolContracts = async () => { twapOracleDollar3poolFacet: null, ubiquityPoolFacet: null, // related contracts - governanceMarket: null, - metaPool: null, + sushiPoolGovernanceDollarLp: null, + curveMetaPoolDollarTriPoolLp: null, }; let diamondAddress = ''; @@ -162,12 +162,12 @@ const useProtocolContracts = async () => { // other related contracts const sushiSwapPool = await protocolContracts.managerFacet.sushiSwapPoolAddress(); const sushiSwapPoolContract = new ethers.Contract(sushiSwapPool, SushiSwapPoolArtifact.abi, provider); - const governanceMarket = new ethers.Contract(await sushiSwapPoolContract.pair(), UniswapV2PairABI, provider); - protocolContracts.governanceMarket = governanceMarket; + const UniswapV2PairContract = new ethers.Contract(await sushiSwapPoolContract.pair(), UniswapV2PairABI, provider); + protocolContracts.sushiPoolGovernanceDollarLp = UniswapV2PairContract; const dollar3poolMarket = await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); - const metaPool = new ethers.Contract(dollar3poolMarket, IMetaPoolArtifact.abi, provider); - protocolContracts.metaPool = metaPool + const metaPoolContract = new ethers.Contract(dollar3poolMarket, IMetaPoolArtifact.abi, provider); + protocolContracts.curveMetaPoolDollarTriPoolLp = metaPoolContract; return protocolContracts; }; diff --git a/packages/dapp/components/redeem/lib/use-prices.ts b/packages/dapp/components/redeem/lib/use-prices.ts index e2e5ece62..ca2f8d5f7 100644 --- a/packages/dapp/components/redeem/lib/use-prices.ts +++ b/packages/dapp/components/redeem/lib/use-prices.ts @@ -20,7 +20,7 @@ const usePrices = (): [BigNumber | null, BigNumber | null, () => Promise] const dollarTokenAddress = await contracts.managerFacet!.dollarTokenAddress(); const newTwapPrice = await contracts.twapOracleDollar3poolFacet!.consult(dollarTokenAddress); - const newSpotPrice = await contracts.metaPool!["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); + const newSpotPrice = await contracts.curveMetaPoolDollarTriPoolLp!["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); setTwapPrice(newTwapPrice); setSpotPrice(newSpotPrice); diff --git a/packages/dapp/components/staking/bonding-shares-explorer.tsx b/packages/dapp/components/staking/bonding-shares-explorer.tsx index 7b18a7df7..76e78fbf9 100644 --- a/packages/dapp/components/staking/bonding-shares-explorer.tsx +++ b/packages/dapp/components/staking/bonding-shares-explorer.tsx @@ -52,7 +52,7 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider useAsyncInit(fetchSharesInformation); async function fetchSharesInformation(processedShareId?: ShareData["id"]) { // cspell: disable-next-line - const { stakingFacet: bonding, chefFacet, stakingShare: bondingToken, metaPool } = await protocolContracts; + const { stakingFacet: bonding, chefFacet, stakingShare: bondingToken, curveMetaPoolDollarTriPoolLp } = await protocolContracts; console.time("BondingShareExplorerContainer contract loading"); const currentBlock = await web3Provider.getBlockNumber(); // cspell: disable-next-line @@ -61,7 +61,7 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider // cspell: disable-next-line const bondingShareIds = await bondingToken!.holderTokens(walletAddress); - const walletLpBalance = await metaPool!.balanceOf(walletAddress); + const walletLpBalance = await curveMetaPoolDollarTriPoolLp!.balanceOf(walletAddress); const shares: ShareData[] = []; await Promise.all( @@ -168,20 +168,20 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider onStake: useCallback( async ({ amount, weeks }) => { - const { stakingFacet: bonding, metaPool } = await protocolContracts; + const { stakingFacet: bonding, curveMetaPoolDollarTriPoolLp } = await protocolContracts; if (!model || model.processing.length) return; console.log(`Staking ${amount} for ${weeks} weeks`); doTransaction("Staking...", async () => {}); // cspell: disable-next-line - const allowance = await metaPool!.allowance(walletAddress, bonding!.address); + const allowance = await curveMetaPoolDollarTriPoolLp!.allowance(walletAddress, bonding!.address); console.log("allowance", ethers.utils.formatEther(allowance)); console.log("lpsAmount", ethers.utils.formatEther(amount)); if (allowance.lt(amount)) { // cspell: disable-next-line - await performTransaction(metaPool!.connect(signer).approve(bonding!.address, amount)); + await performTransaction(curveMetaPoolDollarTriPoolLp!.connect(signer).approve(bonding!.address, amount)); // cspell: disable-next-line - const allowance2 = await metaPool!.allowance(walletAddress, bonding!.address); + const allowance2 = await curveMetaPoolDollarTriPoolLp!.allowance(walletAddress, bonding!.address); console.log("allowance2", ethers.utils.formatEther(allowance2)); } // cspell: disable-next-line diff --git a/packages/dapp/components/staking/deposit-share.tsx b/packages/dapp/components/staking/deposit-share.tsx index 30dfbb113..1d9488edb 100644 --- a/packages/dapp/components/staking/deposit-share.tsx +++ b/packages/dapp/components/staking/deposit-share.tsx @@ -17,7 +17,7 @@ const MAX_WEEKS = 208; type PrefetchedConstants = { totalShares: number; usdPerWeek: number; bondingDiscountMultiplier: BigNumber }; async function prefetchConstants(contracts: NonNullable): Promise { const contract = await contracts; - const reserves = contract.governanceMarket!.getReserves(); + const reserves = contract.sushiPoolGovernanceDollarLp!.getReserves(); const ubqPrice = +reserves[0].toString() / +reserves[1].toString(); const ubqPerBlock = contract.chefFacet!.governancePerBlock(); const ubqMultiplier = contract.chefFacet!.governanceMultiplier(); From 57bc6e12a7894fadc7ed0c9022c59d2ef364c412 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Thu, 5 Oct 2023 14:52:16 -0400 Subject: [PATCH 11/19] fix: object null checking --- packages/dapp/components/lib/utils.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/dapp/components/lib/utils.ts b/packages/dapp/components/lib/utils.ts index 2caf22cb1..400a397b2 100644 --- a/packages/dapp/components/lib/utils.ts +++ b/packages/dapp/components/lib/utils.ts @@ -31,10 +31,10 @@ export async function performTransaction(transaction: Promise { - const treasuryIds = await erc1155UbiquityCtr.holderTokens(addr); + const treasuryIds = await erc1155UbiquityCtr!.holderTokens(addr); const balanceOfs = treasuryIds.map((id: string) => { - return erc1155UbiquityCtr.balanceOf(addr, id); + return erc1155UbiquityCtr!.balanceOf(addr, id); }); const balances = await Promise.all(balanceOfs); let fullBalance = BigNumber.from(0); From 6972f9c1ffdad83d8597586bc7335e8b825a9b94 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Thu, 5 Oct 2023 15:02:25 -0400 Subject: [PATCH 12/19] fix: cleaned refresh balance function --- packages/dapp/components/lib/hooks/use-balances.tsx | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/dapp/components/lib/hooks/use-balances.tsx b/packages/dapp/components/lib/hooks/use-balances.tsx index 46eb99216..6111a6dd5 100644 --- a/packages/dapp/components/lib/hooks/use-balances.tsx +++ b/packages/dapp/components/lib/hooks/use-balances.tsx @@ -5,7 +5,7 @@ import useNamedContracts from "./contracts/use-named-contracts"; import useWalletAddress from "./use-wallet-address"; import { ChildrenShim } from "./children-shim-d"; import useProtocolContracts from "@/components/lib/hooks/contracts/use-protocol-contracts"; -import { getERC20Contract, getIMetaPoolContract } from "@/components/utils/contracts"; +import { getERC20Contract } from "@/components/utils/contracts"; import useWeb3 from "@/components/lib/hooks/use-web-3"; export interface Balances { @@ -40,14 +40,12 @@ export const BalancesContextProvider: React.FC = ({ children }) => const contracts = await protocolContracts; const _3crvToken = await contracts.managerFacet!.curve3PoolTokenAddress(); - const dollar3poolMarket = await contracts.managerFacet!.stableSwapMetaPoolAddress(); const _3crvTokenContract = getERC20Contract(_3crvToken, provider); - const dollarMetapool = getIMetaPoolContract(dollar3poolMarket, provider); const [uad, _3crv, uad3crv, ucr, ubq, ucrNft, stakingShares, usdc, dai, usdt] = await Promise.all([ contracts.dollarToken!.balanceOf(walletAddress), _3crvTokenContract.balanceOf(walletAddress), - dollarMetapool.balanceOf(walletAddress), + contracts.curveMetaPoolDollarTriPoolLp!.balanceOf(walletAddress), contracts.creditToken!.balanceOf(walletAddress), contracts.governanceToken!.balanceOf(walletAddress), erc1155BalanceOf(walletAddress, contracts.creditNft!), From 61ee7f75accdc6f854686be8292a89521e818ae2 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Fri, 6 Oct 2023 10:05:38 -0700 Subject: [PATCH 13/19] fix: hardcoded some addresses and fixed prefetch-constants function --- .../lib/hooks/contracts/use-protocol-contracts.ts | 12 +++++++----- packages/dapp/components/lib/hooks/use-balances.tsx | 3 ++- packages/dapp/components/staking/deposit-share.tsx | 12 ++++++------ 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts b/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts index 5e0d2b208..9e0db19c9 100644 --- a/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts +++ b/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts @@ -160,13 +160,15 @@ const useProtocolContracts = async () => { protocolContracts.ubiquityPoolFacet = new ethers.Contract(diamondAddress, UbiquityPoolFacetArtifact.abi, provider); // other related contracts - const sushiSwapPool = await protocolContracts.managerFacet.sushiSwapPoolAddress(); - const sushiSwapPoolContract = new ethers.Contract(sushiSwapPool, SushiSwapPoolArtifact.abi, provider); - const UniswapV2PairContract = new ethers.Contract(await sushiSwapPoolContract.pair(), UniswapV2PairABI, provider); + // const sushiSwapPool = await protocolContracts.managerFacet.sushiSwapPoolAddress(); + // const sushiSwapPoolContract = new ethers.Contract(sushiSwapPool, SushiSwapPoolArtifact.abi, provider); + // const UniswapV2PairContract = new ethers.Contract(await sushiSwapPoolContract.pair(), UniswapV2PairABI, provider); + const UniswapV2PairContract = new ethers.Contract("0x41e087485f47538752A1195D984109cB8Dc0E429", UniswapV2PairABI, provider); protocolContracts.sushiPoolGovernanceDollarLp = UniswapV2PairContract; - const dollar3poolMarket = await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); - const metaPoolContract = new ethers.Contract(dollar3poolMarket, IMetaPoolArtifact.abi, provider); + // const dollar3poolMarket = await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); + // const metaPoolContract = new ethers.Contract(dollar3poolMarket, IMetaPoolArtifact.abi, provider); + const metaPoolContract = new ethers.Contract("0x20955CB69Ae1515962177D164dfC9522feef567E", IMetaPoolArtifact.abi, provider); protocolContracts.curveMetaPoolDollarTriPoolLp = metaPoolContract; return protocolContracts; diff --git a/packages/dapp/components/lib/hooks/use-balances.tsx b/packages/dapp/components/lib/hooks/use-balances.tsx index 6111a6dd5..d2a53b036 100644 --- a/packages/dapp/components/lib/hooks/use-balances.tsx +++ b/packages/dapp/components/lib/hooks/use-balances.tsx @@ -39,7 +39,8 @@ export const BalancesContextProvider: React.FC = ({ children }) => const contracts = await protocolContracts; - const _3crvToken = await contracts.managerFacet!.curve3PoolTokenAddress(); + // const _3crvToken = await contracts.managerFacet!.curve3PoolTokenAddress(); + const _3crvToken = "0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490"; const _3crvTokenContract = getERC20Contract(_3crvToken, provider); const [uad, _3crv, uad3crv, ucr, ubq, ucrNft, stakingShares, usdc, dai, usdt] = await Promise.all([ diff --git a/packages/dapp/components/staking/deposit-share.tsx b/packages/dapp/components/staking/deposit-share.tsx index 1d9488edb..ab32298a3 100644 --- a/packages/dapp/components/staking/deposit-share.tsx +++ b/packages/dapp/components/staking/deposit-share.tsx @@ -17,17 +17,17 @@ const MAX_WEEKS = 208; type PrefetchedConstants = { totalShares: number; usdPerWeek: number; bondingDiscountMultiplier: BigNumber }; async function prefetchConstants(contracts: NonNullable): Promise { const contract = await contracts; - const reserves = contract.sushiPoolGovernanceDollarLp!.getReserves(); + const reserves = await contract.sushiPoolGovernanceDollarLp!.getReserves(); const ubqPrice = +reserves[0].toString() / +reserves[1].toString(); - const ubqPerBlock = contract.chefFacet!.governancePerBlock(); - const ubqMultiplier = contract.chefFacet!.governanceMultiplier(); + const ubqPerBlock = await contract.chefFacet!.governancePerBlock(); + const ubqMultiplier = await contract.chefFacet!.governanceMultiplier(); const actualUbqPerBlock = toEtherNum(ubqPerBlock.mul(ubqMultiplier).div(`${1e18}`)); - const blockCountInAWeek = toNum(contract.stakingFacet!.blockCountInAWeek()); + const blockCountInAWeek = toNum(await contract.stakingFacet!.blockCountInAWeek()); const ubqPerWeek = actualUbqPerBlock * blockCountInAWeek; - const totalShares = toEtherNum(contract.chefFacet!.totalShares()); + const totalShares = toEtherNum(await contract.chefFacet!.totalShares()); const usdPerWeek = ubqPerWeek * ubqPrice; // cspell: disable-next-line - const bondingDiscountMultiplier = contract.stakingFacet!.stakingDiscountMultiplier(); + const bondingDiscountMultiplier = await contract.stakingFacet!.stakingDiscountMultiplier(); // cspell: disable-next-line return { totalShares, usdPerWeek, bondingDiscountMultiplier }; } From eb6e495072f9ba7fbc3cb78f0af760483c7ec4e3 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Fri, 6 Oct 2023 12:37:43 -0700 Subject: [PATCH 14/19] fix: checking big number zero value --- packages/dapp/components/staking/bonding-shares-explorer.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/dapp/components/staking/bonding-shares-explorer.tsx b/packages/dapp/components/staking/bonding-shares-explorer.tsx index 76e78fbf9..686af865d 100644 --- a/packages/dapp/components/staking/bonding-shares-explorer.tsx +++ b/packages/dapp/components/staking/bonding-shares-explorer.tsx @@ -212,7 +212,7 @@ export const BondingSharesInformation = ({ shares, totalShares, onWithdrawLp, on // cspell: disable-next-line const totalPendingUgov = shares.reduce((sum, val) => sum.add(val.ugov), BigNumber.from(0)); - const poolPercentage = formatEther(totalUserShares.mul(ethers.utils.parseEther("100")).div(totalShares)); + const poolPercentage = totalShares.isZero() ? 0 : formatEther(totalUserShares.mul(ethers.utils.parseEther("100")).div(totalShares)); // cspell: disable-next-line const filteredShares = shares.filter(({ bond: { lpAmount }, ugov }) => lpAmount.gt(0) || ugov.gt(0)); From 88c1b46725f2fda78932a14422a75ef3c86570a5 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Tue, 10 Oct 2023 02:41:27 -0700 Subject: [PATCH 15/19] fix: non-null assertion operator and infinite hook loop --- .../components/lib/hooks/use-balances.tsx | 60 ++++++----- packages/dapp/components/lib/utils.ts | 4 +- .../components/redeem/debt-coupon-deposit.tsx | 25 ++--- .../dapp/components/redeem/lib/use-prices.ts | 14 +-- .../dapp/components/redeem/ucr-nft-redeem.tsx | 32 +++--- .../dapp/components/redeem/ucr-redeem.tsx | 34 +++--- .../staking/bonding-shares-explorer.tsx | 100 +++++++++--------- .../dapp/components/staking/deposit-share.tsx | 14 +-- packages/dapp/pages/credits.tsx | 12 ++- packages/dapp/pages/index.tsx | 2 +- 10 files changed, 154 insertions(+), 143 deletions(-) diff --git a/packages/dapp/components/lib/hooks/use-balances.tsx b/packages/dapp/components/lib/hooks/use-balances.tsx index d2a53b036..227629c2d 100644 --- a/packages/dapp/components/lib/hooks/use-balances.tsx +++ b/packages/dapp/components/lib/hooks/use-balances.tsx @@ -38,36 +38,38 @@ export const BalancesContextProvider: React.FC = ({ children }) => } const contracts = await protocolContracts; - - // const _3crvToken = await contracts.managerFacet!.curve3PoolTokenAddress(); - const _3crvToken = "0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490"; - const _3crvTokenContract = getERC20Contract(_3crvToken, provider); - const [uad, _3crv, uad3crv, ucr, ubq, ucrNft, stakingShares, usdc, dai, usdt] = await Promise.all([ - contracts.dollarToken!.balanceOf(walletAddress), - _3crvTokenContract.balanceOf(walletAddress), - contracts.curveMetaPoolDollarTriPoolLp!.balanceOf(walletAddress), - contracts.creditToken!.balanceOf(walletAddress), - contracts.governanceToken!.balanceOf(walletAddress), - erc1155BalanceOf(walletAddress, contracts.creditNft!), - erc1155BalanceOf(walletAddress, contracts.stakingShare!), - namedContracts.usdc.balanceOf(walletAddress), - namedContracts.dai.balanceOf(walletAddress), - namedContracts.usdt.balanceOf(walletAddress), - ]); - - setBalances({ - uad, - _3crv, - uad3crv, - ucr, - ucrNft, - ubq, - stakingShares, - usdc, - dai, - usdt, - }); + if(contracts.creditNft && contracts.stakingShare) { + // const _3crvToken = await contracts.managerFacet?.curve3PoolTokenAddress(); + const _3crvToken = "0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490"; + const _3crvTokenContract = getERC20Contract(_3crvToken, provider); + + const [uad, _3crv, uad3crv, ucr, ubq, ucrNft, stakingShares, usdc, dai, usdt] = await Promise.all([ + contracts.dollarToken?.balanceOf(walletAddress), + _3crvTokenContract.balanceOf(walletAddress), + contracts.curveMetaPoolDollarTriPoolLp?.balanceOf(walletAddress), + contracts.creditToken?.balanceOf(walletAddress), + contracts.governanceToken?.balanceOf(walletAddress), + erc1155BalanceOf(walletAddress, contracts.creditNft), + erc1155BalanceOf(walletAddress, contracts.stakingShare), + namedContracts.usdc.balanceOf(walletAddress), + namedContracts.dai.balanceOf(walletAddress), + namedContracts.usdt.balanceOf(walletAddress), + ]); + + setBalances({ + uad, + _3crv, + uad3crv, + ucr, + ucrNft, + ubq, + stakingShares, + usdc, + dai, + usdt, + }); + } } useEffect(() => { diff --git a/packages/dapp/components/lib/utils.ts b/packages/dapp/components/lib/utils.ts index 400a397b2..2caf22cb1 100644 --- a/packages/dapp/components/lib/utils.ts +++ b/packages/dapp/components/lib/utils.ts @@ -31,10 +31,10 @@ export async function performTransaction(transaction: Promise { - const treasuryIds = await erc1155UbiquityCtr!.holderTokens(addr); + const treasuryIds = await erc1155UbiquityCtr.holderTokens(addr); const balanceOfs = treasuryIds.map((id: string) => { - return erc1155UbiquityCtr!.balanceOf(addr, id); + return erc1155UbiquityCtr.balanceOf(addr, id); }); const balances = await Promise.all(balanceOfs); let fullBalance = BigNumber.from(0); diff --git a/packages/dapp/components/redeem/debt-coupon-deposit.tsx b/packages/dapp/components/redeem/debt-coupon-deposit.tsx index df692e6a5..a95767a33 100644 --- a/packages/dapp/components/redeem/debt-coupon-deposit.tsx +++ b/packages/dapp/components/redeem/debt-coupon-deposit.tsx @@ -4,8 +4,7 @@ import { useState } from "react"; import { ensureERC20Allowance } from "@/lib/contracts-shortcuts"; import { formatEther } from "@/lib/format"; import { safeParseEther } from "@/lib/utils"; -import useDeployedContracts from "../lib/hooks/contracts/use-deployed-contracts"; -import useManagerManaged from "../lib/hooks/contracts/use-manager-managed"; +import useProtocolContracts from "@/components/lib/hooks/contracts/use-protocol-contracts"; import useBalances from "../lib/hooks/use-balances"; import useSigner from "../lib/hooks/use-signer"; import useTransactionLogger from "../lib/hooks/use-transaction-logger"; @@ -18,8 +17,7 @@ const UcrNftGenerator = () => { const signer = useSigner(); const [balances, refreshBalances] = useBalances(); const [, doTransaction, doingTransaction] = useTransactionLogger(); - const deployedContracts = useDeployedContracts(); - const managedContracts = useManagerManaged(); + const protocolContracts = useProtocolContracts(); const [inputVal, setInputVal] = useState(""); const [expectedDebtCoupon, setExpectedDebtCoupon] = useState(null); @@ -28,16 +26,18 @@ const UcrNftGenerator = () => { return Connect wallet; } - if (!balances || !managedContracts || !deployedContracts) { + if (!balances || !protocolContracts) { return · · ·; } const depositDollarForDebtCoupons = async (amount: BigNumber) => { - const { debtCouponManager } = deployedContracts; - // cspell: disable-next-line - await ensureERC20Allowance("uAD -> DebtCouponManager", managedContracts.dollarToken, amount, signer, debtCouponManager.address); - await (await debtCouponManager.connect(signer).exchangeDollarsForCreditNft(amount)).wait(); - refreshBalances(); + const contracts = await protocolContracts; + if (contracts.dollarToken && contracts.creditNftManagerFacet) { + // cspell: disable-next-line + await ensureERC20Allowance("uCR -> CreditNftManagerFacet", contracts.dollarToken, amount, signer, contracts.creditNftManagerFacet.address); + await (await contracts.creditNftManagerFacet.connect(signer).exchangeDollarsForCreditNft(amount)).wait(); + refreshBalances(); + } }; const handleBurn = async () => { @@ -52,11 +52,12 @@ const UcrNftGenerator = () => { }; const handleInput = async (val: string) => { + const contracts = await protocolContracts; setInputVal(val); const amount = extractValidAmount(val); - if (amount) { + if (amount && contracts.creditNftRedemptionCalculatorFacet) { setExpectedDebtCoupon(null); - setExpectedDebtCoupon(await managedContracts.creditNftCalculator.connect(signer).getCreditNftAmount(amount)); + setExpectedDebtCoupon(await contracts.creditNftRedemptionCalculatorFacet.connect(signer).getCreditNftAmount(amount)); } }; diff --git a/packages/dapp/components/redeem/lib/use-prices.ts b/packages/dapp/components/redeem/lib/use-prices.ts index ca2f8d5f7..062b8d5f4 100644 --- a/packages/dapp/components/redeem/lib/use-prices.ts +++ b/packages/dapp/components/redeem/lib/use-prices.ts @@ -18,11 +18,13 @@ const usePrices = (): [BigNumber | null, BigNumber | null, () => Promise] const contracts = await protocolContracts; - const dollarTokenAddress = await contracts.managerFacet!.dollarTokenAddress(); - const newTwapPrice = await contracts.twapOracleDollar3poolFacet!.consult(dollarTokenAddress); - const newSpotPrice = await contracts.curveMetaPoolDollarTriPoolLp!["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); - setTwapPrice(newTwapPrice); - setSpotPrice(newSpotPrice); + if(contracts.curveMetaPoolDollarTriPoolLp) { + const dollarTokenAddress = await contracts.managerFacet?.dollarTokenAddress(); + const newTwapPrice = await contracts.twapOracleDollar3poolFacet?.consult(dollarTokenAddress); + const newSpotPrice = await contracts.curveMetaPoolDollarTriPoolLp["get_dy(int128,int128,uint256)"](0, 1, utils.parseEther("1")); + setTwapPrice(newTwapPrice); + setSpotPrice(newSpotPrice); + } } catch (error) { console.log("Error in refreshPrices: ", error) @@ -31,7 +33,7 @@ const usePrices = (): [BigNumber | null, BigNumber | null, () => Promise] useEffect(() => { refreshPrices(); - }, [protocolContracts, provider]); + }, [provider]); return [twapPrice, spotPrice, refreshPrices]; }; diff --git a/packages/dapp/components/redeem/ucr-nft-redeem.tsx b/packages/dapp/components/redeem/ucr-nft-redeem.tsx index 44d7c87e8..699bc6773 100644 --- a/packages/dapp/components/redeem/ucr-nft-redeem.tsx +++ b/packages/dapp/components/redeem/ucr-nft-redeem.tsx @@ -1,25 +1,24 @@ import { BigNumber, ethers, Contract } from "ethers"; -import { useEffect, useState } from "react"; +import { useState } from "react"; import { ensureERC1155Allowance } from "@/lib/contracts-shortcuts"; import { formatEther } from "@/lib/format"; import { safeParseEther } from "@/lib/utils"; -import useDeployedContracts from "../lib/hooks/contracts/use-deployed-contracts"; -import useManagerManaged from "../lib/hooks/contracts/use-manager-managed"; +import useProtocolContracts from "@/components/lib/hooks/contracts/use-protocol-contracts"; import useBalances from "../lib/hooks/use-balances"; import useSigner from "../lib/hooks/use-signer"; import useTransactionLogger from "../lib/hooks/use-transaction-logger"; import useWalletAddress from "../lib/hooks/use-wallet-address"; import Button from "../ui/button"; import PositiveNumberInput from "../ui/positive-number-input"; +import useEffectAsync from "../lib/hooks/use-effect-async"; const UcrNftRedeem = () => { const [walletAddress] = useWalletAddress(); const signer = useSigner(); const [, refreshBalances] = useBalances(); const [, doTransaction, doingTransaction] = useTransactionLogger(); - const deployedContracts = useDeployedContracts(); - const managedContracts = useManagerManaged(); + const protocolContracts = useProtocolContracts(); const [inputVal, setInputVal] = useState(""); const [debtIds, setDebtIds] = useState(null); @@ -32,14 +31,15 @@ const UcrNftRedeem = () => { } }; - useEffect(() => { - if (managedContracts && walletAddress) { - fetchDebts(walletAddress, managedContracts.creditNft); + useEffectAsync(async () => { + const contracts = await protocolContracts; + if (contracts.creditNft && walletAddress) { + fetchDebts(walletAddress, contracts.creditNft); } - }, [managedContracts, walletAddress]); + }, [walletAddress]); if (!walletAddress || !signer) return Connect wallet; - if (!deployedContracts || !managedContracts || !debtIds) return · · ·; + if (!protocolContracts || !debtIds) return · · ·; if (debtIds.length === 0) return No uCR-NFT coupons; async function fetchDebts(address: string, contract: Contract) { @@ -67,12 +67,14 @@ const UcrNftRedeem = () => { }; const redeemUcrNftForUad = async (amount: BigNumber) => { - const { debtCouponManager } = deployedContracts; + const contracts = await protocolContracts; const debtId = debtIds[selectedDebtId]; - if (debtId && (await ensureERC1155Allowance("uCR-NFT -> DebtCouponManager", managedContracts.creditNft, signer, debtCouponManager.address))) { - await (await debtCouponManager.connect(signer).redeemCreditNft(debtId, amount)).wait(); - refreshBalances(); - fetchDebts(walletAddress, managedContracts.creditNft); + if (contracts.creditNft && contracts.creditNftManagerFacet) { + if (debtId && (await ensureERC1155Allowance("uCR-NFT -> CreditNftManagerFacet", contracts.creditNft, signer, contracts.creditNftManagerFacet.address))) { + await (await contracts.creditNftManagerFacet.connect(signer).redeemCreditNft(debtId, amount)).wait(); + refreshBalances(); + fetchDebts(walletAddress, contracts.creditNft); + } } }; diff --git a/packages/dapp/components/redeem/ucr-redeem.tsx b/packages/dapp/components/redeem/ucr-redeem.tsx index 5e3097a75..5e113c642 100644 --- a/packages/dapp/components/redeem/ucr-redeem.tsx +++ b/packages/dapp/components/redeem/ucr-redeem.tsx @@ -1,10 +1,9 @@ -import { BigNumber, Contract, ethers } from "ethers"; +import { BigNumber, ethers } from "ethers"; import { useState } from "react"; import { SwapWidget } from "@uniswap/widgets"; import { ensureERC20Allowance } from "@/lib/contracts-shortcuts"; import { safeParseEther } from "@/lib/utils"; -import useDeployedContracts from "../lib/hooks/contracts/use-deployed-contracts"; -import useManagerManaged from "../lib/hooks/contracts/use-manager-managed"; +import useProtocolContracts from "@/components/lib/hooks/contracts/use-protocol-contracts"; import useBalances from "../lib/hooks/use-balances"; import useSigner from "../lib/hooks/use-signer"; import useTransactionLogger from "../lib/hooks/use-transaction-logger"; @@ -12,7 +11,7 @@ import Button from "../ui/button"; import PositiveNumberInput from "../ui/positive-number-input"; import useRouter from "../lib/hooks/use-router"; import useTrade from "../lib/hooks/use-trade"; -import { USDC_ADDRESS, SWAP_WIDGET_TOKEN_LIST, V3_ROUTER_ADDRESS } from "@/lib/utils"; +import { SWAP_WIDGET_TOKEN_LIST, V3_ROUTER_ADDRESS } from "@/lib/utils"; import { getUniswapV3RouterContract } from "../utils/contracts"; import useWeb3 from "@/components/lib/hooks/use-web-3"; @@ -21,8 +20,7 @@ const UcrRedeem = ({ twapInteger }: { twapInteger: number }) => { const signer = useSigner(); const [balances, refreshBalances] = useBalances(); const [, doTransaction, doingTransaction] = useTransactionLogger(); - const deployedContracts = useDeployedContracts(); - const managedContracts = useManagerManaged(); + const protocolContracts = useProtocolContracts(); const [inputVal, setInputVal] = useState("0"); // cspell: disable-next-line @@ -34,22 +32,24 @@ const UcrRedeem = ({ twapInteger }: { twapInteger: number }) => { return Connect wallet; } - if (!managedContracts || !deployedContracts || !balances) { + if (!protocolContracts || !balances) { return · · ·; } const redeemUcr = async (amount: BigNumber) => { - const { debtCouponManager } = deployedContracts; - // cspell: disable-next-line - await ensureERC20Allowance("uCR -> DebtCouponManager", managedContracts.creditToken, amount, signer, debtCouponManager.address); - await (await debtCouponManager.connect(signer).burnCreditTokensForDollars(amount)).wait(); - refreshBalances(); - // cspell: disable-next-line - if (provider && quoteAmount && selectedRedeemToken !== "uAD") { - const routerContract = getUniswapV3RouterContract(V3_ROUTER_ADDRESS, provider); - await (await routerContract.connect(signer).approveMax(managedContracts.dollarToken.address)).wait(); - await useTrade(selectedRedeemToken, quoteAmount); + const contracts = await protocolContracts; + if (contracts.creditToken && contracts.creditNftManagerFacet && contracts.dollarToken) { + // cspell: disable-next-line + await ensureERC20Allowance("uCR -> CreditNftManagerFacet", contracts.creditToken, amount, signer, contracts.creditNftManagerFacet.address); + await (await contracts.creditNftManagerFacet.connect(signer).burnCreditTokensForDollars(amount)).wait(); refreshBalances(); + // cspell: disable-next-line + if (provider && quoteAmount && selectedRedeemToken !== "uAD") { + const routerContract = getUniswapV3RouterContract(V3_ROUTER_ADDRESS, provider); + await (await routerContract.connect(signer).approveMax(contracts.dollarToken.address)).wait(); + await useTrade(selectedRedeemToken, quoteAmount); + refreshBalances(); + } } }; diff --git a/packages/dapp/components/staking/bonding-shares-explorer.tsx b/packages/dapp/components/staking/bonding-shares-explorer.tsx index 686af865d..1c6282a43 100644 --- a/packages/dapp/components/staking/bonding-shares-explorer.tsx +++ b/packages/dapp/components/staking/bonding-shares-explorer.tsx @@ -52,53 +52,55 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider useAsyncInit(fetchSharesInformation); async function fetchSharesInformation(processedShareId?: ShareData["id"]) { // cspell: disable-next-line - const { stakingFacet: bonding, chefFacet, stakingShare: bondingToken, curveMetaPoolDollarTriPoolLp } = await protocolContracts; - console.time("BondingShareExplorerContainer contract loading"); - const currentBlock = await web3Provider.getBlockNumber(); - // cspell: disable-next-line - const blockCountInAWeek = +(await bonding!.blockCountInAWeek()).toString(); - const totalShares = await chefFacet!.totalShares(); - // cspell: disable-next-line - const bondingShareIds = await bondingToken!.holderTokens(walletAddress); + const { stakingFacet, chefFacet, stakingShare: bondingToken, curveMetaPoolDollarTriPoolLp } = await protocolContracts; + if (stakingFacet) { + console.time("BondingShareExplorerContainer contract loading"); + const currentBlock = await web3Provider.getBlockNumber(); + // cspell: disable-next-line + const blockCountInAWeek = +(await stakingFacet.blockCountInAWeek()).toString(); + const totalShares = await chefFacet?.totalShares(); + // cspell: disable-next-line + const bondingShareIds = await bondingToken?.holderTokens(walletAddress); - const walletLpBalance = await curveMetaPoolDollarTriPoolLp!.balanceOf(walletAddress); + const walletLpBalance = await curveMetaPoolDollarTriPoolLp?.balanceOf(walletAddress); - const shares: ShareData[] = []; - await Promise.all( - // cspell: disable-next-line - bondingShareIds.map(async (id: BigNumber) => { + const shares: ShareData[] = []; + await Promise.all( // cspell: disable-next-line - const [ugov, bond, bondingShareInfo, tokenBalance] = await Promise.all([ - // cspell: disable-next-line - chefFacet!.pendingGovernance(id), + bondingShareIds.map(async (id: BigNumber) => { // cspell: disable-next-line - bondingToken!.getStake(id), - chefFacet!.getStakingShareInfo(id), - // cspell: disable-next-line - bondingToken!.balanceOf(walletAddress, id), - ]); + const [ugov, bond, bondingShareInfo, tokenBalance] = await Promise.all([ + // cspell: disable-next-line + chefFacet?.pendingGovernance(id), + // cspell: disable-next-line + bondingToken?.getStake(id), + chefFacet?.getStakingShareInfo(id), + // cspell: disable-next-line + bondingToken?.balanceOf(walletAddress, id), + ]); - const endBlock = +bond.endBlock.toString(); - const blocksLeft = endBlock - currentBlock; - const weeksLeft = Math.round((blocksLeft / blockCountInAWeek) * 100) / 100; + const endBlock = +bond.endBlock.toString(); + const blocksLeft = endBlock - currentBlock; + const weeksLeft = Math.round((blocksLeft / blockCountInAWeek) * 100) / 100; - // If this is 0 it means the share ERC1155 token was transferred to another account - if (+tokenBalance.toString() > 0) { - // cspell: disable-next-line - shares.push({ id: +id.toString(), ugov, bond, sharesBalance: bondingShareInfo[0], weeksLeft }); - } - }) - ); - - const sortedShares = shares.sort((a, b) => a.id - b.id); - - console.timeEnd("BondingShareExplorerContainer contract loading"); - setModel((model) => ({ - processing: model ? model.processing.filter((id) => id !== processedShareId) : [], - shares: sortedShares, - totalShares, - walletLpBalance, - })); + // If this is 0 it means the share ERC1155 token was transferred to another account + if (+tokenBalance.toString() > 0) { + // cspell: disable-next-line + shares.push({ id: +id.toString(), ugov, bond, sharesBalance: bondingShareInfo[0], weeksLeft }); + } + }) + ); + + const sortedShares = shares.sort((a, b) => a.id - b.id); + + console.timeEnd("BondingShareExplorerContainer contract loading"); + setModel((model) => ({ + processing: model ? model.processing.filter((id) => id !== processedShareId) : [], + shares: sortedShares, + totalShares, + walletLpBalance, + })); + } } function allLpAmount(id: number): BigNumber { @@ -118,19 +120,19 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider doTransaction("Withdrawing LP...", async () => { try { // cspell: disable-next-line - const isAllowed = await bondingToken!.isApprovedForAll(walletAddress, bonding!.address); + const isAllowed = await bondingToken?.isApprovedForAll(walletAddress, bonding?.address); if (!isAllowed) { // cspell: disable-next-line // Allow bonding contract to control account share // cspell: disable-next-line - if (!(await performTransaction(bondingToken!.connect(signer).setApprovalForAll(bonding!.address, true)))) { + if (!(await performTransaction(bondingToken?.connect(signer).setApprovalForAll(bonding?.address, true)))) { return; // TODO: Show transaction errors to user } } const bigNumberAmount = amount ? ethers.utils.parseEther(amount.toString()) : allLpAmount(id); // cspell: disable-next-line - await performTransaction(bonding!.connect(signer).removeLiquidity(bigNumberAmount, BigNumber.from(id))); + await performTransaction(bonding?.connect(signer).removeLiquidity(bigNumberAmount, BigNumber.from(id))); } catch (error) { console.log(`Withdrawing LP from ${id} failed:`, error); // throws exception to update the transaction log @@ -152,7 +154,7 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider setModel((prevModel) => (prevModel ? { ...prevModel, processing: [...prevModel.processing, id] } : null)); doTransaction("Claiming Ubiquity Governance tokens...", async () => { try { - await performTransaction(chefFacet!.connect(signer).getRewards(BigNumber.from(id))); + await performTransaction(chefFacet?.connect(signer).getRewards(BigNumber.from(id))); } catch (error) { console.log(`Claiming Ubiquity Governance token rewards from ${id} failed:`, error); // throws exception to update the transaction log @@ -174,18 +176,18 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider doTransaction("Staking...", async () => {}); // cspell: disable-next-line - const allowance = await curveMetaPoolDollarTriPoolLp!.allowance(walletAddress, bonding!.address); + const allowance = await curveMetaPoolDollarTriPoolLp?.allowance(walletAddress, bonding?.address); console.log("allowance", ethers.utils.formatEther(allowance)); console.log("lpsAmount", ethers.utils.formatEther(amount)); if (allowance.lt(amount)) { // cspell: disable-next-line - await performTransaction(curveMetaPoolDollarTriPoolLp!.connect(signer).approve(bonding!.address, amount)); + await performTransaction(curveMetaPoolDollarTriPoolLp?.connect(signer).approve(bonding?.address, amount)); // cspell: disable-next-line - const allowance2 = await curveMetaPoolDollarTriPoolLp!.allowance(walletAddress, bonding!.address); + const allowance2 = await curveMetaPoolDollarTriPoolLp?.allowance(walletAddress, bonding?.address); console.log("allowance2", ethers.utils.formatEther(allowance2)); } // cspell: disable-next-line - await performTransaction(bonding!.connect(signer).deposit(amount, weeks)); + await performTransaction(bonding?.connect(signer).deposit(amount, weeks)); fetchSharesInformation(); refreshBalances(); diff --git a/packages/dapp/components/staking/deposit-share.tsx b/packages/dapp/components/staking/deposit-share.tsx index ab32298a3..7025bc992 100644 --- a/packages/dapp/components/staking/deposit-share.tsx +++ b/packages/dapp/components/staking/deposit-share.tsx @@ -17,17 +17,17 @@ const MAX_WEEKS = 208; type PrefetchedConstants = { totalShares: number; usdPerWeek: number; bondingDiscountMultiplier: BigNumber }; async function prefetchConstants(contracts: NonNullable): Promise { const contract = await contracts; - const reserves = await contract.sushiPoolGovernanceDollarLp!.getReserves(); + const reserves = await contract.sushiPoolGovernanceDollarLp?.getReserves(); const ubqPrice = +reserves[0].toString() / +reserves[1].toString(); - const ubqPerBlock = await contract.chefFacet!.governancePerBlock(); - const ubqMultiplier = await contract.chefFacet!.governanceMultiplier(); + const ubqPerBlock = await contract.chefFacet?.governancePerBlock(); + const ubqMultiplier = await contract.chefFacet?.governanceMultiplier(); const actualUbqPerBlock = toEtherNum(ubqPerBlock.mul(ubqMultiplier).div(`${1e18}`)); - const blockCountInAWeek = toNum(await contract.stakingFacet!.blockCountInAWeek()); + const blockCountInAWeek = toNum(await contract.stakingFacet?.blockCountInAWeek()); const ubqPerWeek = actualUbqPerBlock * blockCountInAWeek; - const totalShares = toEtherNum(await contract.chefFacet!.totalShares()); + const totalShares = toEtherNum(await contract.chefFacet?.totalShares()); const usdPerWeek = ubqPerWeek * ubqPrice; // cspell: disable-next-line - const bondingDiscountMultiplier = await contract.stakingFacet!.stakingDiscountMultiplier(); + const bondingDiscountMultiplier = await contract.stakingFacet?.stakingDiscountMultiplier(); // cspell: disable-next-line return { totalShares, usdPerWeek, bondingDiscountMultiplier }; } @@ -41,7 +41,7 @@ async function calculateApyForWeeks(contracts: NonNullable, p const bigNumberOneUsdAsLp = ethers.utils.parseEther(usdAsLp.toString()); const weeks = BigNumber.from(weeksNum.toString()); // cspell: disable-next-line - const shares = toEtherNum(contract.stakingFormulasFacet!.durationMultiply(bigNumberOneUsdAsLp, weeks, bondingDiscountMultiplier)); + const shares = toEtherNum(contract.stakingFormulasFacet?.durationMultiply(bigNumberOneUsdAsLp, weeks, bondingDiscountMultiplier)); const rewardsPerWeek = (shares / totalShares) * usdPerWeek; const yearlyYield = (rewardsPerWeek / 7) * DAYS_IN_A_YEAR * 100; return Math.round(yearlyYield * 100) / 100; diff --git a/packages/dapp/pages/credits.tsx b/packages/dapp/pages/credits.tsx index 80320e0d2..c5cf19de5 100644 --- a/packages/dapp/pages/credits.tsx +++ b/packages/dapp/pages/credits.tsx @@ -3,7 +3,7 @@ import DollarPrice from "@/components/redeem/dollar-price"; import UcrRedeem from "@/components/redeem/ucr-redeem"; import UcrNftGenerator from "@/components/redeem/debt-coupon-deposit"; import UcrNftRedeem from "@/components/redeem/ucr-nft-redeem"; -import useManagerManaged from "@/components/lib/hooks/contracts/use-manager-managed"; +import useProtocolContracts from "@/components/lib/hooks/contracts/use-protocol-contracts"; import useEffectAsync from "@/components/lib/hooks/use-effect-async"; // import DisabledBlurredMessage from "@/components/ui/DisabledBlurredMessage"; import dynamic from "next/dynamic"; @@ -11,17 +11,19 @@ const WalletConnectionWall = dynamic(() => import("@/components/ui/wallet-connec const PriceStabilization: FC = (): JSX.Element => { const [twapInteger, setTwapInteger] = useState(0); - const managedContracts = useManagerManaged(); + const protocolContracts = useProtocolContracts(); useEffectAsync(async () => { - if (managedContracts) { - const twapPrice = await managedContracts.dollarTwapOracle.consult(managedContracts.dollarToken.address); + const contracts = await protocolContracts; + if (contracts) { + const dollarTokenAddress = await contracts.managerFacet?.dollarTokenAddress(); + const twapPrice = await contracts.twapOracleDollar3poolFacet?.consult(dollarTokenAddress); if (twapPrice) { const twapPriceInteger = (twapPrice as unknown as number) / 1e18; setTwapInteger(twapPriceInteger); } } - }, [managedContracts]); + }, []); return ( diff --git a/packages/dapp/pages/index.tsx b/packages/dapp/pages/index.tsx index 6003cdfbc..a0a0777e0 100644 --- a/packages/dapp/pages/index.tsx +++ b/packages/dapp/pages/index.tsx @@ -26,7 +26,7 @@ const index: FC = (): JSX.Element => { console.log("protocolContracts is null"); setTwapPrice(null); } - }, [protocolContracts]); + }, []); if (process.env.DEBUG === "true") { fetchData(); From 9e07817070438b2cfb2d996271d2fa467ce712e6 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Tue, 10 Oct 2023 03:19:09 -0700 Subject: [PATCH 16/19] fix: contract type in allowance functions --- packages/dapp/components/lib/contracts-shortcuts.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/dapp/components/lib/contracts-shortcuts.ts b/packages/dapp/components/lib/contracts-shortcuts.ts index c1078e25f..3c73d46b3 100644 --- a/packages/dapp/components/lib/contracts-shortcuts.ts +++ b/packages/dapp/components/lib/contracts-shortcuts.ts @@ -1,11 +1,11 @@ -import { BigNumber, ethers } from "ethers"; +import { BigNumber, ethers, Contract } from "ethers"; import { ERC1155Ubiquity, ERC20 } from "types"; import { performTransaction } from "./utils"; export async function ensureERC20Allowance( logName: string, - contract: ERC20, + contract: ERC20 | Contract, amount: BigNumber, signer: ethers.providers.JsonRpcSigner, spender: string, @@ -25,7 +25,7 @@ export async function ensureERC20Allowance( return true; } -export async function ensureERC1155Allowance(logName: string, contract: ERC1155Ubiquity, signer: ethers.providers.JsonRpcSigner, spender: string): Promise { +export async function ensureERC1155Allowance(logName: string, contract: ERC1155Ubiquity | Contract, signer: ethers.providers.JsonRpcSigner, spender: string): Promise { const signerAddress = await signer.getAddress(); const isAllowed = await contract.isApprovedForAll(signerAddress, spender); console.log(`${logName} isAllowed: `, isAllowed); From e7dc29fb3568dd1d4a1443ea42a8dc13b2483881 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Thu, 12 Oct 2023 05:45:51 -0700 Subject: [PATCH 17/19] fix: passed hardcoded addresses as variable --- .../lib/hooks/contracts/use-protocol-contracts.ts | 7 ++++--- packages/dapp/components/lib/hooks/use-balances.tsx | 7 +++---- packages/dapp/components/lib/utils.ts | 4 ++++ 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts b/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts index 9e0db19c9..8f65fb960 100644 --- a/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts +++ b/packages/dapp/components/lib/hooks/contracts/use-protocol-contracts.ts @@ -3,6 +3,7 @@ import { Contract, ethers } from "ethers"; import latestDeployment from "@ubiquity/contracts/broadcast/05_StakingShare.s.sol/31337/run-latest.json"; import useWeb3 from "../use-web-3"; +import { sushiSwapPoolAddress, dollar3poolMarketAddress } from "@/lib/utils"; // contract build artifacts // separately deployed contracts @@ -28,7 +29,7 @@ import StakingFormulasFacetArtifact from "@ubiquity/contracts/out/StakingFormula import TWAPOracleDollar3poolFacetArtifact from "@ubiquity/contracts/out/TWAPOracleDollar3poolFacet.sol/TWAPOracleDollar3poolFacet.json"; import UbiquityPoolFacetArtifact from "@ubiquity/contracts/out/UbiquityPoolFacet.sol/UbiquityPoolFacet.json"; // other related contracts -import SushiSwapPoolArtifact from "@ubiquity/contracts/out/SushiSwapPool.sol/SushiSwapPool.json"; +// import SushiSwapPoolArtifact from "@ubiquity/contracts/out/SushiSwapPool.sol/SushiSwapPool.json"; import IMetaPoolArtifact from "@ubiquity/contracts/out/IMetaPool.sol/IMetaPool.json"; import UniswapV2PairABI from "@/components/config/abis/uniswap-v-2-pair.json"; @@ -163,12 +164,12 @@ const useProtocolContracts = async () => { // const sushiSwapPool = await protocolContracts.managerFacet.sushiSwapPoolAddress(); // const sushiSwapPoolContract = new ethers.Contract(sushiSwapPool, SushiSwapPoolArtifact.abi, provider); // const UniswapV2PairContract = new ethers.Contract(await sushiSwapPoolContract.pair(), UniswapV2PairABI, provider); - const UniswapV2PairContract = new ethers.Contract("0x41e087485f47538752A1195D984109cB8Dc0E429", UniswapV2PairABI, provider); + const UniswapV2PairContract = new ethers.Contract(sushiSwapPoolAddress, UniswapV2PairABI, provider); protocolContracts.sushiPoolGovernanceDollarLp = UniswapV2PairContract; // const dollar3poolMarket = await protocolContracts.managerFacet.stableSwapMetaPoolAddress(); // const metaPoolContract = new ethers.Contract(dollar3poolMarket, IMetaPoolArtifact.abi, provider); - const metaPoolContract = new ethers.Contract("0x20955CB69Ae1515962177D164dfC9522feef567E", IMetaPoolArtifact.abi, provider); + const metaPoolContract = new ethers.Contract(dollar3poolMarketAddress, IMetaPoolArtifact.abi, provider); protocolContracts.curveMetaPoolDollarTriPoolLp = metaPoolContract; return protocolContracts; diff --git a/packages/dapp/components/lib/hooks/use-balances.tsx b/packages/dapp/components/lib/hooks/use-balances.tsx index 227629c2d..0648a01ad 100644 --- a/packages/dapp/components/lib/hooks/use-balances.tsx +++ b/packages/dapp/components/lib/hooks/use-balances.tsx @@ -1,4 +1,4 @@ -import { erc1155BalanceOf } from "@/lib/utils"; +import { erc1155BalanceOf, _3crvTokenAddress } from "@/lib/utils"; import { BigNumber } from "ethers"; import { createContext, useContext, useEffect, useState } from "react"; import useNamedContracts from "./contracts/use-named-contracts"; @@ -40,9 +40,8 @@ export const BalancesContextProvider: React.FC = ({ children }) => const contracts = await protocolContracts; if(contracts.creditNft && contracts.stakingShare) { - // const _3crvToken = await contracts.managerFacet?.curve3PoolTokenAddress(); - const _3crvToken = "0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490"; - const _3crvTokenContract = getERC20Contract(_3crvToken, provider); + // const _3crvTokenAddress = await contracts.managerFacet?.curve3PoolTokenAddress(); + const _3crvTokenContract = getERC20Contract(_3crvTokenAddress, provider); const [uad, _3crv, uad3crv, ucr, ubq, ucrNft, stakingShares, usdc, dai, usdt] = await Promise.all([ contracts.dollarToken?.balanceOf(walletAddress), diff --git a/packages/dapp/components/lib/utils.ts b/packages/dapp/components/lib/utils.ts index 2caf22cb1..87d747854 100644 --- a/packages/dapp/components/lib/utils.ts +++ b/packages/dapp/components/lib/utils.ts @@ -122,6 +122,10 @@ export const uCR_USDT_ADDRESS = "0x9d498aB38Aa889AE0f4A865d30da2116ee9716bC"; // Uniswap Router address export const V3_ROUTER_ADDRESS = "0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"; +export const sushiSwapPoolAddress = "0x41e087485f47538752A1195D984109cB8Dc0E429"; +export const dollar3poolMarketAddress = "0x20955CB69Ae1515962177D164dfC9522feef567E"; +export const _3crvTokenAddress = "0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490"; + export const safeParseEther = (val: string) => { try { return ethers.utils.parseEther(val); From c086a17ac81fde6b93cda29d36f1092349b1cddc Mon Sep 17 00:00:00 2001 From: bojan07 Date: Thu, 12 Oct 2023 06:22:08 -0700 Subject: [PATCH 18/19] fix: updated variable names according to new name convention --- ...plorer.tsx => staking-shares-explorer.tsx} | 82 +++++++++---------- packages/dapp/pages/staking.tsx | 4 +- 2 files changed, 43 insertions(+), 43 deletions(-) rename packages/dapp/components/staking/{bonding-shares-explorer.tsx => staking-shares-explorer.tsx} (77%) diff --git a/packages/dapp/components/staking/bonding-shares-explorer.tsx b/packages/dapp/components/staking/staking-shares-explorer.tsx similarity index 77% rename from packages/dapp/components/staking/bonding-shares-explorer.tsx rename to packages/dapp/components/staking/staking-shares-explorer.tsx index 1c6282a43..bc373a4bb 100644 --- a/packages/dapp/components/staking/bonding-shares-explorer.tsx +++ b/packages/dapp/components/staking/staking-shares-explorer.tsx @@ -15,8 +15,8 @@ import Loading from "../ui/loading"; type ShareData = { id: number; // cspell: disable-next-line - ugov: BigNumber; - bond: { + governanceToken: BigNumber; + stake: { minter: string; lpFirstDeposited: BigNumber; creationBlock: BigNumber; @@ -44,7 +44,7 @@ type Actions = { const USD_TO_LP = 0.7460387929; const LP_TO_USD = 1 / USD_TO_LP; -export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider, walletAddress, signer }: LoadedContext) => { +export const StakingSharesExplorerContainer = ({ protocolContracts, web3Provider, walletAddress, signer }: LoadedContext) => { const [model, setModel] = useState(null); const [, doTransaction] = useTransactionLogger(); const [, refreshBalances] = useBalances(); @@ -52,48 +52,48 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider useAsyncInit(fetchSharesInformation); async function fetchSharesInformation(processedShareId?: ShareData["id"]) { // cspell: disable-next-line - const { stakingFacet, chefFacet, stakingShare: bondingToken, curveMetaPoolDollarTriPoolLp } = await protocolContracts; + const { stakingFacet, chefFacet, stakingShare: stakingToken, curveMetaPoolDollarTriPoolLp } = await protocolContracts; if (stakingFacet) { - console.time("BondingShareExplorerContainer contract loading"); + console.time("StakingShareExplorerContainer contract loading"); const currentBlock = await web3Provider.getBlockNumber(); // cspell: disable-next-line const blockCountInAWeek = +(await stakingFacet.blockCountInAWeek()).toString(); const totalShares = await chefFacet?.totalShares(); // cspell: disable-next-line - const bondingShareIds = await bondingToken?.holderTokens(walletAddress); + const stakingShareIds = await stakingToken?.holderTokens(walletAddress); const walletLpBalance = await curveMetaPoolDollarTriPoolLp?.balanceOf(walletAddress); const shares: ShareData[] = []; await Promise.all( // cspell: disable-next-line - bondingShareIds.map(async (id: BigNumber) => { + stakingShareIds.map(async (id: BigNumber) => { // cspell: disable-next-line - const [ugov, bond, bondingShareInfo, tokenBalance] = await Promise.all([ + const [governanceToken, stake, stakingShareInfo, tokenBalance] = await Promise.all([ // cspell: disable-next-line chefFacet?.pendingGovernance(id), // cspell: disable-next-line - bondingToken?.getStake(id), + stakingToken?.getStake(id), chefFacet?.getStakingShareInfo(id), // cspell: disable-next-line - bondingToken?.balanceOf(walletAddress, id), + stakingToken?.balanceOf(walletAddress, id), ]); - const endBlock = +bond.endBlock.toString(); + const endBlock = +stake.endBlock.toString(); const blocksLeft = endBlock - currentBlock; const weeksLeft = Math.round((blocksLeft / blockCountInAWeek) * 100) / 100; // If this is 0 it means the share ERC1155 token was transferred to another account if (+tokenBalance.toString() > 0) { // cspell: disable-next-line - shares.push({ id: +id.toString(), ugov, bond, sharesBalance: bondingShareInfo[0], weeksLeft }); + shares.push({ id: +id.toString(), governanceToken, stake, sharesBalance: stakingShareInfo[0], weeksLeft }); } }) ); const sortedShares = shares.sort((a, b) => a.id - b.id); - console.timeEnd("BondingShareExplorerContainer contract loading"); + console.timeEnd("StakingShareExplorerContainer contract loading"); setModel((model) => ({ processing: model ? model.processing.filter((id) => id !== processedShareId) : [], shares: sortedShares, @@ -105,7 +105,7 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider function allLpAmount(id: number): BigNumber { if (!model) throw new Error("No model"); - const lpAmount = model.shares.find((s) => s.id === id)?.bond?.lpAmount; + const lpAmount = model.shares.find((s) => s.id === id)?.stake?.lpAmount; if (!lpAmount) throw new Error("Could not find share in model"); return lpAmount; } @@ -113,26 +113,26 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider const actions: Actions = { onWithdrawLp: useCallback( async ({ id, amount }) => { - const { stakingFacet: bonding, stakingShare: bondingToken } = await protocolContracts; + const { stakingFacet: staking, stakingShare: stakingToken } = await protocolContracts; if (!model || model.processing.includes(id)) return; console.log(`Withdrawing ${amount ? amount : "ALL"} LP from ${id}`); setModel((prevModel) => (prevModel ? { ...prevModel, processing: [...prevModel.processing, id] } : null)); doTransaction("Withdrawing LP...", async () => { try { // cspell: disable-next-line - const isAllowed = await bondingToken?.isApprovedForAll(walletAddress, bonding?.address); + const isAllowed = await stakingToken?.isApprovedForAll(walletAddress, staking?.address); if (!isAllowed) { // cspell: disable-next-line - // Allow bonding contract to control account share + // Allow staking contract to control account share // cspell: disable-next-line - if (!(await performTransaction(bondingToken?.connect(signer).setApprovalForAll(bonding?.address, true)))) { + if (!(await performTransaction(stakingToken?.connect(signer).setApprovalForAll(staking?.address, true)))) { return; // TODO: Show transaction errors to user } } const bigNumberAmount = amount ? ethers.utils.parseEther(amount.toString()) : allLpAmount(id); // cspell: disable-next-line - await performTransaction(bonding?.connect(signer).removeLiquidity(bigNumberAmount, BigNumber.from(id))); + await performTransaction(staking?.connect(signer).removeLiquidity(bigNumberAmount, BigNumber.from(id))); } catch (error) { console.log(`Withdrawing LP from ${id} failed:`, error); // throws exception to update the transaction log @@ -170,24 +170,24 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider onStake: useCallback( async ({ amount, weeks }) => { - const { stakingFacet: bonding, curveMetaPoolDollarTriPoolLp } = await protocolContracts; + const { stakingFacet: staking, curveMetaPoolDollarTriPoolLp } = await protocolContracts; if (!model || model.processing.length) return; console.log(`Staking ${amount} for ${weeks} weeks`); doTransaction("Staking...", async () => {}); // cspell: disable-next-line - const allowance = await curveMetaPoolDollarTriPoolLp?.allowance(walletAddress, bonding?.address); + const allowance = await curveMetaPoolDollarTriPoolLp?.allowance(walletAddress, staking?.address); console.log("allowance", ethers.utils.formatEther(allowance)); console.log("lpsAmount", ethers.utils.formatEther(amount)); if (allowance.lt(amount)) { // cspell: disable-next-line - await performTransaction(curveMetaPoolDollarTriPoolLp?.connect(signer).approve(bonding?.address, amount)); + await performTransaction(curveMetaPoolDollarTriPoolLp?.connect(signer).approve(staking?.address, amount)); // cspell: disable-next-line - const allowance2 = await curveMetaPoolDollarTriPoolLp?.allowance(walletAddress, bonding?.address); + const allowance2 = await curveMetaPoolDollarTriPoolLp?.allowance(walletAddress, staking?.address); console.log("allowance2", ethers.utils.formatEther(allowance2)); } // cspell: disable-next-line - await performTransaction(bonding?.connect(signer).deposit(amount, weeks)); + await performTransaction(staking?.connect(signer).deposit(amount, weeks)); fetchSharesInformation(); refreshBalances(); @@ -196,27 +196,27 @@ export const BondingSharesExplorerContainer = ({ protocolContracts, web3Provider ), }; - return ; + return ; }; -export const BondingSharesExplorer = memo(({ model, actions }: { model: Model | null; actions: Actions }) => { - return <>{model ? : }; +export const StakingSharesExplorer = memo(({ model, actions }: { model: Model | null; actions: Actions }) => { + return <>{model ? : }; }); -export const BondingSharesInformation = ({ shares, totalShares, onWithdrawLp, onClaimUbq, onStake, processing, walletLpBalance }: Model & Actions) => { +export const StakingSharesInformation = ({ shares, totalShares, onWithdrawLp, onClaimUbq, onStake, processing, walletLpBalance }: Model & Actions) => { const totalUserShares = shares.reduce((sum, val) => { return sum.add(val.sharesBalance); }, BigNumber.from(0)); const totalLpBalance = shares.reduce((sum, val) => { - return sum.add(val.bond.lpAmount); + return sum.add(val.stake.lpAmount); }, BigNumber.from(0)); // cspell: disable-next-line - const totalPendingUgov = shares.reduce((sum, val) => sum.add(val.ugov), BigNumber.from(0)); + const totalPendingGovernanceToken = shares.reduce((sum, val) => sum.add(val.governanceToken), BigNumber.from(0)); const poolPercentage = totalShares.isZero() ? 0 : formatEther(totalUserShares.mul(ethers.utils.parseEther("100")).div(totalShares)); // cspell: disable-next-line - const filteredShares = shares.filter(({ bond: { lpAmount }, ugov }) => lpAmount.gt(0) || ugov.gt(0)); + const filteredShares = shares.filter(({ stake: { lpAmount }, governanceToken }) => lpAmount.gt(0) || governanceToken.gt(0)); return (
@@ -233,7 +233,7 @@ export const BondingSharesInformation = ({ shares, totalShares, onWithdrawLp, on {filteredShares.length > 0 ? ( {filteredShares.map((share) => ( - + ))} ) : ( @@ -256,7 +256,7 @@ export const BondingSharesInformation = ({ shares, totalShares, onWithdrawLp, on {/* cspell: disable-next-line */} - {formatEther(totalPendingUgov)} + {formatEther(totalPendingGovernanceToken)} @@ -279,12 +279,12 @@ export const BondingSharesInformation = ({ shares, totalShares, onWithdrawLp, on ); }; -type BondingShareRowProps = ShareData & { disabled: boolean; onWithdrawLp: Actions["onWithdrawLp"]; onClaimUbq: Actions["onClaimUbq"] }; +type StakingShareRowProps = ShareData & { disabled: boolean; onWithdrawLp: Actions["onWithdrawLp"]; onClaimUbq: Actions["onClaimUbq"] }; // cspell: disable-next-line -const BondingShareRow = ({ id, ugov, sharesBalance, bond, weeksLeft, disabled, onWithdrawLp, onClaimUbq }: BondingShareRowProps) => { +const StakingShareRow = ({ id, governanceToken, stake, weeksLeft, disabled, onWithdrawLp, onClaimUbq }: StakingShareRowProps) => { const [withdrawAmount] = useState(""); - const numLpAmount = +formatEther(bond.lpAmount); + const numLpAmount = +formatEther(stake.lpAmount); const usdAmount = numLpAmount * LP_TO_USD; function onClickWithdraw() { @@ -297,14 +297,14 @@ const BondingShareRow = ({ id, ugov, sharesBalance, bond, weeksLeft, disabled, o } return ( - + - {weeksLeft <= 0 && bond.lpAmount.gt(0) ? ( + {weeksLeft <= 0 && stake.lpAmount.gt(0) ? ( ) : // cspell: disable-next-line - ugov.gt(0) ? ( + governanceToken.gt(0) ? ( @@ -313,7 +313,7 @@ const BondingShareRow = ({ id, ugov, sharesBalance, bond, weeksLeft, disabled, o
{/* cspell: disable-next-line */} - {formatEther(ugov)} + {formatEther(governanceToken)}
{weeksLeft <= 0 ? "Ready" : {weeksLeft}w} @@ -323,4 +323,4 @@ const BondingShareRow = ({ id, ugov, sharesBalance, bond, weeksLeft, disabled, o ); }; -export default withLoadedContext(BondingSharesExplorerContainer); +export default withLoadedContext(StakingSharesExplorerContainer); diff --git a/packages/dapp/pages/staking.tsx b/packages/dapp/pages/staking.tsx index e26d6cd9e..44d2c372b 100644 --- a/packages/dapp/pages/staking.tsx +++ b/packages/dapp/pages/staking.tsx @@ -1,12 +1,12 @@ import { FC } from "react"; -import BondingSharesExplorer from "@/components/staking/bonding-shares-explorer"; +import StakingSharesExplorer from "@/components/staking/staking-shares-explorer"; import dynamic from "next/dynamic"; const WalletConnectionWall = dynamic(() => import("@/components/ui/wallet-connection-wall"), { ssr: false }); //@note Fix: (Hydration Error) const Staking: FC = (): JSX.Element => { return ( - + ); }; From cd4ce710d737e10c273659ef39ac58c77d9e6668 Mon Sep 17 00:00:00 2001 From: bojan07 Date: Thu, 12 Oct 2023 13:52:33 -0700 Subject: [PATCH 19/19] fix: match contract type according to diamond architecture --- packages/dapp/components/lib/contracts-shortcuts.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/dapp/components/lib/contracts-shortcuts.ts b/packages/dapp/components/lib/contracts-shortcuts.ts index 3c73d46b3..be4f208be 100644 --- a/packages/dapp/components/lib/contracts-shortcuts.ts +++ b/packages/dapp/components/lib/contracts-shortcuts.ts @@ -1,11 +1,10 @@ import { BigNumber, ethers, Contract } from "ethers"; -import { ERC1155Ubiquity, ERC20 } from "types"; import { performTransaction } from "./utils"; export async function ensureERC20Allowance( logName: string, - contract: ERC20 | Contract, + contract: Contract, amount: BigNumber, signer: ethers.providers.JsonRpcSigner, spender: string, @@ -25,7 +24,7 @@ export async function ensureERC20Allowance( return true; } -export async function ensureERC1155Allowance(logName: string, contract: ERC1155Ubiquity | Contract, signer: ethers.providers.JsonRpcSigner, spender: string): Promise { +export async function ensureERC1155Allowance(logName: string, contract: Contract, signer: ethers.providers.JsonRpcSigner, spender: string): Promise { const signerAddress = await signer.getAddress(); const isAllowed = await contract.isApprovedForAll(signerAddress, spender); console.log(`${logName} isAllowed: `, isAllowed);