Git Product home page Git Product logo

joshstevens19 / simple-uniswap-sdk Goto Github PK

View Code? Open in Web Editor NEW
190.0 9.0 96.0 568 KB

Uniswap SDK which handles the routes automatically for you, changes in trade quotes reactive subscriptions, exposure to formatted easy to understand information, bringing back the best trade quotes automatically, generating transactions for you and much more.

License: MIT License

TypeScript 99.88% JavaScript 0.12%

simple-uniswap-sdk's People

Contributors

joshstevens19 avatar liu-zhipeng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simple-uniswap-sdk's Issues

Invalid from or to contract tokens

Hi!

I get this error when I make a new UniswapPair and run createFactory on Arbitrum Goerli (chainId === 421613). I have added multicallContractAddress and cloneUniswapContractDetails, but it still doesn't work. And can i skip nativeCurrency and nativeWrappedTokenInfo ?

So, maybe you can see what the problem is ? Thanks !

Screenshot 2023-07-25 at 11 05 10

Error with MKR token routing

image

Seeing this above error when I try to get routes from MKR token. Here's the code snippet:

const { UniswapPair, ChainId, UniswapVersion, UniswapPairSettings } = require('simple-uniswap-sdk')
const uniswapPair = new UniswapPair({
  fromTokenContractAddress: '0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2', //mkr token
  toTokenContractAddress: '0xdac17f958d2ee523a2206206994597c13d831ec7', //usdt token
  ethereumAddress: '0x4cb2b6dcb8da65f8421fed3d44e0828e0abcda60',
  chainId: ChainId.MAINNET,
  settings: new UniswapPairSettings({
    slippage: 0.005,
    deadlineMinutes: 20,
    disableMultihops: false,
    uniswapVersions: [UniswapVersion.v2],
  })
})

const doWork = async () => {
  const uniswapPairFactory = await uniswapPair.createFactory()
  const trade = await uniswapPairFactory.trade('1')
  console.log('TRADE ', trade.transaction)
  console.log('Trade Route', trade.routeText)
  trade.destroy()
}

doWork()

Work for GetAmountIn

I think this sdk will work for when user entered amount in the first field ,so that we are getting the path of highest amount out of all,But if user entered in the second field we need to get the path which gives lowest amount IN

feat: BSC support

Hey as you told me previously your simple-pancake-sdk is deprecated and we should us this lib, also you told me
"my uniswap sdk I created actually now let’s you map custom networks with full contract addresses (which means it supports forks like pancake)", as I'm not an epxert on blockchain I understand there that I can use custom networks like BSC.

But when I try to do your angular example settings like this

this.uniswapDappSharedLogicContext = {

      supportedNetworkTokens: [
        {
          chainId: 0x38, // 56
          defaultInputToken: '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c', // BNB
          defaultOutputToken: '0x1fd13bB00d80986adc121d5bEF287Bf2ED5C31AF', // GRY
          supportedTokens: [
            { contractAddress: '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c' }, // BNB
            { contractAddress: '0x1fd13bB00d80986adc121d5bEF287Bf2ED5C31AF' }, // GRY
            { contractAddress: '0xd293a7064e7e3b61bfbf2728f976d2500206dc73' }, // GRF
            { contractAddress: '0x6813e7d721694d8f8a2990a3e0a389b326169c6e' }, // FDOX
            { contractAddress: '0x8a3937e12155e07f3a06a84ec4dfdd3ec40d1e6a' }, // Nigels
          ],
        }
      ],
      ethereumAddress: accounts[0],
      ethereumProvider: this.web3Service.provider
      // ,
      // theming: {
      //   backgroundColor: 'red',
      //   button: { textColor: 'white', backgroundColor: 'blue' },
      //   panel: { textColor: 'black', backgroundColor: 'yellow' },
      //   textColor: 'orange',
      // },
    };

I'm running always in the unsupported network error because the simple-uniswap-sdk checks also for chainId, like this and others
ETH.info(this.chainId);

sdk creates trade but transaction doesn't happen

it seems to retrieve tokens successfully and my balance from kovan testnet. but I can't see the transaction in my metamask wallet.

image

Is there an additional function that I need to use to confirm the transaction?

Disable multicall for debug proposes

Hello!

The L2 solution that I'm currently using does not support the multicall v2 contract, so I've disabled the tryAggregate option (it would be useful if it could be set without forking the repo). So I have deployed the multicall v1 version.
There is another problem with the library output. The errors are confusing and it would be useful to add the debug toggle to provide more info for debugging.
The main question is that is it possible to disable multicall? With the following errors, it is almost impossible to determine what is going wrong.

 [error] call revert exception (method="aggregate((address,bytes)[])", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.5.0)

 [error] Error: call revert exception (method="aggregate((address,bytes)[])", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.5.0)
    at Logger.makeError (/project/node_modules/ethereum-multicall/node_modules/@ethersproject/logger/lib/index.js:199:21)
    at Logger.throwError (/project/node_modules/ethereum-multicall/node_modules/@ethersproject/logger/lib/index.js:208:20)
    at Interface.decodeFunctionResult (/project/node_modules/ethereum-multicall/node_modules/@ethersproject/abi/lib/interface.js:384:23)
    at Object.<anonymous> (/project/node_modules/ethereum-multicall/node_modules/@ethersproject/contracts/lib/index.js:390:56)
    at step (/project/node_modules/ethereum-multicall/node_modules/@ethersproject/contracts/lib/index.js:48:23)
    at Object.next (/project/node_modules/ethereum-multicall/node_modules/@ethersproject/contracts/lib/index.js:29:53)
    at fulfilled (/project/node_modules/ethereum-multicall/node_modules/@ethersproject/contracts/lib/index.js:20:58)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

By the way, thanks again for your awesome project!

using this sdk on polygon

hello,

is there a special chain id when im on the polygon network? i keep getting SushiswapError: invalid from or to contract tokens

when i do -

////sushiswap
const sushiswapPair = new SushiswapPair({
// the contract address of the token you want to convert FROM
fromTokenContractAddress: '0x111111111117dC0aa78b770fA6A738034120C302',
// the contract address of the token you want to convert TO
toTokenContractAddress: '0x1985365e9f78359a9B6AD760e32412f4a445E862',
// the ethereum address of the user using this part of the dApp
ethereumAddress: '0xB1E6079212888f0bE0cf55874B2EB9d7a5e02cD9',
// you can pass in the provider url as well if you want
providerUrl: url,
chainId: ChainId.MAINNET,
});

// now to create the factory you just do
const sushiswapPairFactory = await sushiswapPair.createFactory();

const toToken = sushiswapPairFactory.toToken;
console.log("toToken", sushiswapPairFactory);

Output trade fails on Uniswap V2

I found a potential bug in the code used to get the amountInMax:

https://github.com/uniswap-integration/simple-uniswap-sdk/blob/1629b680e615ce9851a4f7e7a3ba0187beac8261/src/factories/router/uniswap-router.factory.ts#L1935

Not sure why there's a check there for UniswapVersion.v3, but seems like this line causes output trades on Uniswap V2 to fail with EXCESSIVE_INPUT_AMOUNT because it subtracts the slippage, resulting in an amountInMax value lower than the expected amount.

Probably related to issue: #28

[UniswapError: invalid from or to contract tokens]

const uniswapPair = new UniswapPair({
    // the contract address of the token you want to convert FROM
    fromTokenContractAddress: '0x419D0d8BdD9aF5e606Ae2232ed285Aff190E711b',
    // the contract address of the token you want to convert TO
    toTokenContractAddress: '0x1985365e9f78359a9B6AD760e32412f4a445E862',
    // the ethereum address of the user using this part of the dApp
    ethereumAddress: '0xB1E6079212888f0bE0cf55874B2EB9d7a5e02cD9',
    chainId: ChainId.RINKEBY,
  });
    // now to create the factory you just do
    const uniswapPairFactory = await uniswapPair.createFactory();
    //the amount is the proper entered amount
    // so if they enter 10 pass in 10
    // it will work it all out for you
    const trade = await uniswapPairFactory.trade(10);

I try to get the trade information but it always shows the error: invalid from or to contract tokens.

Please help to check it.

Thanks

feat: support multiple exchanges and search for best route

Hello again,

I have a feature request or maybe its even already implemented.

Is there a way to get best route to exchange token if there are different liquidity pools on different exchanges?

In our case we have already a LP on TraderJoye and would like to add another to Pangolin (both and Avalanche C-Chain).
Is there a way we can do this?

Or even, bogged.finance has an AGGREGATOR which is already doing the job, is there a way to use the AGGREGATOR instead of a router?

@joshstevens19 @liu-zhipeng @vm06007

Gas limit override feature

Hello, thanks for the awesome project!
Simple-uniswap-sdk is really useful!

I have a problem with the automatic gas limit detection. It is often set for a too-small value, so I keep getting the Warning! Error encountered during contract execution [Out of gas] on my trade transactions. Is there any way to manually set the Gas Limit?

Trades not working - insufficient funds for gas * price + value

Hello.

I'm trying to use simple-uniswap-sdk to execute trades on Uniswap.
The library seems to be awesome, but I'm facing some issues using it.
Here is the code:

import simpleUniswapSdk from 'simple-uniswap-sdk';

const {ChainId, UniswapPair} = simpleUniswapSdk;

import Web3 from 'web3';

const PRIVATE_KEY = "XXXXXXXXXXX";
const ADDRESS = "XXXXXXXXXXX";
const FROM_TOKEN = "0xdac17f958d2ee523a2206206994597c13d831ec7";
const TO_TOKEN = "0x85eee30c52b0b379b046fb0f85f4f3dc3009afec";
const AMOUNT = '10';
const PROVIDER_URL = "https://mainnet.infura.io/v3/XXXXXXXXXXX";

const web3TradeExample = async () => {
  const uniswapPair = new UniswapPair({
    // the contract address of the token you want to convert FROM
    fromTokenContractAddress: FROM_TOKEN,
    // the contract address of the token you want to convert TO
    toTokenContractAddress: TO_TOKEN,
    // the ethereum address of the user using this part of the dApp
    ethereumAddress: ADDRESS,
    // you can pass in the provider url as well if you want
    providerUrl: PROVIDER_URL,
    chainId: ChainId.MAINNET,
  });

  // now to create the factory you just do
  const uniswapPairFactory = await uniswapPair.createFactory();
  const web3 = new Web3(uniswapPairFactory.providerUrl);

  // the amount is the proper entered amount
  const trade = await uniswapPairFactory.trade(AMOUNT);
  trade.transaction.gas = 30000;
    console.log(trade);

  if (!trade.fromBalance.hasEnough) {
    throw new Error('You do not have enough from balance to execute this swap');
  }
  trade.quoteChanged$.subscribe((value) => {
    // value will hold the same info as below but obviously with
    // the new trade info.
  });

  if (trade.approvalTransaction) {
    trade.approvalTransaction.gas = 30000;
console.log(trade.approvalTransaction);
    const signedTransaction = await web3.eth.accounts.signTransaction(
      trade.approvalTransaction,
      PRIVATE_KEY
    );

    console.log('signedTransaction');
    console.log(signedTransaction);
    if (!signedTransaction.rawTransaction) {
      throw new Error('Could not find tx');
    }

    web3.eth
      .sendSignedTransaction(signedTransaction.rawTransaction)
      .once('transactionHash', (transactionHash) => {
        console.log('approved txHash', transactionHash);
      })
      .once('receipt', async (receipt) => {
        console.log('approved receipt', receipt);
        await executeTrade(web3, trade);
      })
      .on('error', async (error) => {
        console.log(`ERROR ${error.message}`);
      });
  } else {
    console.log(
      'already has approved uniswap to move tokens on your behalf or its eth > erc20 token swap'
    );
    await executeTrade(web3, trade);
  }
};

const executeTrade = async (web3, trade) => {
  const signedTransaction = await web3.eth.accounts.signTransaction(
    trade.transaction,
    PRIVATE_KEY
  );
console.log('executeTrade signedTransaction')
console.log(signedTransaction)

  if (!signedTransaction.rawTransaction) {
    throw new Error('Could not find tx');
  }

  web3.eth
    .sendSignedTransaction(signedTransaction.rawTransaction)
    .once('transactionHash', (transactionHash) => {
      console.log('trade txHash', transactionHash);
    })
    .once('receipt', (receipt) => {
      console.log('trade receipt', receipt);
      // once done with trade aka they have sent it and you don't need it anymore call
      trade.destroy();
    })
    .on('error', async (error) => {
      console.log(`ERROR ${error.message}`);
    });
};

web3TradeExample();

And the output:

...
fromBalance: { hasEnough: true, balance: '91.085433' },
...
ERROR Returned error: insufficient funds for gas * price + value

Could you please explain what I'm doing wrong? Thanks in advance.

UniswapError: No routes found on Mainnet

Created liquidity pool at pair MTT > USDT on Mainnet.
Set up disableMultihops: false, but it still works only at MTT <-> USDT, on any other pair i got an error like:
UniswapError: No routes found for MTT > DAI

On uniswap app works great with any other tokens.

fromTokenContractAddress: '0xe0c15f5066FCbAfad6d1972125fB0cC1d2200bbe',
toTokenContractAddress: '0x6b175474e89094c44da98b954eedeac495271d0f',
uniswapVersions: [UniswapVersion.v2, UniswapVersion.v3],
chainId: 1,
settings: new UniswapPairSettings({
	slippage: 0.01,
	deadlineMinutes: 20,
	disableMultihops: false,
	uniswapVersions: [UniswapVersion.v2, UniswapVersion.v3]
})

I am stuck, please help to find out solution.

custom provider not set with pairfactory

Following the docs I am trying to pass my own chainstack web3 provider to the UniswapPair

const provider = new Web3.providers.HttpProvider(providerUrl);

const uniswapPair = new UniswapPair({,
ethereumProvider : provider,
........

When I log I still get some infura provider shown in the object and not my custom provider.

const uniswapPairFactory = await uniswapPair.createFactory();
console.log('pairProvider', uniswapPairFactory._uniswapPairFactoryContext.ethersProvider);

Using this library to provide liquidity

Hello,

I have a question regarding the use of this library and would like to get some directions. I'm trying to create a liquidity pool for, lets say an artificail pair ETH > $TOKEN. How should I procceed? Is this supported from the library? I took a look in the source code and found that the required functionalities are implemented, but what classes should I use? uniswap-router-contract.factory.v2.ts already contains the method addLiquidity. From what I understand the following steps should be followed:

  1. Create a UniswapPair instance
  2. Create a UniswapRouterContractFactoryV2 instance
  3. Call addLiquidity method of UniswapRouterContractFactoryV2 instance and provide the token parameters from UniswapPair instance.
  4. Check for approval
  5. Send the transaction to network using a web3/ethers provider.

Is my assumptions correct? There might be the case that we also need to have a deployed contract for the desired liquidity pool, but I am not sure. I read the uniswap documentations but could not figure how to procceed. You take a very important step by creating this library, which is so much simpler to use than the official Uniswap SDK, so I took the initiate to ask for help here.

UniswapError: invalid from or to contract tokens

Im trying to use one of the examples from this repo but I keep getting this error and I can not find the reason why. I am trying to use my chainstack node provider URL which works with other modules like web3 without issues.

const uniswapPair = new UniswapPair({
// the contract address of the token you want to convert FROM
fromTokenContractAddress : '0xdac17f958d2ee523a2206206994597c13d831ec7',
// the contract address of the token you want to convert TO
toTokenContractAddress : '0x2b591e99afe9f32eaa6214f7b7629768c40eeb39',
// the ethereum address of the user using this part of the dApp
ethereumAddress : '0x1624c82cdac2f518ab47ef34f497af268b6d7916',
chainId : ChainId.MAINNET,
providerUrl :
'myusernamen:[email protected]',
settings : new UniswapPairSettings({
// if not supplied it will use 0.005 which is 0.5%
// please pass it in as a full number decimal so 0.7%
// would be 0.007
slippage : 0.005,
// if not supplied it will use 20 a deadline minutes
deadlineMinutes : 20,
// if not supplied it will try to use multihops
// if this is true it will require swaps to direct
// pairs
disableMultihops : false,
// for example if you only wanted to turn on quotes for v3 and not v3
// you can only support the v3 enum same works if you only want v2 quotes
// if you do not supply anything it query both v2 and v3
uniswapVersions : [
UniswapVersion.v2,
UniswapVersion.v3
]
})
});

How to use native currency on custom network

Using ETH.MAINNET().contractAddress works fine for eth, and I am trying to reproduce that for Polygon and BSC. I see it prints out WETHs address with a suffix _ETH. I tried to make my input token the same way for Polygon 0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270_MATIC and it didn't work. My config is below, I have the nativeCurrency setup for the customNetwork. I have swaped tokens and everything so I know it works, I just don't know how to make the Native Coin of each chain as an input.

A few off topic questions. What does the baseTokens parameter do? How do I access them? Does the baseTokens have anything to do with the NativeCurrency?

Is there anyway I can swap using my wallet, but have the swap send the output to a different wallet?

Thanks

`const config = {
name: 'Polygon Mainnet',
nativeCurrency: {
name: 'Polygon',
symbol: 'MATIC',
decimals: 18,
logoUrl: [tokenImageUrlForContract({ tokenContractChainId: maticMainChainId })]
},
nativeWrappedTokenInfo: {
chainId: maticMainChainId,
contractAddress: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270',
decimals: 18,
symbol: 'WMATIC',
name: 'Wrapped MATIC'
},
multicallContractAddress: '0x275617327c958bD06b5D6b871E7f491D76113dd8',
defaultPairs: {
inputAddress: '0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270',
outputAddress: '0x8f3cf7ad23cd3cadbd9735aff958023239c6a063'
},
uniswapVersions: [UniswapVersion.v3],
cloneUniswapContractDetails: {
v3Override: {
routerAddress: '0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45',
factoryAddress: '0x1f98431c8ad98523631ae4a59f267346ea31f984',
quoterAddress: '0xb27308f9f90d607463bb33ea1bebb41c27ce5ab6'
}
}
}

async function quote({
chainId,
library,
account,
fromTokenContractAddress,
toTokenContractAddress,
slippage,
deadlineMinutes,
tradeAmount,
tradeDirection
}) {
try {
const {
name,
nativeCurrency,
nativeWrappedTokenInfo,
multicallContractAddress,
uniswapVersions,
cloneUniswapContractDetails
} = config

    let settings = new UniswapPairSettings({
        slippage,
        deadlineMinutes,
        disableMultihops: false,
        uniswapVersions,
        gasSettings: {
            getGasPrice: async () => {
                // TODO update
                const gasPrice = await library.getGasPrice()
                return formatUnits(gasPrice, 'gwei')
            }
        }
    })

    if (!ethChains.includes(chainId)) {
        settings = {
            ...settings,
            cloneUniswapContractDetails,
            customNetwork: {
                nameNetwork: name,
                multicallContractAddress,
                nativeCurrency,
                nativeWrappedTokenInfo
            }
        }
    }

    const uniswapPair = new UniswapPair({
        fromTokenContractAddress,
        toTokenContractAddress,
        ethereumAddress: account,
        ethereumProvider: library,
        settings
    })

    const uniswapPairFactory = await uniswapPair.createFactory()

    const trade = await uniswapPairFactory.trade(tradeAmount, tradeDirection)

    //.......
} catch (error) {
    throw error
}

}
`

Error for token dForce that works on uniswap app

The following findBestRoute fails for token with address 0x431ad2ff6a9C365805eBaD47Ee021148d6f7DBe0, but works on uniswap app. The error is likely related to symbol and name of the contract being a bytes32 instead of string.
https://etherscan.io/address/0x431ad2ff6a9C365805eBaD47Ee021148d6f7DBe0#readContract

Error: UniswapError: invalid from or to contract tokens

Example:

  const fromTokenContractAddress = ETH.MAINNET().contractAddress;
  const toTokenContractAddress = '0x431ad2ff6a9C365805eBaD47Ee021148d6f7DBe0'; 
  
  const ethereumAddress = '0xB1E6079212888f0bE0cf55874B2EB9d7a5e02cD9';

  const uniswapPair = new UniswapPair({
    fromTokenContractAddress,
    toTokenContractAddress,
    ethereumAddress,
    chainId: ChainId.MAINNET,
  });

  const uniswapPairFactory = await uniswapPair.createFactory();

  const trade = await uniswapPairFactory.findBestRoute(
    '0.00000000001',
    TradeDirection.input
  );

findBestRoute method returns wrong value for expected amount

try {
        const uniswapPairFactory = await uniswapPair.createFactory();
        const result = await uniswapPairFactory.findBestRoute(
            amount,
            TradeDirection.input
        );

        return {
            path: result.bestRouteQuote.routePathArray,
            expectedOutput:
                result.bestRouteQuote
                    .expectedConvertQuoteOrTokenAmountInMaxWithSlippage,
        };
    } catch (error) {
        console.log("error: ", error);
        throw error;
    }

I used cloneUniswapContractDetails to make this works on cronos chain and every things works fine. but for a particular token, the result.bestRouteQuote.expectedConvertQuoteOrTokenAmountInMaxWithSlippage gives a very wrong value

Liquidity pool support?

This SDK has made exchanging tokens easier in Metamask, thank you.

I'm looking for liquidity pool support, where I can get real usable price comparison data for arbitrage opportunities. I see a pools reference in src/factories/uniswap-factory/v3/uniswap-contract.factory.v3.ts but I don't see any related examples. Any additional info on this for this SDK please, and if so, how cold I subscribe to a pool price update event?

Or am I really completely missing something here?

How to support more chainId?

my code:

// use custom provider:
// Network Name: Heco-Mainnet
// New RPC URL: https://http-mainnet-node.huobichain.com
// ChainID: 128
// Symbol: HT
// Block Explorer URL: https://hecoinfo.com
const rpc_url = "https://http-mainnet-node.huobichain.com";
const provider = new ethers.providers.JsonRpcProvider(rpc_url);

const uniswapPair = new uniswapSimple.UniswapPair({
        fromTokenContractAddress: "0xa71edc38d189767582c38a3145b5873052c3e47a",
        toTokenContractAddress: "0x5545153ccfca01fbd7dd11c0b23ba694d9509a6f",
        ethereumAddress: ethereumAddress,
        ethereumProvider: provider
        // providerUrl: rpc_url,
        // chainId: 128,
});

// throw error
const uniswapPairFactory = await uniswapPair.createFactory();

error:

Error [UniswapError]: ChainId - 128 is not supported. This lib only supports mainnet(1), ropsten(4), kovan(42), rinkeby(4), görli(5) and ropsten(3)

Should I change sdk source code?

Invalid from or to address on custom chain?

Both of these addresses definitely exist, but INIT_CODE_HASH on this chan is likely different, so the pair calculation is likely different. Any idea what this error could mean? This is when i make a new UniswapPair and run createFactory on a non-eth chain. I don't have a canonical Multicall address here so I left that blank, is that OK? Or should I deploy my own multicall contract?

Allow to override tradePath

I'm trying to execute trades from WETH -> other tokens, and I really want to use the WETH that the account already owns.
It seems that the automatic getTradePath then always makes the transaction between unwrapped ETH -> token. For my purpose it would be great if the tokenpair (or createFactory) has an optional parameter to force the tradepath to stay erc20ToErc20 even though one of the tokens is WETH.

Prices vary slightly

The price I get through the sdk call is slightly different from the price on uniswap. For example, the current 1000USDT can be exchanged for 279.157 SUSHI, but the quote in the SDK is 273.387. I want to know where this difference comes from, thanks

Price impact

Has anyone already implemented the functionality of getting a price impact in this library?

Base Network support

How can we use the base network with this package?

I have defined customNetwork and cloneUniswapContractDetails, but when I try to use them, I get the message:

Can not find chain name for 8453. This lib only supports mainnet(1), ropsten(4), kovan(42), rinkeby(4) and görli(5)

This is my config:

 const uniswapPair = new UniswapPair({
  fromTokenContractAddress: "0x4200000000000000000000000000000000000006",
  toTokenContractAddress: "0x347F500323D51E9350285Daf299ddB529009e6AE",
  ethereumAddress: selectedAddress,
  ethereumProvider: metaMaskProvider,
  chainId: 8453,
  settings: new UniswapPairSettings({
   cloneUniswapContractDetails: {
    v2Override: {
     factoryAddress: "0x8909Dc15e40173Ff4699343b6eB8132c65e18eC6",
     routerAddress: "0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD",
     pairAddress: "0x0Aa352230c5C05Fa912DAC0B538551f79121e29B",
    },
    v3Override: {
     factoryAddress: "0x33128a8fC17869897dcE68Ed026d694621f6FDfD",
     routerAddress: "0x2626664c2603336E57B271c5C0b26F421741e481",
     quoterAddress: "0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a",
    },
   },
   customNetwork: {
    nameNetwork: "Base Mainnet",
    multicallContractAddress: "0x275617327c958bD06b5D6b871E7f491D76113dd8",
    nativeCurrency: {
     name: "Ether",
     symbol: "ETH",
    },
    nativeWrappedTokenInfo: {
     chainId: 8453,
     contractAddress: "0x4200000000000000000000000000000000000006",
     decimals: 18,
     symbol: "WETH",
     name: "Wrapped ETH",
    },
   },
   slippage: 0.0005,
   deadlineMinutes: 10,
   uniswapVersions: [UniswapVersion.v2, UniswapVersion.v3],
  }),
 });

Has anyone used this package with Base network? If so, could you kindly provide the configuration you used?
That would greatly help us; we have been struggling with the Uniswap SDK for almost a month now. We just want to use code to trade, and this package is our last hope. =/

not working on goerli test network?

const uniswapPair = new UniswapPair({
fromTokenContractAddress: '0xf74a5ca65e4552cff0f13b116113ccb493c580c5',
toTokenContractAddress: '0x2ac3c1d3e24b45c6c310534bc2dd84b5ed576335',
chainId: ChainId.GÖRLI,
...
})
which returns

UniswapError: invalid from or to contract tokens

Those goerli tokens are from https://explorer.bitquery.io/goerli/tokens which should be valid

TokensFactoryPublic with customNetwork not working

I am attempting to get getAllowanceAndBalanceOfForContracts working with the TokensFactoryPublic for BSC. The constructor takes in a custom network but it doesn't seem to be taking the property as the factory logs out its custom network as undefined.

Code example:
const tokensFactoryPublic = new TokensFactoryPublic({
ethereumProvider: provider,
customNetwork: {
nameNetwork: 'Binance Smart Chain Testnet',
multicallContractAddress: '0x8F3273Fb89B075b1645095ABaC6ed17B2d4Bc576',
nativeCurrency: {
name: 'Binance Coin',
symbol: 'tBNB', // BNB
decimals: 18
},
nativeWrappedTokenInfo: {
chainId: provider._network.chainId,
contractAddress: '0xae13d989dac2f0debff460ac112a837c89baa7cd',
decimals: 18,
symbol: 'WBNB',
name: 'Wrapped BNB'
}
}
})

    console.log(tokensFactoryPublic)

Here is what it logs out:
TokensFactoryPublic {
_ethersProvider: EthersProvider {
_providerContext: { ethereumProvider: [JsonRpcProvider], customNetwork: [Object] },
_ethersProvider: JsonRpcProvider {
_isProvider: true,
_events: [],
_emitted: [Object],
disableCcipRead: false,
formatter: [Formatter],
anyNetwork: false,
_network: [Object],
_maxInternalBlockNumber: -1024,
_lastBlockNumber: -2,
_maxFilterBlockRange: 10,
_pollingInterval: 4000,
_fastQueryDate: 0,
connection: [Object],
_nextId: 42
}
},
_customNetwork: undefined,
_cloneUniswapContractDetails: undefined,
_multicall: CustomMulticall {
_options: {
ethersProvider: [JsonRpcProvider],
tryAggregate: true,
multicallCustomContractAddress: undefined
},
ABI: [ [Object], [Object] ],
_executionType: 'ethers'
}
}

bug(avalanche): native token _ETH is not valid

I'm using the simple-uniswap-sdk and your angular swap on the AVALANCHE main net. But there are problems with the NATIVE token.

My config is mainly this:

(customNetworkData = {
          nameNetwork: 'Avalanche',
          multicallContractAddress: '0xed386Fe855C1EFf2f843B910923Dd8846E45C5A4',
          nativeCurrency: {
              name: 'AVAX',
              symbol: 'AVAX',
          },
          nativeWrappedTokenInfo: {
              chainId: 43114,
              contractAddress: '0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7',
              decimals: 18,
              symbol: 'AVAX', // WAVAX
              name: 'AVAX' // Wrapped AVAX
          },
          baseTokens: {
              usdt: {
                  chainId: 43114,
                  contractAddress: '0xc7198437980c041c805A1EDcbA50c1Ce5db95118',
                  decimals: 6,
                  symbol: 'USDT.e',
                  name: 'USDT.e'
              },
              usdc: {
                  chainId: 43114,
                  contractAddress: '0xa7d7079b0fead91f3e65f86e8915cb59c1a4c664',
                  decimals: 6,
                  symbol: 'USDC.e',
                  name: 'USDC.e'
              },
              wbtc: {
                  chainId: 43114,
                  contractAddress: '0x152b9d0fdc40c096757f570a51e494bd4b943e50',
                  decimals: 8,
                  symbol: 'BTC.b',
                  name: 'BTC.b'
              }
          }
      });

and

this.uniswapDappSharedLogicContext  = {
      supportedNetworkTokens: [
        {
          chainId: 43114,
          // 0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7_ETH
          defaultInputToken: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E', // USDC
          defaultOutputToken: '0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7_ETH', // FOOK
          supportedTokens: [
            { contractAddress: '0x95923F63dA09B4f7520f7C65a31F318D8228B744', tokenImageContext: { image: tokens.fook.logo , isSvg: false } }, // FOOK
            { contractAddress: '0x71124b9199B97E0E232Aee3909e3B0eC28402611', tokenImageContext: { image: tokens.fook.logo, isSvg: false } }, // FOOKF
            { contractAddress: '0x27301e48aF707F950765d5570d7279a6e3E3BC5B', tokenImageContext: { image: tokens.fookz.logo, isSvg: false } }, // FOOKZ
            { contractAddress: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E', tokenImageContext: { image: tokens.usdc.logo, isSvg: false } }, // USDC
            { contractAddress: '0x152b9d0fdc40c096757f570a51e494bd4b943e50', tokenImageContext: { image: tokens.wbtc.logo, isSvg: false } }, // BTC.b
            // { contractAddress: '0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7_ETH', tokenImageContext: { image: tokens.avax.logo , isSvg: false } }, // AVAX
            { contractAddress: '0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7', tokenImageContext: { image: tokens.avax.logo , isSvg: false } } // AVAX
            // { contractAddress: '0xc7198437980c041c805A1EDcbA50c1Ce5db95118' }, // USDT.e
            // { contractAddress: '0xa7d7079b0fead91f3e65f86e8915cb59c1a4c664' } // USDC.e
          ]
        }
      ],
      ethereumAddress: userAddress,
      ethereumProvider: this.web3Service.provider,
      providerUrl: providerUrl,
      settings: new UniswapPairSettings({
          slippage: 0.005,
          deadlineMinutes: 15,
          disableMultihops: false,
          uniswapVersions: [UniswapVersion.v2],
          cloneUniswapContractDetails: targets,
          customNetwork: customNetworkData
      })
  }

It seems that the logic is adding a "_ETH" at the Wrapped WAVAX token address. But once I choose to use this "_ETH" token for the from or to token, so to swap AVAX to another tooken I run into the issue

ERROR Error: Uncaught (in promise): UniswapError: invalid from or to contract tokens
UniswapError: invalid from or to contract tokens
    at new UniswapError (uniswap-error.js:17:28)
    at TokensFactory.<anonymous> (tokens.factory.js:123:31)
    at step (tokens.factory.js:32:23)
    at Object.next (tokens.factory.js:13:53)

@joshstevens19 @liu-zhipeng @vm06007

Make it possible to put in metamask provider

Thanks for this awesome simplification of working with uniswap!

I'm working on a dapp and running into issues of a mismatch between metamask and the calls this library does.
E.g. when I switch metamask to localhost or back to mainnet or a testnet, it would be nice if this library just switches transparently.
I've tried everything I could to get an 'underlying' RPC URL from metamask, but this seems to be not possible, and passing a providerUrl is the only API this library currently supports, so this would mean that I need to make a manual mapping somewhere to map current metamask settings to ChainId + URL combinations.

When I look at the code of the library, it in the end also just uses an ethers provider, so would it be possible to pass in the existing provider I got from metamask? Then everything would work without extra code needed.

Must have a `fromTokenContractAddress` on the context

When defining a UniswapPair:

 const uniswapPair = new UniswapPair({
   fromTokenContractAddress: fromTokenContractAddress,
   toTokenContractAddress: toTokenContractAddress,
   walletAddress: walletAddress,
   chainId: ChainId.ROPSTEN,
 });

Exception: Must have a fromTokenContractAddress on the context

C:\Dev\Uniswap-Misc\Uniswap-v3-Contract-WS\node_modules\simple-uniswap-sdk\dist\cjs\common\errors\uniswap-error.js:20
        var _this = _super.call(this, message) || this;
                           ^

Error [UniswapError]: **Must have a `fromTokenContractAddress` on the context**
    at new UniswapError (C:\Dev\Uniswap-Misc\Uniswap-v3-Contract-WS\node_modules\simple-uniswap-sdk\dist\cjs\common\errors\uniswap-error.js:20:28)
    at new UniswapPair (C:\Dev\Uniswap-Misc\Uniswap-v3-Contract-WS\node_modules\simple-uniswap-sdk\dist\cjs\factories\pair\uniswap-pair.js:55:19)
    at etherTradeExample (C:\Dev\Uniswap-Misc\Uniswap-v3-Contract-WS\Uniswap-v3-SimpleSDK1.js:120:26)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 6
}

Node.js v17.3.0

From what I can see, I have used fromTokenContractAddress. Am I missing something?

Can't use with vite

In a vue + ts + vite setup, importing this module gives the following error:

Module "stream" has been externalized for browser compatibility and cannot be accessed in client code.

Polygon Main/Mumbai Contracts

Edit: I went with Uniswap instead of Sushi.

I am having a hard time finding the SushiSwap Router, Factory and Multicall contract addresses for these chains. I got all the other chains to work. Anyone have any luck?

Here are the addresses I have tried, mixed together in different ways

MultiCall
0xef0881ec094552b2e128cf945ef17a6752b4ec5d
0xc2edad668740f1aa35e4d8f227fb8e17dca888cd

Router
0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F
0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506

Factory/Pair
0xf1c9881Be22EBF108B8927c4d197d126346b5036
0xc35DADB65012eC5796536bD9864eD8773aBc74C4

Here are the other contracts that work, I am sure they will help someone.

BSC Main PancakeSwap
{ multicallContractAddress: '0x65e9a150e06c84003d15ae6a060fc2b1b393342c', cloneUniswapContractDetails: { v2Override: { routerAddress: '0x10ED43C718714eb63d5aA57B78B54704E256024E', factoryAddress: '0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73', pairAddress: '0xca143ce32fe78f1f7019d7d551a6402fc5350c73' } } }

BSC Testnet PancakeSwap
{ multicallContractAddress: '0x8F3273Fb89B075b1645095ABaC6ed17B2d4Bc576', cloneUniswapContractDetails: { v2Override: { routerAddress: '0xD99D1c33F9fC3444f8101754aBC46c52416550D1', factoryAddress: '0x6725F303b657a9451d8BA641348b6761A6CC7a17', pairAddress: '0x6725F303b657a9451d8BA641348b6761A6CC7a17' } } }

Pulse Chain Testnet Uniswap
{ multicallContractAddress: '0x5BA1e12693Dc8F9c48aAD8770482f4739bEeD696', cloneUniswapContractDetails: { v2Override: { routerAddress: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', factoryAddress: '0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95', pairAddress: '0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95' } } }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.