Skip to content

Uniswap #239

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

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
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
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,16 @@
"lint": "next lint"
},
"dependencies": {
"@chakra-ui/icons": "^2.0.12",
"@chakra-ui/react": "2.2.1",
"@chakra-ui/icons": "^2.1.1",
Copy link
Contributor

Choose a reason for hiding this comment

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

why change versions here?

"@chakra-ui/react": "^2.8.1",
"@defillama/sdk": "^3.0.25",
"@emotion/react": "^11",
"@emotion/styled": "^11",
"@gnosis.pm/gp-v2-contracts": "^1.1.2",
"@rainbow-me/rainbowkit": "^0.12.0",
"@tanstack/react-query": "^4.16.1",
"@tanstack/react-virtual": "^3.0.0-beta.36",
"@uniswap/permit2-sdk": "^1.2.0",
"ariakit": "^2.0.0-next.41",
"bignumber.js": "^9.0.2",
"echarts": "^5.4.1",
Expand Down
2 changes: 1 addition & 1 deletion src/components/Aggregator/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const Wrapper = styled.div`
}
`;

const Name = styled(Heading)`
const Name = styled(Heading as any)`
font-size: 26px;

@media screen and (min-width: ${({ theme }) => theme.bpLg}) {
Expand Down
169 changes: 169 additions & 0 deletions src/components/Aggregator/adapters/uniswap/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import { AllowanceData, AllowanceProvider, AllowanceTransfer, PERMIT2_ADDRESS } from '@uniswap/permit2-sdk';
import { ethers } from 'ethers';
import { sendTx } from '../../utils/sendTx';
import { rpcUrls } from '../../rpcs';
import { redirectQuoteReq } from '../utils';

export const chainToId = {
ethereum: 1,
arbitrum: 42161,
optimism: 10
};

const providers = {
ethereum: new ethers.providers.JsonRpcProvider(rpcUrls[1].default, {
name: 'ethereum',
chainId: 1
}),
arbitrum: new ethers.providers.JsonRpcProvider(rpcUrls[42161].default, {
name: 'arbitrum',
chainId: 42161
}),
optimism: new ethers.providers.JsonRpcProvider(rpcUrls[10].default, {
name: 'optimism',
chainId: 10
})
};

export const name = 'Uniswap';
export const token = 'UNI';

const fetchQuote = async ({ chain, from, to, amount, userAddress, signature = null, permit = null }) => {
console.log(
signature
? {
permitSignature: signature,
permitAmount: permit.details.amount,
permitExpiration: permit.details.expiration,
permitSigDeadline: permit.sigDeadline,
permitNonce: permit.details.nonce
}
: {}
);
const quote = await fetch('https://api.uniswap.org/v2/quote', {
headers: {
origin: 'https://app.uniswap.org/'
},
referrer: 'https://app.uniswap.org/',
referrerPolicy: 'strict-origin-when-cross-origin',
body: JSON.stringify({
tokenInChainId: chainToId[chain],
tokenIn: from,
tokenOutChainId: chainToId[chain],
tokenOut: to,
amount,
sendPortionEnabled: false,
type: 'EXACT_INPUT',
configs: [
{
protocols: ['V2', 'V3', 'MIXED'],
enableUniversalRouter: true,
routingType: 'CLASSIC',
recipient: userAddress,
...(signature
? {
permitSignature: signature,
permitAmount: permit.details.amount,
permitExpiration: permit.details.expiration,
permitSigDeadline: permit.sigDeadline,
permitNonce: permit.details.nonce
}
: {})
}
]
}),
method: 'POST',
mode: 'cors',
credentials: 'omit'
}).then((r) => r.json());

return quote;
};

export async function getQuote(chain: string, from: string, to: string, amount: string, extra) {
const { quote } = await fetchQuote({
chain,
from,
to,
userAddress: extra.userAddress,
amount,
permit: extra?.permit,
signature: extra?.signature
});
const routerAddress = quote?.methodParameters?.to;

return {
amountReturned: quote?.quote,
estimatedGas: quote?.quoteGasAdjustedDecimals,
tokenApprovalAddress: PERMIT2_ADDRESS,
rawQuote: {
tx: {
data: quote?.methodParameters?.calldata,
value: quote?.methodParameters?.value,
to: routerAddress
},
gasLimit: quote?.gasUseEstimateQuote
}
};
}

export async function swap({ chain, signer, rawQuote, ...params }) {
const fromAddress = await signer.getAddress();
const routerAddress = rawQuote?.tx?.to;
const { from, to } = params;
const amount = params?.route?.fromAmount;

const signPermitAndSwap = async (provider: ethers.Wallet) => {
const allowanceProvider = new AllowanceProvider(providers[chain], PERMIT2_ADDRESS);
const allowance: AllowanceData = await allowanceProvider?.getAllowanceData(from, fromAddress, routerAddress);
const deadline = (new Date().getTime() / 1000 + 300).toFixed(0);
const permitDetails = {
nonce: allowance.nonce,
token: from,
amount,
expiration: deadline
};
const { domain, types, values } = AllowanceTransfer.getPermitData(
{
spender: routerAddress,
sigDeadline: deadline,
details: permitDetails
},
PERMIT2_ADDRESS,
chainToId[chain]
);
const signature = await provider._signTypedData(domain, types, values);
const permit = {
signature,
details: permitDetails,
sigDeadline: deadline,
spender: routerAddress
};

const quote = await redirectQuoteReq('Uniswap', chain, from, to, amount, { signature, permit });

const res = await sendTx(signer, chain, {
from: fromAddress,
...quote?.rawQuote?.tx,
...(chain === 'optimism' && { gasLimit: rawQuote.gasLimit })
});

return res;
};

return from === ethers.constants.AddressZero
? await sendTx(signer, chain, {
from: fromAddress,
...rawQuote?.tx,
...(chain === 'optimism' && { gasLimit: rawQuote.gasLimit })
})
: await signPermitAndSwap(signer);
}

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

export const getTx = ({ rawQuote }) => ({
to: rawQuote?.tx?.to,
data: rawQuote?.tx?.data,
value: rawQuote?.tx?.value
});
6 changes: 5 additions & 1 deletion src/components/Aggregator/hooks/useEstimateGas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,11 @@ export const useEstimateGas = ({
return {
queryKey: ['estimateGas', route.name, chain, route?.tx?.data, balance],
queryFn: () => estimateGas({ route, token, userAddress, chain, balance }),
enabled: traceRpcs[chain] !== undefined && (chain === 'polygon' && isOutput ? false : true) && !!userAddress // TODO: figure out why it doesn't work
enabled:
traceRpcs[chain] !== undefined &&
(chain === 'polygon' && isOutput ? false : true) &&
!!userAddress &&
route.name !== 'Uniswap' // Uniswap api runs simulation
};
})
});
Expand Down
28 changes: 25 additions & 3 deletions src/components/Aggregator/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,35 @@ import * as paraswap from './adapters/paraswap';
// import * as odos from './adapters/odos';
import * as yieldyak from './adapters/yieldyak';
import * as llamazip from './adapters/llamazip';
import * as uniswap from './adapters/uniswap';

// import * as krystal from './adapters/krystal'

export const adapters = [matcha, inch, cowswap, openocean, yieldyak, paraswap, firebird, hashflow, llamazip, kyberswap];
export const adapters = [
matcha,
inch,
cowswap,
openocean,
yieldyak,
paraswap,
firebird,
hashflow,
llamazip,
kyberswap,
uniswap
];

export const inifiniteApprovalAllowed = [matcha.name, inch.name, cowswap.name, kyberswap.name, paraswap.name];
export const inifiniteApprovalAllowed = [
matcha.name,
inch.name,
cowswap.name,
kyberswap.name,
paraswap.name,
uniswap.name
];

export const adaptersWithApiKeys = {
[matcha.name]: true,
[hashflow.name]: true
[hashflow.name]: true,
[uniswap.name]: true
};
9 changes: 4 additions & 5 deletions src/components/Aggregator/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,20 @@ export function getAllChains() {
return chainsOptions;
}

export async function swap({ chain, from, to, amount, signer, slippage = '1', adapter, rawQuote, tokens }) {
export async function swap({ chain, from, to, amount, signer, slippage = '1', adapter, rawQuote, tokens, route }) {
const aggregator = adaptersMap[adapter];

try {
const res = await aggregator.swap({
return await aggregator.swap({
chain,
from,
to,
amount,
signer,
slippage,
rawQuote,
tokens
tokens,
route
});
return res;
} catch (e) {
throw e;
}
Expand Down
4 changes: 2 additions & 2 deletions src/components/Tooltip/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ interface ITooltip {
as?: any
}

const TooltipPopver = styled(AriaTooltip)`
const TooltipPopver = styled(AriaTooltip as any)`
font-size: 0.85rem;
padding: 1rem;
color: ${({ theme }) => (theme.mode === 'dark' ? 'hsl(0, 0%, 100%)' : 'hsl(204, 10%, 10%)')};
Expand All @@ -25,7 +25,7 @@ const TooltipPopver = styled(AriaTooltip)`
max-width: 228px;
`

const TooltipAnchor2 = styled(TooltipAnchor)`
const TooltipAnchor2 = styled(TooltipAnchor as any)`
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
Expand Down
14 changes: 9 additions & 5 deletions src/props/getTokenList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { nativeTokens } from '~/components/Aggregator/nativeTokens';

import { chainIdToName, geckoChainsMap, geckoTerminalChainsMap } from '~/components/Aggregator/constants';
import { ownTokenList } from '~/constants/tokenlist';
import { protoclIconUrl } from '~/utils';
import { protoclIconUrl, sleep } from '~/utils';
import multichainListRaw from '../data/multichain/250.json';

const tokensToRemove = {
Expand Down Expand Up @@ -103,7 +103,7 @@ export async function getTokenList() {
fetch('https://ks-setting.kyberswap.com/api/v1/tokens?page=1&pageSize=100&isWhitelisted=true&chainIds=59144')
.then((r) => r.json())
.then((r) => r?.data?.tokens.filter((t) => t.chainId === 59144))
.catch((e) => [])
.catch(() => [])
]);

const oneInchList = Object.values(oneInchChains)
Expand Down Expand Up @@ -323,9 +323,13 @@ export const getTopTokensByChain = async (chainId) => {

for (let i = 0; i < 5; i++) {
if (prevRes?.links?.next) {
prevRes = await fetch(prevRes?.links?.next).then((r) => r.json());
resData.push(...prevRes?.data);
resIncluded.push(...prevRes?.included);
prevRes = await fetch(prevRes?.links?.next).then((r) => r.json().catch(() => null));
if (prevRes) {
resData.push(...prevRes?.data);
resIncluded.push(...prevRes?.included);
} else {
await sleep((i + 1) * 100);
}
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/utils/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,5 @@ export const normalizeTokens = (t0 = '0', t1 = '0') => {

return Number(t0) < Number(t1) ? [t0.toLowerCase(), t1.toLowerCase()] : [t1.toLowerCase(), t0.toLowerCase()];
};

export const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));
Loading