Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support asset limit check #15

Merged
merged 3 commits into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 31 additions & 14 deletions src/components/balance-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ interface Props {
balance?: BN;
min?: BN;
asset?: Asset;
assetSupply?: BN;
assetLimit?: BN;
assetOptions?: Asset[];
onChange?: (value: Value) => void;
onAssetChange?: (value: Asset) => void;
Expand All @@ -32,6 +34,8 @@ export default function BalanceInput({
balance,
min,
asset,
assetSupply,
assetLimit,
assetOptions,
onChange = () => undefined,
onAssetChange,
Expand All @@ -52,15 +56,23 @@ export default function BalanceInput({
(e) => {
if (e.target.value) {
if (!Number.isNaN(Number(e.target.value)) && asset) {
onChange(parseValue(e.target.value, asset.decimals, min, balance));
onChange(parseValue(e.target.value, asset.decimals, min, balance, assetLimit, assetSupply));
}
} else {
onChange({ valid: true, input: e.target.value, amount: BN_ZERO });
}
},
[asset, min, balance, onChange],
[asset, min, balance, assetLimit, assetSupply, onChange],
);

useEffect(() => {
// Fire onChange to update `amount`
if (assetRef.current?.decimals !== asset?.decimals) {
onChange(parseValue(value?.input || "", asset?.decimals || 0, min, balance, assetLimit, assetSupply));
}
assetRef.current = asset;
}, [value, asset, min, balance, assetLimit, assetSupply, onChange]);

useEffect(() => {
const inputWidth = inputRef.current?.clientWidth || 1;
const spanWidth = spanRef.current?.clientWidth || 0;
Expand All @@ -82,16 +94,9 @@ export default function BalanceInput({
}
}, [value]);

useEffect(() => {
// Fire onChange to update `amount`
if (assetRef.current?.decimals !== asset?.decimals) {
onChange(parseValue(value?.input || "", asset?.decimals || 0, min, balance));
}
assetRef.current = asset;
}, [value, asset, min, balance, onChange]);

const insufficient = balance && value?.input && balance.lt(value.amount) ? true : false;
const requireMin = min && value?.input && value.amount.lt(min) ? true : false;
const requireLimit = isExcess(assetLimit, assetSupply, value?.amount);

return (
<div
Expand All @@ -112,10 +117,17 @@ export default function BalanceInput({
{asset ? <AssetSelect disabled={disabled} value={asset} options={assetOptions} onChange={onAssetChange} /> : null}

{/* Alert */}
{insufficient ? (
<InputAlert text="* Insufficient" />
{requireLimit ? (
<InputAlert
text={`* Limit: ${formatBalance(assetLimit ?? BN_ZERO, asset?.decimals ?? 0)}, supply: ${formatBalance(
(assetSupply ?? BN_ZERO).add(value?.amount ?? BN_ZERO),
asset?.decimals ?? 0,
)}`}
/>
) : requireMin ? (
<InputAlert text={`* Minimum: ${formatBalance(min ?? BN_ZERO, asset?.decimals ?? 0)}`} />
) : insufficient ? (
<InputAlert text="* Insufficient" />
) : null}

{/* Invisible */}
Expand All @@ -126,14 +138,19 @@ export default function BalanceInput({
);
}

function parseValue(origin: string, decimals: number, min?: BN, max?: BN) {
function parseValue(origin: string, decimals: number, min?: BN, max?: BN, limit?: BN, supply?: BN) {
let input = "";
let amount = BN_ZERO;
const [i, d] = origin.split(".").concat("-1");
if (i) {
input = d === "-1" ? i : d ? `${i}.${d.slice(0, decimals)}` : `${i}.`;
amount = bnToBn(parseUnits(input, decimals));
}
const valid = min && amount.lt(min) ? false : max && amount.gt(max) ? false : true;
const valid =
min && amount.lt(min) ? false : max && amount.gt(max) ? false : isExcess(limit, supply, amount) ? false : true;
return { input, amount, valid };
}

function isExcess(limit?: BN, supply?: BN, amount = BN_ZERO) {
return limit && supply && supply.add(amount).gt(limit) ? true : false;
}
17 changes: 14 additions & 3 deletions src/components/transfer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import Button from "@/ui/button";
import BalanceInput from "./balance-input";
import ChainSelect from "./chain-select";
import TransferSection from "./transfer-section";
import { parseCross } from "@/utils";
import { isAssetExcess, parseCross } from "@/utils";
import { useTalisman, useTransfer } from "@/hooks";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import SwitchCross from "./switch-cross";
import AddressInput from "./address-input";
import { useAccount, useNetwork, useSwitchNetwork } from "wagmi";
import { Asset, ChainConfig, WalletID } from "@/types";
import { BN_ZERO } from "@polkadot/util";
import notification from "@/ui/notification";

const {
defaultSourceChainOptions,
Expand All @@ -24,6 +25,8 @@ const {

export default function Transfer() {
const {
assetLimit,
targetAssetDetails,
sender,
recipient,
sourceChain,
Expand All @@ -50,6 +53,7 @@ export default function Transfer() {
substrateTransfer,
refetchSourceBalance,
refetchTargetBalance,
refetchTargetAssetDetails,
} = useTransfer();
const [sourceChainOptions, _setSourceChainOptions] = useState(defaultSourceChainOptions);
const [targetChainOptions, setTargetChainOptions] = useState(defaultTargetChainOptions);
Expand Down Expand Up @@ -134,14 +138,18 @@ export default function Transfer() {
setTransferAmount({ valid: true, input: "", amount: BN_ZERO });
refetchSourceBalance();
refetchTargetBalance();
refetchTargetAssetDetails();
},
failedCb: () => {
setBusy(false);
},
};

setBusy(true);
if (address && sender?.address === address) {
if (await isAssetExcess(bridgeInstance, transferAmount.amount)) {
notification.error({ title: "Transaction failed", description: "Asset limit exceeded" });
refetchTargetAssetDetails();
setBusy(false);
} else if (address && sender?.address === address) {
await evmTransfer(bridgeInstance, address, recipient.address, transferAmount.amount, callback);
} else if (activeSenderAccount) {
await substrateTransfer(
Expand All @@ -168,6 +176,7 @@ export default function Transfer() {
substrateTransfer,
refetchSourceBalance,
refetchTargetBalance,
refetchTargetAssetDetails,
]);

useEffect(() => {
Expand Down Expand Up @@ -220,6 +229,8 @@ export default function Transfer() {
<BalanceInput
value={transferAmount}
asset={sourceAsset}
assetLimit={assetLimit}
assetSupply={targetAssetDetails?.supply}
min={sourceChain.minCross}
balance={sourceBalance?.asset.value}
assetOptions={sourceAssetOptions}
Expand Down
1 change: 1 addition & 0 deletions src/config/chains/pangolin-chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export const pangolinChain: ChainConfig = {
wallets: [WalletID.RAINBOW, WalletID.TALISMAN],
addressType: "evm",
minCross: bnToBn(3600000), // 3.6 USDT
hasAssetLimit: true,

/**
* Substrate
Expand Down
2 changes: 2 additions & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ export * from "./use-transfer";
export * from "./use-api";
export * from "./use-balance";
export * from "./use-toggle";
export * from "./use-asset-limit";
export * from "./use-asset-details";
31 changes: 31 additions & 0 deletions src/hooks/use-asset-details.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { EvmBridge } from "@/libs";
import type { PalletAssetsAssetDetails } from "@polkadot/types/lookup";
import { useCallback, useEffect, useState } from "react";
import { from, EMPTY } from "rxjs";

export function useAssetDetails(bridge: EvmBridge | undefined, position: "source" | "target") {
const [assetDetails, setAssetDetails] = useState<PalletAssetsAssetDetails>();

const updateBalance = useCallback(() => {
if (bridge) {
return from(position === "source" ? bridge.getSourceAssetDetails() : bridge.getTargetAssetDetails()).subscribe({
next: setAssetDetails,
error: (err) => {
console.error(err);
setAssetDetails(undefined);
},
});
} else {
setAssetDetails(undefined);
}

return EMPTY.subscribe();
}, [bridge, position]);

useEffect(() => {
const sub$$ = updateBalance();
return () => sub$$.unsubscribe();
}, [updateBalance]);

return { assetDetails, refetch: updateBalance };
}
28 changes: 28 additions & 0 deletions src/hooks/use-asset-limit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { EvmBridge } from "@/libs";
import { useEffect, useState } from "react";
import { from, Subscription } from "rxjs";
import { BN } from "@polkadot/util";

export function useAssetLimit(bridge: EvmBridge | undefined) {
const [assetLimit, setAssetLimit] = useState<BN>();

useEffect(() => {
let sub$$: Subscription | undefined;

if (bridge) {
sub$$ = from(bridge.getAssetLimit()).subscribe({
next: setAssetLimit,
error: (err) => {
console.error(err);
setAssetLimit(undefined);
},
});
} else {
setAssetLimit(undefined);
}

return () => sub$$?.unsubscribe();
}, [bridge]);

return { assetLimit };
}
42 changes: 41 additions & 1 deletion src/libs/bridge/base.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Asset, ChainConfig, Cross } from "@/types";
import { ApiPromise } from "@polkadot/api";
import { BN_ZERO, BN } from "@polkadot/util";
import { BN_ZERO, BN, bnToBn } from "@polkadot/util";
import { Option, u128 } from "@polkadot/types";

export abstract class BaseBridge {
protected readonly cross: Cross | undefined;
Expand Down Expand Up @@ -95,5 +96,44 @@ export abstract class BaseBridge {
return { value, asset };
}

/**
* Supply
*/
private async getAssetDetails(api: ApiPromise, asset: Asset) {
const detailsOption = await api.query.assets.asset(asset.id);
return detailsOption.isSome ? detailsOption.unwrap() : undefined;
}

async getSourceAssetDetails() {
return this.getAssetDetails(this.sourceApi, this.sourceAsset);
}

async getTargetAssetDetails() {
return this.getAssetDetails(this.targetApi, this.targetAsset);
}

async getAssetLimit() {
const section = "assetLimit";
const method = "foreignAssetLimit";
const fn = this.targetApi.query[section]?.[method];

if (this.targetChain.hasAssetLimit && fn) {
const limitOption = await (fn({
Xcm: {
parents: 1,
interior: {
X3: [
{ Parachain: bnToBn(this.sourceChain.parachainId) },
{ PalletInstance: 50 },
{ GeneralIndex: bnToBn(this.sourceAsset.id) },
],
},
},
}) as Promise<Option<u128>>);

return limitOption.isSome ? limitOption.unwrap() : undefined;
}
}

abstract transfer(): Promise<undefined>;
}
17 changes: 16 additions & 1 deletion src/providers/transfer-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@

import { Dispatch, PropsWithChildren, SetStateAction, createContext, useCallback, useMemo, useState } from "react";
import { BN, BN_ZERO } from "@polkadot/util";
import type { PalletAssetsAssetDetails } from "@polkadot/types/lookup";
import { Asset, ChainConfig, WalletID } from "@/types";
import { usePublicClient, useWalletClient } from "wagmi";
import { EvmBridge } from "@/libs";

import { WalletAccount } from "@talismn/connect-wallets";
import { Signer } from "@polkadot/api/types";
import { notifyError, notifyTransaction, parseCross, signAndSendExtrinsic } from "@/utils";
import { useApi, useBalance } from "@/hooks";
import { useApi, useAssetDetails, useAssetLimit, useBalance } from "@/hooks";

interface TransferCtx {
assetLimit: BN | undefined;
targetAssetDetails: PalletAssetsAssetDetails | undefined;
bridgeInstance: EvmBridge | undefined;
sourceBalance: { asset: { value: BN; asset: Asset } } | undefined;
targetBalance: { asset: { value: BN; asset: Asset } } | undefined;
Expand Down Expand Up @@ -54,11 +57,14 @@ interface TransferCtx {
) => Promise<void>;
refetchSourceBalance: () => void;
refetchTargetBalance: () => void;
refetchTargetAssetDetails: () => void;
}

const { defaultSourceChain, defaultTargetChain, defaultSourceAsset, defaultTargetAsset } = parseCross();

const defaultValue: TransferCtx = {
assetLimit: undefined,
targetAssetDetails: undefined,
bridgeInstance: undefined,
sourceBalance: undefined,
targetBalance: undefined,
Expand Down Expand Up @@ -87,6 +93,7 @@ const defaultValue: TransferCtx = {
setActiveRecipientWallet: () => undefined,
refetchSourceBalance: () => undefined,
refetchTargetBalance: () => undefined,
refetchTargetAssetDetails: () => undefined,
evmTransfer: async () => undefined,
substrateTransfer: async () => undefined,
};
Expand Down Expand Up @@ -134,8 +141,13 @@ export default function TransferProvider({ children }: PropsWithChildren<unknown
[sourceApi, targetApi, publicClient, walletClient, sourceChain, targetChain, sourceAsset, targetAsset],
);

const { assetLimit } = useAssetLimit(bridgeInstance);
const { balance: sourceBalance, refetch: refetchSourceBalance } = useBalance(bridgeInstance, sender, "source");
const { balance: targetBalance, refetch: refetchTargetBalance } = useBalance(bridgeInstance, recipient, "target");
const { assetDetails: targetAssetDetails, refetch: refetchTargetAssetDetails } = useAssetDetails(
bridgeInstance,
"target",
);

const evmTransfer = useCallback(
async (_bridge: EvmBridge, _sender: string, _recipient: string, _amount: BN, options = transferCb) => {
Expand Down Expand Up @@ -180,6 +192,8 @@ export default function TransferProvider({ children }: PropsWithChildren<unknown
return (
<TransferContext.Provider
value={{
assetLimit,
targetAssetDetails,
bridgeInstance,
sourceBalance,
targetBalance,
Expand Down Expand Up @@ -210,6 +224,7 @@ export default function TransferProvider({ children }: PropsWithChildren<unknown
substrateTransfer,
refetchSourceBalance,
refetchTargetBalance,
refetchTargetAssetDetails,
}}
>
{children}
Expand Down
1 change: 1 addition & 0 deletions src/types/chain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export interface ChainConfig extends Chain {
wallets: WalletID[]; // Supported wallets
addressType: AddressType;
minCross: BN; // Minimum transfer amount
hasAssetLimit?: boolean;

/**
* Substrate
Expand Down
Loading