Giter Site home page Giter Site logo

uniswap-python / uniswap-python Goto Github PK

View Code? Open in Web Editor NEW
880.0 23.0 363.0 3.37 MB

🦄 The unofficial Python client for the Uniswap exchange.

Home Page: https://uniswap-python.com

License: MIT License

Python 99.66% Makefile 0.34%
uniswap uniswap-exchange uniswap-api orderbook dex trade ethereum eth api wrapper

uniswap-python's Introduction

uniswap-python

GitHub Actions codecov Downloads License PyPI Typechecking: Mypy Code style: black GitPOAP Badge

GitHub Repo stars Twitter Follow

The unofficial Python client for Uniswap.

Documentation is available at https://uniswap-python.com/

Want to help implement support for Uniswap v4? See issue #337

Functionality

  • A simple to use Python wrapper for all available contract functions and variables
  • A basic CLI to get prices and token metadata
  • Simple parsing of data returned from the Uniswap contract

Supports

  • Uniswap v3 (as of v0.5.0)
    • Including beta support for Arbitrum & Optimism deployments (as of v0.5.4)
  • Uniswap v2 (as of v0.4.0)
  • Uniswap v1 (deprecated)
  • Various forks (untested, but should work)
    • Honeyswap (xDai)
    • Pancakeswap (BSC)
    • Sushiswap (mainnet)

Getting Started

See our Getting started guide in the documentation.

Testing

Unit tests are under development using the pytest framework. Contributions are welcome!

Test are run on a fork of the main net using ganache-cli. You need to install it with npm install -g ganache-cli before running tests.

To run the full test suite, in the project directory set the PROVIDER env variable to a mainnet provider, and run:

poetry install
export PROVIDER= # URL of provider, e.g. https://mainnet.infura.io/v3/...
make test
# or...
poetry run pytest --capture=no  # doesn't capture output (verbose)

Support our continued work!

You can support us on Gitcoin Grants.

Authors

Want to help out with development? We have funding to those that do! See #181

Contributors also earn this beautiful GitPOAP for their contributions!

Changelog

0.7.2

  • Updated: Default fee is not applied when using Uniswap V3. Default fee for Uniswap V1 and V2 is still 0.3%.
  • Updated: InvalidFeeTier exception is raised when a tier is not supported by the protocol version. See all supported tiers in uniswap.fee.FeeTier

0.7.1

  • incomplete changelog

0.7.0

  • incomplete changelog

0.5.4

  • added use of gas estimation instead of a fixed gas limit (to support Arbitrum)
  • added use_estimate_gas constructor argument (used in testing)
  • added constants/basic support for Arbitrum, Optimism, Polygon, and Fantom. (untested)
  • incomplete changelog

0.5.3

  • incomplete changelog

0.5.2

  • incomplete changelog

0.5.1

  • Updated dependencies
  • Fixed minor typing issues

0.5.0

  • Basic support for Uniswap V3
  • Added new methods get_price_input and get_price_output
  • Made a lot of previously public methods private
  • Added documentation site
  • Removed ENS support (which was probably broken to begin with)

0.4.6

  • Bug fix: Update bleach package from 3.1.4 to 3.3.0

0.4.5

  • Bug fix: Use .eth instead of .ens

0.4.4

  • General: Add new logo for Uniswap V2
  • Bug fix: Invalid balance check (#25)
  • Bug fix: Fixed error when passing WETH as token

0.4.3

  • Allow kwargs in approved decorator.

0.4.2

  • Add note about Uniswap V2 support

0.4.1

  • Update changelog for PyPi and clean up

0.4.0

A huge thank you Erik Bjäreholt for adding Uniswap V2 support, as well as all changes in this version!

  • Added support for Uniswap v2
  • Handle arbitrary tokens (by address) using the factory contract
  • Switched from setup.py to pyproject.toml/poetry
  • Switched from Travis to GitHub Actions
  • For CI to work in your repo, you need to set the secret MAINNET_PROVIDER. I use Infura.
  • Running tests on a local fork of mainnet using ganache-cli (started as a fixture)
  • Fixed tests for make_trade and make_trade_output
  • Added type annotations to the entire codebase and check them with mypy in CI
  • Formatted entire codebase with black
  • Moved stuff around such that the basic import becomes from uniswap import Uniswap (instead of from uniswap.uniswap import UniswapWrapper)
  • Fixed misc bugs

0.3.3

  • Provide token inputs as addresses instead of names

0.3.2

  • Add ability to transfer tokens after a trade
  • Add tests for this new functionality

0.3.1

  • Add tests for all types of trades

0.3.0

  • Add ability to make all types of trades
  • Add example to README

0.2.1

  • Add liquidity tests

0.2.0

  • Add liquidity and ERC20 pool methods

0.1.1

  • Major README update

0.1.0

  • Add market endpoints
  • Add tests for market endpoints

uniswap-python's People

Contributors

anryko avatar antazoey avatar antibagr avatar christianperez34 avatar cmackeen avatar dependabot[bot] avatar ehtec avatar ekzhang avatar ericjang avatar erikbjare avatar jhb10c avatar jibranbinsaleem avatar jz448 avatar keremp avatar leibniz137 avatar lfeng100 avatar liquid-8 avatar matteljay avatar nimcon avatar nsuarez75 avatar nxet avatar pawlowskiadrian avatar rishirandhawa avatar shanefontaine avatar voyz avatar ytoast 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uniswap-python's Issues

Can't get ETH-USDT price from uniswap .

Thanks, @shanefontaine for the great work.
I have a humble problem. I can't get ETH-USDT price from UNISWP.
There is code:

    dai = Web3.toChecksumAddress("0x0e2298E3B3390e3b945a5456fBf59eCc3f55DA16")
    usdt = Web3.toChecksumAddress("0xdac17f958d2ee523a2206206994597c13d831ec7")
    uniswap_wrapper = Uniswap(address, private_key, version=2, web3=w3)
    print(f"{round(uniswap_wrapper.get_eth_token_input_price(dai, 1 * 10 ** 18) / 10 ** 18, 6)}") # works 
    print(f"{round(uniswap_wrapper.get_eth_token_output_price(dai, 1 * 10 ** 18) / 10 ** 18, 6)}") # works 

    print(f"{round(uniswap_wrapper.get_eth_token_input_price(usdt, 1 * 10 ** 18) / 10 ** 18, 6)}") # doesn't work
    print(f"{round(uniswap_wrapper.get_eth_token_output_price(usdt, 1 * 10 ** 18) / 10 ** 18, 6)}") # doesn't work

Dependency issue when trying to install through pip

Recently I tried to install the new package and got this issue though pip

ERROR: Could not find a version that satisfies the requirement rusty-rlp<0.2,>=0.1.15 (from rlp<=2.0.0.alpha-1,>=1.0.0->eth-account<0.6.0,>=0.5.3->web3<6.0.0,>=5.12.0->uniswap-python) (from versions: none) ERROR: No matching distribution found for rusty-rlp<0.2,>=0.1.15 (from rlp<=2.0.0.alpha-1,>=1.0.0->eth-account<0.6.0,>=0.5.3->web3<6.0.0,>=5.12.0->uniswap-python)

TypeError: 'module' object is not callable

Receiving error while using the library as below
from uniswap import uniswap
account_1="..."
private_key="..."
uniswap_wrapper = uniswap(account_1, private_key, version=2) # pass version=2 to use Uniswap

the error is

" uniswap_wrapper = uniswap(account_1, private_key, version=2) # pass version=2 to use Uniswap
TypeError: 'module' object is not callable"

pls advise the solution

Can not install uniswap-python.

After running pip install uniswap-python
it shows :

Building wheel for bitarray (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: 'c:\users\administrator\appdata\local\programs\python\python38\python.exe' -u -c 'import sys, setuptools, to
kenize; sys.argv[0] = '"'"'C:\\Users\\Administrator\\AppData\\Local\\Temp\\3\\pip-install-y212_y8j\\bitarray\\setup.py'"
'"'; __file__='"'"'C:\\Users\\Administrator\\AppData\\Local\\Temp\\3\\pip-install-y212_y8j\\bitarray\\setup.py'"'"';f=ge
tattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compi
le(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Administrator\AppData\Local\Temp\3\pip-wheel-wfsoxatw'
       cwd: C:\Users\Administrator\AppData\Local\Temp\3\pip-install-y212_y8j\bitarray\
  Complete output (19 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.8
  creating build\lib.win-amd64-3.8\bitarray
  copying bitarray\test_bitarray.py -> build\lib.win-amd64-3.8\bitarray
  copying bitarray\test_util.py -> build\lib.win-amd64-3.8\bitarray
  copying bitarray\util.py -> build\lib.win-amd64-3.8\bitarray
  copying bitarray\__init__.py -> build\lib.win-amd64-3.8\bitarray
  running build_ext
  building 'bitarray._bitarray' extension
  creating build\temp.win-amd64-3.8
  creating build\temp.win-amd64-3.8\Release
  creating build\temp.win-amd64-3.8\Release\bitarray
  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ic:\u
sers\administrator\appdata\local\programs\python\python38\include -Ic:\users\administrator\appdata\local\programs\python
\python38\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Microsoft
 Visual Studio 14.0\VC\ATLMFC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" /Tcbitarray/
_bitarray.c /Fobuild\temp.win-amd64-3.8\Release\bitarray/_bitarray.obj
  _bitarray.c
  c:\users\administrator\appdata\local\programs\python\python38\include\pyconfig.h(206): fatal error C1083: 无法打开包括
文件: “basetsd.h”: No such file or directory
  error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit st
atus 2
  ----------------------------------------
  ERROR: Failed building wheel for bitarray
  Running setup.py clean for bitarray
Failed to build bitarray
DEPRECATION: Could not build wheels for bitarray which do not use PEP 517. pip will fall back to legacy 'setup.py instal
l' for these. pip 21.0 will remove support for this functionality. A possible replacement is to fix the wheel build issu
e reported above. You can find discussion regarding this at https://github.com/pypa/pip/issues/8368.

I tried install bitarray whl in https://www.lfd.uci.edu/~gohlke/pythonlibs/#bitarray, Still not success.

Add support for instatiating Uniswap class without supplying address and private key

It's quite common to want to use the class to merely get price info and similar, for which an address and private key isn't needed.

We should probably add the ability for users to instantiate the class without them. My current workaround is to simply use 0x0000000000000000000000000000000000000000 as the address and 0x0000000000000000000000000000000000000000000000000000000000000000 as the priv key.

getAmountsOut() Function missing

I'm getting the following error when using make_trade() function:

Could not identify the intended function with name getAmountsOut, positional argument(s) of type (<class 'float'>, <class 'list'>) and keyword argument(s) of type {}.
Found 1 function(s) with the name getAmountsOut: ['getAmountsOut(uint256,address[])']
Function invocation failed due to no matching argument types.

Any ideas?

Slippage in _eth_to_token_swap_output(...)?

Hi!

Code is

def _eth_to_token_swap_output(
        self, output_token: AddressLike, qty: int, recipient: Optional[AddressLike]
    ) -> HexBytes:
        """Convert ETH to tokens given an output amount."""
        if self.version == 1:
            token_funcs = self.exchange_contract(output_token).functions
            eth_qty = self.get_eth_token_output_price(output_token, qty)
            tx_params = self._get_tx_params(eth_qty)
            func_params: List[Any] = [qty, self._deadline()]
            if not recipient:
                function = token_funcs.ethToTokenSwapOutput(*func_params)
            else:
                func_params.append(recipient)
                function = token_funcs.ethToTokenTransferOutput(*func_params)
            return self._build_and_send_tx(function, tx_params)
        else:
            if recipient is None:
                recipient = self.address

            eth_qty = self.get_eth_token_output_price(output_token, qty) #<----------------------------

            return self._build_and_send_tx(
                self.router.functions.swapETHForExactTokens(
                    qty,
                    [self.get_weth_address(), output_token],
                    recipient,
                    self._deadline(),
                ),
                self._get_tx_params(eth_qty),
            )

It seems for me that highlighted string should be smth like that:

eth_qty = int(
        (1 + self.max_slippage)*
        self.get_eth_token_output_price(output_token, qty))

Am I right? As written I have no idea how slippage can be taken into account. Thanks in advance!

price history

how to get the price history? would be a great feature to have

How to setup provider with IPC

I am running a local geth node. The following works:

from web3 import Web3
w3 = Web3(Web3.IPCProvider("//root/.ethereum/geth.ipc"))
w3.eth.blockNumber

However, this does not work:

from uniswap import Uniswap
import os
os.environ["PROVIDER"] = "//root/.ethereum/geth.ipc" // Here I am setting the provider environment variable
address = "0x0000000000000000000000000000000000000000"    
private_key = None
uniswap_wrapper = Uniswap(address, private_key, version=2)

I have tried various variations of formatting the provider string, but I keep on getting errors, such as:

MissingSchema: Invalid URL '//root/.ethereum/geth.ipc': No schema supplied.
Or
InvalidSchema: No connection adapters were found for 'ipc://root/.ethereum/geth.ipc'

Any advice on how to get this to work?

Wrong prices for some tokens

Hi.

Code is
swapInput=int(volume*10**18)
swapOutput = uniswap_wrapper.get_token_token_input_price(_addr_to_str(token0), _addr_to_str(token1), swapInput)

token0 is ETH
token1 is 0xdf7a06fa60bea43d77c5210c0afb5f244b729e57
Code returns price 0.000000000000542003 but real price is 542003 tokens per ETH

Same here
token0 is ETH
token1 is 0x2260fac5e5542a773aa44fbcfedf7c193bc2c599
Code returns price 0.000000000003088910 but real price is 0.0308901 tokens per ETH

I have no idea what's wrong with it because code works totally fine for other tokens.
Any suggestions?

install uniswap-python error

My python env:
python 3.7.0

when I "pip install uniswap-python",the error is below:
Could not find a version that satisfies the requirement ipfshttpclient==0.7.0a1

I think whether the python's version is not true?
I see the pkg: ipfshttpclient==0.7.0a1 is a pre-release version.

please help me, thank you!!!

Private key required for Uniswap() class

If I want to use some methods of the Uniswap() class, it seems I need to initialize a personal wallet address and private key. Shoul this be optional, that way it is only required for action-based methods?

API not returning proper prices

API that are used to get token prices are not returning accurate prices. The prices are determined by considering the ether balance and token balance (eth_balance / token_balance) of token exchange contract.
For example :
Dai/Sai Uniswapcontract: 0x09cabEC1eAd1c0Ba254B09efb3EE13841712bE14 has 90 eth and 17520 DAI. The price is returned by calculating 90/17520 which is incorrect. Can you please look into this or correct me if i am wrong. Thanks.

Decipher output values

having a very hard time understanding the values here. Documentation makes no clear guidance on what to do with this giant number in output.

address = "0x0000000000000000000000000000000000000000"
private_key =  None
infura_url = 'https://mainnet.infura.io/v3/[PROJECT SECRET]'
uniswap_wrapper = Uniswap(address, private_key,infura_url,version=2)
dai = "0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359"
bat = "0x0D8775F648430679A709E98d2b0Cb6250d2887EF"

# Get the public price for ETH to Token trades with an exact output
print(uniswap_wrapper.get_eth_token_output_price(bat, 1*10**18))
print(uniswap_wrapper.get_eth_token_output_price(dai, 5*10**18))

Output

230523704775368

26449488570500131

Way to get the total liquidity of token or tokenpair

Hello, I was wondering whether there is a possibility to see the total liquidity of a token in a uniswap pool.

At the moment i'm running selenium to get the liquidity of a token, but that's of course much slower than being able to get it via an API.

big price difference: API vs web

For some tokens with ample liquidity and volume, I am seeing big differences between price returned by get_token_token_input_price and the uniswap web application. Specifically, price impact implied by API returns is significantly larger.

For example, ESD -> USDC trade. for 10 ESD, API returned 9.08 USDC while web returned 9.89 USDC; for 100 ESD, API returned 47.86 USDC while web returned 98.9. i.e. price impact implied by API returns was ~50%, while that of web returns was almost none.

Can anyone shine some light on this question?

Add support for swapExactTokensForTokensSupportingFeeOnTransferTokens

There is newer function for tokens that have Fee on Transfer that is causing issues on some transfers, could you please take a look to have a sanctity check [tokenin or tokenout] have this function in the abi to use the correct transfer method to prevent failed TX's

https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokenssupportingfeeontransfertokens
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;

Thanks for keeping this project alive and well!

OverflowError: Python int too large to convert to C ssize_t

weth = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
dai = "0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359"
test = uniswap_wrapper.get_token_token_input_price( weth , dai, 1*10**18)

returns bug
OverflowError: Python int too large to convert to C ssize_t

Web3 Exception: Could not decode contract function call getAmountsOut return data b'' for output_types ['uint256[]']

Getting a Web3 error with the getAmountsOut error when I call the make_trade function, something with how the function is being called:

Traceback (most recent call last):
File "C:\Users\vikra\PycharmProjects\uniswap\venv\lib\site-packages\uniswap\uniswap.py", line 69, in approved
return method(self, *args)
File "C:\Users\vikra\PycharmProjects\uniswap\venv\lib\site-packages\uniswap\uniswap.py", line 426, in make_trade
return self._eth_to_token_swap_input(output_token, Wei(qty), recipient)
File "C:\Users\vikra\PycharmProjects\uniswap\venv\lib\site-packages\uniswap\uniswap.py", line 485, in _eth_to_token_swap_input
* self.get_eth_token_input_price(output_token, qty)
File "C:\Users\vikra\PycharmProjects\uniswap\venv\lib\site-packages\uniswap\uniswap.py", line 82, in check_version
return f(self, *args, **kwargs)
File "C:\Users\vikra\PycharmProjects\uniswap\venv\lib\site-packages\uniswap\uniswap.py", line 294, in get_eth_token_input_price
qty, [self.get_weth_address(), token]
File "C:\Users\vikra\PycharmProjects\uniswap\venv\lib\site-packages\web3\contract.py", line 964, in call
**self.kwargs
File "C:\Users\vikra\PycharmProjects\uniswap\venv\lib\site-packages\web3\contract.py", line 1529, in call_contract_function
raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not decode contract function call getAmountsOut return data b'' for output_types ['uint256[]']

I'm sure the trade amount is being casted as an int -- was previously getting an error that another user had indicated where the getAmountsOut() function was missing, but this error is different.

Reproducable with the following code. Any idea what I'm doing wrong? I noticed that sometimes it works, sometimes it doesn't which makes it even more confusing. Thanks!

def makeTrade(contractaddress,ethamount):
    my_address = Web3.toChecksumAddress('')
    pk = ''
    uniconnect = uni.Uniswap(my_address, pk, web3=w3, version=2)
    eth = Web3.toChecksumAddress("0x0000000000000000000000000000000000000000")
    token = Web3.toChecksumAddress(contractaddress)
    tradeamount = int(ethamount*10**18)
    uniconnect.make_trade(eth, token, tradeamount)

makeTrade(contractaddress,tradesize)

how to set gas price and gas limit for a trade ?

hi, using uniswap-python lib, Could I set the gas price and gas limit for the trade ?
seem I do not find this from readme document, please help

also have same question with slip page setting.
Do we support this in near future ?

make_trade(...) contract does not exist

Web3 is complaining the contract address doesn't exist for uniswap v2 make_trade. Is there something missing?

Code:

uniswap_wrapper = Uniswap(address="my_public_eth_address", private_key="my_private_eth_address", version=2)
print(uniswap_wrapper.make_trade(eth, bat, ONE_ETH))

Error:

    print(uniswap_wrapper.make_trade(eth, bat, ONE_ETH))
  File "/Users/ben/Library/Python/3.7/lib/python/site-packages/uniswap/uniswap.py", line 62, in approved
    is_approved = self._is_approved(token)
  File "/Users/ben/Library/Python/3.7/lib/python/site-packages/uniswap/uniswap.py", line 714, in _is_approved
    .functions.allowance(self.address, contract_addr)
  File "/Users/ben/Library/Python/3.7/lib/python/site-packages/web3/contract.py", line 964, in call
    **self.kwargs
  File "/Users/ben/Library/Python/3.7/lib/python/site-packages/web3/contract.py", line 1529, in call_contract_function
    raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not transact with/call contract function, is contract deployed correctly and chain synced?

cannot get price for uni

I added
uni='0x1f9840a85d5af5bf1d1762f925bdaddc4201f984'
contract number taken from https://www.coingecko.com/en/coins/uniswap
and use uniswap_wrapper.get_eth_token_input_price(uni, 1*10**18) function
have a long error explanation with

web3.exceptions.InvalidAddress: ('Address has an invalid EIP-55 checksum. After looking up the address from the original source, try again.', '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984')

in the end

non-python files are missing from install packages

I have run pip install uniswap tried to import/initialize an instance of UniswapWrapper. I am getting the following error:

File "/home/raphael/.virtualenvs/raiden_installer/lib/python3.7/site-packages/uniswap/uniswap.py", line 35, in __init__
    with open(os.path.abspath(path + "contract_addresses.JSON")) as f:
FileNotFoundError: [Errno 2] No such file or directory: '/home/raphael/code/brainbot/raiden/installer/uniswap/assets/contract_addresses.JSON'

This is most likely due to the setup.py not including non-python code. This can be fixed by adding the assets folder in the package_data attribute or by a proper Manifest.in file.

I can prepare a PR to solve this.

[help needed] get_token_eth_output_price spitting huge values

I'm working on a very lightweight discord bot, and just need a simple command to check the price of a token on uniswap.
I've come up with
prq_val = uniswap_wrapper.get_token_eth_output_price("0x362bc847A3a9637d3af6624EeC853618a43ed7D2", 1*10**18)
as seen in your documentation, and getting a return of "1059715878516377184220" and other numbers in similar ranges. I imagine the error is blindingly obvious, and I gather it's to do with the parameters, but I'll be going around in circles for hours if I didn't just ask. Appreciate it!

Can't get all tokens

Code is:

from dotenv import load_dotenv
import os

from pathlib import Path
from pprint import pprint

from uniswap import Uniswap


env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)

ADDRESS = os.getenv("ADDRESS")
PRIVATE_KEY = os.getenv("PRIVATE_KEY")

uniswap_wrapper = Uniswap(ADDRESS, PRIVATE_KEY, version=1)

eth = "0x0000000000000000000000000000000000000000"
bat = "0x0D8775F648430679A709E98d2b0Cb6250d2887EF"
dai = "0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359"

pprint(uniswap_wrapper.get_all_tokens())

Error:
uniswap.uniswap.InvalidToken: Invalid token address: 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2

Checking amount of token in liquidity pool (Uniswap v2)

It is unclear how to use something like get_token_balance() with respect to the Uniswap v2 factory contract. I am trying to view the amount of a token in the Uniswap v2 liquidity pool, and it seems all I can check is the ERC20 token balance globally.

Edit: I see now I can use get_ex_token_balance(), but I am receiving the Uniswap v1 pool amounts. When I switch to version 2 the Factory methods seem broken. I see it may be a work in progress with Erik, and am interested about the new Web3 market data read functions. Thanks!

Code requires address and private key

Hi
Executing the following command results in TypeError: init() missing 2 required positional arguments: 'address' and 'private_key'

from uniswap import Uniswap
uniswap_wrapper = Uniswap()
eth = "0x0000000000000000000000000000000000000000"
bat = "0x0D8775F648430679A709E98d2b0Cb6250d2887EF"
dai = "0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359"

uniswap_wrapper.get_eth_balance(bat)

Could not find the clarification on how to set the address/private key in ReadMe file... Would appreciate help on the issue.
Thanks!

I can't run it if I change any other ecr20 token address

Thank you for providing such a good program, but I run a little problem, please help solve it. I changed another ecr20 token address, and i can't run my program.

from uniswap import Uniswap
from web3 import Web3
provide = 'https://mainnet.infura.io/v3/02c03b06ce7344d1bbde374834b349de'
address = '0xfd895ACd6960054B25Fe8CDdaA0dc271EF18716f'
private_key = '***'
uniswap_wrapper = Uniswap(address, private_key, provide, version=2)
eth = "0x0000000000000000000000000000000000000000"
pickle = Web3.toChecksumAddress("0xbd17b1ce622d73bd438b9e658aca5996dc394b0d")
print(uniswap_wrapper.get_eth_token_input_price(pickle, 1*10**18))

The error code isTraceback (most recent call last):
  File "D:\python\python38\lib\site-packages\web3-5.12.0-py3.8.egg\web3\contract.py", line 1509, in call_contract_function
    output_data = web3.codec.decode_abi(output_types, return_data)
  File "D:\python\python38\lib\site-packages\eth_abi\codec.py", line 181, in decode_abi
    return decoder(stream)
  File "D:\python\python38\lib\site-packages\eth_abi\decoding.py", line 127, in __call__
    return self.decode(stream)
  File "D:\python\python38\lib\site-packages\eth_utils\functional.py", line 45, in inner
    return callback(fn(*args, **kwargs))
  File "D:\python\python38\lib\site-packages\eth_abi\decoding.py", line 173, in decode
    yield decoder(stream)
  File "D:\python\python38\lib\site-packages\eth_abi\decoding.py", line 127, in __call__
    return self.decode(stream)
  File "D:\python\python38\lib\site-packages\eth_abi\decoding.py", line 142, in decode
    start_pos = decode_uint_256(stream)
  File "D:\python\python38\lib\site-packages\eth_abi\decoding.py", line 127, in __call__
    return self.decode(stream)
  File "D:\python\python38\lib\site-packages\eth_abi\decoding.py", line 198, in decode
    raw_data = self.read_data_from_stream(stream)
  File "D:\python\python38\lib\site-packages\eth_abi\decoding.py", line 305, in read_data_from_stream
    raise InsufficientDataBytes(
eth_abi.exceptions.InsufficientDataBytes: Tried to read 32 bytes.  Only got 0 bytes

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:/workspace/python/selen/test_uniswap.py", line 13, in <module>
    print(uniswap_wrapper.get_eth_token_input_price(Web3.toChecksumAddress(pickle), 1*10**18))
  File "D:\python\python38\lib\site-packages\uniswap_python-0.4.2-py3.8.egg\uniswap\uniswap.py", line 82, in check_version
    return f(self, *args, **kwargs)
  File "D:\python\python38\lib\site-packages\uniswap_python-0.4.2-py3.8.egg\uniswap\uniswap.py", line 293, in get_eth_token_input_price
    price = self.router.functions.getAmountsOut(
  File "D:\python\python38\lib\site-packages\web3-5.12.0-py3.8.egg\web3\contract.py", line 954, in call
    return call_contract_function(
  File "D:\python\python38\lib\site-packages\web3-5.12.0-py3.8.egg\web3\contract.py", line 1532, in call_contract_function
    raise BadFunctionCallOutput(msg) from e
web3.exceptions.BadFunctionCallOutput: Could not decode contract function call getAmountsOut return data b'' for output_types ['uint256[]']

_token_to_eth_swap_input checks price instead of balance

I have discovered a bug that _token_to_eth_swap_input checks price instead of balance and throws an error.

    tx = self.make_trade(address_in, address_out, amount_in)
  File "../../../libs/crypto_api\crypto_api\uniswap.py", line 66, in approved
    return method(self, *args)
  File "../../../libs/crypto_api\crypto_api\uniswap.py", line 200, in make_trade
    return self._token_to_eth_swap_input(input_token, qty, recipient)
  File "C:\ProgramData\Anaconda3\lib\site-packages\uniswap\uniswap.py", line 505, in _token_to_eth_swap_input
    raise InsufficientBalance(input_balance, cost)
uniswap.uniswap.InsufficientBalance: Insufficient balance. Had 115549539029086413, needed 137927441360803636

This is how it can be fixed:

    def _token_to_eth_swap_input(
        self, input_token: AddressLike,
        qty: int, recipient: Optional[AddressLike]
    ) -> HexBytes:
        """Convert tokens to ETH given an input amount."""
        # Balance check
        input_balance = self.get_token_balance(input_token)
        if qty > input_balance:
            raise InsufficientBalance(input_balance, qty)

        if self.version == 1:
            token_funcs = self.exchange_contract(input_token).functions
            func_params: List[Any] = [qty, 1, self._deadline()]
            if not recipient:
                function = token_funcs.tokenToEthSwapInput(*func_params)
            else:
                func_params.append(recipient)
                function = token_funcs.tokenToEthTransferInput(*func_params)
            return self._build_and_send_tx(function)
        else:
            if recipient is None:
                recipient = self.address
            return self._build_and_send_tx(
                self.router.functions.swapExactTokensForETH(
                    qty,
                    int((1 - self.max_slippage) * qty),
                    [input_token, self.get_weth_address()],
                    recipient,
                    self._deadline(),
                ),
            )

make trade questions

Hello
I am quite new to w3 and uniswap-python

I have managed to follow some of the examples retrieving price of some tokens, using checksum versions of the contract names, etc.

However I have certain questions regarding make_trade. How to specify the quantity and why such format.

What if I want to specify an exact ammount of ETH and tokens with certain slippage and gas adjusting at aspecific price. Just imagine if the price moves heavily just when you are trying to get in. Are also more examples about it available?

Thank you.

KeyError: 'PROVIDER'

I just installed Uniswap module and couldn't run simple example
I used

from uniswap import Uniswap
address = "0x0000000000000000000000000000000000000000"
private_key = ""
uniswap_wrapper = Uniswap(address, private_key, version=2)
Traceback (most recent call last):
File "", line 1, in
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/uniswap/uniswap.py", line 147, in init
self.provider = provider or os.environ["PROVIDER"]
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 678, in getitem
raise KeyError(key) from None
KeyError: 'PROVIDER'

make_trade raises ValidationError

...
>>>uniswap_wrapper.make_trade(eth, aave, 8e16)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/root/miniconda3/envs/paddington/lib/python3.7/site-packages/uniswap/uniswap.py", line 72, in approved
    return method(self, *args, **kwargs)
  File "/root/miniconda3/envs/paddington/lib/python3.7/site-packages/uniswap/uniswap.py", line 446, in make_trade
    return self._eth_to_token_swap_input(output_token, Wei(qty), recipient)
  File "/root/miniconda3/envs/paddington/lib/python3.7/site-packages/uniswap/uniswap.py", line 505, in _eth_to_token_swap_input
    * self.get_eth_token_input_price(output_token, qty)
  File "/root/miniconda3/envs/paddington/lib/python3.7/site-packages/uniswap/uniswap.py", line 85, in check_version
    return f(self, *args, **kwargs)
  File "/root/miniconda3/envs/paddington/lib/python3.7/site-packages/uniswap/uniswap.py", line 299, in get_eth_token_input_price
    qty, [self.get_weth_address(), token]
  File "/root/miniconda3/envs/paddington/lib/python3.7/site-packages/web3/contract.py", line 875, in __call__
    clone._set_function_info()
  File "/root/miniconda3/envs/paddington/lib/python3.7/site-packages/web3/contract.py", line 885, in _set_function_info
    self.kwargs
  File "/root/miniconda3/envs/paddington/lib/python3.7/site-packages/web3/_utils/contracts.py", line 163, in find_matching_fn_abi
    raise ValidationError(message)
web3.exceptions.ValidationError: 
Could not identify the intended function with name `getAmountsOut`, positional argument(s) of type `(<class 'float'>, <class 'list'>)` and keyword argument(s) of type `{}`.
Found 1 function(s) with the name `getAmountsOut`: ['getAmountsOut(uint256,address[])']
Function invocation failed due to no matching argument types.

Quickswap support

hello
quickswap is a uniswap fork running on matic network.
would be cool if we could use this wrapper for quickswap on almost gasfree L2.

pls respond :)

v2 vs v1 api

Hi how to differentiate the functions between v2 vs v1 api? so for example if I wanted to make a trade with v2 instead of v1, how do I do it? thanks!

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.