Skip to content

Commit

Permalink
fix: update redirect error + update vite.config + update piplineconve…
Browse files Browse the repository at this point in the history
…rtform
  • Loading branch information
Space-Bean committed Sep 20, 2024
1 parent 54466a3 commit bfcd29c
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 95 deletions.
32 changes: 22 additions & 10 deletions projects/sdk/src/lib/matcha/zeroX.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ZeroExAPIRequestParams, ZeroExQuoteResponse } from "./types";

export class ZeroX {
readonly swapV1Endpoint = "http://arbitrum.api.0x.org/swap/v1/quote";
readonly swapV1Endpoint = "https://arbitrum.api.0x.org/swap/v1/quote";

constructor(private _apiKey: string = "") {}

Expand All @@ -14,14 +14,14 @@ export class ZeroX {

/**
* fetch the quote from the 0x API
* @notes defaults:
* @notes defaults:
* - slippagePercentage: In human readable form. 0.01 = 1%. Defaults to 0.001 (0.1%)
* - skipValidation: defaults to true
* - shouldSellEntireBalance: defaults to false
*/
async fetchSwapQuote<T extends ZeroExAPIRequestParams = ZeroExAPIRequestParams>(
args: T ,
requestInit?: Omit<RequestInit, 'headers' | 'method'>
args: T,
requestInit?: Omit<RequestInit, "headers" | "method">
): Promise<ZeroExQuoteResponse> {
if (!this._apiKey) {
throw new Error("Cannot fetch from 0x without an API key");
Expand All @@ -35,8 +35,10 @@ export class ZeroX {
...requestInit,
method: "GET",
headers: new Headers({
"Content-Type": "application/json",
Accept: "application/json",
"0x-api-key": this._apiKey
}),
})
};

const url = `${this.swapV1Endpoint}?${fetchParams.toString()}`;
Expand All @@ -47,10 +49,12 @@ export class ZeroX {
/**
* Generate the params for the 0x API
* @throws if required params are missing
*
*
* @returns the params for the 0x API
*/
private generateQuoteParams<T extends ZeroExAPIRequestParams = ZeroExAPIRequestParams>(params: T): ZeroExAPIRequestParams {
private generateQuoteParams<T extends ZeroExAPIRequestParams = ZeroExAPIRequestParams>(
params: T
): ZeroExAPIRequestParams {
if (!params.buyToken && !params.sellToken) {
throw new Error("buyToken and sellToken and required");
}
Expand All @@ -59,8 +63,7 @@ export class ZeroX {
throw new Error("sellAmount or buyAmount is required");
}

// Return all the params to filter out the ones that are not part of the request
return {
const quoteParams = {
sellToken: params.sellToken,
buyToken: params.buyToken,
sellAmount: params.sellAmount,
Expand All @@ -75,7 +78,16 @@ export class ZeroX {
buyTokenPercentageFee: params.buyTokenPercentageFee,
priceImpactProtectionPercentage: params.priceImpactProtectionPercentage,
feeRecipientTradeSurplus: params.feeRecipientTradeSurplus,
shouldSellEntireBalance: params.shouldSellEntireBalance ?? false,
shouldSellEntireBalance: params.shouldSellEntireBalance ?? false
};

Object.keys(quoteParams).forEach((_key) => {
const key = _key as keyof typeof quoteParams;
if (quoteParams[key] === undefined || quoteParams[key] === null) {
delete quoteParams[key];
}
});

return quoteParams;
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect } from 'react';
import React, { useCallback } from 'react';

import { Form } from 'formik';
import BigNumber from 'bignumber.js';
Expand Down Expand Up @@ -34,7 +34,7 @@ import TxnAccordion from '~/components/Common/TxnAccordion';
import StatHorizontal from '~/components/Common/StatHorizontal';

import { ActionType, displayFullBN } from '~/util';
import { useAccount } from 'wagmi';
import useSdk from '~/hooks/sdk';
import { BaseConvertFormProps } from './types';

interface Props extends BaseConvertFormProps {
Expand Down Expand Up @@ -86,7 +86,6 @@ const PipelineConvertFormInner = ({
setFieldValue,
}: PipelineConvertFormProps) => {
const [tokenSelectOpen, showTokenSelect, hideTokenSelect] = useToggle();
const account = useAccount();
const getBDV = useBDV();

const sourceToken = sourceWell.lpToken; // LP token of source well
Expand All @@ -109,80 +108,69 @@ const PipelineConvertFormInner = ({

const debouncedAmountIn = useDebounce(amountIn ?? ZERO_BN);

const sourceIndexes = getWellTokenIndexes(sourceWell, BEAN);
const targetIndexes = getWellTokenIndexes(targetWell, BEAN);
const sourceIdx = getWellTokenIndexes(sourceWell, BEAN);
const targetIdx = getWellTokenIndexes(targetWell, BEAN);

const sellToken = sourceWell.tokens[sourceIndexes.nonBeanIndex]; // token we will sell when after removing liquidity in equal parts
const buyToken = targetWell.tokens[targetIndexes.nonBeanIndex]; // token we will buy to add liquidity
const sellToken = sourceWell.tokens[sourceIdx.nonBeanIndex]; // token we will sell when after removing liquidity in equal parts
const buyToken = targetWell.tokens[targetIdx.nonBeanIndex]; // token we will buy to add liquidity

const slippage = values.settings.slippage;

const fetchEnabled = account.address && maxConvertableBN.gt(0);

const { data: removeOut, ...removeOutQuery } = useQuery({
queryKey: queryKeys.wellLPOut(sourceWell, targetWell, debouncedAmountIn),
queryFn: async () => {
const outAmount = await sourceWell.getRemoveLiquidityOutEqual(
sourceWell.lpToken.fromHuman(debouncedAmountIn.toString())
);

console.log(`[pipelineConvert/removeOutQuery (1)]: amountOut: `, {
BEAN: outAmount[sourceIndexes.beanIndex].toNumber(),
[`${sellToken.symbol}`]:
outAmount[sourceIndexes.nonBeanIndex].toNumber(),
});
return outAmount;
},
enabled: fetchEnabled && debouncedAmountIn?.gt(0) && amountIn?.gt(0),
initialData: defaultWellLpOut,
...baseQueryOptions,
});

const beanAmountOut = removeOut[sourceIndexes.beanIndex];
const swapAmountIn = removeOut[sourceIndexes.nonBeanIndex];

// prettier-ignore
const { data: swapQuote, ...swapOutQuery } = useQuery({
queryKey: queryKeys.swapOut(sellToken, buyToken, swapAmountIn, slippage),
queryFn: async () => {
const quote = await sdk.zeroX.fetchSwapQuote({
// 0x requests are formatted such that 0.01 = 1%. Everywhere else in the UI we use 0.01 = 0.01% ?? BS3TODO: VALIDATE ME
slippagePercentage: (slippage / 10).toString(),
sellToken: sellToken.address,
buyToken: buyToken.address,
sellAmount: swapAmountIn.blockchainString,
});
console.log(
`[pipelineConvert/swapOutQuery (2)]: buyAmount: ${quote?.buyAmount}`
);
return quote;
},
retryDelay: 500, // We get 10 requests per second from 0x, so wait 500ms before trying again.
enabled: fetchEnabled && swapAmountIn?.gt(0) && getNextChainedQueryEnabled(removeOutQuery),
...baseQueryOptions,
});

const buyAmount = buyToken.fromBlockchain(swapQuote?.buyAmount || '0');
const addLiqTokens = targetWell.tokens;

const { data: targetAmountOut, ...addLiquidityQuery } = useQuery({
queryKey: queryKeys.addLiquidity(addLiqTokens, beanAmountOut, buyAmount),
const { data } = useQuery({
queryKey: ['pipelineConvert', sourceWell.address, targetWell.address, debouncedAmountIn.toString()],
queryFn: async () => {
const outAmount = await targetWell.getAddLiquidityOut([
beanAmountOut,
buyAmount,
]);

setFieldValue('tokens.0.amountOut', new BigNumber(outAmount.toHuman()));
console.log(
`[pipelineConvert/addLiquidityQuery (3)]: amountOut: ${outAmount.toNumber()}`
);
return outAmount;
setFieldValue('tokens.0.quoting', true);
try {
const sourceLPAmountOut = await sourceWell.getRemoveLiquidityOutEqual(
sourceWell.lpToken.fromHuman(debouncedAmountIn.toString())
);

console.debug(`[pipelineConvert/removeLiquidity (1)] result:`, {
BEAN: sourceLPAmountOut[sourceIdx.beanIndex].toNumber(),
[`${sellToken.symbol}`]: sourceLPAmountOut[sourceIdx.nonBeanIndex].toNumber(),
});

const beanAmountOut = sourceLPAmountOut[sourceIdx.beanIndex];
const swapAmountIn = sourceLPAmountOut[sourceIdx.nonBeanIndex];

const quote = await sdk.zeroX.fetchSwapQuote({
sellToken: sellToken.address,
buyToken: buyToken.address,
sellAmount: swapAmountIn.blockchainString,
takerAddress: sdk.contracts.pipeline.address,
shouldSellEntireBalance: true,
// 0x requests are formatted such that 0.01 = 1%. Everywhere else in the UI we use 0.01 = 0.01% ?? BS3TODO: VALIDATE ME
slippagePercentage: (slippage / 10).toString(),
});

console.debug(`[pipelineConvert/0xQuote (2)] result:`, { quote });

const swapAmountOut = buyToken.fromBlockchain(quote?.buyAmount || '0');
const targetLPAmountOut = await targetWell.getAddLiquidityOut([
beanAmountOut,
swapAmountOut,
]);
console.debug(`[pipelineConvert/addLiquidity (3)] result:`, {
amount: targetLPAmountOut.toNumber(),
});

setFieldValue('tokens.0.amountOut', new BigNumber(targetLPAmountOut.toHuman()));
return {
beanAmountOut,
swapAmountIn,
swapAmountOut,
quote,
targetLPAmountOut,
};
} catch (e) {
console.debug('[pipelineConvert/query] FAILED: ', e);
throw e;
} finally {
setFieldValue('tokens.0.quoting', false);
}
},
enabled:
fetchEnabled &&
buyAmount.gt(0) &&
getNextChainedQueryEnabled(swapOutQuery),
enabled: maxConvertableBN.gt(0) && debouncedAmountIn?.gt(0),
...baseQueryOptions,
});

Expand All @@ -201,12 +189,7 @@ const PipelineConvertFormInner = ({
}
};

// prettier-ignore
const isLoading = removeOutQuery.isLoading || swapOutQuery.isLoading || addLiquidityQuery.isLoading;
useEffect(() => {
setFieldValue('tokens.0.quoting', isLoading);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isLoading]);
const isQuoting = values.tokens?.[0]?.quoting;

return (
<>
Expand All @@ -222,20 +205,22 @@ const PipelineConvertFormInner = ({
<Stack gap={1}>
<TokenInputField
name="tokens.0.amount"
token={sourceToken}
balanceLabel="Deposited Balance"
// MUI
fullWidth
max={new BigNumber(maxConvertable)}
InputProps={{
endAdornment: (
<TokenAdornment
token={targetToken}
token={sourceToken}
onClick={showTokenSelect}
buttonLabel={targetToken.symbol}
buttonLabel={sourceToken.symbol}
disabled={isSubmitting}
/>
),
}}
balance={maxConvertableBN}
quote={
<Row gap={0.5} sx={{ display: { xs: 'none', md: 'flex' } }}>
<Tooltip
Expand Down Expand Up @@ -268,7 +253,7 @@ const PipelineConvertFormInner = ({
</Box>
</Tooltip>
{/* {displayQuote(state.amountOut, tokenOut)} */}
{isLoading && (
{isQuoting && (
<CircularProgress
variant="indeterminate"
size="small"
Expand All @@ -294,7 +279,7 @@ const PipelineConvertFormInner = ({
You may lose Grown Stalk through this transaction.
</WarningAlert>
</Box>
{amountIn?.gt(0) && targetAmountOut?.gt(0) && (
{amountIn?.gt(0) && data?.targetLPAmountOut?.gt(0) && (
<Box>
<TxnAccordion defaultExpanded={false}>
<TxnPreview
Expand All @@ -305,7 +290,7 @@ const PipelineConvertFormInner = ({
amountIn,
sourceToken.displayDecimals
)} ${sourceToken.name} to ${displayFullBN(
targetAmountOut || ZERO_BN,
data?.targetLPAmountOut || ZERO_BN,
targetToken.displayDecimals
)} ${targetToken.name}.`,
},
Expand All @@ -326,7 +311,7 @@ const PipelineConvertFormInner = ({
};

export const PipelineConvertForm = ({ values, sdk, ...restProps }: Props) => {
const sourceToken = values.tokens[0].token;
const sourceToken = values.tokens?.[0].token;
const targetToken = values.tokenOut;

// No need to memoize wells since they their object references don't change
Expand Down Expand Up @@ -369,6 +354,21 @@ function getNextChainedQueryEnabled(query: Omit<UseQueryResult, 'data'>) {
query.isSuccess && !query.isLoading && !query.isFetching && !query.isError
);
}

function useBuildWorkflow(
sourceWell: BasinWell,
targetWell: BasinWell,
amountIn: TokenValue,
swapTokenIn: Token,
swapTokenOut: Token,
swapAmountOut: TokenValue,
minTargetLPOut: TokenValue,
slippage: number
) {
const sdk = useSdk();

const buildWorkflow = useCallback(async () => {}, []);
}
// const swapAmountIn = removeOutQuery.data?.[sourceWellNonBeanIndex];

// const swapOutQuery = useQuery({
Expand Down
10 changes: 7 additions & 3 deletions projects/ui/vite.config.mts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { defineConfig, splitVendorChunkPlugin, UserConfig } from 'vite';
import { defineConfig, splitVendorChunkPlugin } from 'vite';
import path from 'path';
import { createHtmlPlugin } from 'vite-plugin-html';
import react from '@vitejs/plugin-react';
Expand Down Expand Up @@ -41,6 +41,7 @@ const CSP = buildCSP({
'*.google-analytics.com',
'*.doubleclick.net',
'https://gateway-arbitrum.network.thegraph.com', // Decentralized subgraph
'*.0x.org', // 0x API
],
'style-src': [
"'self'",
Expand All @@ -63,7 +64,10 @@ const CSP = buildCSP({
'https://cf-ipfs.com/', // Gov proposal images,
'https://*.ipfs.cf-ipfs.com/',
],
'frame-src': ['https://verify.walletconnect.com/', 'https://verify.walletconnect.org'], // for walletconnect
'frame-src': [
'https://verify.walletconnect.com/',
'https://verify.walletconnect.org',
], // for walletconnect
});

// @ts-ignore
Expand Down Expand Up @@ -129,4 +133,4 @@ export default defineConfig(({ command }) => ({
],
},
},
}));
}));

0 comments on commit bfcd29c

Please sign in to comment.