Ejemplo n.º 1
0
def test_spot_price(network, config, web3, T1, T2, alice_wallet):
    """Test calculation of prices on spot."""
    (price, price_sans_fee) = _spotPrices(network, config, web3, T1, T2,
                                          alice_wallet, 1, 1, 1, 1)
    assert price_sans_fee == to_wei(1)
    assert price == to_wei("1.000001000001000001")

    (price, price_sans_fee) = _spotPrices(network, config, web3, T1, T2,
                                          alice_wallet, 90, 10, 9, 1)
    assert price_sans_fee == to_wei(1)
    assert price == to_wei("1.000001000001000001")

    (price, price_sans_fee) = _spotPrices(network, config, web3, T1, T2,
                                          alice_wallet, 1, 2, 1, 1)
    assert price_sans_fee == to_wei("0.5")
    assert price == to_wei("0.500000500000500001")

    (price, price_sans_fee) = _spotPrices(network, config, web3, T1, T2,
                                          alice_wallet, 2, 1, 1, 1)
    assert price_sans_fee == to_wei(2)
    assert price == to_wei("2.000002000002000002")

    (price, price_sans_fee) = _spotPrices(network, config, web3, T1, T2,
                                          alice_wallet, 9, 10, 9, 1)
    assert price_sans_fee == to_wei("0.1")
    assert price == to_wei("0.100000100000100000")
Ejemplo n.º 2
0
def test_ERC20(
    network, web3, alice_wallet, alice_address, bob_wallet, bob_address, OCEAN_address
):
    """Tests an OCEAN token approval, allowance and transfers."""
    token = BToken(web3, OCEAN_address)

    token.approve(bob_address, 0, from_wallet=alice_wallet)
    # generating ERC20 Tokens, so the symbol is irrelevant
    assert token.symbol() == "DTT"
    assert token.decimals() == 18
    assert token.balanceOf(alice_address) > to_wei(10)
    assert token.balanceOf(bob_address) > to_wei(10)

    assert token.allowance(alice_address, bob_address) == 0
    token.approve(bob_address, to_wei(1), from_wallet=alice_wallet)
    assert token.allowance(alice_address, bob_address) == to_wei(1)

    # alice sends all her OCEAN to Bob, then Bob sends it back
    alice_OCEAN = token.balanceOf(alice_address)
    bob_OCEAN = token.balanceOf(bob_address)
    token.transfer(bob_address, alice_OCEAN, from_wallet=alice_wallet)
    assert token.balanceOf(alice_address) == 0
    assert token.balanceOf(bob_address) == (alice_OCEAN + bob_OCEAN)

    token.transfer(alice_address, alice_OCEAN, from_wallet=bob_wallet)
    assert token.balanceOf(alice_address) == alice_OCEAN
    assert token.balanceOf(bob_address) == bob_OCEAN
def test_ocean_balancer_helpers(OCEAN_address, alice_ocean, alice_wallet,
                                alice_address, bob_ocean):
    DT = alice_ocean.create_data_token("DataToken1",
                                       "DT1",
                                       alice_wallet,
                                       blob="foo")
    DT.mint(alice_address, to_wei(1000), alice_wallet)

    with pytest.raises(Exception):  # not enough liquidity
        pool = alice_ocean.pool.create(DT.address,
                                       data_token_amount=0,
                                       OCEAN_amount=0,
                                       from_wallet=alice_wallet)

    pool = alice_ocean.pool.create(
        DT.address,
        data_token_amount=to_wei(90),
        OCEAN_amount=to_wei(10),
        from_wallet=alice_wallet,
    )
    pool_address = pool.address

    assert alice_ocean.pool.ocean_address == OCEAN_address
    assert alice_ocean.pool.get_token_address(pool.address) == DT.address

    assert alice_ocean.pool.get(alice_ocean.web3,
                                pool_address).address == pool_address
    assert bob_ocean.pool.get(alice_ocean.web3,
                              pool_address).address == pool_address

    DT_price = bob_ocean.pool.get_token_price(pool_address)
    assert DT_price > 0
Ejemplo n.º 4
0
def sell_data(
    ocean,
    private_key,
    data_token,
    amount,
    fixed_price=True,
):
    """Sell a dataset on the Ocean market.
    Mint the datatokens.
    In the create() step below, ganache OCEAN is needed.
    Finally, Approve the datatoken for sale.
    Args:
        ocean ():
        wallet ():
        data_token ():
        amount ():
        fixed_price (bool): Whether or not to sell the data at a fixed price.
    Returns:
        (bool): Returns True if successful.
    """
    wallet = Wallet(ocean.web3, private_key, ocean.config.block_confirmations)
    data_token.mint(wallet.address, to_wei(amount), wallet)
    OCEAN_token = BToken(ocean.web3, ocean.OCEAN_address)
    assert OCEAN_token.balanceOf(wallet.address) > 0, 'need OCEAN'
    data_token.approve(ocean.exchange._exchange_address, to_wei(amount),
                       wallet)
    return True
Ejemplo n.º 5
0
def buy_data(
    ocean,
    private_key,
    token_address,
    seller_wallet,
    min_amount,
    max_amount,
):
    """Buy a dataset on the market.
    Define wallet, verify that there is enough ganache ETH and OCEAN.
    Create an exchange_id for a new exchange.
    Args:
        ocean ():
        private_key (str):
        token_address (str):
        seller_wallet (Wallet):
        min_amount (float):
        max_amount (float):
    Returns:

    """
    wallet = Wallet(ocean.web3, private_key, ocean.config.block_confirmations)
    assert ocean.web3.eth.get_balance(wallet.address) > 0, 'need ganache ETH'
    OCEAN_token = BToken(ocean.web3, ocean.OCEAN_address)
    assert OCEAN_token.balanceOf(wallet.address) > 0, 'need ganache OCEAN'
    exchange_id = ocean.exchange.create(token_address, to_wei(min_amount),
                                        seller_wallet)
    tx_result = ocean.exchange.buy_at_fixed_rate(to_wei(min_amount), wallet,
                                                 to_wei(max_amount),
                                                 exchange_id, token_address,
                                                 seller_wallet.address)
    assert tx_result, 'failed buying data tokens at fixed rate.'
Ejemplo n.º 6
0
def test_transfer_event(alice_ocean, alice_wallet, alice_address, bob_wallet,
                        bob_address):
    """Tests that a transfer event is registered."""
    token = alice_ocean.create_data_token("DataToken1",
                                          "DT1",
                                          from_wallet=alice_wallet,
                                          blob="foo_blob")
    block_confirmations = alice_ocean.config.block_confirmations.value

    block = alice_ocean.web3.eth.block_number
    transfer_event = token.get_transfer_event(
        block - (block_confirmations + 1), alice_address, bob_address)
    # different way of retrieving
    transfer_events = token.get_event_logs("Transfer", None, block, block)
    assert transfer_events == ()

    token.mint(alice_address, to_wei(100), from_wallet=alice_wallet)
    token.approve(bob_address, to_wei(1), from_wallet=alice_wallet)
    token.transfer(bob_address, to_wei(5), from_wallet=alice_wallet)

    block = alice_ocean.web3.eth.block_number
    transfer_event = token.get_transfer_event(
        block - (block_confirmations + 1), alice_address, bob_address)
    assert transfer_event["args"]["from"] == alice_address
    assert transfer_event["args"]["to"] == bob_address

    # same transfer event, different way of retrieving
    transfer_event = token.get_event_logs("Transfer", None,
                                          block - (block_confirmations + 1),
                                          block)[0]
    assert transfer_event["args"]["from"] == alice_address
    assert transfer_event["args"]["to"] == bob_address
Ejemplo n.º 7
0
def make_info(name, private_key_name):
    # assume that this account has ETH with gas.
    class _Info:
        pass

    info = _Info()
    web3 = get_web3()
    config = ExampleConfig.get_config()

    info.web3 = web3

    info.private_key = os.environ.get(private_key_name)
    info.wallet = Wallet(
        web3,
        private_key=info.private_key,
        block_confirmations=config.block_confirmations,
        transaction_timeout=config.transaction_timeout,
    )
    info.address = info.wallet.address
    wallet = get_ganache_wallet()
    if wallet:
        assert get_ether_balance(
            web3, wallet.address) >= to_wei(4), "Ether balance less than 4."
        if get_ether_balance(web3, info.address) < to_wei(2):
            send_ether(wallet, info.address, to_wei(4))

    from ocean_lib.ocean.ocean import Ocean

    info.ocean = Ocean(config)
    info.T1 = _deployAndMintToken(web3, "TOK1", info.address)
    info.T2 = _deployAndMintToken(web3, "TOK2", info.address)

    return info
Ejemplo n.º 8
0
def test_calculateFee(alice_ocean, alice_wallet):
    """Tests the DataToken calculateFee method."""
    token = alice_ocean.create_data_token("DataToken1",
                                          "DT1",
                                          from_wallet=alice_wallet,
                                          blob="foo_blob")

    fee = token.calculateFee(to_wei(100), DataToken.OPF_FEE_PER_TOKEN)
    assert fee == to_wei("0.1")
Ejemplo n.º 9
0
def test_get_token_minter(web3, alice_wallet, dtfactory_address, alice_address):
    """Tests proper retrieval of token minter from DTFactory."""
    dtfactory = DTFactory(web3, dtfactory_address)

    dt_address = dtfactory.createToken(
        "foo_blob", "DT1", "DT1", to_wei(1000), from_wallet=alice_wallet
    )
    dt = DataToken(web3, dtfactory.get_token_address(dt_address))
    dt.mint(alice_address, to_wei(10), from_wallet=alice_wallet)
    assert dtfactory.get_token_minter(dt.address) == alice_address
Ejemplo n.º 10
0
def test_setSwapFee_fails(network, config, web3, alice_wallet, alice_address,
                          bob_wallet, bob_address):
    """Tests that someone who isn't a controller can not set the swap fee."""
    factory = BFactory(web3, get_bfactory_address(config.address_file,
                                                  network))
    pool_address = factory.newBPool(alice_wallet)
    pool = BPool(web3, pool_address)
    with pytest.raises(Exception):
        pool.setSwapFee(to_wei("0.011"),
                        from_wallet=bob_wallet)  # not ok, bob isn't controller
    pool.setController(bob_address, from_wallet=alice_wallet)
    pool.setSwapFee(to_wei("0.011"), from_wallet=bob_wallet)  # ok now
Ejemplo n.º 11
0
def test_calculate_token_holders(alice_ocean, alice_wallet, alice_address):
    """Test the calculate_token_holders methods."""
    token = alice_ocean.create_data_token("DataToken1",
                                          "DT1",
                                          from_wallet=alice_wallet,
                                          blob="foo_blob")
    token.mint(alice_address, to_wei(100), from_wallet=alice_wallet)
    block = alice_ocean.web3.eth.block_number
    block_confirmations = alice_ocean.config.block_confirmations.value
    token_holders = token.calculate_token_holders(
        block - (block_confirmations + 1), block, to_wei(1))
    assert len(token_holders) == 1
Ejemplo n.º 12
0
def test_calcSpotPrice(network, config, web3, T1, T2, alice_address,
                       alice_wallet):
    """Tests pricing with calcSpotPrice."""
    pool = _deployBPool(web3, config.address_file, network, alice_wallet)
    x = pool.calcSpotPrice(
        tokenBalanceIn=to_wei(10),
        tokenWeightIn=to_wei(1),
        tokenBalanceOut=to_wei(11),
        tokenWeightOut=to_wei(1),
        swapFee=0,
    )
    assert x == to_wei("0.909090909090909091")
Ejemplo n.º 13
0
def test_setMinter(alice_ocean, alice_wallet, alice_address, bob_wallet,
                   bob_address):
    """Tests that a minter can be assigned for a Datatoken."""
    ocean = alice_ocean
    token = ocean.create_data_token("DataToken1",
                                    "DT1",
                                    from_wallet=alice_wallet,
                                    blob="foo_blob")

    # alice is the minter
    token.mint(alice_address, to_wei(10), from_wallet=alice_wallet)
    token.mint(bob_address, to_wei(10), from_wallet=alice_wallet)
    with pytest.raises(Exception):
        token.mint(alice_address, to_wei(10), from_wallet=bob_wallet)

    # switch minter to bob
    token.proposeMinter(bob_address, from_wallet=alice_wallet)
    time.sleep(5)
    token.approveMinter(from_wallet=bob_wallet)
    token.mint(alice_address, to_wei(10), from_wallet=bob_wallet)
    with pytest.raises(Exception):
        token.mint(alice_address, to_wei(10), from_wallet=alice_wallet)
    with pytest.raises(Exception):
        token.mint(bob_address, to_wei(10), from_wallet=alice_wallet)

    # switch minter back to alice
    token.proposeMinter(alice_address, from_wallet=bob_wallet)
    time.sleep(5)
    token.approveMinter(from_wallet=alice_wallet)
    token.mint(alice_address, to_wei(10), from_wallet=alice_wallet)
    with pytest.raises(Exception):
        token.mint(alice_address, to_wei(10), from_wallet=bob_wallet)
Ejemplo n.º 14
0
def test_rebind_more_tokens(network, config, web3, T1, T2, alice_wallet):
    """Tests that we can rebind more tokens on a pool."""
    pool = _createPoolWith2Tokens(network, config, web3, T1, T2, alice_wallet,
                                  90, 10, 9, 1)

    # insufficient allowance
    with pytest.raises(Exception):
        pool.rebind(T1.address,
                    to_wei(120),
                    to_wei(9),
                    from_wallet=alice_wallet)

    # sufficient allowance
    T1.approve(pool.address, to_wei(30), from_wallet=alice_wallet)
    pool.rebind(T1.address, to_wei(120), to_wei(9), from_wallet=alice_wallet)
Ejemplo n.º 15
0
 def verify_supply(mint_amount=to_wei(50)):
     supply = dtc.contract.caller.totalSupply()
     if supply <= 0:
         _tx_id = dtc.mint(receiver_address, mint_amount, minter_wallet)
         dtc.get_tx_receipt(dtc.web3, _tx_id)
         supply = dtc.contract.caller.totalSupply()
     return supply
Ejemplo n.º 16
0
def test_status_functions(alice_ocean, alice_wallet, alice_address):
    """Tests various status functions of the DataToken class."""
    token = alice_ocean.create_data_token("DataToken1",
                                          "DT1",
                                          from_wallet=alice_wallet,
                                          blob="foo_blob")

    token.mint(alice_address, to_wei(100), from_wallet=alice_wallet)

    assert token.balanceOf(alice_address) == to_wei(100)
    assert token.totalSupply() == 100_000_000_000_000_000_000
    assert token.cap() == 1_000_000_000_000_000_000_000
    assert token.datatoken_name() == "DataToken1"
    assert token.minter() == alice_address
    assert token.isMinter(alice_address)
    with pytest.raises(ValueError):
        token.get_event_signature("not a registered event")
Ejemplo n.º 17
0
def test_chain_id_send_ether(alice_wallet, bob_address):
    """Tests if the chainId has the right value for send ether transactions."""
    receipt = send_ether(alice_wallet, bob_address, to_wei(1))
    assert receipt, "Send ether was unsuccessful."
    tx = alice_wallet.web3.eth.get_transaction(receipt["transactionHash"])
    # Formula: v = CHAIN_ID * 2 + 35 or v = CHAIN_ID * 2 + 36
    chain_ids = [(tx["v"] - 35) / 2, (tx["v"] - 36) / 2]
    result = True if alice_wallet.web3.eth.chain_id in chain_ids else False
    assert result, "The chain ID is not the right one."
Ejemplo n.º 18
0
def mint_fake_OCEAN(config: Config) -> None:
    """
    Does the following:
    1. Mints tokens
    2. Distributes tokens to TEST_PRIVATE_KEY1 and TEST_PRIVATE_KEY2
    """
    addresses_file = config.address_file

    with open(addresses_file) as f:
        network_addresses = json.load(f)

    web3 = get_web3(config.network_url)
    deployer_wallet = Wallet(
        web3,
        private_key=os.environ.get("FACTORY_DEPLOYER_PRIVATE_KEY"),
        block_confirmations=config.block_confirmations,
        transaction_timeout=config.transaction_timeout,
    )

    OCEAN_token = DataToken(web3, address=network_addresses["development"]["Ocean"])

    amt_distribute = to_wei(1000)

    OCEAN_token.mint(
        deployer_wallet.address, 2 * amt_distribute, from_wallet=deployer_wallet
    )

    for key_label in ["TEST_PRIVATE_KEY1", "TEST_PRIVATE_KEY2"]:
        key = os.environ.get(key_label)
        if not key:
            continue

        w = Wallet(
            web3,
            private_key=key,
            block_confirmations=config.block_confirmations,
            transaction_timeout=config.transaction_timeout,
        )

        if OCEAN_token.balanceOf(w.address) < amt_distribute:
            OCEAN_token.transfer(w.address, amt_distribute, from_wallet=deployer_wallet)

        if get_ether_balance(web3, w.address) < to_wei(2):
            send_ether(deployer_wallet, w.address, to_wei(4))
Ejemplo n.º 19
0
def test_unbind(network, config, web3, T1, T2, alice_wallet):
    """Tests that a pool can be unbound."""
    pool = _createPoolWith2Tokens(network, config, web3, T1, T2, alice_wallet,
                                  1, 1, 1, 1)

    pool.unbind(T1.address, from_wallet=alice_wallet)

    assert pool.getNumTokens() == 1
    assert pool.getCurrentTokens() == [T2.address]
    assert pool.getBalance(T2.address) == to_wei(1)
Ejemplo n.º 20
0
    def get_order_requirements(
        did: str,
        service_endpoint: str,
        consumer_address: str,
        service_id: Union[str, int],
        service_type: str,
        token_address: str,
        userdata: Optional[Dict] = None,
    ) -> Optional[OrderRequirements]:
        """

        :param did:
        :param service_endpoint:
        :param consumer_address: hex str the ethereum account address of the consumer
        :param service_id:
        :param service_type:
        :param token_address:
        :return: OrderRequirements instance -- named tuple (amount, data_token_address, receiver_address, nonce),

        """

        req = PreparedRequest()
        params = {
            "documentId": did,
            "serviceId": service_id,
            "serviceType": service_type,
            "dataToken": token_address,
            "consumerAddress": consumer_address,
        }

        if userdata:
            userdata = json.dumps(userdata)
            params["userdata"] = userdata

        req.prepare_url(service_endpoint, params)
        initialize_url = req.url

        logger.info(f"invoke the initialize endpoint with this url: {initialize_url}")
        response = DataServiceProvider._http_method("get", initialize_url)
        # The returned json should contain information about the required number of tokens
        # to consume `service_id`. If service is not available there will be an error or
        # the returned json is empty.
        if response.status_code != 200:
            return None
        order = dict(response.json())

        return OrderRequirements(
            to_wei(
                Decimal(order["numTokens"])
            ),  # comes as float, needs to be converted
            order["dataToken"],
            order["to"],
            int(order["nonce"]),
            order.get("computeAddress"),
        )
Ejemplo n.º 21
0
def test_data_token_creation(web3, alice_wallet, dtfactory_address):
    """Tests that a data token can be created using a DTFactory object."""
    dtfactory = DTFactory(web3, dtfactory_address)

    dt_address = dtfactory.createToken(
        "foo_blob", "DT1", "DT1", to_wei(1000), from_wallet=alice_wallet
    )
    dt = DataToken(web3, dtfactory.get_token_address(dt_address))
    assert isinstance(dt, DataToken)
    assert dt.blob() == "foo_blob"
    assert dtfactory.verify_data_token(dt.address)
Ejemplo n.º 22
0
def _createPoolWith2Tokens(
    network: str,
    config: Config,
    web3: Web3,
    T1: BToken,
    T2: BToken,
    wallet: Wallet,
    bal1: Union[Decimal, str, int],
    bal2: Union[Decimal, str, int],
    w1: Union[Decimal, str, int],
    w2: Union[Decimal, str, int],
):
    """Helper function to create a basic pool containing 2 tokens."""
    pool = _deployBPool(web3, config.address_file, network, wallet)

    T1.get_tx_receipt(
        web3, T1.approve(pool.address, to_wei(bal1), from_wallet=wallet))
    T2.get_tx_receipt(
        web3, T2.approve(pool.address, to_wei(bal2), from_wallet=wallet))

    if pool.isBound(T1.address):
        pool.unbind(T1.address, wallet)

    if pool.isBound(T2.address):
        pool.unbind(T2.address, wallet)

    pool.bind(T1.address, to_wei(bal1), to_wei(w1), from_wallet=wallet)
    pool.bind(T2.address, to_wei(bal2), to_wei(w2), from_wallet=wallet)

    return pool
Ejemplo n.º 23
0
def test_verify_order_tx(alice_address, bob_address, alice_ocean,
                         alice_wallet):
    """Tests verify_order_tx function."""
    token = alice_ocean.create_data_token("DataToken1",
                                          "DT1",
                                          from_wallet=alice_wallet,
                                          blob="foo_blob")

    token.mint(alice_address, to_wei(100), from_wallet=alice_wallet)
    token.approve(bob_address, to_wei(1), from_wallet=alice_wallet)
    transfer_tx_id = token.transfer(bob_address,
                                    to_wei(5),
                                    from_wallet=alice_wallet)

    with pytest.raises(TimeExhausted):
        with patch("ocean_lib.models.data_token.DataToken.get_tx_receipt"
                   ) as mock:
            # dummy tx id which is not found in the chain
            # catches TimeExhausted exception from web3
            mock.side_effect = TimeExhausted()
            token.verify_order_tx("0x0", "some_did", "some_index",
                                  "some_amount", alice_address)

    transfer_tx_id = token.transfer(bob_address,
                                    to_wei(5),
                                    from_wallet=alice_wallet)
    with pytest.raises(AssertionError):
        # tx id is from transfer, not order
        token.verify_order_tx(transfer_tx_id, "some_did", "some_index",
                              "some_amount", alice_address)

    sample_ddo_path = get_resource_path("ddo", "ddo_sa_sample.json")
    asset = V3Asset(json_filename=sample_ddo_path)
    order_tx_id = token.startOrder(alice_address, to_wei(1), 1, ZERO_ADDRESS,
                                   alice_wallet)

    with pytest.raises(AssertionError):
        # the wrong asset did, this is a sample
        token.verify_order_tx(order_tx_id, asset.did, "some_index",
                              "some_amount", alice_address)
Ejemplo n.º 24
0
def test_finalize(network, config, web3, T1, T2, alice_address, alice_wallet):
    """Tests that a pool containing tokens can be finalized."""
    pool = _createPoolWith2Tokens(network, config, web3, T1, T2, alice_wallet,
                                  90, 10, 9, 1)

    assert not pool.isPublicSwap()
    assert not pool.isFinalized()
    assert pool.totalSupply() == 0
    assert pool.balanceOf(alice_address) == 0
    assert pool.allowance(alice_address, pool.address) == 0

    pool.finalize(from_wallet=alice_wallet)
    assert str(pool) != ""

    assert pool.isPublicSwap()
    assert pool.isFinalized()
    assert pool.totalSupply() == to_wei(100)
    assert pool.balanceOf(alice_address) == to_wei(100)
    assert pool.allowance(alice_address, pool.address) == 0

    assert pool.getFinalTokens() == [T1.address, T2.address]
    assert pool.getCurrentTokens() == [T1.address, T2.address]
Ejemplo n.º 25
0
def _deployAndMintToken(web3: Web3, symbol: str,
                        to_address: str) -> btoken.BToken:
    wallet = get_factory_deployer_wallet(_NETWORK)
    dt_address = DataToken.deploy(
        web3,
        wallet,
        "Template Contract",
        "TEMPLATE",
        wallet.address,
        to_wei(1000),
        DTFactory.FIRST_BLOB,
        to_address,
    )
    dt_factory = DTFactory(
        web3, DTFactory.deploy(web3, wallet, dt_address, to_address))
    token_address = dt_factory.get_token_address(
        dt_factory.createToken(symbol, symbol, symbol, DataToken.DEFAULT_CAP,
                               wallet))
    token = DataToken(web3, token_address)
    token.mint(to_address, to_wei(1000), wallet)

    return btoken.BToken(web3, token.address)
Ejemplo n.º 26
0
def setup_all(request, config, web3):
    # a test can skip setup_all() via decorator "@pytest.mark.nosetup_all"
    if "nosetup_all" in request.keywords:
        return

    wallet = get_ganache_wallet()

    if not wallet:
        return

    addresses_file = config.address_file
    if not os.path.exists(addresses_file):
        return

    with open(addresses_file) as f:
        network_addresses = json.load(f)

    print(f"sender: {wallet.key}, {wallet.address}, {wallet.keys_str()}")
    print(
        f"sender balance: {from_wei(get_ether_balance(web3, wallet.address))}")
    assert get_ether_balance(
        web3, wallet.address) >= to_wei(10), "Ether balance less than 10."

    from ocean_lib.models.data_token import DataToken

    OCEAN_token = DataToken(web3,
                            address=network_addresses["development"]["Ocean"])

    amt_distribute = to_wei(1000)

    for w in (get_publisher_wallet(), get_consumer_wallet()):
        if get_ether_balance(web3, w.address) < to_wei(2):
            send_ether(wallet, w.address, to_wei(4))

        if OCEAN_token.balanceOf(w.address) < to_wei(100):
            OCEAN_token.mint(wallet.address,
                             amt_distribute,
                             from_wallet=wallet)
            OCEAN_token.transfer(w.address, amt_distribute, from_wallet=wallet)
Ejemplo n.º 27
0
def test_joinSwapExternAmountIn(network, config, web3, T1, T2, alice_wallet,
                                alice_address):
    """Tests adding an external amount inside a pool.

    When the pool is not public, assert that an Exception is thrown.
    When the pool is public, assert that the swap is made and the correct balance remains.
    """
    init_T1balance = T1.balanceOf(alice_address)
    T2balance = T2.balanceOf(alice_address)
    pool = _createPoolWith2Tokens(network, config, web3, T1, T2, alice_wallet,
                                  90, 10, 9, 1)
    T1.approve(pool.address, to_wei(100), from_wallet=alice_wallet)

    # pool's not public
    with pytest.raises(Exception):
        pool.swapExactAmountOut(
            tokenIn_address=T1.address,
            maxAmountIn=to_wei(100),
            tokenOut_address=T2.address,
            tokenAmountOut=to_wei(10),
            maxPrice=HUGEINT,
            from_wallet=alice_wallet,
        )

    # pool's public
    pool.setPublicSwap(True, from_wallet=alice_wallet)
    pool.swapExactAmountOut(
        tokenIn_address=T1.address,
        maxAmountIn=to_wei(100),
        tokenOut_address=T2.address,
        tokenAmountOut=to_wei(1),
        maxPrice=HUGEINT,
        from_wallet=alice_wallet,
    )
    new_balance = init_T1balance - to_wei("91.055")
    assert (new_balance - to_wei("0.005") <= T1.balanceOf(alice_address) <=
            new_balance + to_wei("0.005"))
    assert T2.balanceOf(alice_address) == T2balance - to_wei(9)

    block = web3.eth.block_number
    block_confirmations = config.block_confirmations.value
    swap_log = pool.get_swap_logs(block - (block_confirmations + 1), block)[0]
    assert swap_log["args"]["tokenIn"] == T1.address
Ejemplo n.º 28
0
def test_verify_transfer_tx(alice_address, bob_address, alice_ocean,
                            alice_wallet):
    """Tests verify_transfer_tx function."""
    token = alice_ocean.create_data_token("DataToken1",
                                          "DT1",
                                          from_wallet=alice_wallet,
                                          blob="foo_blob")

    with pytest.raises(TransactionNotFound):
        # dummy tx id which is not found in the chain
        # need to catch TransactionNotFound exception from web3
        token.verify_transfer_tx("0x0", alice_address, bob_address)

    # an actual transfer does happen
    token.mint(alice_address, to_wei(100), from_wallet=alice_wallet)
    token.approve(bob_address, to_wei(1), from_wallet=alice_wallet)
    tx_id = token.transfer(bob_address, to_wei(5), from_wallet=alice_wallet)

    assert len(token.verify_transfer_tx(tx_id, alice_address,
                                        bob_address)) == 2

    with pytest.raises(AssertionError):
        token.verify_transfer_tx(tx_id, "0x0", bob_address)
Ejemplo n.º 29
0
def test_gulp(network, config, web3, T1, alice_wallet):
    """Test pool gulp."""
    pool = _deployBPool(web3, config.address_file, network, alice_wallet)

    # bind T1 to the pool, with a balance of 2.0
    T1.approve(pool.address, to_wei(50), from_wallet=alice_wallet)
    pool.bind(T1.address, to_wei(2), to_wei(50), from_wallet=alice_wallet)

    # T1 is now pool's (a) ERC20 balance (b) _records[token].balance
    assert T1.balanceOf(pool.address) == to_wei(2)  # ERC20 balance
    assert pool.getBalance(T1.address) == to_wei(2)  # records[]

    # but then some joker accidentally sends 5.0 tokens to the pool's address
    #  rather than binding / rebinding. So it's in ERC20 bal but not records[]
    T1.transfer(pool.address, to_wei(5), from_wallet=alice_wallet)
    assert T1.balanceOf(pool.address) == to_wei(2 + 5)  # ERC20 bal
    assert pool.getBalance(T1.address) == to_wei(2)  # records[]

    # so, 'gulp' gets the pool to absorb the tokens into its balances.
    # i.e. to update _records[token].balance to be in sync with ERC20 balance
    pool.gulp(T1.address, from_wallet=alice_wallet)
    assert T1.balanceOf(pool.address) == to_wei(2 + 5)  # ERC20
    assert pool.getBalance(T1.address) == to_wei(2 + 5)  # records[]
Ejemplo n.º 30
0
def test_transfer_event_filter(alice_ocean, alice_wallet, alice_address,
                               bob_address):
    token = alice_ocean.create_data_token("DataToken1",
                                          "DT1",
                                          from_wallet=alice_wallet,
                                          blob="foo_blob")

    token.mint(alice_address, to_wei(100), from_wallet=alice_wallet)
    token.approve(bob_address, to_wei(1), from_wallet=alice_wallet)
    token.transfer(bob_address, to_wei(5), from_wallet=alice_wallet)

    block = alice_ocean.web3.eth.block_number
    event_filter = EventFilter(token.events.Transfer(),
                               from_block=block,
                               to_block=block)

    assert event_filter.filter_id, "Event filter ID is None."

    event_filter.uninstall()
    event_filter.recreate_filter()

    assert (event_filter.get_new_entries() == []
            ), "There are new entries for EventFilter."