Exemple #1
0
def create_new_offer(bc_interface, bc_contract, energy, price, seller):
    unlock_account(bc_interface.chain, bc_interface.users[seller].address)
    bc_energy = int(energy * BC_NUM_FACTOR)
    tx_hash = bc_contract.functions.offer(bc_energy, int(
        price * BC_NUM_FACTOR)).transact(
            {"from": bc_interface.users[seller].address})
    tx_hash_hex = hex(int.from_bytes(tx_hash, byteorder='big'))
    log.debug(f"tx_hash of New Offer {tx_hash_hex}")

    tx_receipt = bc_interface.chain.eth.waitForTransactionReceipt(tx_hash)
    status = tx_receipt["status"]
    log.debug(f"tx_receipt Status: {status}")
    assert status > 0
    wait_for_node_synchronization(bc_interface)

    def get_offer_id():
        return bc_contract.events.NewOffer().processReceipt(
            tx_receipt)[0]['args']["offerId"]

    wait_until_timeout_blocking(lambda: get_offer_id() is not 0, timeout=20)

    offer_id = get_offer_id()

    log.debug(f"offer_id: {offer_id}")
    assert offer_id is not 0
    return offer_id
Exemple #2
0
def create_market_contract(bc_interface, duration_s, listeners=[]):
    if not bc_interface:
        return None
    contract = bc_interface.init_contract(
        "Market.sol", "Market",
        [bc_interface.contracts['ClearingToken'].address, duration_s],
        listeners)
    clearing_contract_instance = bc_interface.contracts['ClearingToken']
    market_address = contract.address
    unlock_account(bc_interface.chain, bc_interface.chain.eth.accounts[0])
    tx_hash = clearing_contract_instance.functions \
        .globallyApprove(market_address, 10 ** 18) \
        .transact({'from': bc_interface.chain.eth.accounts[0]})
    tx_receipt = bc_interface.chain.eth.waitForTransactionReceipt(tx_hash)
    status = tx_receipt["status"]
    log.debug(f"tx_receipt Status: {status}")
    approve_retval = clearing_contract_instance.events \
        .ApproveClearingMember() \
        .processReceipt(tx_receipt)
    wait_for_node_synchronization(bc_interface)
    assert len(approve_retval) > 0
    assert approve_retval[0]["args"][
        "approver"] == bc_interface.chain.eth.accounts[0]
    assert approve_retval[0]["args"]["market"] == market_address
    assert approve_retval[0]["event"] == "ApproveClearingMember"
    return contract
Exemple #3
0
    def __getitem__(self, username_or_addr):
        unlock_account(self._chain, self._chain.eth.accounts[0])

        user = self._users.get(username_or_addr)
        if not user:
            if username_or_addr.startswith("0x"):
                raise KeyError("User with address {} doesn't exist".format(
                    username_or_addr))
            self._users[username_or_addr] = user = self._mk_user(
                username_or_addr)
            self._users[user.address] = user
            self._chain.eth.waitForTransactionReceipt(
                self._contracts["ClearingToken"].functions.globallyApprove(
                    user.address, self._default_balance).transact(
                        {"from": self._chain.eth.accounts[0]}))
        return user
Exemple #4
0
def trade_offer(bc_interface, bc_contract, offer_id, energy, buyer):
    unlock_account(bc_interface.chain, bc_interface.users[buyer].address)
    trade_energy = int(energy * BC_NUM_FACTOR)
    tx_hash = bc_contract.functions.trade(offer_id, trade_energy). \
        transact({"from": bc_interface.users[buyer].address})
    tx_hash_hex = hex(int.from_bytes(tx_hash, byteorder='big'))
    log.debug(f"tx_hash of Trade {tx_hash_hex}")
    tx_receipt = bc_interface.chain.eth.waitForTransactionReceipt(tx_hash)
    status = tx_receipt["status"]
    log.debug(f"tx_receipt Status: {status}")
    assert status > 0

    wait_for_node_synchronization(bc_interface)
    new_trade_retval = bc_contract.events.NewTrade().processReceipt(tx_receipt)
    if len(new_trade_retval) == 0:
        wait_until_timeout_blocking(lambda: len(bc_contract.events.NewTrade(
        ).processReceipt(tx_receipt)) is not 0,
                                    timeout=20)
        new_trade_retval = bc_contract.events.NewTrade().processReceipt(
            tx_receipt)
        log.debug(f"new_trade_retval after retry: {new_trade_retval}")

    offer_changed_retval = bc_contract.events \
        .OfferChanged() \
        .processReceipt(tx_receipt)

    if len(offer_changed_retval) > 0 and \
            not offer_changed_retval[0]['args']['success']:
        raise InvalidBlockchainOffer(
            f"Invalid blockchain offer changed. Transaction return "
            f"value {offer_changed_retval}")

    if not new_trade_retval[0]['args']['success']:
        raise InvalidBlockchainTrade(
            f"Invalid blockchain trade. Transaction return "
            f"value {new_trade_retval}")

    trade_id = new_trade_retval[0]['args']['tradeId']
    new_offer_id = offer_changed_retval[0]['args']['newOfferId'] \
        if len(offer_changed_retval) > 0 \
        else None
    return trade_id, new_offer_id
Exemple #5
0
    def init_contract(self, contract_filename: str, contract_name: str,
                      args: list, listeners: Optional[List] = None, id_: str = None):

        log.trace("Initializing contract '%s'", contract_name)
        compiled_sol = compile_source(get_cached_joined_contract_source(contract_filename))
        contract_interface = compiled_sol['<stdin>:' + contract_name]

        contract = self.chain.eth.contract(abi=contract_interface['abi'],
                                           bytecode=contract_interface['bin'])
        unlock_account(self.chain, self.chain.eth.accounts[0])
        tx_hash = contract.constructor(*args).transact({'from': self.chain.eth.accounts[0]})
        wait_until_timeout_blocking(lambda: self.chain.eth.waitForTransactionReceipt(tx_hash).
                                    contractAddress is not None, timeout=20)
        contract_address = self.chain.eth.waitForTransactionReceipt(tx_hash).contractAddress
        contract = self.chain.eth.contract(address=contract_address,
                                           abi=contract_interface['abi'],
                                           ContractFactoryClass=Contract)
        log.debug(f"{contract_name} SmartContract deployed with Address: {contract_address}")
        self.contracts[contract.address] = contract
        if id_:
            self.contracts[id_] = contract
        if listeners:
            self.listeners[contract.address].extend(listeners)
        return contract
Exemple #6
0
def cancel_offer(bc_interface, bc_contract, offer):
    unlock_account(bc_interface.chain,
                   bc_interface.users[offer.seller].address)
    bc_interface.chain.eth.waitForTransactionReceipt(
        bc_contract.functions.cancel(offer.real_id).transact(
            {"from": bc_interface.users[offer.seller].address}))