Giter Club home page Giter Club logo

1inch_wrapper's Introduction

1inch.py

1inch.py

1inch.py is a wrapper around the 1inch API and price Oracle. It has full coverage of the swap API endpoint and All chains support by 1inch are included in the OneInchSwap and OneInchOracle methods. Package also includes a helper method to ease the submission of transactions to the network. Limited chains currently supported.

API Documentation

The full 1inch swap API docs can be found at https://docs.1inch.io/

Installation

Use the package manager pip to install 1inch.py.

pip install 1inch.py

Usage

A quick note on decimals. The wrapper is designed for ease of use, and as such accepts amounts in "Ether" or whole units. If you prefer, you can use decimal=0 and specify amounts in wei. This will also help with any potential floating point errors.

from oneinch_py import OneInchSwap, TransactionHelper, OneInchOracle

rpc_url = "yourRPCURL.com"
binance_rpc = "adifferentRPCurl.com"
public_key = "yourWalletAddress"
private_key = "yourPrivateKey" #remember to protect your private key. Using environmental variables is recommended. 
api_key = "" # 1 Inch API key

exchange = OneInchSwap(api_key, public_key)
bsc_exchange = OneInchSwap(api_key, public_key, chain='binance')
helper = TransactionHelper(api_key, rpc_url, public_key, private_key)
bsc_helper = TransactionHelper(api_key, binance_rpc, public_key, private_key, chain='binance')
oracle = OneInchOracle(rpc_url, chain='ethereum')


# See chains currently supported by the helper method:
helper.chains
# {"ethereum": "1", "binance": "56", "polygon": "137", "avalanche": "43114"}

# To get gas prices
helper.get_gas_prices()

# Straight to business:
# Get a swap and do the swap
result = exchange.get_swap("USDT", "ETH", 10, 0.5) # get the swap transaction
result = helper.build_tx(result) # prepare the transaction for signing, gas price defaults to fast.
result = helper.sign_tx(result) # sign the transaction using your private key
result = helper.broadcast_tx(result) #broadcast the transaction to the network and wait for the receipt. 

## If you already have token addresses you can pass those in instead of token names to all OneInchSwap functions that require a token argument
result = exchange.get_swap("0x7fc66500c84a76ad7e9c93437bfc5ac33e2ddae9", "0x43dfc4159d86f3a37a5a4b3d4580b888ad7d4ddd", 10, 0.5) 


#USDT to ETH price on the Oracle. Note that you need to indicate the token decimal if it is anything other than 18.
oracle.get_rate_to_ETH("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", src_token_decimal=6)

# Get the rate between any two tokens.
oracle.get_rate(src_token="0x6B175474E89094C44Da98b954EedeAC495271d0F", dst_token="0x111111111117dC0aa78b770fA6A738034120C302")

exchange.health_check()
# 'OK'

# Address of the 1inch router that must be trusted to spend funds for the swap
exchange.get_spender()

# Generate data for calling the contract in order to allow the 1inch router to spend funds. Token symbol or address is required. If optional "amount" variable is not supplied (in ether), unlimited allowance is granted.
exchange.get_approve("USDT")
exchange.get_approve("0xdAC17F958D2ee523a2206206994597C13D831ec7", amount=100)

# Get the number of tokens (in Wei) that the router is allowed to spend. Option "send address" variable. If not supplied uses address supplied when Initialization the exchange object. 
exchange.get_allowance("USDT")
exchange.get_allowance("0xdAC17F958D2ee523a2206206994597C13D831ec7", send_address="0x12345")

# Token List is stored in memory
exchange.tokens
# {
#  '1INCH': {'address': '0x111111111117dc0aa78b770fa6a738034120c302',
#            'decimals': 18,
#            'logoURI': 'https://tokens.1inch.exchange/0x111111111117dc0aa78b770fa6a738034120c302.png',
#            'name': '1INCH Token',
#            'symbol': '1INCH'},
#   'ETH': {'address': '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
#          'decimals': 18,
#          'logoURI': 'https://tokens.1inch.exchange/0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee.png',
#          'name': 'Ethereum',
#          'symbol': 'ETH'},
#   ......
# }

# Returns the exchange rate of two tokens. 
# Tokens can be provided as symbols or addresses
# "amount" is supplied in ether
# NOTE: When using custom tokens, the token decimal is assumed to be 18. If your custom token has a different decimal - please manually pass it to the function (decimal=x)
# Also returns the "price" of more expensive token in the cheaper tokens. Optional variables can be supplied as **kwargs
exchange.get_quote(from_token_symbol='ETH', to_token_symbol='USDT', amount=1)
# (
#     {
#         "fromToken": {
#             "symbol": "ETH",
#             "name": "Ethereum",
#             "decimals": 18,
#             "address": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
#             "logoURI": "https://tokens.1inch.io/0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee.png",
#             "tags": ["native"],
#         },
#         "toToken": {
#             "symbol": "USDT",
#             "name": "Tether USD",
#             "address": "0xdac17f958d2ee523a2206206994597c13d831ec7",
#             "decimals": 6,
#             "logoURI": "https://tokens.1inch.io/0xdac17f958d2ee523a2206206994597c13d831ec7.png",
#             "tags": ["tokens"],
#         ...
#     Decimal("1076.503093"),
# )

# Creates the swap data for two tokens.
# Tokens can be provided as symbols or addresses
# Optional variables can be supplied as **kwargs
# NOTE: When using custom tokens, the token decimal is assumed to be 18. If your custom token has a different decimal - please manually pass it to the function (decimal=x)

exchange.get_swap(from_token_symbol='ETH', to_token_symbol='USDT', amount=1, slippage=0.5)
# {
#     "fromToken": {
#         "symbol": "ETH",
#         "name": "Ethereum",
#         "decimals": 18,
#         "address": "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
#         "logoURI": "https://tokens.1inch.io/0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee.png",
#         "tags": ["native"],
#     },
#     "toToken": {
#         "symbol": "USDT",
#         "name": "Tether USD",
#         "address": "0xdac17f958d2ee523a2206206994597c13d831ec7",
#         "decimals": 6,
#         "logoURI": "https://tokens.1inch.io/0xdac17f958d2ee523a2206206994597c13d831ec7.png",
#         "tags": ["tokens"],
#
#     ...
#
#     ],
#     "tx": {
#         "from": "0x1d05aD0366ad6dc0a284C5fbda46cd555Fb4da27",
#         "to": "0x1111111254fb6c44bac0bed2854e76f90643097d",
#         "data": "0xe449022e00000000000000000000000000000000000000000000000006f05b59d3b20000000000000000000000000000000000000000000000000000000000001fed825a0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000140000000000000000000000011b815efb8f581194ae79006d24e0d814b7697f6cfee7c08",
#         "value": "500000000000000000",
#         "gas": 178993,
#         "gasPrice": "14183370651",
#     },
# }

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Thanks to @Makbeta for all of their work in migrating the wrapper to the new 1inch api system.

License

MIT

1inch_wrapper's People

Contributors

makbeta avatar richardatct 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

Watchers

 avatar  avatar  avatar

1inch_wrapper's Issues

get_approve - not signing.

Was trying to approve busd spending with 1inch. i made an extra function -> get_approve_with_contract I dont like looking things up with token names because there can be duplicates. Also removed the amount because amount is optional in 1inch api.

A missing amount = infinite.

    result = bsc_exchange.get_approve_with_contract(from_address=src,  decimal=decimal)  # get the swap transaction , AMOUNT + SLIPPAGE ARE FLOATS NOT STRING
{'data': '..............................ff',
 'gasPrice': '15000000000',
 'to': '0xe9e7cea3dedca5984780bafc599bd69add087d56',
 'value': '0'}

I tried to sign the tx - even removed the build_tx piece to just sign and broadcast.

result = helper.build_tx(result)  # prepare the transaction for signing, gas price defaults to fast.
    pprint(result)
    result = helper.sign_tx(result)  # sign the transaction using your private key
    pprint(result)
    result = helper.broadcast_tx(result)  # broadcast the transaction to the network and wait for the receipt.
    pprint(result)


    def get_approve(self, from_token_symbol: str, amount=None):
        from_address = self._token_to_address(from_token_symbol)
        amount_in_wei = Decimal(amount * 10 ** self.tokens[from_token_symbol]['decimals'])
        url = f'{self.base_url}/{self.version}/{self.chain_id}/approve/transaction'
        url = url + f"?tokenAddress={from_address}&amount={amount_in_wei}"
        result = self._get(url)
        return result

    def get_approve_with_contract(self, from_address: str, decimal: int, amount=None):
        url = f'{self.base_url}/{self.version}/{self.chain_id}/approve/transaction'
        if amount == None:
            url = url + f"?tokenAddress={from_address}"
        if amount != None:
            amount_in_wei = Decimal(amount * 10 ** decimal)
            url = url + f"?tokenAddress={from_address}&amount={amount_in_wei}"
        result = self._get(url)
        return result


GAS

Is it possible to introduce the gas limit and price of gwei you wanna pay fot the tx?

Mistake in getting tokens by symbol for swaps

It seems they changed keys for tokens: {'0x5aea5775959fbc2557cc8789bc1bf90a239d9a91': {'symbol': 'WETH', 'name': 'Wrapped Ether', 'address': '0x5aea5775959fbc2557cc8789bc1bf90a239d9a91', 'decimals': 18,

When writing "USDT' to get swap it returns KEY_Error. While if writing USDT CONTRACT works perfectly.

Try: chain polugon
From^ MATIC
TO: USDT

1inch Fusion version

Richard,

Nice 1inch wrapper for Python!

Noticed you updated it yesterday.
Please could you make a short version for the new @1inch Fusion mode = zero gas fees etc..
https://1inch.io/fusion

https://github.com/1inch/fusion-sdk
how-to-swap-with-fusion-mode

const makerPrivateKey = '0x123....'
const makerAddress = '0x123....'

const nodeUrl = '....'

const blockchainProvider = new PrivateKeyProviderConnector(
    makerPrivateKey,
    new Web3(nodeUrl)
)

const sdk = new FusionSDK({
    url: 'https://fusion.1inch.io',
    network: 1,
    blockchainProvider
})

sdk.placeOrder({
    fromTokenAddress: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // WETH
    toTokenAddress: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // USDC
    amount: '50000000000000000', // 0.05 ETH
    walletAddress: makerAddress
}).then(console.log)

Thanks

get_swap method errors out

The code generates the following error, fails due to API changes

Traceback (most recent call last):
  File "test.py", line 30, in <module>
    result = exchange.get_quote("ETH", "USDT", 1000000000000000) 
  File "/home/beta/projects/1inch_wrapper/oneinch_py/main.py", line 160, in get_quote
    from_base = Decimal(result['fromTokenAmount']) / Decimal(10 ** result['fromToken']['decimals'])
KeyError: 'fromTokenAmount'

Solution is forthcoming.

zksync oracle

ADd zk sync oracle.
main.py Line 287
"zksync": "0xC762d56614D3411eC6fABD56cb075D904b801613"

get_quote broken

quote endpoint is now providing significantly less information. Method needs to be rewritten

Dependency - requests

1inch.py is looking for the METADATA file in requests Lib\site-packages\requests-2.28.1.dist-info

requests-2.25.1.dist-info has the METADATA file but 2.28 does not.

Workaround
pip install 1inch.py --ignore-installed requests

Token symbols no longer work generate "Token not in 1inch Token List" error post upgrade

After the recent upgrade, I noticed that when I call a method with tokens like this exchange.get_swap("ETH", "USDT", 0.0000001, 0.5)
I get an error token not in a list, although they should be.

raise UnknownToken("Token not in 1inch Token List")
oneinch_py.main.UnknownToken: Token not in 1inch Token List

I was able to identify the problem, looks like the token fetching endpoint was switched, the code handling the response wasn't updated to match the format API returns. I'll be submitting a solution shortly.

Not enough allowance

Hello,

I am having difficulty doing a basic swap and I'm not sure I understand why

Here's the error message I'm getting:

{"statusCode":400,"error":"Bad Request","description":"Not enough allowance. Amount: 1000000. Allowance: 0. Spender: 0x1111111254eeb25477b68fb85ed929f73a960582","meta":[{"type":"amount","value":"1000000"},{"type":"allowance","value":"0"}],"requestId":"2ba5f7dd-9064-4824-abda-cbece14595ae"}

Thing is I am running the get_approve & get_allowance before the get_swap function, but the allowance amount stays at 0 for some reason. According to the 1inch docs, if no amount is supplied in approve, infinite allowance is assumed. I am using a metamask waller with infura node.

exchange = OneInchSwap(public_key)
helper = TransactionHelper(rpc_url, public_key, private_key)
oracle = OneInchOracle(rpc_url, chain='ethereum')

exchange.get_approve("USDT")
exchange.get_allowance("USDT")

exchange.get_swap(from_token_symbol='USDT', to_token_symbol='ETH', amount=1, slippage=0.5)

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.