Skip to content

Commit

Permalink
Remove some instances where brownie was used instead of web3.
Browse files Browse the repository at this point in the history
  • Loading branch information
calina-c committed Aug 2, 2023
1 parent ff686ed commit d3015ea
Show file tree
Hide file tree
Showing 10 changed files with 59 additions and 42 deletions.
4 changes: 2 additions & 2 deletions conftest_ganache.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from ocean_lib.models.datatoken1 import Datatoken1
from ocean_lib.models.factory_router import FactoryRouter
from ocean_lib.models.fixed_rate_exchange import FixedRateExchange
from ocean_lib.ocean.util import get_address_of_type, to_wei
from ocean_lib.ocean.util import get_address_of_type, send_ether, to_wei
from ocean_lib.web3_internal.contract_utils import get_contracts_addresses_all_networks
from tests.resources.helper_functions import (
deploy_erc721_erc20,
Expand Down Expand Up @@ -61,7 +61,7 @@ def setup_all(request, config, ocean_token):
balance = config["web3_instance"].eth.get_balance(w.address)

if balance < to_wei(2):
wallet.transfer(w, to_wei(4))
send_ether(config, wallet, w.address, to_wei(4))

if ocean_token.balanceOf(w) < to_wei(100):
ocean_token.mint(w, amt_distribute, {"from": wallet})
Expand Down
8 changes: 5 additions & 3 deletions ocean_lib/models/datatoken_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from enum import IntEnum
from typing import Any, Dict, List, Optional, Tuple, Union

from brownie.network.state import Chain
from enforce_typing import enforce_types
from web3.main import Web3

Expand Down Expand Up @@ -236,8 +235,11 @@ def get_start_order_logs(
from_block: Optional[int] = 0,
to_block: Optional[int] = "latest",
) -> Tuple:
chain = Chain()
to_block = to_block if to_block != "latest" else chain[-1].number
to_block = (
to_block
if to_block != "latest"
else self.config_dict["web3_instance"].block_number
)

return self.contract.events.get_sequence(from_block, to_block, "OrderStarted")

Expand Down
4 changes: 2 additions & 2 deletions ocean_lib/models/test/test_fake_ocean.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import os

import pytest
from brownie.network import accounts
from eth_account import Account

from ocean_lib.ocean.mint_fake_ocean import mint_fake_OCEAN
from ocean_lib.ocean.util import to_wei
Expand Down Expand Up @@ -33,5 +33,5 @@ def test_use_mint_fake_ocean(config, factory_deployer_wallet, ocean_token):
if not key:
continue

w = accounts.add(key)
w = Account.from_key(private_key=key)
assert ocean_token.balanceOf(w.address) >= expected_amt_distribute
14 changes: 8 additions & 6 deletions ocean_lib/ocean/mint_fake_ocean.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
#
import os

from brownie.network import accounts
from enforce_typing import enforce_types
from eth_account import Account

from ocean_lib.models.datatoken_base import DatatokenBase
from ocean_lib.ocean.util import get_ocean_token_address, to_wei
from ocean_lib.ocean.util import get_ocean_token_address, send_ether, to_wei


@enforce_types
Expand All @@ -18,7 +18,9 @@ def mint_fake_OCEAN(config: dict) -> None:
1. Mints tokens
2. Distributes tokens to TEST_PRIVATE_KEY1 and TEST_PRIVATE_KEY2
"""
deployer_wallet = accounts.add(os.environ.get("FACTORY_DEPLOYER_PRIVATE_KEY"))
deployer_wallet = Account.from_key(
private_key=os.getenv("FACTORY_DEPLOYER_PRIVATE_KEY")
)

OCEAN_token = DatatokenBase.get_typed(
config, address=get_ocean_token_address(config)
Expand All @@ -30,10 +32,10 @@ def mint_fake_OCEAN(config: dict) -> None:
if not key:
continue

w = accounts.add(key)
w = Account.from_key(private_key=key)

if OCEAN_token.balanceOf(w.address) < amt_distribute:
OCEAN_token.mint(w.address, amt_distribute, {"from": deployer_wallet})

if accounts.at(w.address).balance() < to_wei(2):
deployer_wallet.transfer(w.address, "4 ether")
if config["web3_instance"].eth.getBalance(w.address) < to_wei(2):
send_ether(config, deployer_wallet, w.address, to_wei(4))
16 changes: 1 addition & 15 deletions ocean_lib/ocean/test/test_ocean_assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
from datetime import datetime, timezone
from unittest.mock import patch

import brownie
import pytest
from brownie.network import accounts

from ocean_lib.agreements.service_types import ServiceTypes
from ocean_lib.assets.ddo import DDO
Expand All @@ -22,7 +20,6 @@
from ocean_lib.ocean.ocean_assets import OceanAssets
from ocean_lib.ocean.util import get_address_of_type, to_wei
from ocean_lib.services.service import Service
from ocean_lib.web3_internal.constants import ZERO_ADDRESS
from tests.resources.ddo_helpers import (
build_credentials_dict,
build_default_services,
Expand Down Expand Up @@ -457,17 +454,6 @@ def test_asset_creation_errors(publisher_ocean, publisher_wallet, config):
)
metadata = get_default_metadata()

some_random_address = ZERO_ADDRESS
with pytest.raises(brownie.exceptions.ContractNotFound):
publisher_ocean.assets.create(
metadata=metadata,
tx_dict={"from": publisher_wallet},
services=[],
data_nft_address=some_random_address,
deployed_datatokens=[datatoken],
encrypt_flag=True,
)

with patch("ocean_lib.aquarius.aquarius.Aquarius.ddo_exists") as mock:
mock.return_value = True
with pytest.raises(AquariusError):
Expand Down Expand Up @@ -547,7 +533,7 @@ def test_create_pricing_schemas(
assert dt_np.get_exchanges() == []

# pay_for_access service has insufficient balance and can't buy or dispense
empty_wallet = accounts.add()
empty_wallet = config["web3_instance"].eth.account.create()

with pytest.raises(InsufficientBalance):
ocean_assets.pay_for_access_service(
Expand Down
22 changes: 22 additions & 0 deletions ocean_lib/ocean/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,25 @@ def get_args_object(args, kwargs, args_class):
args_to_use = args_class(*args, **kwargs)

return args_to_use


@enforce_types
def send_ether(config, from_wallet, to_address: str, amount: int):
if not Web3.isChecksumAddress(to_address):
to_address = Web3.toChecksumAddress(to_address)

web3 = config["web3_instance"]
chain_id = web3.eth.chain_id
tx = {
"from": from_wallet.address,
"to": to_address,
"value": amount,
"chainId": chain_id,
"nonce": web3.eth.get_transaction_count(from_wallet.address),
}
tx["gas"] = web3.eth.estimate_gas(tx)
tx["gasPrice"] = int(web3.eth.gas_price * 1.1)

signed_tx = web3.eth.account.signTransaction(tx, from_wallet.privateKey)
tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction)
return web3.eth.wait_for_transaction_receipt(tx_hash)
7 changes: 3 additions & 4 deletions ocean_lib/services/test/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from unittest.mock import Mock, patch

import pytest
from brownie.network import accounts
from requests.models import Response

from ocean_lib.assets.ddo import DDO
Expand Down Expand Up @@ -155,10 +154,10 @@ def test_utilitary_functions_for_trusted_algorithm_publishers(publisher_ocean):
compute_service = ddo.services[1]
assert compute_service.type == "compute"

addr1 = accounts.add().address
addr1 = publisher_ocean.config_dict["web3_instance"].eth.account.create().address
compute_service.compute_values["publisherTrustedAlgorithmPublishers"] = [addr1]

addr2 = accounts.add().address
addr2 = publisher_ocean.config_dict["web3_instance"].eth.account.create().address
# add a new trusted algorithm to the publisher_trusted_algorithms list
new_publisher_trusted_algo_publishers = (
compute_service.add_publisher_trusted_algorithm_publisher(addr2)
Expand All @@ -182,7 +181,7 @@ def test_utilitary_functions_for_trusted_algorithm_publishers(publisher_ocean):

assert len(new_publisher_trusted_algo_publishers) == 1

addr3 = accounts.add().address
addr3 = publisher_ocean.config_dict["web3_instance"].eth.account.create().address
# remove a trusted algorithm that does not belong to publisher_trusted_algorithms list
new_publisher_trusted_algo_publishers = (
compute_service.remove_publisher_trusted_algorithm_publisher(addr3)
Expand Down
6 changes: 3 additions & 3 deletions ocean_lib/web3_internal/test/test_wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@
import os

import pytest
from brownie.network import accounts

from ocean_lib.ocean.util import to_wei
from tests.resources.helper_functions import generate_wallet


@pytest.mark.unit
def test_generating_wallets(ocean_token):
def test_generating_wallets(ocean_token, config):
generated_wallet = generate_wallet()
assert generated_wallet.address, "Wallet has not an address."
assert accounts.at(generated_wallet.address).balance() == to_wei(3)

assert config["web3_instance"].eth.getBalance(generated_wallet.address) == to_wei(3)

assert ocean_token.balanceOf(generated_wallet.address) == to_wei(50)

Expand Down
11 changes: 6 additions & 5 deletions tests/integration/remote/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
import warnings

from brownie.exceptions import ContractNotFound, TransactionError, VirtualMachineError
from brownie.network import accounts
from enforce_typing import enforce_types
from eth_account import Account
from web3.exceptions import ExtraDataLengthError

from ocean_lib.web3_internal.utils import get_gas_fees
Expand Down Expand Up @@ -58,8 +58,8 @@ def get_wallets():
assert bob_private_key, f"Need envvar REMOTE_TEST_PRIVATE_KEY2. {instrs}"

# wallets
alice_wallet = accounts.add(alice_private_key)
bob_wallet = accounts.add(bob_private_key)
alice_wallet = Account.from_key(private_key=alice_private_key)
bob_wallet = Account.from_key(private_key=bob_private_key)

print(f"alice_wallet.address = '{alice_wallet.address}'")
print(f"bob_wallet.address = '{bob_wallet.address}'")
Expand All @@ -75,7 +75,8 @@ def do_nonocean_tx_and_handle_gotchas(ocean, alice_wallet, bob_wallet):
automatically in remote testnets, then just skip
"""
# Simplest possible tx: Alice send Bob some fake MATIC
bob_eth_before = accounts.at(bob_wallet.address).balance()
web3 = ocean.config_dict["web3_instance"]
bob_eth_before = web3.eth.get_balance(bob_wallet.address)
normalized_unixtime = time.time() / 1e9
amt_send = 1e-8 * (random.random() + normalized_unixtime)

Expand All @@ -87,7 +88,7 @@ def do_nonocean_tx_and_handle_gotchas(ocean, alice_wallet, bob_wallet):
f"{amt_send:.15f} ether",
priority_fee=priority_fee,
)
bob_eth_after = accounts.at(bob_wallet.address).balance()
bob_eth_after = web3.eth.get_balance(bob_wallet.address)
except ERRORS_TO_CATCH as e:
if error_is_skippable(str(e)):
warnings.warn(UserWarning(f"Warning: EVM reported error: {e}"))
Expand Down
9 changes: 7 additions & 2 deletions tests/resources/helper_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from ocean_lib.models.data_nft_factory import DataNFTFactoryContract
from ocean_lib.models.datatoken_base import DatatokenBase
from ocean_lib.ocean.ocean import Ocean
from ocean_lib.ocean.util import get_address_of_type, to_wei
from ocean_lib.ocean.util import get_address_of_type, send_ether, to_wei
from ocean_lib.structures.file_objects import FilesTypeFactory
from ocean_lib.web3_internal.constants import ZERO_ADDRESS
from ocean_lib.web3_internal.utils import sign_with_key, split_signature
Expand Down Expand Up @@ -82,7 +82,12 @@ def generate_wallet():

new_wallet = Account.from_key(private_key=private_key)
deployer_wallet = get_factory_deployer_wallet(config)
deployer_wallet.transfer(new_wallet, to_wei(3))
send_ether(
config,
deployer_wallet,
new_wallet.address,
to_wei(3),
)

ocean = Ocean(config)
OCEAN = ocean.OCEAN_token
Expand Down

0 comments on commit d3015ea

Please sign in to comment.