style: run format

This commit is contained in:
bartosz-lipinski 2020-11-26 00:05:24 -06:00
parent 097dc95f5f
commit 453b7efb4e
18 changed files with 142 additions and 114 deletions

View File

@ -24,5 +24,5 @@ Any content produced by Solana, or developer resources that Solana provides, are
# TOP for tomorrow # TOP for tomorrow
* subscribe to all dex markets that are used by lending reserves - subscribe to all dex markets that are used by lending reserves
* finish reserve overivew - finish reserve overivew

View File

@ -42,8 +42,7 @@ export const borrow = async (
exsistingObligation?: ParsedAccount<LendingObligation>, exsistingObligation?: ParsedAccount<LendingObligation>,
obligationAccount?: PublicKey, obligationAccount?: PublicKey
) => { ) => {
notify({ notify({
message: "Borrowing funds...", message: "Borrowing funds...",
@ -59,34 +58,34 @@ export const borrow = async (
AccountLayout.span AccountLayout.span
); );
const obligation = exsistingObligation ? const obligation = exsistingObligation
exsistingObligation.pubkey : ? exsistingObligation.pubkey
createUninitializedObligation( : createUninitializedObligation(
instructions, instructions,
wallet.publicKey, wallet.publicKey,
await connection.getMinimumBalanceForRentExemption( await connection.getMinimumBalanceForRentExemption(
LendingObligationLayout.span LendingObligationLayout.span
), ),
signers signers
); );
const obligationMint = exsistingObligation ? const obligationMint = exsistingObligation
exsistingObligation.info.tokenMint : ? exsistingObligation.info.tokenMint
createUninitializedMint( : createUninitializedMint(
instructions, instructions,
wallet.publicKey, wallet.publicKey,
await connection.getMinimumBalanceForRentExemption(MintLayout.span), await connection.getMinimumBalanceForRentExemption(MintLayout.span),
signers signers
); );
const obligationTokenOutput = obligationAccount ? const obligationTokenOutput = obligationAccount
obligationAccount : ? obligationAccount
createUninitializedAccount( : createUninitializedAccount(
instructions, instructions,
wallet.publicKey, wallet.publicKey,
accountRentExempt, accountRentExempt,
signers signers
); );
let toAccount = await findOrCreateAccountByMint( let toAccount = await findOrCreateAccountByMint(
wallet.publicKey, wallet.publicKey,
@ -110,14 +109,13 @@ export const borrow = async (
type: "success", type: "success",
}); });
} }
notify({ notify({
message: "Adding Liquidity...", message: "Adding Liquidity...",
description: "Please review transactions to approve.", description: "Please review transactions to approve.",
type: "warn", type: "warn",
}); });
signers = []; signers = [];
instructions = []; instructions = [];
cleanupInstructions = []; cleanupInstructions = [];
@ -130,7 +128,7 @@ export const borrow = async (
let amountLamports: number = 0; let amountLamports: number = 0;
let fromLamports: number = 0; let fromLamports: number = 0;
if (amountType === BorrowAmountType.LiquidityBorrowAmount) { if (amountType === BorrowAmountType.LiquidityBorrowAmount) {
// approve max transfer // approve max transfer
// TODO: improve contrain by using dex market data // TODO: improve contrain by using dex market data
const approvedAmount = from.info.amount.toNumber(); const approvedAmount = from.info.amount.toNumber();

View File

@ -6,10 +6,7 @@ import {
} from "@solana/web3.js"; } from "@solana/web3.js";
import { sendTransaction } from "../contexts/connection"; import { sendTransaction } from "../contexts/connection";
import { notify } from "../utils/notifications"; import { notify } from "../utils/notifications";
import { import { LendingReserve, withdrawInstruction } from "./../models/lending";
LendingReserve,
withdrawInstruction,
} from "./../models/lending";
import { AccountLayout, Token } from "@solana/spl-token"; import { AccountLayout, Token } from "@solana/spl-token";
import { LENDING_PROGRAM_ID, TOKEN_PROGRAM_ID } from "../constants/ids"; import { LENDING_PROGRAM_ID, TOKEN_PROGRAM_ID } from "../constants/ids";
import { findOrCreateAccountByMint } from "./account"; import { findOrCreateAccountByMint } from "./account";

View File

@ -1,6 +1,14 @@
import React, { useCallback, useMemo, useState } from "react"; import React, { useCallback, useMemo, useState } from "react";
import { useTokenName, useUserBalance, useUserObligationByReserve } from "../../hooks"; import {
import { BorrowAmountType, LendingReserve, LendingReserveParser } from "../../models"; useTokenName,
useUserBalance,
useUserObligationByReserve,
} from "../../hooks";
import {
BorrowAmountType,
LendingReserve,
LendingReserveParser,
} from "../../models";
import { TokenIcon } from "../TokenIcon"; import { TokenIcon } from "../TokenIcon";
import { Button, Card } from "antd"; import { Button, Card } from "antd";
import { cache, ParsedAccount } from "../../contexts/accounts"; import { cache, ParsedAccount } from "../../contexts/accounts";
@ -38,7 +46,9 @@ export const BorrowInput = (props: {
collateralReserve?.info.collateralMint collateralReserve?.info.collateralMint
); );
const { userObligationsByReserve } = useUserObligationByReserve(borrowReserve.pubkey) const { userObligationsByReserve } = useUserObligationByReserve(
borrowReserve.pubkey
);
const onBorrow = useCallback(() => { const onBorrow = useCallback(() => {
if (!collateralReserve) { if (!collateralReserve) {
@ -56,13 +66,13 @@ export const BorrowInput = (props: {
borrowReserve, borrowReserve,
collateralReserve, collateralReserve,
userObligationsByReserve.length > 0 ? userObligationsByReserve.length > 0
userObligationsByReserve[0].obligation : ? userObligationsByReserve[0].obligation
undefined, : undefined,
userObligationsByReserve.length > 0 ? userObligationsByReserve.length > 0
userObligationsByReserve[0].userAccounts[0].pubkey : ? userObligationsByReserve[0].userAccounts[0].pubkey
undefined : undefined
); );
}, [ }, [
connection, connection,

View File

@ -1,4 +1,4 @@
import React, { } from "react"; import React from "react";
import { LendingReserve } from "../../models/lending"; import { LendingReserve } from "../../models/lending";
import { Card } from "antd"; import { Card } from "antd";
import { PublicKey } from "@solana/web3.js"; import { PublicKey } from "@solana/web3.js";

View File

@ -1,12 +1,15 @@
import React, { useEffect, useMemo, useRef } from "react"; import React, { useEffect, useMemo, useRef } from "react";
import { LendingReserve } from "../../models/lending"; import { LendingReserve } from "../../models/lending";
import echarts from "echarts"; import echarts from "echarts";
import { formatNumber, formatUSD, fromLamports, wadToLamports } from "../../utils/utils"; import {
formatNumber,
formatUSD,
fromLamports,
wadToLamports,
} from "../../utils/utils";
import { useMint } from "../../contexts/accounts"; import { useMint } from "../../contexts/accounts";
export const ReserveUtilizationChart = (props: { export const ReserveUtilizationChart = (props: { reserve: LendingReserve }) => {
reserve: LendingReserve;
}) => {
const chartDiv = useRef<HTMLDivElement>(null); const chartDiv = useRef<HTMLDivElement>(null);
// dispose chart // dispose chart
@ -26,7 +29,10 @@ export const ReserveUtilizationChart = (props: {
const totalBorrows = useMemo( const totalBorrows = useMemo(
() => () =>
fromLamports(wadToLamports(props.reserve.borrowedLiquidityWad), liquidityMint), fromLamports(
wadToLamports(props.reserve.borrowedLiquidityWad),
liquidityMint
),
[props.reserve, liquidityMint] [props.reserve, liquidityMint]
); );
@ -42,12 +48,12 @@ export const ReserveUtilizationChart = (props: {
const data = [ const data = [
{ {
name: 'Available Liquidity', name: "Available Liquidity",
value: avilableLiquidity, value: avilableLiquidity,
tokens: avilableLiquidity, tokens: avilableLiquidity,
}, },
{ {
name: 'Total Borrowed', name: "Total Borrowed",
value: totalBorrows, value: totalBorrows,
tokens: totalBorrows, tokens: totalBorrows,
}, },
@ -66,7 +72,7 @@ export const ReserveUtilizationChart = (props: {
{ {
name: "Liquidity", name: "Liquidity",
type: "pie", type: "pie",
radius: ['50%', '70%'], radius: ["50%", "70%"],
top: 0, top: 0,
bottom: 0, bottom: 0,
left: 0, left: 0,
@ -104,5 +110,5 @@ export const ReserveUtilizationChart = (props: {
}); });
}, [totalBorrows, avilableLiquidity]); }, [totalBorrows, avilableLiquidity]);
return <div ref={chartDiv} style={{ height: 300, width: 400 }} /> return <div ref={chartDiv} style={{ height: 300, width: 400 }} />;
} };

View File

@ -40,7 +40,7 @@ export function LendingProvider({ children = null as any }) {
export const useLending = () => { export const useLending = () => {
const connection = useConnection(); const connection = useConnection();
const [lendingAccounts, setLendingAccounts] = useState<any[]>([]); const [lendingAccounts, setLendingAccounts] = useState<any[]>([]);
const precacheMarkets = usePrecacheMarket() const precacheMarkets = usePrecacheMarket();
// TODO: query for all the dex from reserves // TODO: query for all the dex from reserves
@ -78,31 +78,30 @@ export const useLending = () => {
.filter((item) => item !== undefined); .filter((item) => item !== undefined);
const lendingReserves = accounts const lendingReserves = accounts
.filter( .filter(
(acc) => (acc?.info as LendingReserve).lendingMarket !== undefined (acc) => (acc?.info as LendingReserve).lendingMarket !== undefined
) )
.map((acc) => acc as ParsedAccount<LendingReserve>); .map((acc) => acc as ParsedAccount<LendingReserve>);
const toQuery = [ const toQuery = [
...lendingReserves ...lendingReserves.map((acc) => {
.map((acc) => { const result = [
const result = [ cache.registerParser(
cache.registerParser( acc?.info.collateralMint.toBase58(),
acc?.info.collateralMint.toBase58(), MintParser
MintParser ),
), cache.registerParser(
cache.registerParser( acc?.info.liquidityMint.toBase58(),
acc?.info.liquidityMint.toBase58(), MintParser
MintParser ),
), // ignore dex if its not set
// ignore dex if its not set cache.registerParser(
cache.registerParser( acc?.info.dexMarketOption ? acc?.info.dexMarket.toBase58() : "",
acc?.info.dexMarketOption ? acc?.info.dexMarket.toBase58() : "", DexMarketParser
DexMarketParser ),
), ].filter((_) => _);
].filter((_) => _); return result;
return result; }),
}),
].flat() as string[]; ].flat() as string[];
// This will pre-cache all accounts used by pools // This will pre-cache all accounts used by pools

View File

@ -185,9 +185,12 @@ export function MarketProvider({ children = null as any }) {
[marketByMint, accountsToObserve] [marketByMint, accountsToObserve]
); );
const precacheMarkets = useCallback((mints: string[]) => { const precacheMarkets = useCallback(
setMarketMints([...new Set([...marketMints, ...mints]).values()]) (mints: string[]) => {
}, [setMarketMints, marketMints]); setMarketMints([...new Set([...marketMints, ...mints]).values()]);
},
[setMarketMints, marketMints]
);
return ( return (
<MarketsContext.Provider <MarketsContext.Provider
@ -239,7 +242,7 @@ export const useMidPriceInUSD = (mint: string) => {
export const usePrecacheMarket = () => { export const usePrecacheMarket = () => {
const context = useMarkets(); const context = useMarkets();
return context.precacheMarkets; return context.precacheMarkets;
} };
const getMidPrice = (marketAddress?: string, mintAddress?: string) => { const getMidPrice = (marketAddress?: string, mintAddress?: string) => {
const SERUM_TOKEN = TOKEN_MINTS.find( const SERUM_TOKEN = TOKEN_MINTS.find(

View File

@ -4,9 +4,15 @@ import { LendingReserve } from "../models/lending";
import { fromLamports } from "../utils/utils"; import { fromLamports } from "../utils/utils";
import { useUserBalance } from "./useUserBalance"; import { useUserBalance } from "./useUserBalance";
export function useCollateralBalance(reserve?: LendingReserve, account?: PublicKey) { export function useCollateralBalance(
reserve?: LendingReserve,
account?: PublicKey
) {
const mint = useMint(reserve?.collateralMint); const mint = useMint(reserve?.collateralMint);
const { balanceLamports, accounts } = useUserBalance(reserve?.collateralMint, account); const { balanceLamports, accounts } = useUserBalance(
reserve?.collateralMint,
account
);
const collateralRatioLamports = const collateralRatioLamports =
(reserve?.availableLiqudity.toNumber() || 0) * (reserve?.availableLiqudity.toNumber() || 0) *

View File

@ -9,7 +9,11 @@ export function useUserBalance(mint?: PublicKey, account?: PublicKey) {
const mintInfo = useMint(mint); const mintInfo = useMint(mint);
const accounts = useMemo(() => { const accounts = useMemo(() => {
return userAccounts return userAccounts
.filter((acc) => mint?.equals(acc.info.mint) && (!account || account.equals(acc.pubkey))) .filter(
(acc) =>
mint?.equals(acc.info.mint) &&
(!account || account.equals(acc.pubkey))
)
.sort((a, b) => b.info.amount.sub(a.info.amount).toNumber()); .sort((a, b) => b.info.amount.sub(a.info.amount).toNumber());
}, [userAccounts, mint, account]); }, [userAccounts, mint, account]);

View File

@ -12,20 +12,21 @@ export function useUserDeposits() {
return reserveAccounts.reduce((result, item) => { return reserveAccounts.reduce((result, item) => {
result.set(item.info.collateralMint.toBase58(), item); result.set(item.info.collateralMint.toBase58(), item);
return result; return result;
} }, new Map<string, ParsedAccount<LendingReserve>>());
, new Map<string, ParsedAccount<LendingReserve>>())
}, [reserveAccounts]); }, [reserveAccounts]);
const userDeposits = useMemo(() => { const userDeposits = useMemo(() => {
return userAccounts return userAccounts
.filter((acc) => reservesByCollateralMint.has(acc.info.mint.toBase58())) .filter((acc) => reservesByCollateralMint.has(acc.info.mint.toBase58()))
.map(item => ({ .map((item) => ({
account: item, account: item,
reserve: reservesByCollateralMint.get(item.info.mint.toBase58()) as ParsedAccount<LendingReserve>, reserve: reservesByCollateralMint.get(
item.info.mint.toBase58()
) as ParsedAccount<LendingReserve>,
})); }));
}, [userAccounts, reservesByCollateralMint]); }, [userAccounts, reservesByCollateralMint]);
return { return {
userDeposits userDeposits,
}; };
} }

View File

@ -14,7 +14,7 @@ import { LendingReserve } from "./reserve";
export enum BorrowAmountType { export enum BorrowAmountType {
LiquidityBorrowAmount = 0, LiquidityBorrowAmount = 0,
CollateralDepositAmount = 1 CollateralDepositAmount = 1,
} }
/// Borrow tokens from a reserve by depositing collateral tokens. The number of borrowed tokens /// Borrow tokens from a reserve by depositing collateral tokens. The number of borrowed tokens

View File

@ -4,4 +4,4 @@ export * from "./obligation";
export * from "./lending"; export * from "./lending";
export * from "./borrow"; export * from "./borrow";
export * from "./deposit"; export * from "./deposit";
export * from "./withdraw"; export * from "./withdraw";

View File

@ -47,4 +47,4 @@ export const withdrawInstruction = (
programId: LENDING_PROGRAM_ID, programId: LENDING_PROGRAM_ID,
data, data,
}); });
}; };

View File

@ -1,8 +1,5 @@
import React from "react"; import React from "react";
import { import { useCollateralBalance, useTokenName } from "../../hooks";
useCollateralBalance,
useTokenName,
} from "../../hooks";
import { LendingReserve } from "../../models/lending"; import { LendingReserve } from "../../models/lending";
import { TokenIcon } from "../../components/TokenIcon"; import { TokenIcon } from "../../components/TokenIcon";
import { formatNumber } from "../../utils/utils"; import { formatNumber } from "../../utils/utils";
@ -15,10 +12,12 @@ export const DepositItem = (props: {
reserve: ParsedAccount<LendingReserve>; reserve: ParsedAccount<LendingReserve>;
account: TokenAccount; account: TokenAccount;
}) => { }) => {
const mintAddress = props.reserve.info.liquidityMint; const mintAddress = props.reserve.info.liquidityMint;
const name = useTokenName(mintAddress); const name = useTokenName(mintAddress);
const { balance: collateralBalance } = useCollateralBalance(props.reserve.info, props.account.pubkey); const { balance: collateralBalance } = useCollateralBalance(
props.reserve.info,
props.account.pubkey
);
return ( return (
<Card> <Card>
@ -31,7 +30,7 @@ export const DepositItem = (props: {
{formatNumber.format(collateralBalance)} {name} {formatNumber.format(collateralBalance)} {name}
</div> </div>
<div>--</div> <div>--</div>
<div style={{ display: "flex", justifyContent: 'flex-end' }}> <div style={{ display: "flex", justifyContent: "flex-end" }}>
<Link to={`/deposit/${props.reserve.pubkey.toBase58()}`}> <Link to={`/deposit/${props.reserve.pubkey.toBase58()}`}>
<Button> <Button>
<span>Deposit</span> <span>Deposit</span>

View File

@ -21,9 +21,9 @@ export const DashboardView = () => {
<div>{LABELS.TABLE_TITLE_ACTION}</div> <div>{LABELS.TABLE_TITLE_ACTION}</div>
</div> </div>
)} )}
{userDeposits.map(deposit => <DepositItem reserve={deposit.reserve} account={deposit.account} />) {userDeposits.map((deposit) => (
<DepositItem reserve={deposit.reserve} account={deposit.account} />
} ))}
</div> </div>
<div className="dashboard-right"> <div className="dashboard-right">
<span>{LABELS.DASHBOARD_TITLE_LOANS}</span> <span>{LABELS.DASHBOARD_TITLE_LOANS}</span>

View File

@ -36,7 +36,7 @@ export const ObligationItem = (props: {
{formatNumber.format(borrowAmount)} {name} {formatNumber.format(borrowAmount)} {name}
</div> </div>
<div>--</div> <div>--</div>
<div style={{ display: "flex", justifyContent: 'flex-end' }}> <div style={{ display: "flex", justifyContent: "flex-end" }}>
<Link to={`/borrow/${borrowReserve.pubkey.toBase58()}`}> <Link to={`/borrow/${borrowReserve.pubkey.toBase58()}`}>
<Button> <Button>
<span>Borrow</span> <span>Borrow</span>

View File

@ -1,6 +1,10 @@
import React, { useMemo } from "react"; import React, { useMemo } from "react";
import { useTokenName } from "../../hooks"; import { useTokenName } from "../../hooks";
import { calculateBorrowAPY, calculateDepositAPY, LendingReserve } from "../../models/lending"; import {
calculateBorrowAPY,
calculateDepositAPY,
LendingReserve,
} from "../../models/lending";
import { TokenIcon } from "../../components/TokenIcon"; import { TokenIcon } from "../../components/TokenIcon";
import { import {
wadToLamports, wadToLamports,
@ -28,7 +32,10 @@ export const LendingReserveItem = (props: {
const totalBorrows = useMemo( const totalBorrows = useMemo(
() => () =>
fromLamports(wadToLamports(props.reserve.borrowedLiquidityWad), liquidityMint), fromLamports(
wadToLamports(props.reserve.borrowedLiquidityWad),
liquidityMint
),
[props.reserve, liquidityMint] [props.reserve, liquidityMint]
); );
@ -40,7 +47,7 @@ export const LendingReserveItem = (props: {
props.reserve, props.reserve,
]); ]);
const marketSize = availableLiqudity+totalBorrows; const marketSize = availableLiqudity + totalBorrows;
return ( return (
<Link to={`/reserve/${props.address.toBase58()}`}> <Link to={`/reserve/${props.address.toBase58()}`}>
@ -59,9 +66,7 @@ export const LendingReserveItem = (props: {
<div title={depositAPY.toString()}> <div title={depositAPY.toString()}>
{formatPct.format(depositAPY)} {formatPct.format(depositAPY)}
</div> </div>
<div title={borrowAPY.toString()}> <div title={borrowAPY.toString()}>{formatPct.format(borrowAPY)}</div>
{formatPct.format(borrowAPY)}
</div>
</div> </div>
</Card> </Card>
</Link> </Link>