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

feat/Refactor tx handlers #222

Merged
merged 10 commits into from
Jun 2, 2023
344 changes: 78 additions & 266 deletions apps/common/utils/actions.tsx

Large diffs are not rendered by default.

47 changes: 46 additions & 1 deletion apps/common/utils/toWagmiProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import {captureException} from '@sentry/nextjs';
import {prepareWriteContract, waitForTransaction, writeContract} from '@wagmi/core';
import {toAddress} from '@yearn-finance/web-lib/utils/address';
import {ETH_TOKEN_ADDRESS, ZERO_ADDRESS} from '@yearn-finance/web-lib/utils/constants';
import {isTAddress} from '@yearn-finance/web-lib/utils/isTAddress';
import {defaultTxStatus} from '@yearn-finance/web-lib/utils/web3/transaction';
import {assert} from '@common/utils/assert';

import type {BaseError} from 'viem';
import type {Connector} from 'wagmi';
import type {TAddress} from '@yearn-finance/web-lib/types';
import type {defaultTxStatus} from '@yearn-finance/web-lib/utils/web3/transaction';
import type {TTxResponse} from '@yearn-finance/web-lib/utils/web3/transaction';
import type {GetWalletClientResult} from '@wagmi/core';

export type TWagmiProviderContract = {
Expand Down Expand Up @@ -38,3 +42,44 @@ export function assertAddress(addr: string | TAddress | undefined, name?: string
assert(toAddress(addr) !== ZERO_ADDRESS, `${name || 'Address'} is 0x0`);
assert(toAddress(addr) !== ETH_TOKEN_ADDRESS, `${name || 'Address'} is 0xE`);
}

type TPrepareWriteContractProp = Parameters<typeof prepareWriteContract>[0];

export async function handleTx(
args: TWriteTransaction,
props: Omit<TPrepareWriteContractProp, 'value'> & { value?: bigint; }
): Promise<TTxResponse> {
args.statusHandler?.({...defaultTxStatus, pending: true});
const wagmiProvider = await toWagmiProvider(args.connector);

assertAddress(props.address, 'contractAddress');
assertAddress(wagmiProvider.address, 'userAddress');
Majorfi marked this conversation as resolved.
Show resolved Hide resolved
try {
const {request} = await prepareWriteContract({
...wagmiProvider,
...props,
address: props.address,
value: undefined
});
const {hash} = await writeContract(request);
const receipt = await waitForTransaction({chainId: wagmiProvider.chainId, hash});
if (receipt.status === 'success') {
args.statusHandler?.({...defaultTxStatus, success: true});
} else if (receipt.status === 'reverted') {
args.statusHandler?.({...defaultTxStatus, error: true});
}
return ({isSuccessful: receipt.status === 'success', receipt});
} catch (error) {
console.error(error);
const errorAsBaseError = error as BaseError;
if (process.env.NODE_ENV === 'production') {
captureException(errorAsBaseError);
}
args.statusHandler?.({...defaultTxStatus, error: true});
return ({isSuccessful: false, error: errorAsBaseError || ''});
} finally {
setTimeout((): void => {
args.statusHandler?.({...defaultTxStatus});
}, 3000);
}
}
2 changes: 1 addition & 1 deletion apps/vaults/contexts/useSolver.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ function WithSolverContextApp({children}: { children: React.ReactElement }): Rea
if (currentNonce !== executionNonce.current) {
return;
}
const requestHash = await hash(serialize({...request, solver, expectedOut: quote.value.raw.toString()}));
const requestHash = await hash(serialize({...request, solver, expectedOut: quote.value.raw}));
performBatchedUpdates((): void => {
set_currentSolverState({...ctx, quote: quote.value, hash: requestHash});
set_isLoading(false);
Expand Down
8 changes: 4 additions & 4 deletions apps/vaults/hooks/useSolverCowswap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async function getQuote(
kind: OrderQuoteSide.kind.SELL, // always sell
partiallyFillable: false, // always false
validTo: 0,
sellAmountBeforeFee: toBigInt(request?.inputAmount || 0).toString() // amount to sell, in wei
sellAmountBeforeFee: toBigInt(request?.inputAmount).toString() // amount to sell, in wei
};

if (isZeroAddress(quoteRequest.from)) {
Expand Down Expand Up @@ -253,7 +253,7 @@ export function useSolverCowswap(): TSolverContext {
}
return (
toNormalizedBN(
toBigInt(latestQuote?.current?.quote?.buyAmount.toString()),
toBigInt(latestQuote?.current?.quote?.buyAmount),
request?.current?.outputToken?.decimals || 18
)
);
Expand Down Expand Up @@ -308,7 +308,7 @@ export function useSolverCowswap(): TSolverContext {
provider,
request.current.inputToken.value, //token to approve
SOLVER_COW_VAULT_RELAYER_ADDRESS, //Cowswap relayer
toBigInt(amount.toString())
toBigInt(amount)
);
if (isApproved) {
return onSuccess();
Expand All @@ -317,7 +317,7 @@ export function useSolverCowswap(): TSolverContext {
connector: provider,
contractAddress: request.current.inputToken.value,
spenderAddress: SOLVER_COW_VAULT_RELAYER_ADDRESS,
amount: toBigInt(amount.toString()),
amount: toBigInt(amount),
statusHandler: txStatusSetter
});
if (result.isSuccessful) {
Expand Down
8 changes: 4 additions & 4 deletions apps/vaults/hooks/useSolverPortals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async function getQuote(
): Promise<{data: TPortalEstimate | undefined, error: Error | undefined}> {
const params = {
sellToken: toAddress(request.inputToken.value),
sellAmount: toBigInt(request.inputAmount || 0).toString(),
sellAmount: toBigInt(request.inputAmount).toString(),
buyToken: toAddress(request.outputToken.value),
slippagePercentage: String(zapSlippage / 100)
};
Expand Down Expand Up @@ -152,7 +152,7 @@ export function useSolverPortals(): TSolverContext {
params: {
takerAddress: toAddress(address),
sellToken: toAddress(request.current.inputToken.value),
sellAmount: toBigInt(request.current.inputAmount || 0).toString(),
sellAmount: toBigInt(request.current.inputAmount).toString(),
buyToken: toAddress(request.current.outputToken.value),
slippagePercentage: String(zapSlippage / 100),
validate: true
Expand Down Expand Up @@ -220,7 +220,7 @@ export function useSolverPortals(): TSolverContext {
params: {
takerAddress: toAddress(request.current.from),
sellToken: toAddress(request.current.inputToken.value),
sellAmount:toBigInt(request.current.inputAmount || 0).toString(),
sellAmount:toBigInt(request.current.inputAmount).toString(),
buyToken: toAddress(request.current.outputToken.value)
}
});
Expand Down Expand Up @@ -261,7 +261,7 @@ export function useSolverPortals(): TSolverContext {
params: {
takerAddress: toAddress(request.current.from),
sellToken: toAddress(request.current.inputToken.value),
sellAmount:toBigInt(request.current.inputAmount || 0).toString(),
sellAmount:toBigInt(request.current.inputAmount).toString(),
buyToken: toAddress(request.current.outputToken.value)
}
});
Expand Down
Loading