uniswap 自动交易程序

admin7个月前科学家165
import json
import time
import web3
from uniswap import Uniswap
from uniswap.uniswap import ETH_ADDRESS

#  PROVIDER 可以自己在infura.io上注册一个
PROVIDER = 'https://mainnet.infura.io/v3/......'
EIP20_ABI = json.loads(
    '[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_owner","type":"address"},{"indexed":true,"name":"_spender","type":"address"},{"indexed":false,"name":"_value","type":"uint256"}],"name":"Approval","type":"event"}]')  # noqa: 501

# 设置以太地址和私钥
address = "0x............................."
private_key = None

uniswap_wrapper = Uniswap(address, private_key, provider=PROVIDER, version=2)  

eth = ETH_ADDRESS
dai = "0x6b175474e89094c44da98b954eedeac495271d0f"
usdt = "0xdac17f958d2ee523a2206206994597c13d831ec7"


def swap(from_coin, to_coin, from_amount):
    """
    使用 uniswap 进行交易
    :param from_coin:
    :param to_coin:
    :param from_amount: 数量
    :return:
    """
    if from_coin != eth:
        from_coin = uniswap_wrapper.w3.toChecksumAddress(from_coin)
        # 取各币种的 DECIMALS
        from_contract = uniswap_wrapper.w3.eth.contract(from_coin, abi=EIP20_ABI)
        from_decimals = from_contract.functions.decimals().call()
        from_name = from_contract.functions.symbol().call()
    else:
        from_decimals = 18
        from_name = 'ETH'

    if to_coin != eth:
        to_coin = uniswap_wrapper.w3.toChecksumAddress(to_coin)
        to_contract = uniswap_wrapper.w3.eth.contract(to_coin, abi=EIP20_ABI)
        to_decimals = to_contract.functions.decimals().call()
        to_name = to_contract.functions.symbol().call()
    else:
        to_decimals = 18
        to_name = 'ETH'

    per_amount = 1 * 10 ** from_decimals
    try:
        if (from_coin == eth) and (to_coin != eth):
            price = uniswap_wrapper.get_eth_token_input_price(to_coin, per_amount)
        elif (from_coin != eth) and (to_coin == eth):
            price = uniswap_wrapper.get_token_eth_input_price(from_coin, per_amount)
        else:
            price = uniswap_wrapper.get_token_token_input_price(from_coin, to_coin, per_amount)
    except web3.exceptions.ContractLogicError:
        return 1

    price = price / (10 ** to_decimals)
    print(f"当前价格: {price} {to_name}/{from_name}")

    # 设置 gas 价格
    gas = input(f'请设置交易的 gas 价格:')
    try:
        gas = int(gas)
    except ValueError:
        print("输入错误,退出!")
        return -1

    def value_based_gas_price_strategy(web3, transaction_params=None):
        return web3.toWei(gas, 'gwei')

    uniswap_wrapper.w3.eth.setGasPriceStrategy(value_based_gas_price_strategy)

    gprice = uniswap_wrapper.w3.eth.generateGasPrice()
    gprice = uniswap_wrapper.w3.fromWei(gprice, 'gwei')
    print(f"gas 价格设置为: {gprice}")

    answer = input(f'{from_name} => {to_name}, 是否交易? y/n: ')
    if answer not in ('Y', 'y'):
        print('退出交易!')
        return -1

    # 交易
    if private_key is not None:
        amount = int(from_amount * 10 ** from_decimals)
        uniswap_wrapper.make_trade(from_coin, to_coin, amount)
        print('交易已发送!')
        return 0
    else:
        print('没有私钥,不能提交交易!')
        return -1


if __name__ == '__main__':
    # 将 eth 换成 dai
    ret = swap(eth, dai, 0.1)


安装

pip install uniswap-python


相关文章

如何实现简单的ETH 链上程序监控

准备你最好会一点python ,如果一点程序也不懂,可以试着学习一些简单的python你需要有一台 mac 或linux 电脑,会打开终端(Terminal)注册一个infura.io 的账号,拿到a...

比特币的 UTXO 模型

比特币的 UTXO 模型

比特币的区块链由一个个区块串联构成,而每个区块又包含一个或多个交易。如果我们观察任何一个交易,它总是由若干个输入(Input)和若干个输出(Output)构成,一个Input指向的是前面区块的某个Ou...

各种一键安装脚本

LINUX一键安装脚本包集合,废除宝塔一键安装Flask环境 需要提前准备一个已绑定IP的域名wget -N --no-check-certificate https:/...

What is the bitcoin network fee?

Transaction fees are included with your bitcoin transaction in order to have your transaction proces...

MobaXterm license

https://inused.github.io/pages/file/tool/MobaXtermKeygen.htmlThen copy Custom.mxtpro to C:\Program F...

如何在离线电脑上WIN 7系统上安装扫描二维码

如何在离线电脑上WIN 7系统上安装扫描二维码

首先是开源工具https://github.com/1357310795/QrCodeScanner/releaseswin 7 使用V1.4.1版本 QRCODE 扫描器MyQrCodeScanne...