Example #1
0
def setup_all(request):
    # a test can skip setup_all() via decorator "@pytest.mark.nosetup_all"
    if "nosetup_all" in request.keywords:
        return
    config = ExampleConfig.get_config()
    ConfigProvider.set_config(config)
    Web3Provider.init_web3(
        provider=get_web3_connection_provider(config.network_url))
    ContractHandler.set_artifacts_path(config.artifacts_path)

    network = Web3Helper.get_network_name()
    wallet = get_ganache_wallet()
    if network in ["ganache", "development"] and wallet:

        print(
            f"sender: {wallet.key}, {wallet.address}, {wallet.password}, {wallet.keysStr()}"
        )
        print(
            f"sender balance: {Web3Helper.from_wei(Web3Helper.get_ether_balance(wallet.address))}"
        )
        assert Web3Helper.from_wei(Web3Helper.get_ether_balance(
            wallet.address)) > 10

        from ocean_lib.models.data_token import DataToken

        OCEAN_token = DataToken(get_ocean_token_address(network))
        amt_distribute = 1000
        amt_distribute_base = to_base_18(float(amt_distribute))
        for w in (get_publisher_wallet(), get_consumer_wallet()):
            if Web3Helper.from_wei(Web3Helper.get_ether_balance(
                    w.address)) < 2:
                Web3Helper.send_ether(wallet, w.address, 4)

            if OCEAN_token.token_balance(w.address) < 100:
                OCEAN_token.transfer(w.address,
                                     amt_distribute_base,
                                     from_wallet=wallet)
Example #2
0
def run_compute(did, consumer_wallet, algorithm_file, pool_address, order_id=None):
    ocean = Ocean(config=Config(options_dict=get_config_dict()))

    # Get asset DDO/metadata and service
    asset = ocean.assets.resolve(did)
    service = asset.get_service(ServiceTypes.CLOUD_COMPUTE)

    # check the price in ocean tokens
    num_ocean = ocean.pool.calcInGivenOut(
        pool_address, ocean.OCEAN_address, asset.data_token_address, 1.0
    )

    # buy datatoken to be able to run the compute service
    dt = DataToken(asset.asset_id)
    dt_balance = dt.token_balance(consumer_wallet.address)
    if dt_balance < 1.0:
        pool = BPool(pool_address)
        txid = ocean.pool.buy_data_tokens(
            pool_address, 1.0, num_ocean + 0.1, consumer_wallet
        )
        receipt = pool.get_tx_receipt(txid)
        if not receipt or receipt.status != 1:
            print(f"buying data token failed: txId={txid}, txReceipt={receipt}")
            return None, None

    tx_id = order_id
    if not tx_id:
        tx_id = ocean.assets.pay_for_service(
            1.0,
            asset.data_token_address,
            did,
            service.index,
            fee_receiver=asset.publisher,
            from_wallet=consumer_wallet,
            consumer=consumer_wallet.address,
        )

    # load python algorithm to run in the compute job
    with open(algorithm_file) as f:
        algorithm_text = f.read()

    # whether to publish the algorithm results as an Ocean assets
    output_dict = {"publishOutput": False, "publishAlgorithmLog": False}
    # start the compute job (submit the compute service request)
    algorithm_meta = AlgorithmMetadata(
        {
            "language": "python",
            "rawcode": algorithm_text,
            "container": {
                "tag": "latest",
                "image": "amancevice/pandas",
                "entrypoint": "python $ALGO",
            },
        }
    )
    job_id = ocean.compute.start(
        did, consumer_wallet, tx_id, algorithm_meta=algorithm_meta, output=output_dict
    )

    # check the status of the compute job
    status = ocean.compute.status(did, job_id, consumer_wallet)
    print(f"status of compute job {job_id}: {status}")

    # get the result of the compute run
    result = ocean.compute.result(did, job_id, consumer_wallet)
    print(f"got result of compute job {job_id}: {result}")
    return job_id, status
Example #3
0
def test_fixed_rate_exchange(
    alice_ocean, alice_wallet, T1, bob_wallet, T2, contracts_addresses
):
    """
    tests:
        create
        generateExchangeId
        getExchange
        getExchanges
        getNumberOfExchanges
        get_base_token_quote
        buy_data_token

    """
    base_unit = to_base_18(1.0)
    fixed_ex = FixedRateExchange(contracts_addresses[FixedRateExchange.CONTRACT_NAME])
    num_ex = fixed_ex.getNumberOfExchanges()
    assert num_ex == len(
        fixed_ex.getExchanges()
    ), "num exchanges do not match num of exchange ids."

    ocean_t = alice_ocean.OCEAN_address
    ocn_token = DataToken(ocean_t)
    # owner_wallet = get_ganache_wallet()
    # ocn_token.transfer_tokens(bob_wallet.address, 100, owner_wallet)
    assert ocn_token.token_balance(bob_wallet.address) >= 100, (
        f"bob wallet does not have the expected OCEAN tokens balance, "
        f"got {ocn_token.token_balance(bob_wallet.address)} instead of 100"
    )

    # clear any previous ocean token allowance for the exchange contract
    assert (
        ocn_token.get_tx_receipt(
            ocn_token.approve(fixed_ex.address, 1, bob_wallet)
        ).status
        == 1
    ), "approve failed"
    assert ocn_token.allowance(bob_wallet.address, fixed_ex.address) == 1, ""

    rate = to_base_18(0.1)
    tx_id = fixed_ex.create(ocean_t, T1.address, rate, alice_wallet)
    r = fixed_ex.get_tx_receipt(tx_id)
    assert r.status == 1, f"create fixed rate exchange failed: TxId {tx_id}."

    ex_id = fixed_ex.generateExchangeId(ocean_t, T1.address, alice_wallet.address).hex()
    ex_data = fixed_ex.getExchange(ex_id)
    expected_values = (alice_wallet.address, T1.address, ocean_t, rate, True, 0)
    assert ex_data == expected_values, (
        f"fixed rate exchange {ex_id} with values {ex_data} "
        f"does not match the expected values {expected_values}"
    )

    assert (
        fixed_ex.getNumberOfExchanges() == num_ex + 1
    ), f"Number of exchanges does not match, expected {num_ex+1} got {fixed_ex.getNumberOfExchanges()}."

    ###################
    # Test quote and buy datatokens
    amount = to_base_18(10.0)  # 10 data tokens
    base_token_quote = fixed_ex.get_base_token_quote(ex_id, amount)
    # quote = from_base_18(base_token_quote)
    assert base_token_quote == (
        amount * rate / base_unit
    ), f"quote does not seem correct: expected {amount*rate/base_unit}, got {base_token_quote}"
    assert from_base_18(base_token_quote) == 1.0, ""
    # buy without approving OCEAN tokens, should fail
    assert (
        run_failing_tx(fixed_ex, fixed_ex.buy_data_token, ex_id, amount, bob_wallet)
        == 0
    ), (
        f"buy_data_token/swap on EX {ex_id} is expected to fail but did not, "
        f"maybe the FixedRateExchange is already approved as spender for bob_wallet."
    )
    # approve ocean tokens, buying should still fail because datatokens are not approved by exchange owner
    assert (
        ocn_token.get_tx_receipt(
            ocn_token.approve(fixed_ex.address, base_token_quote, bob_wallet)
        ).status
        == 1
    ), "approve failed"
    assert (
        run_failing_tx(fixed_ex, fixed_ex.buy_data_token, ex_id, amount, bob_wallet)
        == 0
    ), (
        f"buy_data_token/swap on EX {ex_id} is expected to fail but did not, "
        f"maybe the FixedRateExchange is already approved as spender for bob_wallet."
    )

    # approve data token, now buying should succeed
    assert (
        T1.get_tx_receipt(T1.approve(fixed_ex.address, amount, alice_wallet)).status
        == 1
    ), "approve failed"
    assert (
        ocn_token.allowance(bob_wallet.address, fixed_ex.address) == base_token_quote
    ), ""
    tx_id = fixed_ex.buy_data_token(ex_id, amount, bob_wallet)
    r = fixed_ex.get_tx_receipt(tx_id)
    assert (
        r.status == 1
    ), f"buy_data_token/swap on EX {ex_id} failed with status 0: amount {amount}."
    # verify bob's datatokens balance
    assert T1.balanceOf(bob_wallet.address) == amount, (
        f"bobs datatoken balance is not right, "
        f"should be {amount}, got {T1.balanceOf(bob_wallet.address)}"
    )
    assert ocn_token.allowance(bob_wallet.address, fixed_ex.address) == 0, ""

    #####################
    # create another ex then do more tests
    rate2 = to_base_18(0.8)
    tx_id = fixed_ex.create(ocean_t, T2.address, rate2, alice_wallet)
    r = fixed_ex.get_tx_receipt(tx_id)
    assert r.status == 1, f"create fixed rate exchange failed: TxId {tx_id}."

    assert fixed_ex.getNumberOfExchanges() == num_ex + 2, (
        f"Number of exchanges does not match, "
        f"expected {num_ex+2} got {fixed_ex.getNumberOfExchanges()}."
    )

    t2_ex_id = fixed_ex.generateExchangeId(
        ocean_t, T2.address, alice_wallet.address
    ).hex()
    exchange_ids = {ti.hex() for ti in fixed_ex.getExchanges()}
    assert ex_id in exchange_ids, "exchange id not found."
    assert t2_ex_id in exchange_ids, "exchange id not found."

    ##############################
    # test activate/deactivate
    assert fixed_ex.isActive(ex_id) is True, f"exchange {ex_id} is not active."
    assert fixed_ex.isActive(t2_ex_id) is True, f"exchange {t2_ex_id} is not active."

    assert (
        run_failing_tx(fixed_ex, fixed_ex.deactivate, t2_ex_id, bob_wallet) == 0
    ), f"exchange {t2_ex_id} deactivate (using bob_wallet) should fail but did not."

    assert (
        fixed_ex.get_tx_receipt(fixed_ex.deactivate(t2_ex_id, alice_wallet)).status == 1
    ), f"exchange {t2_ex_id} deactivate failed."
    assert (
        fixed_ex.isActive(t2_ex_id) is False
    ), f"exchange {t2_ex_id} is active, but it should be deactivated."

    ###################################
    # try buying from deactivated ex
    amount = to_base_18(4.0)  # num data tokens
    base_token_quote = fixed_ex.get_base_token_quote(
        t2_ex_id, amount
    )  # num base token (OCEAN tokens
    assert base_token_quote == (
        amount * rate2 / base_unit
    ), f"quote does not seem correct: expected {amount*rate2/base_unit}, got {base_token_quote}"
    ocn_token.get_tx_receipt(
        ocn_token.approve(fixed_ex.address, base_token_quote, bob_wallet)
    )
    # buy should fail (deactivated exchange)
    assert (
        run_failing_tx(fixed_ex, fixed_ex.buy_data_token, t2_ex_id, amount, bob_wallet)
        == 0
    ), (
        f"buy_data_token/swap on EX {t2_ex_id} is expected to fail but did not, "
        f"maybe the FixedRateExchange is already approved as spender for bob_wallet."
    )
    assert (
        ocn_token.allowance(bob_wallet.address, fixed_ex.address) == base_token_quote
    ), ""
    assert (
        fixed_ex.get_tx_receipt(fixed_ex.activate(t2_ex_id, alice_wallet)).status == 1
    ), f"exchange {t2_ex_id} deactivate failed."
    assert (
        fixed_ex.isActive(t2_ex_id) is True
    ), f"exchange {t2_ex_id} is not active, but it should be."

    ##############################
    # buy should still fail as datatokens are not approved to spend by the exchange contract
    assert (
        run_failing_tx(fixed_ex, fixed_ex.buy_data_token, t2_ex_id, amount, bob_wallet)
        == 0
    ), (
        f"buy_data_token/swap on EX {t2_ex_id} is expected to fail but did not, "
        f"maybe the FixedRateExchange is already approved as spender for bob_wallet."
    )

    # now buy tokens should succeed
    assert (
        T2.get_tx_receipt(T2.approve(fixed_ex.address, amount * 3, alice_wallet)).status
        == 1
    ), "approve failed"
    assert (
        fixed_ex.get_tx_receipt(
            fixed_ex.buy_data_token(t2_ex_id, amount, bob_wallet)
        ).status
        == 1
    ), f"buy_data_token/swap on EX {ex_id} failed, "
    assert ocn_token.allowance(bob_wallet.address, fixed_ex.address) == 0, ""

    # approve again for another purchase
    ocn_token.get_tx_receipt(
        ocn_token.approve(fixed_ex.address, base_token_quote, bob_wallet)
    )
    assert (
        run_failing_tx(
            fixed_ex, fixed_ex.buy_data_token, t2_ex_id, to_base_18(5.0), bob_wallet
        )
        == 0
    ), f"buy_data_token/swap on EX {t2_ex_id} should fail because not enough Ocean tokens are approved by buyer."

    # get new quote for new amount
    base_token_quote = fixed_ex.get_base_token_quote(
        t2_ex_id, to_base_18(5.0)
    )  # num base token (OCEAN tokens
    ocn_token.get_tx_receipt(
        ocn_token.approve(fixed_ex.address, base_token_quote, bob_wallet)
    )
    assert (
        fixed_ex.get_tx_receipt(
            fixed_ex.buy_data_token(t2_ex_id, to_base_18(5.0), bob_wallet)
        ).status
        == 1
    ), f"buy_data_token/swap on EX {t2_ex_id} failed."
    assert ocn_token.allowance(bob_wallet.address, fixed_ex.address) == 0, ""

    ##############################
    # test getRate/setRate
    assert (
        fixed_ex.getRate(t2_ex_id) == rate2
    ), f"T2 exchange rate does not match {rate2}, got {fixed_ex.getRate(t2_ex_id)}"
    assert (
        fixed_ex.getRate(ex_id) == rate
    ), f"T1 exchange rate does not match {rate}, got {fixed_ex.getRate(ex_id)}"
    rate2 = to_base_18(0.75)
    assert (
        fixed_ex.get_tx_receipt(fixed_ex.setRate(t2_ex_id, rate2, alice_wallet)).status
        == 1
    ), "setRate failed."
    assert (
        fixed_ex.getRate(t2_ex_id) == rate2
    ), f"T2 exchange rate does not match {rate2}, got {fixed_ex.getRate(t2_ex_id)}"

    assert (
        run_failing_tx(
            fixed_ex, fixed_ex.setRate, t2_ex_id, to_base_18(0.0), alice_wallet
        )
        == 0
    ), "should not accept rate of Zero."
    assert (
        run_failing_tx(
            fixed_ex, fixed_ex.setRate, t2_ex_id, -to_base_18(0.05), alice_wallet
        )
        == 0
    ), "should not accept a negative rate."
    assert (
        fixed_ex.get_tx_receipt(
            fixed_ex.setRate(t2_ex_id, to_base_18(1000.0), alice_wallet)
        ).status
        == 1
    ), "setRate failed."