Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

feat: add tx links for add/remove liquidity #338

Merged
merged 4 commits into from
Jun 24, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat: add tx links on add/remove liquidity
  • Loading branch information
pedronauck committed Jun 23, 2022
commit a173dd159534adef19ac80376166944b9e2ed12c
35 changes: 21 additions & 14 deletions packages/app/src/systems/Core/utils/feedback.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { TransactionResult } from "fuels";
import toast from "react-hot-toast";

Expand All @@ -10,37 +11,43 @@ export function getBlockExplorerLink(path: string) {
)}`;
}

type TxLinkProps = {
id?: string;
};

export function TxLink({ id }: TxLinkProps) {
return (
<p className="text-xs text-gray-300 mt-1">
<Link isExternal href={getBlockExplorerLink(`/transaction/${id}`)}>
View it on Fuel Explorer
</Link>
</p>
);
}

export function txFeedback(
txMsg: string,
onSuccess: () => void | Promise<void>
onSuccess: (data: TransactionResult<any>) => void | Promise<void>
) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return async (data: TransactionResult<any> | undefined) => {
const txLink = (
<p className="text-xs text-gray-300 mt-1">
<Link
isExternal
href={getBlockExplorerLink(`/transaction/${data?.transactionId}`)}
>
View it on Fuel Explorer
</Link>
</p>
);
const txLink = <TxLink id={data?.transactionId} />;

/**
* Show a toast success message if status.type === 'success'
*/
if (data?.status.type === "success") {
await onSuccess(data);
toast.success(
<>
{txMsg} {txLink}
{" "}
{txMsg} {txLink}{" "}
</>,
{ duration: 8000 }
);
await onSuccess();
return;
}

console.log(data);
/**
* Show a toast error if status.type !== 'success''
*/
Expand Down
84 changes: 38 additions & 46 deletions packages/app/src/systems/Pool/hooks/useAddLiquidity.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useEffect, useState } from 'react';
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useMemo, useState } from 'react';
import toast from 'react-hot-toast';
import { useMutation } from 'react-query';
import { useNavigate } from 'react-router-dom';
Expand All @@ -7,6 +8,7 @@ import { useUserPositions } from './useUserPositions';

import type { UseCoinInput } from '~/systems/Core';
import { getDeadline, useContract, toBigInt } from '~/systems/Core';
import { txFeedback } from '~/systems/Core/utils/feedback';
import { getOverrides } from '~/systems/Core/utils/gas';
import type { Coin } from '~/types';

Expand All @@ -25,11 +27,11 @@ export function useAddLiquidity({
coinTo,
onSettle,
}: UseAddLiquidityProps) {
const [errorsCreatePull, setErrorsCreatePull] = useState<string[]>([]);
const contract = useContract()!;
const [stage, setStage] = useState(0);
const navigate = useNavigate();
const { poolRatio } = useUserPositions();

// Add liquidity is a multi step process
// Trying to calculate gas fee on add_liquidity
// is a very inaccurate without the two deposits
Expand All @@ -38,6 +40,7 @@ export function useAddLiquidity({
// the local tx measures with a + 50% margin to avoid issues
// TODO: https://github.com/FuelLabs/swayswap-demo/issues/42
const networkFee = toBigInt(10);
const successMsg = poolRatio ? 'Added liquidity to the pool.' : 'New pool created.';

useEffect(() => {
fromInput.setGasFee(networkFee);
Expand Down Expand Up @@ -74,58 +77,51 @@ export function useAddLiquidity({
setStage(2);
// Create liquidity pool
const deadline = await getDeadline(contract);
const liquidityTokens = await contract.submit.add_liquidity(
return contract.submitResult.add_liquidity(
1,
deadline,
getOverrides({
variableOutputs: 2,
gasLimit: toBigInt(1500000),
})
);
setStage(3);

return liquidityTokens;
},
{
onSuccess: (liquidityTokens) => {
if (liquidityTokens) {
toast.success(poolRatio ? 'Added liquidity to the pool.' : 'New pool created.');
fromInput.setAmount(BigInt(0));
toInput.setAmount(BigInt(0));
navigate('../');
} else {
toast.error(
`Error when trying to ${poolRatio ? 'add liquidity to' : 'create'} this pool.`
);
}
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onError: (e: any) => {
const errors = e?.response?.errors;

if (errors?.length) {
if (errors[0].message === 'enough coins could not be found') {
toast.error(
`Not enough balance in your wallet to ${
poolRatio ? 'add liquidity to' : 'create'
} this pool.`
);
}
} else {
toast.error(
`Error when trying to ${poolRatio ? 'add liquidity to' : 'create'} this pool.`
);
}
},
onSettled: async () => {
onSettle?.();
navigate('../');
setStage(0);
},
onSuccess: txFeedback(successMsg, handleSuccess),
onError: handleError,
onSettled: handleSettled,
}
);

const validateCreatePool = () => {
function handleSuccess() {
fromInput.setAmount(BigInt(0));
toInput.setAmount(BigInt(0));
navigate('../');
}

function handleError(e: any) {
const errors = e?.response?.errors;

if (errors?.length) {
if (errors[0].message === 'enough coins could not be found') {
toast.error(
`Not enough balance in your wallet to ${
poolRatio ? 'add liquidity to' : 'create'
} this pool.`
);
}
} else {
toast.error(`Error when trying to ${poolRatio ? 'add liquidity to' : 'create'} this pool.`);
}
}

async function handleSettled() {
onSettle?.();
navigate('../');
setStage(0);
}

const errorsCreatePull = useMemo(() => {
const errors = [];

if (!fromInput.amount) {
Expand All @@ -142,10 +138,6 @@ export function useAddLiquidity({
}

return errors;
};

useEffect(() => {
setErrorsCreatePull(validateCreatePool());
}, [
fromInput.amount,
toInput.amount,
Expand Down
31 changes: 11 additions & 20 deletions packages/app/src/systems/Pool/pages/RemoveLiquidity.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useMemo } from "react";
import { useMutation } from "react-query";
import { useNavigate } from "react-router-dom";

Expand All @@ -24,11 +23,11 @@ import {
} from "~/systems/Core";
import { CoinBalance } from "~/systems/Core/components/CoinBalance";
import { useTransactionCost } from "~/systems/Core/hooks/useTransactionCost";
import { txFeedback } from "~/systems/Core/utils/feedback";
import { Button, Card } from "~/systems/UI";

export function RemoveLiquidityPage() {
const navigate = useNavigate();
const [errors, setErrors] = useState<string[]>([]);
const contract = useContract()!;
const balances = useBalances();
const ethBalance = useEthBalance();
Expand All @@ -50,26 +49,22 @@ export function RemoveLiquidityPage() {
if (!txCost.total) return;
// TODO: Add way to set min_eth and min_tokens
// https://github.com/FuelLabs/swayswap/issues/55
await submitRemoveLiquidity(contract, amount, txCost);
return submitRemoveLiquidity(contract, amount, txCost);
},
{
onSuccess: async () => {
toast.success("Liquidity removed successfully!");
tokenInput.setAmount(ZERO);
await balances.refetch();
navigate("../");
},
onError: (error: Error) => {
toast.error(error.message);
},
}
{ onSuccess: txFeedback("Liquidity removed successfully!", handleSuccess) }
);

async function handleSuccess() {
tokenInput.setAmount(ZERO);
await balances.refetch();
navigate("../");
}

if (!liquidityToken) {
return null;
}

const validateRemoveLiquidity = () => {
const errors = useMemo(() => {
const errorList = [];

if (!tokenInput.amount) {
Expand All @@ -80,10 +75,6 @@ export function RemoveLiquidityPage() {
}

return errorList;
};

useEffect(() => {
setErrors(validateRemoveLiquidity());
}, [tokenInput.amount, tokenInput.hasEnoughBalance]);

const hasEnoughBalance = (ethBalance.raw || ZERO) > txCost.fee;
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/systems/Pool/utils/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export async function submitRemoveLiquidity(
txCost: TransactionCost
) {
const deadline = await getDeadline(contract);
return contract.submit.remove_liquidity(
return contract.submitResult.remove_liquidity(
1,
1,
deadline,
Expand Down