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 17 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
204 changes: 204 additions & 0 deletions src/components/Aggregator/adapters/0xV2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
import { BigNumber, ethers } from 'ethers';
import { sendTx } from '../utils/sendTx';
import { getAllowance, oldErc } from '../utils/getAllowance';

export const name = 'Argon';
mintdart marked this conversation as resolved.
Show resolved Hide resolved
export const token = 'ZRX';
export const isOutputAvailable = false;

export const chainToId = {
ethereum: '1',
bsc: '56',
polygon: '137',
optimism: '10',
arbitrum: '42161',
avax: '43114',
// fantom: '250',
// celo: '42220',
base: '8453'
};

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;

// only fetch permit api quote if user is connected
const [permitApiQuote, allowanceHolderApiQuote] = await Promise.all([
extra.userAddress !== '0x0000000000000000000000000000000000000000'
? 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
}
}
).then(async (r) => {
if (r.status !== 200) {
throw new Error('Failed to fetch');
}

const data = await r.json();

return data;
})
: null,
fetch(
`https://api.0x.org/swap/allowance-holder/quote?chainId=${chainToId[chain]}&buyToken=${tokenTo}&${amountParam}&sellToken=${tokenFrom}&slippageBps=${slippage}&taker=${taker}&tradeSurplusRecipient=${feeCollectorAddress}`,
{
headers: {
'0x-api-key': process.env.OX_API_KEY
}
}
).then(async (r) => {
if (r.status !== 200) {
throw new Error('Failed to fetch');
}

const data = await r.json();

return data;
})
]);

let isPermitSwap = false;

// check for traditional swap approval address allowance
// if it's already approved then swap via allowance-holder api
const isApprovedForTraditionalSwap = allowanceHolderApiQuote.issues?.allowance?.spender
? await isTokenApproved({
token: tokenFrom,
chain,
address: taker,
spender: allowanceHolderApiQuote.issues?.allowance.spender,
amount
})
: true;

if (!isApprovedForTraditionalSwap && permitApiQuote) {
// if permit2 === null then there's no need for approval and signature, so use permit2 flow
if (permitApiQuote.permit2 === null) {
isPermitSwap = true;
} else {
// check if permit2 contract approval address matches
if (
permitApiQuote.permit2 !== null &&
permitApiQuote.permit2.eip712.domain.verifyingContract.toLowerCase() !== permit2Address.toLowerCase()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this check seems useless? since verifyingContract is never used

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if user has enough allowance for permit2Address then permit2 will be null

no need for approval signature, but user can sign -> swap via permit2

instead of approving spender from allowanceHolderApiQuote -> swap

example: they approved on matcha.xyz or uniswap.org and trying to swap on llamaswap , we don't need to ask them to approve again

) {
throw new Error(`Approval address does not match`);
}

// check for permit2 contract approval address allowance
// if already approved -> swap via permit, else swap via traditional swap flow (so we can skip signature part)
const isApprovedForPermitSwap = await isTokenApproved({
token: tokenFrom,
chain,
address: taker,
spender: permit2Address,
amount
});

isPermitSwap = isApprovedForPermitSwap;
}
}

const data = isPermitSwap ? permitApiQuote : allowanceHolderApiQuote;

return {
amountReturned: data?.buyAmount || 0,
amountIn: data?.sellAmount || 0,
tokenApprovalAddress: isPermitSwap
? permit2Address
: allowanceHolderApiQuote?.issues?.allowance?.spender ?? null,
estimatedGas: data.transaction.gas,
rawQuote: { ...data, gasLimit: data.transaction.gas },
isSignatureNeededForSwap: isPermitSwap ? true : false,
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 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.replace(MAGIC_CALLDATA_STRING, signature.slice(2))
: rawQuote.transaction.data,
value: rawQuote.transaction.value,
...(chain === 'optimism' && { gasLimit: rawQuote.gasLimit })
mintdart marked this conversation as resolved.
Show resolved Hide resolved
});

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
Loading