Exemplo n.º 1
0
def deploy_contract(
        web3,
        contracts_compiled_data,
        contract_name,
        transaction,
        txn_wait=200,
        args=[]
):
    contract_interface = contracts_compiled_data[contract_name]

    # Instantiate and deploy contract
    contract = web3.eth.contract(
        abi=contract_interface['abi'],
        bytecode=contract_interface['bytecode']
    )

    # Get transaction hash from deployed contract
    txhash = contract.deploy(transaction=transaction, args=args)

    # Get tx receipt to get contract address
    receipt = check_succesful_tx(web3, txhash, txn_wait)
    print('{0} address: {1}. Gas used: {2}'.format(
        contract_name,
        receipt['contractAddress'],
        receipt['gasUsed'])
    )
    return receipt['contractAddress']
Exemplo n.º 2
0
def register_token_network(
    web3: Web3,
    private_key: str,
    token_registry_abi: Dict,
    token_registry_address: str,
    token_address: str,
    wait=10,
    gas_limit=4000000,
):
    """Register token with a TokenNetworkRegistry contract."""
    token_network_registry = web3.eth.contract(
        abi=token_registry_abi,
        address=token_registry_address,
    )
    token_network_registry = PrivateContract(token_network_registry)
    txhash = token_network_registry.functions.createERC20TokenNetwork(
        token_address, ).transact(
            {'gas_limit': gas_limit},
            private_key=private_key,
        )
    log.debug(
        "calling createERC20TokenNetwork(%s) txHash=%s" % (
            token_address,
            encode_hex(txhash),
        ), )
    receipt = check_succesful_tx(web3, txhash, wait)

    print(
        'TokenNetwork address: {0} Gas used: {1}'.format(
            token_network_registry.functions.token_to_token_networks(
                token_address).call(),
            receipt['gasUsed'],
        ), )
    def deploy(
        self,
        contract_name: str,
        args=None,
    ):
        if args is None:
            args = list()
        contract_interface = self.contract_manager.get_contract(
            contract_name, )

        # Instantiate and deploy contract
        contract = self.web3.eth.contract(
            abi=contract_interface['abi'],
            bytecode=contract_interface['bin'],
        )
        contract = PrivateContract(contract)

        # Get transaction hash from deployed contract
        txhash = self.send_deployment_transaction(contract, args)

        # Get tx receipt to get contract address
        log.debug("Deploying %s txHash=%s" %
                  (contract_name, encode_hex(txhash)))
        receipt = check_succesful_tx(self.web3, txhash, self.wait)
        log.info(
            '{0} address: {1}. Gas used: {2}'.format(
                contract_name,
                receipt['contractAddress'],
                receipt['gasUsed'],
            ), )
        return receipt
Exemplo n.º 4
0
def deploy_contract(
    web3,
    contracts_compiled_data,
    contract_name,
    transaction,
    txn_wait=200,
    args=None,
):
    contract_interface = contracts_compiled_data[contract_name]

    # Instantiate and deploy contract
    contract = web3.eth.contract(
        abi=contract_interface['abi'],
        bytecode=contract_interface['bin'],
    )

    log.info(f'Deploying {contract_name}')
    # Get transaction hash from deployed contract
    txhash = contract.deploy(transaction=transaction, args=args)

    # Get tx receipt to get contract address
    log.debug(f"TxHash: {txhash}")
    receipt = check_succesful_tx(web3, txhash, txn_wait)
    log.info(
        '{0} address: {1}. Gas used: {2}'.format(
            contract_name,
            receipt['contractAddress'],
            receipt['gasUsed'],
        ), )
    return receipt['contractAddress']
def deprecation_test(
    ctx,
    private_key,
    rpc_provider,
    wait,
    gas_price,
    gas_limit,
):
    setup_ctx(ctx, private_key, rpc_provider, wait, gas_price, gas_limit)
    deployer = ctx.obj['deployer']

    # We deploy the Raiden Network contracts and register a token network
    token_amount = MAX_ETH_CHANNEL_PARTICIPANT * 6
    (
        token_network_registry,
        token_network,
        token_contract,
    ) = deprecation_test_setup(deployer, token_amount)

    log.info('Checking that channels can be opened and deposits can be made.')

    # Check that we can open channels and deposit on behalf of A and B
    # Some arbitrary Ethereum addresses
    A = '0x6AA63296FA94975017244769F00F0c64DB7d7115'
    B = '0xc9a4fad99B6d7D3e48D18d2585470cd8f27FA61e'
    channel_identifier = open_and_deposit(A, B, token_network, deployer)
    log.info('Seding transaction to activate the deprecation switch.')

    # Activate deprecation switch
    txhash = token_network.functions.deprecate().transact(
        deployer.transaction,
        private_key=deployer.private_key,
    )
    log.debug(f'Deprecation txHash={encode_hex(txhash)}')
    check_succesful_tx(deployer.web3, txhash, deployer.wait)
    assert token_network.functions.safety_deprecation_switch().call() is True

    log.info(
        'Checking that channels cannot be opened anymore and no more deposits are allowed.'
    )

    # Check that we cannot open more channels or deposit
    C = '0x5a23cedB607684118ccf7906dF3e24Efd2964719'
    D = '0x3827B9cDc68f061aa614F1b97E23664ef3b9220A'
    open_and_deposit(C, D, token_network, deployer, channel_identifier, False)

    log.info('Deprecation switch test OK.')
Exemplo n.º 6
0
def main(**kwargs):
    rpc_provider = kwargs['rpc_provider']
    json_file = kwargs['json']
    owner = kwargs['owner']
    supply = kwargs['supply']
    token_name = kwargs['token_name']
    token_decimals = kwargs['token_decimals']
    token_symbol = kwargs['token_symbol']
    token_address = kwargs['token_address']
    supply *= 10**(token_decimals)
    txn_wait = kwargs['wait']
    gas_price = kwargs['gas_price']

    print('''Make sure chain is running, you can connect to it and it is synced,
          or you'll get timeout''')

    web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={'timeout': 60}))
    print('Web3 provider is', web3.providers[0])

    owner = owner or web3.eth.accounts[0]
    assert owner and is_address(owner), 'Invalid owner provided.'
    owner = to_checksum_address(owner)
    print('Owner is', owner)
    assert web3.eth.getBalance(owner) > 0, 'Account with insuficient funds.'

    transaction = {'from': owner}
    if gas_price == 0:
        transaction['gasPrice'] = gas_price

    with open(json_file) as json_data:
        contracts_compiled_data = json.load(json_data)

        if not token_address:
            token_address = deploy_contract(
                web3,
                contracts_compiled_data,
                'CustomToken',
                transaction,
                txn_wait,
                [supply, token_decimals, token_name, token_symbol]
            )

        assert token_address and is_address(token_address)
        token_address = to_checksum_address(token_address)

        secret_registry_address = deploy_contract(
            web3,
            contracts_compiled_data,
            'SecretRegistry',
            transaction,
            txn_wait
        )

        token_network_registry_address = deploy_contract(
            web3,
            contracts_compiled_data,
            'TokenNetworksRegistry',
            transaction,
            txn_wait,
            [secret_registry_address, int(web3.version.network)]
        )

        token_network_registry = instantiate_contract(
            web3,
            contracts_compiled_data,
            'TokenNetworksRegistry',
            token_network_registry_address
        )

        txhash = token_network_registry.transact(transaction).createERC20TokenNetwork(
            token_address
        )
        receipt = check_succesful_tx(web3, txhash, txn_wait)

        print('TokenNetwork address: {0}. Gas used: {1}'.format(
            token_network_registry.call().token_to_token_networks(token_address),
            receipt['gasUsed'])
        )
Exemplo n.º 7
0
def main(
    rpc_provider,
    owner,
    wait,
    gas_price,
    gas_limit,
    deploy_token,
    supply,
    token_name,
    token_decimals,
    token_symbol,
    token_address,
):
    supply *= 10**token_decimals

    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger('web3').setLevel(logging.INFO)
    logging.getLogger('urllib3').setLevel(logging.INFO)

    web3 = Web3(HTTPProvider(rpc_provider, request_kwargs={'timeout': 60}))
    web3.middleware_stack.inject(geth_poa_middleware, layer=0)
    print('Web3 provider is', web3.providers[0])

    owner = owner or web3.eth.accounts[0]
    assert owner and is_address(owner), 'Invalid owner provided.'
    owner = to_checksum_address(owner)
    print('Owner is', owner)
    assert web3.eth.getBalance(owner) > 0, 'Account with insuficient funds.'

    password = getpass(f'Enter password for {owner}:')

    transaction = {'from': owner, 'gas': gas_limit}
    if gas_price != 0:
        transaction['gasPrice'] = gas_price * 10**9

    contract_manager = ContractManager(CONTRACTS_SOURCE_DIRS)
    contract_manager._compile_all_contracts()
    contracts_compiled_data = contract_manager._contracts

    deployed_contracts = {}

    web3.personal.unlockAccount(owner, password)
    deployed_contracts[CONTRACT_ENDPOINT_REGISTRY] = deploy_contract(
        web3,
        contracts_compiled_data,
        CONTRACT_ENDPOINT_REGISTRY,
        transaction,
        wait,
    )

    web3.personal.unlockAccount(owner, password)
    secret_registry_address = deploy_contract(
        web3,
        contracts_compiled_data,
        CONTRACT_SECRET_REGISTRY,
        transaction,
        wait,
    )
    deployed_contracts[CONTRACT_SECRET_REGISTRY] = secret_registry_address

    web3.personal.unlockAccount(owner, password)
    token_network_registry_address = deploy_contract(
        web3,
        contracts_compiled_data,
        CONTRACT_TOKEN_NETWORK_REGISTRY,
        transaction,
        wait,
        [
            secret_registry_address,
            int(web3.version.network),
            DEPLOY_SETTLE_TIMEOUT_MIN,
            DEPLOY_SETTLE_TIMEOUT_MAX,
        ],
    )
    deployed_contracts[
        CONTRACT_TOKEN_NETWORK_REGISTRY] = token_network_registry_address

    if deploy_token:
        if not token_address:
            web3.personal.unlockAccount(owner, password)
            deployed_contracts[
                'CustomToken'] = token_address = deploy_contract(
                    web3,
                    contracts_compiled_data,
                    'CustomToken',
                    transaction,
                    wait,
                    [supply, token_decimals, token_name, token_symbol],
                )

        assert token_address and is_address(token_address)
        token_address = to_checksum_address(token_address)

        token_network_registry = instantiate_contract(
            web3,
            contracts_compiled_data,
            CONTRACT_TOKEN_NETWORK_REGISTRY,
            token_network_registry_address,
        )

        web3.personal.unlockAccount(owner, password)
        txhash = token_network_registry.transact(
            transaction).createERC20TokenNetwork(token_address, )
        receipt = check_succesful_tx(web3, txhash, wait)

        print(
            'TokenNetwork address: {0}. Gas used: {1}'.format(
                token_network_registry.functions.token_to_token_networks(
                    token_address).call(),
                receipt['gasUsed'],
            ), )
    print(json.dumps(deployed_contracts, indent=4))
def open_and_deposit(
    A,
    B,
    token_network,
    deployer,
    channel_identifier=None,
    txn_success_status=True,
):
    try:
        txhash = token_network.functions.openChannel(
            A, B, DEPLOY_SETTLE_TIMEOUT_MIN).transact(
                deployer.transaction,
                private_key=deployer.private_key,
            )
        log.debug(
            f'Opening a channel between {A} and {B} txHash={encode_hex(txhash)}'
        )
        check_succesful_tx(deployer.web3, txhash, deployer.wait)

        # Get the channel identifier
        channel_identifier = token_network.functions.getChannelIdentifier(
            A, B).call()
        success_status = True
    except ValueError as ex:
        success_status = False
        log.info(f'Cannot open a new channel {ex}')

    assert txn_success_status == success_status, \
        f'openChannel txn status is {success_status} instead of {txn_success_status}'

    assert channel_identifier is not None
    try:
        txhash = token_network.functions.setTotalDeposit(
            channel_identifier,
            A,
            int(MAX_ETH_CHANNEL_PARTICIPANT / 2),
            B,
        ).transact(
            deployer.transaction,
            private_key=deployer.private_key,
        )
        log.debug(
            f'Depositing {MAX_ETH_CHANNEL_PARTICIPANT} tokens for {A} in a channel with '
            f'identifier={channel_identifier} and partner= {B} txHash={encode_hex(txhash)}',
        )
        check_succesful_tx(deployer.web3, txhash, deployer.wait)
        success_status = True
    except ValueError as ex:
        success_status = False
        log.info(
            f'Cannot deposit more tokens in channel={channel_identifier}, {ex}'
        )

    assert txn_success_status == success_status, \
        f'setTotalDeposit txn status is {success_status} instead of {txn_success_status}'

    try:
        txhash = token_network.functions.setTotalDeposit(
            channel_identifier,
            B,
            int(MAX_ETH_CHANNEL_PARTICIPANT / 2),
            A,
        ).transact(
            deployer.transaction,
            private_key=deployer.private_key,
        )
        log.debug(
            f'Depositing {MAX_ETH_CHANNEL_PARTICIPANT} tokens for {B} in a channel with '
            f'identifier={channel_identifier} and partner= {A} txHash={encode_hex(txhash)}',
        )
        check_succesful_tx(deployer.web3, txhash, deployer.wait)
        success_status = True
    except ValueError as ex:
        success_status = False
        log.info(
            f'Cannot deposit more tokens in channel={channel_identifier}, {ex}'
        )

    assert txn_success_status == success_status, \
        f'setTotalDeposit txn status is {success_status} instead of {txn_success_status}'

    return channel_identifier
def deprecation_test_setup(deployer, token_amount):
    deployed_contracts = deploy_raiden_contracts(deployer)['contracts']

    token_network_registry_abi = deployer.contract_manager.get_contract_abi(
        CONTRACT_TOKEN_NETWORK_REGISTRY, )
    token_network_registry = deployer.web3.eth.contract(
        abi=token_network_registry_abi,
        address=deployed_contracts[CONTRACT_TOKEN_NETWORK_REGISTRY]['address'],
    )
    token_network_registry = PrivateContract(token_network_registry)

    token_decimals = 18
    multiplier = 10**token_decimals
    token_supply = 10**6 * multiplier
    token_amount = int(token_amount * multiplier)

    deployed_token = deploy_token_contract(
        deployer,
        token_supply,
        token_decimals,
        'TestToken',
        'TTT',
        CONTRACT_CUSTOM_TOKEN,
    )
    token_address = deployed_token[CONTRACT_CUSTOM_TOKEN]
    token_abi = deployer.contract_manager.get_contract_abi(
        CONTRACT_CUSTOM_TOKEN)
    token_contract = deployer.web3.eth.contract(
        abi=token_abi,
        address=token_address,
    )
    token_contract = PrivateContract(token_contract)

    # Mint some tokens for the owner
    txhash = token_contract.functions.mint(token_amount).transact(
        deployer.transaction,
        private_key=deployer.private_key,
    )

    log.debug(f'Minting tokens txHash={encode_hex(txhash)}')
    check_succesful_tx(deployer.web3, txhash, deployer.wait)
    assert token_contract.functions.balanceOf(
        deployer.owner).call() >= token_amount

    abi = deployer.contract_manager.get_contract_abi(
        CONTRACT_TOKEN_NETWORK_REGISTRY)
    token_network_address = register_token_network(
        web3=deployer.web3,
        private_key=deployer.private_key,
        token_registry_abi=abi,
        token_registry_address=deployed_contracts[
            CONTRACT_TOKEN_NETWORK_REGISTRY]['address'],
        token_address=token_address,
        wait=deployer.wait,
    )

    token_network_abi = deployer.contract_manager.get_contract_abi(
        CONTRACT_TOKEN_NETWORK)
    token_network = deployer.web3.eth.contract(
        abi=token_network_abi,
        address=token_network_address,
    )
    token_network = PrivateContract(token_network)

    log.info(
        f'Registered the token and created a TokenNetwork contract at {token_network_address}.',
    )

    txhash = token_contract.functions.approve(
        token_network.address, token_amount).transact(
            deployer.transaction,
            private_key=deployer.private_key,
        )
    log.debug(
        f'Aproving tokens for the TokenNetwork contract txHash={encode_hex(txhash)}'
    )
    check_succesful_tx(deployer.web3, txhash, deployer.wait)

    assert token_contract.functions.allowance(
        deployer.owner,
        token_network.address,
    ).call() >= token_amount
    log.info(
        f'Approved {token_amount} tokens for the TokenNetwork contract '
        f'from owner {deployer.owner}.', )

    return (token_network_registry, token_network, token_contract)