Example #1
0
def get_price(web3, bpool_address, tokenin_address, tokenout_address):
    """Get price at a balancer pool located at address bpool_address.
    Price is given as the number of tokenin required to buy a single tokenout."""
    if is_pool_empty(web3, bpool_address):
        return 0

    if not is_token_in_exchange(
            Token.from_address(tokenin_address).symbol, bpool_address):
        return 0

    if not is_token_in_exchange(
            Token.from_address(tokenout_address).symbol, bpool_address):
        return 0

    bpool = web3.eth.contract(address=bpool_address, abi=bpool_abi)
    tokenin_decimals = Token().from_address(tokenin_address).decimals
    tokenout_decimals = Token().from_address(tokenout_address).decimals

    # Get spot price - it represents the ratio of one asset to another in terms of wei
    # on both sides. It's the number of wei you'll receive of one asset per wei of the
    # other asset. It is represented as an 18-decimal number so we divide that out.
    # mathematically: spot_price = num_wei_output_token / one_wei_input_token
    spot_price = (
        10**-18 *
        bpool.functions.getSpotPrice(tokenin_address, tokenout_address).call())
    # since spot price is in terms of wei, we multiply out the two tokens decimals
    # to get price in 'normal' units
    spot_price_converted = spot_price * (10**(tokenout_decimals -
                                              tokenin_decimals))
    # print(f"{spot_price_converted} units of {tokenin_address} buys 1 unit of {tokenout_address}")

    return spot_price_converted
Example #2
0
    def test_tokens(self):
        from token_class import Token

        self.assertEqual(
            Token.from_symbol("0xBTC").address,
            "0xB6eD7644C69416d67B522e20bC294A9a9B405B31")
        self.assertEqual(
            Token.from_symbol("0xbtc").address,
            "0xB6eD7644C69416d67B522e20bC294A9a9B405B31")
        self.assertEqual(Token.from_symbol("UNI").decimals, 18)
        self.assertEqual(Token.from_symbol("USDT").decimals, 6)
        self.assertEqual(
            Token.from_address(
                "0xba100000625a3754423978a60c9317c58a424e3D").symbol, "BAL")
        self.assertEqual(
            Token.from_address(
                "0xB6eD7644C69416d67B522e20bC294A9a9B405B31").symbol, "0xBTC")
        self.assertEqual(
            Token.from_address(
                "0xb6ed7644c69416d67b522e20bc294a9a9b405b31").symbol, "0xBTC")