示例#1
0
async def uniswap_buy_input(input_token, output_token, input_quantity,
                            max_slippage, max_gas, account, ethereum_provider):
    # set web3 with gas price
    global gas_in_gwei
    gas_in_gwei = max_gas
    w3 = Web3(Web3.HTTPProvider(ethereum_provider))
    w3.eth.setGasPriceStrategy(gas_price_strategy)

    # set uniswap with w3 and slippage
    uniswap_wrapper = Uniswap(account['address'],
                              account['pkey'],
                              web3=w3,
                              version=2,
                              max_slippage=max_slippage)

    # trade exact input_quantity of input_token for output_token
    if input_token == ETH_ADDRESS:
        req = uniswap_wrapper._eth_to_token_swap_input(
            Web3.toChecksumAddress(output_token), input_quantity, None)
    else:
        req = uniswap_wrapper.make_trade(Web3.toChecksumAddress(input_token),
                                         Web3.toChecksumAddress(output_token),
                                         input_quantity)
    tx = w3.eth.waitForTransactionReceipt(req)

    # reformat output
    tx_dict = to_dict(tx)
    return tx_dict
示例#2
0
def client(request, web3: Web3, ganache: GanacheInstance):
    uniswap = Uniswap(ganache.eth_address,
                      ganache.eth_privkey,
                      web3=web3,
                      version=request.param)
    uniswap._buy_test_assets()
    return uniswap
def test_assets(client: Uniswap):
    """
    Buy some DAI and USDC to test with.
    """
    tokens = client._get_token_addresses()

    for token_name, amount in [("DAI", 100 * 10 ** 18), ("USDC", 100 * 10 ** 6)]:
        token_addr = tokens[token_name]
        price = client.get_eth_token_output_price(token_addr, amount)
        logger.info(f"Cost of {amount} {token_name}: {price}")
        logger.info("Buying...")

        tx = client.make_trade_output(tokens["ETH"], token_addr, amount)
        client.w3.eth.waitForTransactionReceipt(tx)
示例#4
0
    def __init__(self, currency_symbol):
        super().__init__()
        try:
            # self._exchange_addresses = getExchangeAddressesForToken(currency_symbol)
            self._decimals = Token().from_symbol(currency_symbol).decimals
        except IndexError:
            raise RuntimeError(
                "Unknown currency_symbol {}, need to add address to token_class.py"
                .format(currency_symbol))

        self.currency_symbol = currency_symbol
        self.exchange_name = "Uniswap v3"
        self.command_names = ["uniswap"]
        self.short_url = "https://bit.ly/35nae4n"  # main uniswap pre-selected to 0xbtc
        self.volume_eth = 0
        self.show_yield = True

        self.hourly_volume_tokens = [
        ]  # list of volume for each of the last N hours
        self._time_volume_last_updated = 0

        self._w3 = Web3(Web3.HTTPProvider(ETHEREUM_NODE_URL))
        self._uniswap_api = Uniswap(address=None,
                                    private_key=None,
                                    version=3,
                                    web3=self._w3)
 def test_remove_liquidity(
     self, client: Uniswap, web3: Web3, token, max_token, expectation
 ):
     with expectation:
         r = client.remove_liquidity(token, max_token)
         tx = web3.eth.waitForTransactionReceipt(r)
         assert tx.status  # type: ignore
 def test_get_ex_token_balance(
     self, client: Uniswap, token,
 ):
     if not client.version == 1:
         pytest.skip("Tested method only supported on Uniswap v1")
     r = client.get_ex_token_balance(token)
     assert r
示例#7
0
 def get_exchange_rate(
     self,
     client: Uniswap,
     token,
 ):
     r = client.get_exchange_rate(token)
     assert r
示例#8
0
def buy(front_runner_data: FrontRunnerData, trade_amount: int,
        uniswap_wrapper: Uniswap, w3: Web3):
    print("buying ", trade_amount, " of ",
          front_runner_data.input_decoded[1]['path'][1])
    tx = uniswap_wrapper.make_trade(
        DefaultConfig.eth, front_runner_data.input_decoded[1]['path'][1],
        trade_amount)
    print("https://etherscan.io/tx/" + json.loads(w3.toJSON(tx)))
示例#9
0
    def test_make_trade(
        self,
        client: Uniswap,
        web3: Web3,
        input_token,
        output_token,
        qty: int,
        recipient,
        expectation,
    ):
        with expectation():
            bal_in_before = client.get_token_balance(input_token)

            r = client.make_trade(input_token, output_token, qty, recipient)
            tx = web3.eth.waitForTransactionReceipt(r)
            assert tx.status  # type: ignore

            # TODO: Checks for ETH, taking gas into account
            bal_in_after = client.get_token_balance(input_token)
            if input_token != self.eth:
                assert bal_in_before - qty == bal_in_after
示例#10
0
def get_slippage_percentage(front_runner_data: FrontRunnerData, w3: Web3,
                            uniswap_wrapper: Uniswap):
    value_villain_tx = int(w3.toJSON(front_runner_data.tx['value']))
    coin_villain = front_runner_data.input_decoded[1]['path'][1]
    front_runner_data.public_amount_min = uniswap_wrapper.get_eth_token_input_price(
        coin_villain, value_villain_tx)
    front_runner_data.amount_min = front_runner_data.input_decoded[1][
        'amountOutMin']
    front_runner_data.trade_amount = front_runner_data.public_amount_min - front_runner_data.amount_min

    print_debug_info(front_runner_data, w3)

    return (front_runner_data.public_amount_min -
            front_runner_data.amount_min) / front_runner_data.amount_min * 100
示例#11
0
def sell(front_runner_data: FrontRunnerData, trade_amount: int,
         uniswap_wrapper: Uniswap, w3: Web3):
    coin = Web3.toChecksumAddress(
        front_runner_data.input_decoded[1]['path'][1])
    for i in range(1000):
        try:
            trade_amount = get_balance_by_token(coin)
            print("selling ", trade_amount, " of ", coin)
            tx = uniswap_wrapper.make_trade(coin, DefaultConfig.eth,
                                            int(trade_amount))
            print("https://etherscan.io/tx/" + str(json.loads(w3.toJSON(tx))))
        except Exception as e:
            print(e)
            time.sleep(1)
        else:
            sys.exit()
            break
示例#12
0
block_number = 0


def get_price(cfg):
    return cfg['SAI'] / cfg['0']


def bootstrapped_data(f, cfg, rows):
    f.write("Uniswap in 0 gets {:.0f};\n".format(cfg['0']))
    f.write("Uniswap in SAI gets {:.0f};\n".format(cfg['SAI']))
    f.write("GetPrice SAI 0;\n")
    for row in rows:
        f.write(row)


uniswap = Uniswap()
line_num = 0

for line in fin.readlines():
    line_num += 1
    if 'block' in line:
        words = line.split()
        block_number = int(words[-1])
    if block_number > int(sys.argv[3]):
        break

    uniswap.process(line)

    if block_number < int(sys.argv[2]):
        config = deepcopy(uniswap.config())  #arghhhhh!
    elif block_number <= int(sys.argv[3]):
示例#13
0
infura_key = secrets["INFURA_KEY"]
wallet_name = secrets["WALLET_NAME"]
wallet_address = secrets["WALLET_ADDRESS"]
private_key = secrets["PRIVATE_KEY"]

print(f"Using {wallet_name}, with a public address of {wallet_address}")

##############################---WEB3---#######################################
infura_url = f"https://mainnet.infura.io/v3/{infura_key}"
web3 = Web3(Web3.HTTPProvider(infura_url))
assert web3.isConnected(), "Not connected to ETH node in INFURA"

#############################---UNISWAP---#####################################
uniswap_v1 = Uniswap(
    address=wallet_address,
    private_key=private_key,
    web3=web3,
    version=1,
)

uniswap_v2 = Uniswap(
    address=wallet_address,
    private_key=private_key,
    web3=web3,
    version=2,
)

#############################---TOKENS---######################################
tokens = utils.getJSONinfo("Tokens.json")
blacklist = ["ETH", "WETH", "BZRX", "BAL"]  # Note that ETH and WETH are == ETH

# These tokens give different problems.
示例#14
0
 def test_get_fee_taker(self, client: Uniswap):
     r = client.get_fee_taker()
     assert r == 0.003
示例#15
0
    miner.print_block_state()

    for _ in range(10):
        miner.block_update()
    miner.print_block_state()
    """test rewarding system"""
    balances_Gwei = []
    balances_GAS = []

    miner.print_balance_state()
    balances_Gwei.append(miner.balance_Gwei)
    balances_GAS.append(miner.balance_GAS)

    # case 1: pool
    from uniswap import Uniswap
    us = Uniswap('-1', 100000, 20000000, 1000000)  # 1:200
    print(miner.reward(pool=us))

    miner.print_balance_state()
    balances_Gwei.append(miner.balance_Gwei)
    balances_GAS.append(miner.balance_GAS)

    # case 2: oracle
    miner.reward_mode = "oracle"
    print(miner.reward(oracle_ratio=400.))

    miner.print_balance_state()
    balances_Gwei.append(miner.balance_Gwei)
    balances_GAS.append(miner.balance_GAS)
    """Plot"""
    rounds = [0, 1, 2]
示例#16
0
from web3 import Web3, middleware
from web3.gas_strategies.time_based import construct_time_based_gas_price_strategy


def value_based_gas_price_strategy(web3, transaction_params=None):
    # todo base on villain gas and value of transfer
    return Web3.toWei(150, 'gwei')


w3 = Web3(Web3.IPCProvider(DefaultConfig.ipc_provider))

w3.eth.setGasPriceStrategy(value_based_gas_price_strategy)

uniswap_wrapper = Uniswap(DefaultConfig.address,
                          DefaultConfig.private_key,
                          version=2,
                          web3=w3,
                          max_slippage=10.0)

uni_contract = w3.eth.contract(address=DefaultConfig.uniswap_router_address,
                               abi=json.loads(DefaultConfig.abi))

coin = Web3.toChecksumAddress("0xb1fda21901afbded910af72588c8dfd6020aced1")

trade_amount = 200 * 10**9


def buy():
    for i in range(10000):
        try:
            print("buying ", trade_amount, " of ", coin)
示例#17
0
from uniswap import Uniswap
address = "0x0000000000000000000000000000000000000001"
private_key = None
PROVIDER = "https://mainnet.infura.io/v3/PRIVATE-KEY"

uniswap_wrapper = Uniswap(address, private_key, provider=PROVIDER, version=2)
eth_c = "0x0000000000000000000000000000000000000000"
bat = "0x0D8775F648430679A709E98d2b0Cb6250d2887EF"
dai = "0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359"
usdt = "0xdAC17F958D2ee523a2206206994597C13D831ec7"
uni = "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984"

dai_rate = uniswap_wrapper.get_eth_token_input_price(dai, 5 * 10**18)
bat_rate = uniswap_wrapper.get_eth_token_input_price(bat, 1 * 10**18)

print(dai_rate)
print(bat_rate)

conversion = ((1 / bat_rate) * (dai_rate / 10**6)) * (10**18)
print(conversion)
print('${:,.2f}'.format(conversion))
示例#18
0
文件: gol.py 项目: cybercongress/port
import requests

from uniswap import Uniswap
from config import PROVIDER

address = "0x0000000000000000000000000000000000000000"
private_key = None
uniswap_wrapper = Uniswap(
    address, private_key, version=2,
    provider=PROVIDER)  # pass version=2 to use Uniswap v2
eth = "0x0000000000000000000000000000000000000000"
gol = "0xF4ecdBa8ba4144Ff3a2d8792Cad9051431Aa4F64"

ETH_GGOL_PRICE = uniswap_wrapper.get_eth_token_output_price(gol,
                                                            1) / (1 * 10**18)
GGOL_SUPPLY = 14_406_844_988_437 / 10**9


def get_data():
    return requests.get(
        'https://api.coingecko.com/api/v3/coins/ethereum').json()


def get_gol_market_data():
    resp = get_data()
    current_price = get_current_price(resp)['current_price']
    market_cap = get_market_cap(current_price)['market_cap']
    return {
        "market_data": {
            "current_price": current_price,
            "market_cap": market_cap,
示例#19
0
import os
os.environ['PROVIDER'] = 'https://goerli.prylabs.net/'
#os.environ['PROVIDER'] = 'https://main-rpc.linkpool.io'
import time

from uniswap import Uniswap
address = "0xFe594E862c3ce76E192997EABFC41Afd7C975b52"
private_key = "3a8bb854c7a86d950c0d3e0b5b1bbcd3912389a95fa530e46c911fe1de099808"  # or None, if you're not going to make transactions

uniswap_wrapper = Uniswap(address, private_key,
                          version=2)  # pass version=2 to use Uniswap v2

eth = "0x0000000000000000000000000000000000000000"
weth = uniswap_wrapper.w3.toChecksumAddress(
    "0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6")
kwh = uniswap_wrapper.w3.toChecksumAddress(
    "0x78B57C213a18DF1DAbC647149902ea1966E0119C")

amount = 1 * 10**18


# Recursive function to get the price to the  plus minus 2 percent range within price
def bump_price(target_price_cents):

    eth_bal = uniswap_wrapper.get_eth_balance()
    kwh_bal = uniswap_wrapper.get_token_balance(kwh)

    # current price ETH per one unit of KWH
    current_price = uniswap_wrapper.get_token_token_input_price(
        kwh, weth, amount) / 10**18
    current_price_cents = current_price * 400 * 100
示例#20
0
            return self._buy_ETH(pool)


if __name__ == "__main__":
    from uniswap import Uniswap

    import random
    import matplotlib.pyplot as plt

    random.seed(12345)

    # Arbitrager
    arbitrager = Arbitrager(1000000000, 200.)
    balances = []
    """init"""
    us = Uniswap('-1', 100000, 20000000, 1000000)  # 1:200
    us.print_pool_state(bool_LT=True)
    """Providing Liquidity"""
    us.join('0', 2000, 400001)
    us.print_pool_state(bool_LT=True)
    """Txs"""
    for _ in range(1000):
        if random.random() < 0.5:
            us.ETH_to_ERC20(1000)
        else:
            us.ERC20_to_ETH_exact(1000)

        # print(us.ETH, '\t', us.ERC20, '\t', float(us.ERC20 / us.ETH), '\t', arbitrager.balance_ERC20)
        arbitrager.arbitrage(us)
        # print(us.ETH, '\t', us.ERC20, '\t', float(us.ERC20 / us.ETH), '\t', arbitrager.balance_ERC20)
        # print()
示例#21
0
        figure = plt.gcf()  # get current figure
        figure.set_size_inches(8, 6)
        plt.savefig(get_PATH(args.path) + 'ETHNERC20_Curve.png',
                    format='png',
                    dpi=300)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--seed', type=int, default=950327)
    parser.add_argument('--path')  # location of log files
    parser.add_argument('--no-save', action='store_true')
    args = parser.parse_args()
    print(args)

    random.seed(args.seed)
    """init"""
    us = Uniswap(
        address='-1',
        amount_ETH=1000000,
        amount_ERC20=200000000,  # ETH:ERC20 = 1:200
        init_LT=1000000,
        fee=0.003)
    arbitrager = Arbitrager(1000000000, 200.)  # [ERC20]
    """Simulation)
    # ETH <-> ERC20 & Arbitraging Timing
    # k & Arbitraging Timing
    # Arbitrager's Gain
    """
    Arbitraging_Curve(args, us, arbitrager, display=args.no_save)
示例#22
0
            return self._buy_Gwei(pool)


if __name__ == "__main__":
    from uniswap import Uniswap

    import random
    import matplotlib.pyplot as plt

    random.seed(12345)

    # Arbitrager
    arbitrager = Arbitrager(1000000000, 200.)
    balances = []
    """init"""
    us = Uniswap('-1', 100000, 20000000, 1000000)  # 1:200
    us.print_pool_state(bool_LT=True)
    """Providing Liquidity"""
    us.join('0', 2000, 400001)
    us.print_pool_state(bool_LT=True)
    """Txs"""
    for _ in range(1000):
        if random.random() < 0.5:
            us.Gwei_to_GAS(1000)
        else:
            us.GAS_to_Gwei_exact(1000)

        # print(us.Gwei, '\t', us.GAS, '\t', float(us.GAS / us.Gwei), '\t', arbitrager.balance_GAS)
        arbitrager.arbitrage(us)
        # print(us.Gwei, '\t', us.GAS, '\t', float(us.GAS / us.Gwei), '\t', arbitrager.balance_GAS)
        # print()
    else:
        figure = plt.gcf()  # get current figure
        figure.set_size_inches(8, 6)
        plt.savefig(get_PATH(args.path) + 'GweiNGAS_Curve.png', format='png', dpi=300)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--seed', type=int, default=950327)
    parser.add_argument('--path')  # location of log files
    parser.add_argument('--no-save', action='store_true')
    args = parser.parse_args()
    print(args)

    random.seed(args.seed)

    """init"""
    us = Uniswap(address='-1',
                 amount_Gwei=1000000,
                 amount_GAS=200000000,  # Gwei:GAS = 1:200
                 init_LT=1000000,
                 fee=0.003)
    arbitrager = Arbitrager(1000000000, 200.)  # [GAS]

    """Simulation)
    # Gwei <-> GAS & Arbitraging Timing
    # k & Arbitraging Timing
    # Arbitrager's Gain
    """
    Arbitraging_Curve(args, us, arbitrager, display=args.no_save)
 def test_get_fee_taker(self, client: Uniswap):
     if client.version not in [1, 2]:
         pytest.skip("Tested method not supported in this Uniswap version")
     r = client.get_fee_taker()
     assert r == 0.003
def client(request, web3: Web3, ganache: GanacheInstance):
    return Uniswap(
        ganache.eth_address, ganache.eth_privkey, web3=web3, version=request.param
    )

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--seed', type=int, default=950327)
    parser.add_argument('--path')  # location of log files
    parser.add_argument('--no-save', action='store_true')
    args = parser.parse_args()
    print(args)

    random.seed(args.seed)

    """init"""
    us = Uniswap(address='-1',
                 amount_ETH=1000000,
                 amount_ERC20=200000000,  # ETH:ERC20 = 1:200
                 init_LT=1000000,
                 fee=0.003)

    print(">>> init pool.")
    us.print_pool_state(bool_LT=True)

    """Simulation 1-1) Swap & k"""
    Swap_k_Curve(args, us, display=args.no_save)

    """Simulation 1-2) ETH -> ERC20 Swap Curve"""
    ETH2ERC20_Swap_Curve(args, us, display=args.no_save)

    """Simulation 1-3) ERC20 -> ETH Swap Curve"""
    ERC202ETH_Swap_Curve(args, us, display=args.no_save)
示例#27
0
 def test_add_liquidity(self, client: Uniswap, web3: Web3, token, max_eth):
     r = client.add_liquidity(token, max_eth)
     tx = web3.eth.waitForTransactionReceipt(r, timeout=6000)
     assert tx.status  # type: ignore
示例#28
0
import os
from web3 import Web3
from uniswap import Uniswap
from decimal import Decimal

w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/'))

address = "0x0000000000000000000000000000000000000000"
private_key = None
uniswap_wrapper = Uniswap(
    address,
    private_key,
    version=2,
    provider='https://mainnet.infura.io/v3/0948dcdb150c41efb91e1e9e35aee742'
)  # pass version=2 to use Uniswap v2
bond_address = '0x64C29aAc69d3122f6e5531CecA1B753F95350AF4'
bond_abi = '[{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0Out","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1Out","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint112","name":"reserve0","type":"uint112"},{"indexed":false,"internalType":"uint112","name":"reserve1","type":"uint112"}],"name":"Sync","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"constant":true,"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"MINIMUM_LIQUIDITY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"PERMIT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"getReserves","outputs":[{"internalType":"uint112","name":"_reserve0","type":"uint112"},{"internalType":"uint112","name":"_reserve1","type":"uint112"},{"internalType":"uint32","name":"_blockTimestampLast","type":"uint32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"}],"name":"initialize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"kLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"liquidity","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"price0CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"price1CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"skim","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"amount0Out","type":"uint256"},{"internalType":"uint256","name":"amount1Out","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swap","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"sync","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"token0","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"token1","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]'

sum = Web3.toChecksumAddress(bond_address)
bond_contract = w3.eth.contract(address=bond_address, abi=bond_abi)
reserve = bond_contract.functions.getReserves().call()
print(reserve)
print(w3.fromWei(reserve[1], 'ether'))
print(uniswap_wrapper.get_fee_maker(), uniswap_wrapper.get_fee_taker())
print(Decimal(reserve[0] * 10**-8) / w3.fromWei(reserve[1], 'ether'))


def buying_amount(qty, token, abi):

    token_contract = w3.eth.contract(address=token, abi=abi)
    reserve = token_contract.functions.getReserves().call()
    parser = argparse.ArgumentParser()
    parser.add_argument('--seed', type=int, default=950327)
    parser.add_argument('--path')  # location of log files
    parser.add_argument('--no-save', action='store_true')
    args = parser.parse_args()
    print(args)

    random.seed(args.seed)

    current_block_number = 0
    current_block_gas_limit = 12000000

    """init"""
    us = Uniswap(address='-1',
                 amount_Gwei=1000000,
                 amount_GAS=200000000,  # Gwei:GAS = 1:200
                 init_LT=1000000,
                 fee=0.003)

    miner = Miner(current_block_number,
                  current_block_gas_limit)

    print(">>> init pool.")
    us.print_pool_state(bool_LT=True)

    """Simulation)
    # Test rewarding system
    # Simulate one at a time.
    """

    # """Simulation 1-1) pool"""