Uniswap / smart-order-router

GNU General Public License v3.0
417 stars 424 forks source link

alpha router uniswap CORS error #625

Open WingsDevelopment opened 5 months ago

WingsDevelopment commented 5 months ago

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
GreenWojak commented 5 months ago

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 commented 4 months ago

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 commented 4 months ago

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 commented 4 months ago

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: https://github.com/Uniswap/smart-order-router/issues/523