Skip to content

Commit

Permalink
Feat :add btc wallet
Browse files Browse the repository at this point in the history
  • Loading branch information
lq0-github committed Jan 14, 2025
1 parent fe90487 commit 0647da4
Show file tree
Hide file tree
Showing 24 changed files with 1,085 additions and 123 deletions.
5 changes: 4 additions & 1 deletion api/get-account-meme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ const getAccountMEME = async () => {
const assets = await getAssetsMEMEDetailed();
const tokenIds = assets.map((asset) => asset.token_id);
const shadowRecords = await getShadowRecords();
const accountBalance = (await account.getAccountBalance()).available;
let accountBalance = "0";
try {
accountBalance = (await account.getAccountBalance()).available;
} catch (error) {}
const balances = await Promise.all(
tokenIds.map((id) => getBalance(id, accountId, shadowRecords)),
);
Expand Down
8 changes: 4 additions & 4 deletions api/get-account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { getAssetsDetailed } from "../store";
import getBalance from "./get-balance";
import getPortfolio from "./get-portfolio";
import getShadowRecords from "./get-shadows";
import { blackAssets } from "../utils/config";
import { getAccount as getAccountWallet } from "../utils/wallet-selector-compat";

const getAccount = async () => {
Expand All @@ -13,13 +12,14 @@ const getAccount = async () => {
const assets = await getAssetsDetailed();
const tokenIds = assets.map((asset) => asset.token_id);
const shadowRecords = await getShadowRecords();
const accountBalance = (await account.getAccountBalance()).available;
let accountBalance = "0";
try {
accountBalance = (await account.getAccountBalance()).available;
} catch (error) {}
const balances = await Promise.all(
tokenIds.map((id) => getBalance(id, accountId, shadowRecords)),
);
const portfolio = await getPortfolio(accountId);
// delete portfolio.positions["shadow_ref_v1-0"];
// portfolio.supplied = portfolio.supplied.filter((a) => !blackAssets.includes(a.token_id));
return { accountId, accountBalance, balances, portfolio, tokenIds };
}

Expand Down
5 changes: 3 additions & 2 deletions api/get-assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ const getLptMetadata = (lp_token_details: IUnitLptAssetDetail, priceMap, metadat
};

const getAssets = async () => {
const assets_pending = await getAssetsDetailed();
const assets = assets_pending.filter((asset) => !blackAssets.includes(asset.token_id));
const assetsPendng = await getAssetsDetailed();
// TODO for satoshi
const assets = assetsPendng.filter((asset) => asset.token_id.indexOf(lpTokenPrefix) === -1);
const token_ids_from_regular = assets
.filter((asset) => asset.token_id.indexOf(lpTokenPrefix) === -1)
.map((asset) => asset.token_id);
Expand Down
11 changes: 8 additions & 3 deletions components/Header/WalletButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useState, useEffect, useRef, createContext, useContext } from "react";
import { Button, Box, useTheme, Modal as MUIModal } from "@mui/material";
import type { WalletSelector } from "@near-wallet-selector/core";
import { BeatLoader } from "react-spinners";
import { useDebounce } from "react-use";
import { fetchAssets, fetchRefPrices } from "../../redux/assetsSlice";
import { fetchAssetsMEME } from "../../redux/assetsSliceMEME";
import { logoutAccount, fetchAccount, setAccountId } from "../../redux/accountSlice";
Expand Down Expand Up @@ -77,9 +78,13 @@ const WalletButton = () => {
}
};

useEffect(() => {
onMount();
}, [accountId]);
useDebounce(
() => {
onMount();
},
500,
[accountId],
);

const onWalletButtonClick = async () => {
if (!hasAgreedDisclaimer) {
Expand Down
75 changes: 75 additions & 0 deletions components/Icons/Icons.tsx

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions components/Modal/Action.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState, useMemo, useEffect } from "react";
import Decimal from "decimal.js";
import { useBtcWalletSelector } from "btc-wallet";
import { nearTokenId } from "../../utils";
import { toggleUseAsCollateral, hideModal } from "../../redux/appSlice";
import {
Expand Down Expand Up @@ -28,8 +29,10 @@ export default function Action({ maxBorrowAmount, healthFactor, collateralType,
const [loading, setLoading] = useState(false);
const { amount, useAsCollateral, isMax } = useAppSelector(getSelectedValues);
const { enable_pyth_oracle } = useAppSelector(getConfig); // TODO33 need query from api?
const selectedWalletId = window.selector?.store?.getState()?.selectedWalletId;
const dispatch = useAppDispatch();
const asset = useAppSelector(getAssetData);
const { account, autoConnect } = useBtcWalletSelector();
const { action = "Deposit", tokenId, borrowApy, price, portfolio, isLpToken, position } = asset;
const { isRepayFromDeposits } = useDegenMode();
const isMeme = useAppSelector(isMemeCategory);
Expand All @@ -56,6 +59,10 @@ export default function Action({ maxBorrowAmount, healthFactor, collateralType,
}, [useAsCollateral]);

const handleActionButtonClick = async () => {
if (!account && selectedWalletId === "btc-wallet") {
autoConnect();
return;
}
setLoading(true);
trackActionButton(action, {
tokenId,
Expand Down
9 changes: 9 additions & 0 deletions components/Modal/components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -417,3 +417,12 @@ export function useRepayTrigger(tokenId: string, position?: string) {
}
};
}

export const Receive = ({ value }: { value: string }) => {
return (
<div className="flex items-center justify-between">
<span className="text-sm text-gray-300">Receive Amount</span>
<span className="text-sm">{value}</span>
</div>
);
};
13 changes: 12 additions & 1 deletion components/Modal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { recomputeHealthFactorRepay } from "../../redux/selectors/recomputeHealt
import { getAssetsCategory } from "../../redux/assetsSelectors";
import { recomputeHealthFactorRepayFromDeposits } from "../../redux/selectors/recomputeHealthFactorRepayFromDeposits";
import { formatWithCommas_number } from "../../utils/uiNumber";
import { DEFAULT_POSITION, lpTokenPrefix } from "../../utils/config";
import { DEFAULT_POSITION, lpTokenPrefix, NBTCTokenId } from "../../utils/config";
import { Wrapper } from "./style";
import { getModalData } from "./utils";
import {
Expand All @@ -36,6 +36,7 @@ import {
CollateralSwitch,
CollateralTip,
BorrowLimit,
Receive,
} from "./components";
import Controls from "./Controls";
import Action from "./Action";
Expand All @@ -47,6 +48,7 @@ import {
CollateralTypeSelectorBorrow,
CollateralTypeSelectorRepay,
} from "./CollateralTypeSelector";
import { useBtcAction } from "../../hooks/useBtcBalance";

export const ModalContext = createContext(null) as any;
const Modal = () => {
Expand Down Expand Up @@ -80,6 +82,10 @@ const Modal = () => {
const maxBorrowAmountPositions = useAppSelector(getBorrowMaxAmount(tokenId));
const maxWithdrawAmount = useAppSelector(getWithdrawMaxAmount(tokenId));
const repayPositions = useAppSelector(getRepayPositions(tokenId));
const { availableBalance: btcAvailableBalance, receiveAmount } = useBtcAction({
inputAmount: amount,
decimals: asset.decimals,
});
const activePosition =
action === "Repay" || action === "Borrow"
? selectedCollateralType
Expand Down Expand Up @@ -138,6 +144,7 @@ const Modal = () => {
};
const repay_to_lp =
action === "Repay" && isRepayFromDeposits && selectedCollateralType !== DEFAULT_POSITION;
const isBtc = action === "Supply" && asset.tokenId === NBTCTokenId;
return (
<MUIModal open={isOpen} onClose={handleClose}>
<Wrapper
Expand All @@ -146,6 +153,9 @@ const Modal = () => {
backgroundColor: theme.custom.scrollbarBg,
},
}}
style={{
overflowY: "auto",
}}
>
<ModalContext.Provider
value={{
Expand Down Expand Up @@ -179,6 +189,7 @@ const Modal = () => {
available$={available$}
/>
<div className="flex flex-col gap-4 mt-6">
{isBtc ? <Receive value={receiveAmount} /> : null}
<HealthFactor value={healthFactor} />
{repay_to_lp ? (
<HealthFactor value={single_healthFactor} title="Health Factor(Single)" />
Expand Down
54 changes: 54 additions & 0 deletions hooks/useBtcBalance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { useEffect, useState } from "react";
import { useDebounce } from "react-use";
import Decimal from "decimal.js";
import { useBtcWalletSelector, getBtcBalance, estimateDepositAmount } from "btc-wallet";
import { expandToken, shrinkToken } from "../store/helper";

export function useBtcAction({ updater, inputAmount, decimals }: any) {
const [balance, setBalance] = useState<number>(0);
const [receiveAmount, setReceiveAmount] = useState<string>("0");
const [availableBalance, setAvailableBalance] = useState<number>(0);
const btcSelector = useBtcWalletSelector();
const expandInputAmount = expandToken(inputAmount || 0, decimals || 0, 0);
useDebounce(
() => {
if (btcSelector?.account) {
getBtcBalance().then((res) => {
const { rawBalance, balance: btcBalance, availableBalance: btcAvailableBalance } = res;
setBalance(btcBalance || 0);
setAvailableBalance(btcAvailableBalance || 0);
// eslint-disable-next-line no-console
console.log("----------------Balance", btcBalance);
// eslint-disable-next-line no-console
console.log("----------------btcAvailableBalance", btcAvailableBalance);
});
}
},
500,
[btcSelector?.account, updater],
);
useDebounce(
() => {
const inputAmountDecimal = new Decimal(expandInputAmount || 0);
if (inputAmountDecimal.lte(0)) {
setReceiveAmount("0");
} else {
estimateDepositAmount(expandInputAmount, { env: "private_mainnet" }).then(
(received: number) => {
setReceiveAmount(shrinkToken(received || "0", decimals));
// eslint-disable-next-line no-console
console.log("---------------receivedBalance", shrinkToken(received || "0", decimals));
},
);
}
},
500,
[expandInputAmount],
);

return {
balance,
availableBalance,
receiveAmount,
};
}
14 changes: 12 additions & 2 deletions hooks/useUserBalance.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import Decimal from "decimal.js";
import { useAppSelector } from "../redux/hooks";
import { useAppSelector, useAppDispatch } from "../redux/hooks";
import { getAssetDataByTokenId } from "../redux/appSelectors";
import { getBorrowMaxAmount } from "../redux/selectors/getBorrowMaxAmount";
import { NEAR_STORAGE_DEPOSIT } from "../store";
import { useBtcAction } from "./useBtcBalance";

export function useUserBalance(tokenId: string, isWrappedNear: boolean) {
const asset = useAppSelector(getAssetDataByTokenId(tokenId));
const maxBorrowAmountPositions = useAppSelector(getBorrowMaxAmount(tokenId));
const { available, availableNEAR, availableLiquidity } = asset;

const { availableBalance: btcAvailableBalance } = useBtcAction({
decimals: asset.decimals,
});

// get supply balance
let supplyBalance = "0";
if (isWrappedNear) {
Expand All @@ -19,5 +25,9 @@ export function useUserBalance(tokenId: string, isWrappedNear: boolean) {
supplyBalance = new Decimal(available || 0).toFixed();
}
// borrowBalance = Decimal.min(Math.max(0, maxBorrowAmount), availableLiquidity || 0).toFixed();
return { supplyBalance, maxBorrowAmountPositions };
return {
supplyBalance,
btcSupplyBalance: new Decimal(btcAvailableBalance || 0).toFixed(),
maxBorrowAmountPositions,
};
}
3 changes: 2 additions & 1 deletion interfaces/burrow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ export type IViewReturnType =
| IMarginConfig
| IMarginAccountDetailedView
| IPoolDcl[]
| IQuoteResult;
| IQuoteResult
| IAssetDetailed[];

export interface IBurrow {
selector: WalletSelector;
Expand Down
1 change: 1 addition & 0 deletions interfaces/contract-methods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export enum ViewMethodsLogic {
get_asset,
get_assets,
get_assets_paged,
get_assets_paged_detailed,
// config
get_config,
get_margin_config,
Expand Down
13 changes: 13 additions & 0 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,19 @@ module.exports = {
},
exclude: /node_modules/,
});
config.module.rules.push({
test: /satoshi-wellet/,
use: [
{
loader: "ts-loader",
options: {
compilerOptions: { noEmit: false },
onlyCompileBundledFiles: true,
allowTsInNodeModules: true,
},
},
],
});

if (!isServer) {
config.resolve.fallback.fs = false;
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
"big.js": "^6.2.2",
"bn.js": "^5.2.1",
"borsh": "^0.7.0",
"btc-wallet": "^0.4.2-beta",
"crypto-browserify": "3.12.0",
"dayjs": "1.11.10",
"decimal.js": "^10.4.1",
Expand Down
Loading

0 comments on commit 0647da4

Please sign in to comment.