Exemple #1
0
def test_autofetch(network, config):
    network.connect("mainnet")
    with pytest.raises(ValueError):
        Contract("0xdAC17F958D2ee523a2206206994597C13D831ec7")

    config.settings["autofetch_sources"] = True
    Contract("0xdAC17F958D2ee523a2206206994597C13D831ec7")
Exemple #2
0
def test_alias(network):
    network.connect("mainnet")
    contract = Contract.from_explorer("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2")

    contract.set_alias("testalias")

    assert contract.alias == "testalias"
    assert Contract("testalias") == contract

    contract.set_alias(None)

    assert contract.alias is None
    with pytest.raises(ValueError):
        Contract("testalias")
def test_autofetch_missing(network, config, mocker):
    # an issue woth pytest-mock prevents spying on Contract.from_explorer,
    # so we watch requests.get which is only called inside Contract.from_explorer
    mocker.spy(requests, "get")

    network.connect("mainnet")
    config.settings["autofetch_sources"] = True

    with pytest.raises(ValueError):
        Contract("0xff031750F29b24e6e5552382F6E0c065830085d2")
    assert requests.get.call_count == 2

    with pytest.raises(ValueError):
        Contract("0xff031750F29b24e6e5552382F6E0c065830085d2")
    assert requests.get.call_count == 2
Exemple #4
0
def test_deprecated_init_ethpm(ipfs_mock, network):
    network.connect("ropsten")

    with pytest.warns(DeprecationWarning):
        old = Contract("ComplexNothing", manifest_uri="ipfs://testipfs-complex")

    assert old == Contract.from_ethpm("ComplexNothing", manifest_uri="ipfs://testipfs-complex")
Exemple #5
0
def test_retrieve_existing(network):
    network.connect("mainnet")
    with pytest.warns(BrownieCompilerWarning):
        new = Contract.from_explorer("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2")

    existing = Contract("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2")
    assert new == existing
Exemple #6
0
 def _load_deployments(self) -> None:
     if not CONFIG["active_network"].get("persist", None):
         return
     network = CONFIG["active_network"]["name"]
     path = self._path.joinpath(f"build/deployments/{network}")
     path.mkdir(exist_ok=True)
     deployments = list(
         self._path.glob(
             f"build/deployments/{CONFIG['active_network']['name']}/*.json")
     )
     deployments.sort(key=lambda k: k.stat().st_mtime)
     for build_json in deployments:
         with build_json.open() as fp:
             build = json.load(fp)
         if build["contractName"] not in self._containers:
             build_json.unlink()
             continue
         if "pcMap" in build:
             contract = ProjectContract(self, build, build_json.stem)
         else:
             contract = Contract(  # type: ignore
                 build["contractName"], build_json.stem, build["abi"])
             contract._project = self
         container = self._containers[build["contractName"]]
         _add_contract(contract)
         container._contracts.append(contract)
Exemple #7
0
def test_namespace_collision(tester, build):
    build['abi'].append({
        'constant':
        False,
        'inputs': [{
            'name': '_to',
            'type': 'address'
        }, {
            'name': '_value',
            'type': 'uint256'
        }, {
            'name': '_test',
            'type': 'uint256'
        }],
        'name':
        'bytecode',
        'outputs': [{
            'name': '',
            'type': 'bool'
        }],
        'payable':
        False,
        'stateMutability':
        'nonpayable',
        'type':
        'function'
    })
    with pytest.raises(AttributeError):
        Contract(tester.address, None, build['abi'])
Exemple #8
0
def test_overloaded(testproject, tester, build):
    build["abi"].append(
        {
            "constant": False,
            "inputs": [
                {"name": "_to", "type": "address"},
                {"name": "_value", "type": "uint256"},
                {"name": "_test", "type": "uint256"},
            ],
            "name": "revertStrings",
            "outputs": [{"name": "", "type": "bool"}],
            "payable": False,
            "stateMutability": "nonpayable",
            "type": "function",
        }
    )
    del testproject.BrownieTester[0]
    c = Contract(tester.address, None, build["abi"])
    fn = c.revertStrings
    assert type(fn) == OverloadedMethod
    assert len(fn) == 2
    assert type(fn["uint"]) == ContractTx
    assert fn["address", "uint256", "uint256"] == fn["address, uint256, uint256"]
    assert fn["uint"] == fn["uint256"]
    assert fn["uint"] != fn["address, uint256, uint256"]
    repr(fn)
Exemple #9
0
def test_namespace_collision():
    b = deepcopy(build.get('Token'))
    b['abi'].append({
        'constant':
        False,
        'inputs': [{
            'name': '_to',
            'type': 'address'
        }, {
            'name': '_value',
            'type': 'uint256'
        }, {
            'name': '_test',
            'type': 'uint256'
        }],
        'name':
        'bytecode',
        'outputs': [{
            'name': '',
            'type': 'bool'
        }],
        'payable':
        False,
        'stateMutability':
        'nonpayable',
        'type':
        'function'
    })
    with pytest.raises(AttributeError):
        Contract(str(accounts[1]), b, None)
Exemple #10
0
def test_namespace_collision(tester, build):
    build["abi"].append({
        "constant":
        False,
        "inputs": [
            {
                "name": "_to",
                "type": "address"
            },
            {
                "name": "_value",
                "type": "uint256"
            },
            {
                "name": "_test",
                "type": "uint256"
            },
        ],
        "name":
        "bytecode",
        "outputs": [{
            "name": "",
            "type": "bool"
        }],
        "payable":
        False,
        "stateMutability":
        "nonpayable",
        "type":
        "function",
    })
    with pytest.raises(AttributeError):
        Contract(None, tester.address, build["abi"])
Exemple #11
0
def test_existing_different_chains(network):
    network.connect("mainnet")
    Contract.from_explorer("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2")

    network.disconnect()
    network.connect("ropsten")
    with pytest.raises(ValueError):
        Contract("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2")
Exemple #12
0
def _find_contract(address: Any) -> Any:
    address = _resolve_address(address)
    if address in _contract_map:
        return _contract_map[address]
    if "chainid" in CONFIG.active_network:
        try:
            from brownie.network.contract import Contract

            return Contract(address)
        except ValueError:
            pass
Exemple #13
0
def _find_contract(address: Any) -> Any:
    address = _resolve_address(address)
    if address in _contract_map:
        return _contract_map[address]
    if CONFIG.network_type == "live":
        try:
            from brownie.network.contract import Contract

            return Contract(address)
        except ValueError:
            pass
Exemple #14
0
def test_set_methods():
    c = Contract(str(accounts[1]), build.get('Token'), None)
    for item in build.get('Token')['abi']:
        if item['type'] != "function":
            if 'name' not in item:
                continue
            assert not hasattr(c, item['name'])
        elif item['stateMutability'] in ('view', 'pure'):
            assert type(getattr(c, item['name'])) == ContractCall
        else:
            assert type(getattr(c, item['name'])) == ContractTx
Exemple #15
0
def test_as_proxy_for(network, original, impl):
    network.connect("mainnet")
    original = Contract.from_explorer(original)
    proxy = Contract.from_explorer(original, as_proxy_for=impl)
    implementation = Contract(impl)

    assert original.abi == proxy.abi
    assert original.address == proxy.address

    assert proxy.abi == implementation.abi
    assert proxy.address != implementation.address
Exemple #16
0
def test_as_proxy_for(network):
    network.connect("mainnet")
    original = Contract.from_explorer("0x3d9819210a31b4961b30ef54be2aed79b9c9cd3b")
    proxy = Contract.from_explorer(
        "0x3d9819210a31b4961b30ef54be2aed79b9c9cd3b",
        as_proxy_for="0x97BD4Cc841FC999194174cd1803C543247a014fe",
    )
    implementation = Contract("0x97BD4Cc841FC999194174cd1803C543247a014fe")
    assert original.abi != proxy.abi
    assert original.address == proxy.address

    assert proxy.abi == implementation.abi
    assert proxy.address != implementation.address
Exemple #17
0
def test_as_proxy_for(network):
    proxy = "0xAfE212AEDf1c8dCd0E470d73B3B4035D32A75Efd"
    impl = "0x098DCb095318A8B5321c5f2DB3fA04a55A780A20"
    network.connect("ropsten")

    original = Contract.from_explorer(proxy)
    proxy = Contract.from_explorer(proxy, as_proxy_for=impl)
    implementation = Contract(impl)

    assert original.abi == proxy.abi
    assert original.address == proxy.address

    assert proxy.abi == implementation.abi
    assert proxy.address != implementation.address
Exemple #18
0
def test_as_proxy_for(network):
    network.connect("mainnet")
    original = Contract.from_explorer("0x3d9819210a31b4961b30ef54be2aed79b9c9cd3b")
    proxy = Contract.from_explorer(
        "0x3d9819210a31b4961b30ef54be2aed79b9c9cd3b",
        as_proxy_for="0x7b5e3521a049C8fF88e6349f33044c6Cc33c113c",
    )
    implementation = Contract("0x7b5e3521a049C8fF88e6349f33044c6Cc33c113c")

    assert original.abi == proxy.abi
    assert original.address == proxy.address

    assert proxy.abi == implementation.abi
    assert proxy.address != implementation.address
Exemple #19
0
def test_as_proxy_for(network):
    network.connect("mainnet")
    original = Contract.from_explorer(
        "0x3d9819210a31b4961b30ef54be2aed79b9c9cd3b")
    proxy = Contract.from_explorer(
        "0x3d9819210a31b4961b30ef54be2aed79b9c9cd3b",
        as_proxy_for="0x9d0a0443ff4bb04391655b8cd205683d9fa75550",
    )
    implementation = Contract("0x9d0a0443ff4bb04391655b8cd205683d9fa75550")

    assert original.abi == proxy.abi
    assert original.address == proxy.address

    assert proxy.abi == implementation.abi
    assert proxy.address != implementation.address
Exemple #20
0
def test_as_proxy_for(network):
    network.connect("mainnet")
    original = Contract.from_explorer(
        "0x3d9819210a31b4961b30ef54be2aed79b9c9cd3b")
    proxy = Contract.from_explorer(
        "0x3d9819210a31b4961b30ef54be2aed79b9c9cd3b",
        as_proxy_for="0xAf601CbFF871d0BE62D18F79C31e387c76fa0374",
    )
    implementation = Contract("0xAf601CbFF871d0BE62D18F79C31e387c76fa0374")

    assert original.abi == proxy.abi
    assert original.address == proxy.address

    assert proxy.abi == implementation.abi
    assert proxy.address != implementation.address
Exemple #21
0
def test_overloaded(testproject, tester, build):
    build['abi'].append({
        'constant':
        False,
        'inputs': [{
            'name': '_to',
            'type': 'address'
        }, {
            'name': '_value',
            'type': 'uint256'
        }, {
            'name': '_test',
            'type': 'uint256'
        }],
        'name':
        'revertStrings',
        'outputs': [{
            'name': '',
            'type': 'bool'
        }],
        'payable':
        False,
        'stateMutability':
        'nonpayable',
        'type':
        'function'
    })
    del testproject.BrownieTester[0]
    c = Contract(tester.address, None, build['abi'])
    fn = c.revertStrings
    assert type(fn) == OverloadedMethod
    assert len(fn) == 2
    assert type(fn['uint']) == ContractTx
    assert fn['address', 'uint256',
              'uint256'] == fn['address, uint256, uint256']
    assert fn['uint'] == fn['uint256']
    assert fn['uint'] != fn['address, uint256, uint256']
    repr(fn)
Exemple #22
0
 def _load_deployments(self) -> None:
     if CONFIG.network_type != "live":
         return
     chainid = CONFIG.active_network["chainid"]
     path = self._path.joinpath(f"build/deployments/{chainid}")
     path.mkdir(exist_ok=True)
     deployments = list(path.glob("*.json"))
     deployments.sort(key=lambda k: k.stat().st_mtime)
     for build_json in deployments:
         with build_json.open() as fp:
             build = json.load(fp)
         if build["contractName"] not in self._containers:
             build_json.unlink()
             continue
         if "pcMap" in build:
             contract = ProjectContract(self, build, build_json.stem)
         else:
             contract = Contract(  # type: ignore
                 build["contractName"], build_json.stem, build["abi"])
             contract._project = self
         container = self._containers[build["contractName"]]
         _add_contract(contract)
         container._contracts.append(contract)
Exemple #23
0
    def _load_deployments(self) -> None:
        if CONFIG.network_type != "live" and not CONFIG.settings[
                "dev_deployment_artifacts"]:
            return
        chainid = CONFIG.active_network[
            "chainid"] if CONFIG.network_type == "live" else "dev"
        path = self._build_path.joinpath(f"deployments/{chainid}")
        path.mkdir(exist_ok=True)
        deployments = list(path.glob("*.json"))
        deployments.sort(key=lambda k: k.stat().st_mtime)
        deployment_map = self._load_deployment_map()
        for build_json in deployments:
            with build_json.open() as fp:
                build = json.load(fp)

            contract_name = build["contractName"]
            if contract_name not in self._containers:
                build_json.unlink()
                continue
            if "pcMap" in build:
                contract = ProjectContract(self, build, build_json.stem)
            else:
                contract = Contract(  # type: ignore
                    contract_name, build_json.stem, build["abi"])
                contract._project = self
            container = self._containers[contract_name]
            _add_contract(contract)
            container._contracts.append(contract)

            # update deployment map for the current chain
            instances = deployment_map.setdefault(chainid, {}).setdefault(
                contract_name, [])
            if build_json.stem in instances:
                instances.remove(build_json.stem)
            instances.insert(0, build_json.stem)

        self._save_deployment_map(deployment_map)
Exemple #24
0
def test_overloaded():
    b = deepcopy(build.get('Token'))
    b['abi'].append({
        'constant':
        False,
        'inputs': [{
            'name': '_to',
            'type': 'address'
        }, {
            'name': '_value',
            'type': 'uint256'
        }, {
            'name': '_test',
            'type': 'uint256'
        }],
        'name':
        'transfer',
        'outputs': [{
            'name': '',
            'type': 'bool'
        }],
        'payable':
        False,
        'stateMutability':
        'nonpayable',
        'type':
        'function'
    })
    c = Contract(str(accounts[1]), b, None)
    fn = c.transfer
    assert type(fn) == OverloadedMethod
    assert len(fn) == 2
    assert type(fn['address', 'uint']) == ContractTx
    assert fn['address, uint256'] != fn['address, uint256, uint256']
    assert fn['address', 'uint'] == fn['address,uint256']
    repr(fn)
Exemple #25
0
def test_alias_not_exists(network):
    network.connect("mainnet")

    with pytest.raises(ValueError):
        Contract("doesnotexist")
Exemple #26
0
def test_retrieve_existing(network):
    network.connect("mainnet")
    new = Contract.from_explorer("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2")

    existing = Contract("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2")
    assert new == existing
Exemple #27
0
def test_deprecated_init_abi(tester):
    old = Contract("BrownieTester", tester.address, tester.abi)
    assert old == Contract.from_abi("BrownieTester", tester.address, tester.abi)
def test_deprecated_init_abi(tester):
    with pytest.warns(DeprecationWarning):
        old = Contract("BrownieTester", tester.address, tester.abi)

    assert old == Contract.from_abi("BrownieTester", tester.address,
                                    tester.abi)
Exemple #29
0
def test_contract_from_ethpm_no_deployments(ipfs_mock, network):
    network.connect("kovan")
    with pytest.raises(ContractNotFound):
        Contract("ComplexNothing", manifest_uri="ipfs://testipfs-complex")
Exemple #30
0
def test_contract_from_ethpm_multiple_deployments(ipfs_mock, network):
    network.connect("mainnet")
    with pytest.raises(ValueError):
        Contract("ComplexNothing", manifest_uri="ipfs://testipfs-complex")