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

integrate 0x v2 #278

Open
wants to merge 29 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
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
150 changes: 150 additions & 0 deletions src/components/Aggregator/adapters/0xV2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { BigNumber, ethers } from 'ethers';
import { sendTx } from '../utils/sendTx';
import { getAllowance, oldErc } from '../utils/getAllowance';

export const name = 'Matcha/0x v2';
export const token = 'ZRX';
export const isOutputAvailable = false;

export const chainToId = {
ethereum: '1',
bsc: '56',
polygon: '137',
optimism: '10',
arbitrum: '42161',
avax: '43114',
base: '8453',
linea: '59144',
scroll: '534352',
blast: '43114'
};

const nativeToken = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
const feeCollectorAddress = '0x9Ab6164976514F1178E2BB4219DA8700c9D96E9A';
const permit2Address = '0x000000000022d473030f116ddee9f6b43ac78ba3';

export async function getQuote(chain: string, from: string, to: string, amount: string, extra) {
// amount should include decimals

const tokenFrom = from === ethers.constants.AddressZero ? nativeToken : from;
const tokenTo = to === ethers.constants.AddressZero ? nativeToken : to;

if (extra.amountOut && extra.amountOut !== '0') {
throw new Error('Invalid query params');
}

const amountParam = `sellAmount=${amount}`;

const taker =
extra.userAddress === '0x0000000000000000000000000000000000000000'
? '0x1000000000000000000000000000000000000000'
: extra.userAddress;

// only expects integer
const slippage = (extra.slippage * 100) | 0;

const data = await fetch(
`https://api.0x.org/swap/permit2/quote?chainId=${chainToId[chain]}&buyToken=${tokenTo}&${amountParam}&sellToken=${tokenFrom}&slippageBps=${slippage}&taker=${taker}&tradeSurplusRecipient=${feeCollectorAddress}`,
{
headers: {
'0x-api-key': process.env.OX_API_KEY,
'0x-version': 'v2'
}
}
).then(async (r) => {
if (r.status !== 200) {
mintdart marked this conversation as resolved.
Show resolved Hide resolved
throw new Error('Failed to fetch');
}

const data = await r.json();

return data;
});

if (
data.permit2 !== null &&
data.permit2.eip712.domain.verifyingContract.toLowerCase() !== permit2Address.toLowerCase()
) {
throw new Error(`Approval address does not match`);
}

return {
amountReturned: data?.buyAmount || 0,
amountIn: data?.sellAmount || 0,
tokenApprovalAddress: permit2Address,
estimatedGas: data.transaction.gas,
rawQuote: { ...data, gasLimit: data.transaction.gas },
isSignatureNeededForSwap: true,
logo: 'https://www.gitbook.com/cdn-cgi/image/width=40,height=40,fit=contain,dpr=2,format=auto/https%3A%2F%2F1690203644-files.gitbook.io%2F~%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FKX9pG8rH3DbKDOvV7di7%252Ficon%252F1nKfBhLbPxd2KuXchHET%252F0x%2520logo.png%3Falt%3Dmedia%26token%3D25a85a3e-7f72-47ea-a8b2-e28c0d24074b'
};
}

const MAGIC_CALLDATA_STRING = 'f'.repeat(130); // used when signing the eip712 message

export async function signatureForSwap({ rawQuote, signTypedDataAsync }) {
const signature = await signTypedDataAsync({
domain: rawQuote.permit2.eip712.domain,
types: rawQuote.permit2.eip712.types,
primaryType: rawQuote.permit2.eip712.primaryType,
value: rawQuote.permit2.eip712.message
});

return signature;
}

export async function swap({ signer, rawQuote, chain, signature }) {
const fromAddress = await signer.getAddress();

const signatureLengthInHex = signature ? ethers.utils.hexValue(ethers.utils.hexDataLength(signature)) : null;

const tx = await sendTx(signer, chain, {
from: fromAddress,
to: rawQuote.transaction.to,
// signature not needed for unwrapping native tokens
data: signature
mintdart marked this conversation as resolved.
Show resolved Hide resolved
? rawQuote.transaction.data.includes(MAGIC_CALLDATA_STRING)
? rawQuote.transaction.data.replace(MAGIC_CALLDATA_STRING, signature.slice(2))
: ethers.utils.hexConcat([rawQuote.transaction.data, signatureLengthInHex, signature])
: rawQuote.transaction.data,
value: rawQuote.transaction.value
});

return tx;
}
mintdart marked this conversation as resolved.
Show resolved Hide resolved

export const getTxData = ({ rawQuote }) => rawQuote?.transaction?.data;

export const getTx = ({ rawQuote }) => ({
to: rawQuote.transaction.to,
data: rawQuote.transaction.data,
value: rawQuote.transaction.value
});

async function isTokenApproved({ token, chain, amount, address, spender }) {
try {
const allowance = await getAllowance({
token,
chain,
address,
spender
});

const isOld = token ? oldErc.includes(token.toLowerCase()) : false;

const shouldRemoveApproval =
isOld &&
allowance &&
amount &&
!Number.isNaN(Number(amount)) &&
allowance.lt(BigNumber.from(amount)) &&
!allowance.eq(0);

if (!shouldRemoveApproval && allowance.gte(BigNumber.from(amount))) {
return true;
}

return false;
} catch (error) {
return false;
}
}
37 changes: 2 additions & 35 deletions src/components/Aggregator/hooks/useTokenApprove.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,47 +2,14 @@ import { BigNumber, ethers } from 'ethers';
import { useState } from 'react';
import { erc20ABI, useAccount, useContractWrite, useNetwork, usePrepareContractWrite } from 'wagmi';
import { nativeAddress } from '../constants';
import { providers } from '../rpcs';
import { useQuery } from '@tanstack/react-query';

// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
const oldErc = [
'0xdAC17F958D2ee523a2206206994597C13D831ec7'.toLowerCase(), // USDT
'0x5A98FcBEA516Cf06857215779Fd812CA3beF1B32'.toLowerCase() // LDO
];
import { getAllowance, oldErc } from '../utils/getAllowance';

const chainsWithDefaltGasLimit = {
fantom: true,
arbitrum: true
};

async function getAllowance({
token,
chain,
address,
spender
}: {
token?: string;
chain: string;
address?: `0x${string}`;
spender?: `0x${string}`;
}) {
if (!spender || !token || !address || token === ethers.constants.AddressZero) {
return null;
}
try {
const provider = providers[chain];
const tokenContract = new ethers.Contract(token, erc20ABI, provider);
const allowance = await tokenContract.allowance(address, spender);
return allowance;
} catch (error) {
throw new Error(error instanceof Error ? `[Allowance]:${error.message}` : '[Allowance]: Failed to fetch allowance');
}
}

const useGetAllowance = ({
token,
spender,
Expand All @@ -56,7 +23,7 @@ const useGetAllowance = ({
}) => {
const { address } = useAccount();

const isOld = token ? oldErc.includes(token?.toLowerCase()) : false;
const isOld = token ? oldErc.includes(token.toLowerCase()) : false;

const {
data: allowance,
Expand Down
103 changes: 99 additions & 4 deletions src/components/Aggregator/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import {
import ReactSelect from '~/components/MultiSelect';
import FAQs from '~/components/FAQs';
import SwapRoute, { LoadingRoute } from '~/components/SwapRoute';
import { adaptersNames, getAllChains, swap, gaslessApprove } from './router';
import { adaptersNames, getAllChains, swap, gaslessApprove, signatureForSwap } from './router';
import { inifiniteApprovalAllowed } from './list';
import Loader from './Loader';
import { useTokenApprove } from './hooks';
Expand Down Expand Up @@ -755,10 +755,26 @@ export function AggregatorContainer({ tokenList, sandwichList }) {
: false
: isTokenApproved
: true
: selectedRoute?.price?.tokenApprovalAddress === null
? true
: isTokenApproved;

const isUSDTNotApprovedOnEthereum =
selectedChain && finalSelectedFromToken && selectedChain.id === 1 && shouldRemoveApproval;

const signatureForSwapMutation = useMutation({
mutationFn: (params: { adapter: string; signTypedDataAsync: typeof signTypedDataAsync; rawQuote: any }) =>
signatureForSwap(params)
});

const handleSignatureForMutation = () => {
signatureForSwapMutation.mutate({
signTypedDataAsync,
adapter: selectedRoute.name,
rawQuote: selectedRoute.price.rawQuote
});
};

const swapMutation = useMutation({
mutationFn: (params: {
chain: string;
Expand All @@ -775,6 +791,7 @@ export function AggregatorContainer({ tokenList, sandwichList }) {
index: number;
route: any;
approvalData: any;
signature: any;
}) => swap(params),
onSuccess: (data, variables) => {
let txUrl;
Expand Down Expand Up @@ -914,6 +931,8 @@ export function AggregatorContainer({ tokenList, sandwichList }) {
})
);
});

signatureForSwapMutation.reset();
},
onError: (err: { reason: string; code: string }, variables) => {
if (err.code !== 'ACTION_REJECTED' || err.code.toString() === '-32603') {
Expand Down Expand Up @@ -949,6 +968,24 @@ export function AggregatorContainer({ tokenList, sandwichList }) {
});
return;
}

if (
selectedRoute.price.isSignatureNeededForSwap
? (selectedRoute.price.rawQuote as any).permit2
? signatureForSwapMutation.data
? false
: true
: false
: false
) {
toast({
title: 'Signature needed for swap',
description: 'Swap is blocked, please try another route.',
status: 'error'
});
return;
}

swapMutation.mutate({
chain: selectedChain.value,
from: finalSelectedFromToken.value,
Expand All @@ -963,10 +1000,12 @@ export function AggregatorContainer({ tokenList, sandwichList }) {
route: selectedRoute,
amount: selectedRoute.amount,
amountIn: selectedRoute.amountIn,
approvalData: gaslessApprovalMutation?.data ?? {}
approvalData: gaslessApprovalMutation?.data ?? {},
signature: signatureForSwapMutation?.data
});
}
};

const handleGaslessApproval = ({ isInfiniteApproval }: { isInfiniteApproval: boolean }) => {
gaslessApprovalMutation.mutate({
signTypedDataAsync,
Expand Down Expand Up @@ -1199,6 +1238,24 @@ export function AggregatorContainer({ tokenList, sandwichList }) {
</Flex>
)}

{selectedRoute &&
isApproved &&
!isGaslessApproval &&
selectedRoute.price.isSignatureNeededForSwap &&
(selectedRoute.price.rawQuote as any).permit2 ? (
<Button
isLoading={signatureForSwapMutation.isLoading}
loadingText={'Confirming'}
colorScheme={'messenger'}
onClick={() => {
handleSignatureForMutation();
}}
disabled={signatureForSwapMutation.isLoading || signatureForSwapMutation.data}
>
Sign
</Button>
) : null}

{(hasPriceImapct || isUnknownPrice) && !isLoading && selectedRoute && isApproved ? (
<SwapConfirmation
isUnknownPrice={isUnknownPrice}
Expand Down Expand Up @@ -1251,7 +1308,17 @@ export function AggregatorContainer({ tokenList, sandwichList }) {
!selectedRoute ||
slippageIsWorng ||
!isAmountSynced ||
isApproveInfiniteLoading
isApproveInfiniteLoading ||
signatureForSwapMutation.isLoading ||
(selectedRoute.price.isSignatureNeededForSwap
? (selectedRoute.price.rawQuote as any).permit2
? isApproved
? signatureForSwapMutation.data
? false
: true
: false
: false
: false)
}
>
{!selectedRoute
Expand Down Expand Up @@ -1462,6 +1529,24 @@ export function AggregatorContainer({ tokenList, sandwichList }) {
</Flex>
)}

{selectedRoute &&
isApproved &&
!isGaslessApproval &&
selectedRoute.price.isSignatureNeededForSwap &&
(selectedRoute.price.rawQuote as any).permit2 ? (
<Button
isLoading={signatureForSwapMutation.isLoading}
loadingText={'Confirming'}
colorScheme={'messenger'}
onClick={() => {
handleSignatureForMutation();
}}
disabled={signatureForSwapMutation.isLoading || signatureForSwapMutation.data}
>
Sign
</Button>
) : null}

{(hasPriceImapct || isUnknownPrice) && !isLoading && selectedRoute && isApproved ? (
<SwapConfirmation
isUnknownPrice={isUnknownPrice}
Expand Down Expand Up @@ -1509,7 +1594,17 @@ export function AggregatorContainer({ tokenList, sandwichList }) {
isApproveResetLoading ||
!selectedRoute ||
slippageIsWorng ||
!isAmountSynced
!isAmountSynced ||
signatureForSwapMutation.isLoading ||
(selectedRoute.price.isSignatureNeededForSwap
? (selectedRoute.price.rawQuote as any).permit2
? isApproved
? signatureForSwapMutation.data
? false
: true
: false
: false
: false)
}
>
{!selectedRoute
Expand Down
Loading