Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #10 - test rinkeby #96

Merged
merged 22 commits into from
May 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 8 additions & 14 deletions dftool
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ ADDRESS_FILE -- eg for barge: export ADDRESS_FILE={networkutil.chainIdToAddressF
os.mkdir(CSV_DIR)

# brownie setup
_connectToChain(CHAINID)
networkutil.connect(CHAINID)
chain = brownie.network.chain

if "-" in ST:
Expand Down Expand Up @@ -279,7 +279,7 @@ Transactions are signed with envvar 'DFTOOL_KEY`.
assert DFREWARDS_ADDR is not None

# main work
_connectToChain(CHAINID)
networkutil.connect(CHAINID)
from_account = _getPrivateAccount()
token_symbol = B.Simpletoken.at(TOKEN_ADDR).symbol()
rewards = csvs.loadRewardsCsv(CSV_DIR, token_symbol)
Expand Down Expand Up @@ -340,7 +340,7 @@ Usage: dftool newdfrewards CHAINID
print(f"Arguments: CHAINID={CHAINID}")

# main work
_connectToChain(CHAINID)
networkutil.connect(CHAINID)
from_account = _getPrivateAccount()
df_rewards = B.DFRewards.deploy({"from": from_account})
print(f"New dispense contract deployed at address: {df_rewards.address}")
Expand Down Expand Up @@ -407,7 +407,7 @@ Usage: dftool mine BLOCKS [TIMEDELTA]
print(f"Arguments: BLOCKS={BLOCKS}, TIMEDELTA={TIMEDELTA}")

# main work
_connectToChain(DEV_CHAINID) # hardcoded bc it's the only one we can force
networkutil.connect(DEV_CHAINID)
chain = brownie.network.chain
if TIMEDELTA is None:
chain.mine(blocks=BLOCKS, timedelta=TIMEDELTA)
Expand All @@ -432,7 +432,7 @@ Usage: dftool newacct
assert sys.argv[1] == "newacct"

# main work
_connectToChain(DEV_CHAINID) # hardcoded bc it's the only one we can force
networkutil.connect(DEV_CHAINID)
account = brownie.network.accounts.add()
print("Generated new account:")
print(f" private_key = {account.private_key}")
Expand All @@ -457,7 +457,7 @@ Usage: dftool newtoken CHAINID
print(f"Arguments:\n CHAINID={CHAINID}")

# main work
_connectToChain(CHAINID)
networkutil.connect(CHAINID)
from_account = _getPrivateAccount()
token = B.Simpletoken.deploy("TST", "Test Token", 18, 1e21, {"from": from_account})
print(f"Token '{token.symbol()}' deployed at address: {token.address}")
Expand Down Expand Up @@ -487,7 +487,7 @@ If envvar ADDRESS_FILE is not None, it gives balance for OCEAN token too.

# do work
print("Account info:")
_connectToChain(CHAINID)
networkutil.connect(CHAINID)
if len(str(ACCOUNT_ADDR)) == 1:
addr_i = int(ACCOUNT_ADDR)
ACCOUNT_ADDR = brownie.accounts[addr_i]
Expand Down Expand Up @@ -525,7 +525,7 @@ Usage: dftool chaininfo CHAINID
CHAINID = int(sys.argv[2])

# do work
_connectToChain(CHAINID)
networkutil.connect(CHAINID)
# blocks = len(brownie.network.chain)
print("\nChain info:")
print(f" # blocks: {len(brownie.network.chain)}")
Expand Down Expand Up @@ -553,12 +553,6 @@ def _getPrivateAccount():
return account


@enforce_types
def _connectToChain(chainID: int):
network = networkutil.chainIdToNetwork(chainID)
brownie.network.connect(network)


# ========================================================================
# main
@enforce_types
Expand Down
44 changes: 22 additions & 22 deletions util/networkutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,20 @@
from util.constants import CONTRACTS

_BARGE_ADDRESS_FILE = "~/.ocean/ocean-contracts/artifacts/address.json"
_BARGE_SUBGRAPH_URI = (
"http://127.0.0.1:9000/subgraphs/name/oceanprotocol/ocean-subgraph"
)


# Chainid values & names are from brownie, where possible.
# https://eth-brownie.readthedocs.io/en/stable/network-management.html
# Otherwise, values & names are from networkutil.org.
# Development chainid is from brownie, rest are from chainlist.org
# Chain values to fit Ocean subgraph urls as given in
# https://v3.docs.oceanprotocol.com/concepts/networks/
_CHAINID_TO_NETWORK = {
8996: "development", # ganache
1: "mainnet", # eth mainnet
1: "mainnet",
3: "ropsten",
4: "rinkeby",
56: "Binance Smart Chain",
137: "Polygon Mainnet",
246: "Energy Web Chain",
1284: "Moonbeam",
1285: "Moonriver",
56: "bsc",
137: "polygon",
246: "energyweb",
1284: "moonbeam",
1285: "moonriver",
}
_NETWORK_TO_CHAINID = {
network: chainID for chainID, network in _CHAINID_TO_NETWORK.items()
Expand All @@ -33,21 +29,20 @@


@enforce_types
def chainIdToAddressFile(chainID: int) -> str:
def chainIdToAddressFile(chainID: int) -> str: # pylint: disable=unused-argument
"""Returns the address file for a given chainID"""
if chainID == DEV_CHAINID:
return os.path.expanduser(_BARGE_ADDRESS_FILE)

raise NotImplementedError()
return os.path.expanduser(_BARGE_ADDRESS_FILE)


@enforce_types
def chainIdToSubgraphUri(chainID: int) -> str:
"""Returns the subgraph URI for a given chainID"""
sg = "/subgraphs/name/oceanprotocol/ocean-subgraph"
if chainID == DEV_CHAINID:
return _BARGE_SUBGRAPH_URI
return "http://127.0.0.1:9000" + sg

raise NotImplementedError()
network_str = chainIdToNetwork(chainID)
return f"https://v4.subgraph.{network_str}.oceanprotocol.com" + sg


@enforce_types
Expand All @@ -66,7 +61,7 @@ def networkToChainId(network: str) -> int:
def connect(chainID: int):
network = brownie.network
if network.is_connected():
network.disconnect()
disconnect() # call networkutil.disconnect(), *NOT* brownie directly
network.connect(chainIdToNetwork(chainID))


Expand All @@ -80,4 +75,9 @@ def disconnect():
if chainID in CONTRACTS:
del CONTRACTS[chainID]

network.disconnect()
try:
network.disconnect()
except: # pylint: disable=bare-except
# overcome brownie issue
# https://github.com/eth-brownie/brownie/issues/1144
pass
3 changes: 2 additions & 1 deletion util/oceanutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,8 @@ def createBPoolFromDatatoken(
):
TOK_have = fromBase18(base_TOKEN.balanceOf(from_account))
TOK_need = init_TOKEN_liquidity
assert TOK_have >= TOK_need, f"have {TOK_have} TOK, need {TOK_need}"
TOK_name = base_TOKEN.symbol()
assert TOK_have >= TOK_need, f"have {TOK_have} {TOK_name}, need {TOK_need}"

pool_template = PoolTemplate()
router = factoryRouter() # router.routerOwner() = '0xe2DD..' = accounts[0]
Expand Down
19 changes: 8 additions & 11 deletions util/test/test_networkutil.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,27 @@
from enforce_typing import enforce_types
import pytest

from util import networkutil


@enforce_types
def test_chainIdToSubgraphUri():
assert (
networkutil.chainIdToSubgraphUri(networkutil.DEV_CHAINID)[:21]
== "http://127.0.0.1:9000"
)

for chainID in [1, 137]:
with pytest.raises(NotImplementedError):
networkutil.chainIdToSubgraphUri(chainID)
for chainID, network_str in networkutil._CHAINID_TO_NETWORK.items():
uri = networkutil.chainIdToSubgraphUri(chainID)
if chainID == networkutil.DEV_CHAINID:
assert uri[:21] == "http://127.0.0.1:9000"
else:
assert network_str in uri


@enforce_types
def test_chainIdToNetwork():
assert networkutil.chainIdToNetwork(8996) == "development"
assert networkutil.chainIdToNetwork(1) == "mainnet"
assert networkutil.chainIdToNetwork(137) == "Polygon Mainnet"
assert networkutil.chainIdToNetwork(137) == "polygon"


@enforce_types
def test_networkToChainId():
assert networkutil.networkToChainId("development") == 8996
assert networkutil.networkToChainId("mainnet") == 1
assert networkutil.networkToChainId("Polygon Mainnet") == 137
assert networkutil.networkToChainId("polygon") == 137
75 changes: 52 additions & 23 deletions util/test/test_rinkeby.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,67 @@
# import brownie
import os
import types

from enforce_typing import enforce_types

# from pprint import pprint
import pytest
from util import networkutil

PREV = None

CHAINID = networkutil.networkToChainId("rinkeby")


@enforce_types
def test_chainIdToNetwork():
network_str = networkutil.chainIdToNetwork(CHAINID)
assert network_str == "rinkeby"


# from util import networkutil, oceanutil, oceantestutil
# from util.graphutil import submitQuery
@enforce_types
def test_chainIdToSubgraphUri():
uri = networkutil.chainIdToSubgraphUri(CHAINID)
assert "subgraph.rinkeby.oceanprotocol.com" in uri


@enforce_types
@pytest.mark.skip(reason="need to implement")
def test_query_approvedTokens():
print("hello")
def test_main(tmp_path):
# brownie has a bug when trying to shut down non-ganache networks
# details in https://github.com/eth-brownie/brownie/issues/1144
# in file venv/lib/python3.8/site-packages/brownie/network/state.py
# function: _remove_contract()
# code: del _contract_map[contract.address]

# This isn't a problem from cli, since it cleans up mem
# But it is a problem for unit tests. Our workaround is to do a system call.

# OCEAN = oceanutil.OCEANtoken()
ACCOUNT_ADDR = "0xc945a5a960fef1a9c3fef8593fc2446d1d7c6146"
TOKEN_ADDR = "0xddea378a6ddc8afec82c36e9b0078826bf9e68b6"
fn = os.path.join(tmp_path, "out.txt")
cmd = f"./dftool acctinfo {CHAINID} {ACCOUNT_ADDR} {TOKEN_ADDR}>{fn} 2>{fn}"
os.system(cmd)

# oceantestutil.randomDeployPool(accounts[0], OCEAN)
s = None
with open(fn, "r") as f:
s = f.read()
assert " ZRX" in s

# query = "{ opcs{approvedTokens} }"
# result = submitQuery(query, chainID)

# pprint(result)
@enforce_types
def setup_module():
global PREV

PREV = types.SimpleNamespace()

PREV.WEB3_INFURA_PROJECT_ID = os.environ.get("WEB3_INFURA_PROJECT_ID")

# @enforce_types
# def setup_function():
# chainID = networkutil.networkToChainId("rinkeby")
# networkutil.connect(chainID)
# got this value from https://rpc.info/. We could also use our own
os.environ["WEB3_INFURA_PROJECT_ID"] = "9aa3d95b3bc440fa88ea12eaa4456161"

# address_file = networkutil.chainIdToAddressFile(chainID)
# oceanutil.recordDeployedContracts(address_file)
# oceantestutil.fillAccountsWithOCEAN()

@enforce_types
def teardown_module():
global PREV

# @enforce_types
# def teardown_function():
# networkutil.disconnect()
if PREV.WEB3_INFURA_PROJECT_ID is None:
del os.environ["WEB3_INFURA_PROJECT_ID"]
else:
os.environ["WEB3_INFURA_PROJECT_ID"] = PREV.WEB3_INFURA_PROJECT_ID