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

alpha router uniswap CORS error #625

Open
WingsDevelopment opened this issue Jul 1, 2024 · 4 comments
Open

alpha router uniswap CORS error #625

WingsDevelopment opened this issue Jul 1, 2024 · 4 comments

Comments

@WingsDevelopment
Copy link

WingsDevelopment commented Jul 1, 2024

  • I'm submitting a ...
    [ x] bug report
    [ ] feature request
    [ ] question about the decisions made in the repository
    [ ] question about how to use this project

  • I am trying to implement swap form with uniswap SDK, but i am getting CORS error.

here is my code (mostly copied from uniswap repo):

import {
  BigintIsh,
  ChainId,
  CurrencyAmount,
  Token,
  TradeType,
} from "@uniswap/sdk-core";
import {
  AlphaRouter,
  AlphaRouterConfig,
  nativeOnChain,
} from "@uniswap/smart-order-router";
import JSBI from "jsbi";
import { Protocol } from "@uniswap/router-sdk";

import { getMainnetProvider, getProvider } from "./providers";
import { QuoteState, transformSwapRouteToGetQuoteResult } from "./transform";

const routers = new Map<ChainId, AlphaRouter>();
export function getRouter(chainId: ChainId): AlphaRouter {
  const provider = getProvider();
  const router = new AlphaRouter({ chainId, provider: getMainnetProvider() });
  routers.set(chainId, router);
  return router;
}
export enum SwapRouterNativeAssets {
  MATIC = "MATIC",
  BNB = "BNB",
  AVAX = "AVAX",
  ETH = "ETH",
}

async function getQuote(
  {
    tradeType,
    tokenIn,
    tokenOut,
    amount: amountRaw,
  }: {
    tradeType: TradeType;
    tokenIn: {
      address: string;
      chainId: number;
      decimals: number;
      symbol?: string;
    };
    tokenOut: {
      address: string;
      chainId: number;
      decimals: number;
      symbol?: string;
    };
    amount: BigintIsh;
  },
  routerConfig: Partial<AlphaRouterConfig>,
  router: AlphaRouter
): Promise<any> {
  const tokenInIsNative = Object.values(SwapRouterNativeAssets).includes(
    tokenIn.address as any
  );
  const tokenOutIsNative = Object.values(SwapRouterNativeAssets).includes(
    tokenOut.address as any
  );

  const currencyIn = tokenInIsNative
    ? nativeOnChain(tokenIn.chainId)
    : new Token(
        tokenIn.chainId,
        tokenIn.address,
        tokenIn.decimals,
        tokenIn.symbol
      );
  const currencyOut = tokenOutIsNative
    ? nativeOnChain(tokenOut.chainId)
    : new Token(
        tokenOut.chainId,
        tokenOut.address,
        tokenOut.decimals,
        tokenOut.symbol
      );

  const baseCurrency =
    tradeType === TradeType.EXACT_INPUT ? currencyIn : currencyOut;
  const quoteCurrency =
    tradeType === TradeType.EXACT_INPUT ? currencyOut : currencyIn;

  const amount = CurrencyAmount.fromRawAmount(
    baseCurrency,
    JSBI.BigInt(amountRaw.toString()) // Ensure amountRaw is converted to JSBI.BigInt
  );
  // TODO (WEB-2055): explore initializing client side routing on first load (when amountRaw is null) if there are enough users using client-side router preference.
  const swapRoute = await router.route(
    amount,
    quoteCurrency,
    tradeType,
    /*swapConfig=*/ undefined,
    routerConfig
  );

  if (!swapRoute) {
    return { state: QuoteState.NOT_FOUND };
  }

  return transformSwapRouteToGetQuoteResult(tradeType, amount, swapRoute);
}

export async function getClientSideQuote(
  {
    tokenInAddress,
    tokenInChainId,
    tokenInDecimals,
    tokenInSymbol,
    tokenOutAddress,
    tokenOutChainId,
    tokenOutDecimals,
    tokenOutSymbol,
    amount,
    tradeType,
  }: any,
  config: Partial<AlphaRouterConfig> = {
    protocols: [Protocol.V3, Protocol.V2, Protocol.MIXED],
  },
  router: AlphaRouter = getRouter(ChainId.MAINNET)
) {
  return getQuote(
    {
      tradeType,
      tokenIn: {
        address: tokenInAddress,
        chainId: tokenInChainId,
        decimals: tokenInDecimals,
        symbol: tokenInSymbol,
      },
      tokenOut: {
        address: tokenOutAddress,
        chainId: tokenOutChainId,
        decimals: tokenOutDecimals,
        symbol: tokenOutSymbol,
      },
      amount: JSBI.BigInt(amount.toString()),
    },
    config,
    router
  );
}

const mainnetProvider = new ethers.providers.JsonRpcProvider(
  CurrentConfig.rpc.mainnet
);
export function getMainnetProvider(): BaseProvider {
  return mainnetProvider;
}

here is error that i am getting:

Access to XMLHttpRequest at 'https://cloudflare-ipfs.com/ipns/api.uniswap.org/v1/pools/v3/mainnet.json' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
routing.ts:42 
        
        
       GET https://cloudflare-ipfs.com/ipns/api.uniswap.org/v1/pools/v3/mainnet.json net::ERR_FAILED
dispatchXhrRequest @ xhr.js:187
xhrAdapter @ xhr.js:13
dispatchRequest @ dispatchRequest.js:53
request @ Axios.js:108
Axios.<computed> @ Axios.js:129
wrap @ bind.js:9
async_retry__WEBPACK_IMPORTED_MODULE_0___default.retries @ uri-subgraph-provider.js:43
runAttempt @ index.js:42
RetryOperation.attempt @ retry_operation.js:116
run @ index.js:55
retry @ index.js:58
getPools @ uri-subgraph-provider.js:35
getPools @ caching-subgraph-provider.js:29
await in getPools (async)
getPools @ subgraph-provider-with-fallback.js:22
getV3CandidatePools @ get-candidate-pools.js:101
getSwapRouteFromChain @ alpha-router.js:700
route @ alpha-router.js:499
await in route (async)
generateRoute @ routing.ts:42
fetchUscEquivalent @ BuyTab.tsx:151
eval @ BuyTab.tsx:200
commitHookEffectListMount @ react-dom.development.js:20998
commitHookPassiveMountEffects @ react-dom.development.js:23051
commitPassiveMountOnFiber @ react-dom.development.js:23156
recursivelyTraversePassiveMountEffects @ react-dom.development.js:23134

Show 213 more frames
Show less

  • my dependency version:
    "@uniswap/v2-sdk": "^3.0.1",
    "@uniswap/v3-periphery": "1.4.4",
    "@uniswap/router-sdk": "1.9.2",
    "@uniswap/v3-core": "1.0.1",
    "@uniswap/smart-order-router": "3.17.3",
    "@uniswap/sdk-core": "^3.1.0",
    "@uniswap/v3-sdk": "^3.9.0",
@GreenWojak
Copy link

I'm having the same issue. For some reason this same "No 'Access-Control-Allow-Origin' header" error has been popping up since very recently and hasn't stopped appearing since, making us unable to make use of the alpha router. Please look into this!

@WingsDevelopment
Copy link
Author

I'm having the same issue. For some reason this same "No 'Access-Control-Allow-Origin' header" error has been popping up since very recently and hasn't stopped appearing since, making us unable to make use of the alpha router. Please look into this!

Did you manage to solve this somehow ? :(

@GreenWojak
Copy link

I did actually find a workaround for this specific issue - If you have a back-end, import the package there and let the front-end make get requests to the back-end in order to obtain routes using the alpha router. This resolved the issue for me. Hope it helps!

@Universal-Hacker
Copy link

I did actually find a workaround for this specific issue - If you have a back-end, import the package there and let the front-end make get requests to the back-end in order to obtain routes using the alpha router. This resolved the issue for me. Hope it helps!

I tried this for me it doesn't work. i can't initialize alpha router on backend side... i get this problem: #523

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants