Python eth_abi.encode_single() Examples

The following are 13 code examples of eth_abi.encode_single(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module eth_abi , or try the search function .
Example #1
Source File: ethereum_classic.py    From clove with GNU General Public License v3.0 7 votes vote down vote up
def find_transaction_details_in_redeem_event(self, recipient_address: str, secret_hash: str, block_number: int):
        # web3.gastracker.io node does not support filtering
        # etc-geth.0xinfra.com not is not stable so it is used only for filtering
        filterable_web3 = Web3(HTTPProvider('https://etc-geth.0xinfra.com/'))

        event_signature_hash = self.web3.sha3(text="RedeemSwap(address,bytes20,bytes32)").hex()
        filter_options = {
            'fromBlock': block_number,
            'address': self.contract_address,
            'topics': [
                event_signature_hash,
                '0x' + encode_single('address', recipient_address).hex(),
                '0x' + encode_single('bytes20', bytes.fromhex(secret_hash)).hex()
            ]
        }

        event_filter = filterable_web3.eth.filter(filter_options)

        for _ in range(ETH_FILTER_MAX_ATTEMPTS):
            events = event_filter.get_all_entries()
            if events:
                return {
                    'secret': events[0]['data'][2:],
                    'transaction_hash': events[0]['transactionHash'].hex()
                } 
Example #2
Source File: proofs.py    From raiden-contracts with MIT License 6 votes vote down vote up
def pack_balance_proof(
    token_network_address: HexAddress,
    chain_identifier: ChainID,
    channel_identifier: ChannelID,
    balance_hash: BalanceHash,
    nonce: Nonce,
    additional_hash: AdditionalHash,
    msg_type: MessageTypeId,
) -> bytes:
    return (
        Web3.toBytes(hexstr=token_network_address)
        + encode_single("uint256", chain_identifier)
        + encode_single("uint256", msg_type)
        + encode_single("uint256", channel_identifier)
        + balance_hash
        + encode_single("uint256", nonce)
        + additional_hash
    ) 
Example #3
Source File: proofs.py    From raiden-contracts with MIT License 6 votes vote down vote up
def pack_cooperative_settle_message(
    token_network_address: HexAddress,
    chain_identifier: ChainID,
    channel_identifier: ChannelID,
    participant1_address: HexAddress,
    participant1_balance: TokenAmount,
    participant2_address: HexAddress,
    participant2_balance: TokenAmount,
) -> bytes:
    return (
        Web3.toBytes(hexstr=token_network_address)
        + encode_single("uint256", chain_identifier)
        + encode_single("uint256", MessageTypeId.COOPERATIVE_SETTLE)
        + encode_single("uint256", channel_identifier)
        + Web3.toBytes(hexstr=participant1_address)
        + encode_single("uint256", participant1_balance)
        + Web3.toBytes(hexstr=participant2_address)
        + encode_single("uint256", participant2_balance)
    ) 
Example #4
Source File: proofs.py    From raiden-contracts with MIT License 6 votes vote down vote up
def pack_withdraw_message(
    token_network_address: HexAddress,
    chain_identifier: ChainID,
    channel_identifier: ChannelID,
    participant: HexAddress,
    amount_to_withdraw: TokenAmount,
    expiration_block: BlockExpiration,
) -> bytes:
    return (
        Web3.toBytes(hexstr=token_network_address)
        + encode_single("uint256", chain_identifier)
        + encode_single("uint256", MessageTypeId.WITHDRAW)
        + encode_single("uint256", channel_identifier)
        + Web3.toBytes(hexstr=participant)
        + encode_single("uint256", amount_to_withdraw)
        + encode_single("uint256", expiration_block)
    ) 
Example #5
Source File: proofs.py    From raiden-contracts with MIT License 6 votes vote down vote up
def pack_reward_proof(
    monitoring_service_contract_address: HexAddress,
    chain_id: ChainID,
    token_network_address: HexAddress,
    non_closing_participant: HexAddress,
    non_closing_signature: Signature,
    reward_amount: TokenAmount,
) -> bytes:
    return (
        Web3.toBytes(hexstr=monitoring_service_contract_address)
        + encode_single("uint256", chain_id)
        + encode_single("uint256", MessageTypeId.MSReward)
        + Web3.toBytes(hexstr=token_network_address)
        + Web3.toBytes(hexstr=non_closing_participant)
        + non_closing_signature
        + encode_single("uint256", reward_amount)
    ) 
Example #6
Source File: proofs.py    From raiden-contracts with MIT License 6 votes vote down vote up
def sign_one_to_n_iou(
    privatekey: PrivateKey,
    sender: HexAddress,
    receiver: HexAddress,
    amount: TokenAmount,
    expiration_block: BlockExpiration,
    one_to_n_address: HexAddress,
    chain_id: ChainID,
    v: int = 27,
) -> bytes:
    iou_hash = eth_sign_hash_message(
        Web3.toBytes(hexstr=one_to_n_address)
        + encode_single("uint256", chain_id)
        + encode_single("uint256", MessageTypeId.IOU)
        + Web3.toBytes(hexstr=sender)
        + Web3.toBytes(hexstr=receiver)
        + encode_single("uint256", amount)
        + encode_single("uint256", expiration_block)
    )
    return sign(privkey=privatekey, msg_hash=iou_hash, v=v) 
Example #7
Source File: test_logging.py    From vyper with Apache License 2.0 5 votes vote down vote up
def test_hashed_indexed_topics_calldata(tester, keccak, get_contract):
    loggy_code = """
event MyLog:
    arg1: indexed(Bytes[36])
    arg2: indexed(int128[2])
    arg3: indexed(String[7])

@external
def foo(a: Bytes[36], b: int128[2], c: String[7]):
    log MyLog(a, b, c)
    """

    c = get_contract(loggy_code)
    tx_hash = c.foo(b"bar", [1, 2], "weird", transact={})
    receipt = tester.get_transaction_receipt(tx_hash.hex())

    # Event id is always the first topic
    event_id = keccak(b"MyLog(bytes,int128[2],string)")
    assert receipt["logs"][0]["topics"][0] == event_id.hex()

    topic1 = f"0x{keccak256(b'bar').hex()}"
    assert receipt["logs"][0]["topics"][1] == topic1

    topic2 = f"0x{keccak256(eth_abi.encode_single('int128[2]', [1,2])).hex()}"
    assert receipt["logs"][0]["topics"][2] == topic2

    topic3 = f"0x{keccak256(b'weird').hex()}"
    assert receipt["logs"][0]["topics"][3] == topic3

    # Event abi is created correctly
    assert c._classic_contract.abi[0] == {
        "name": "MyLog",
        "inputs": [
            {"type": "bytes", "name": "arg1", "indexed": True},
            {"type": "int128[2]", "name": "arg2", "indexed": True},
            {"type": "string", "name": "arg3", "indexed": True},
        ],
        "anonymous": False,
        "type": "event",
    } 
Example #8
Source File: test_logging.py    From vyper with Apache License 2.0 5 votes vote down vote up
def test_hashed_indexed_topics_storxxage(tester, keccak, get_contract):
    loggy_code = """
event MyLog:
    arg1: indexed(Bytes[64])
    arg2: indexed(int128[3])
    arg3: indexed(String[21])

@external
def foo():
    log MyLog(b"wow", [6,66,666], "madness!")
    """

    c = get_contract(loggy_code)
    tx_hash = c.foo(transact={})
    receipt = tester.get_transaction_receipt(tx_hash.hex())

    # Event id is always the first topic
    event_id = keccak(b"MyLog(bytes,int128[3],string)")
    assert receipt["logs"][0]["topics"][0] == event_id.hex()

    topic1 = f"0x{keccak256(b'wow').hex()}"
    assert receipt["logs"][0]["topics"][1] == topic1

    topic2 = f"0x{keccak256(eth_abi.encode_single('int128[3]', [6, 66, 666])).hex()}"
    assert receipt["logs"][0]["topics"][2] == topic2

    topic3 = f"0x{keccak256(b'madness!').hex()}"
    assert receipt["logs"][0]["topics"][3] == topic3 
Example #9
Source File: iou.py    From raiden-services with MIT License 5 votes vote down vote up
def packed_data(self) -> bytes:
        return (
            self.one_to_n_address
            + encode_single("uint256", self.chain_id)
            + encode_single("uint256", MessageTypeId.IOU)
            + self.sender
            + self.receiver
            + encode_single("uint256", self.amount)
            + encode_single("uint256", self.expiration_block)
        ) 
Example #10
Source File: iou.py    From raiden-services with MIT License 5 votes vote down vote up
def session_id(self) -> str:
        """Session ID as used for OneToN.settled_sessions"""
        return encode_hex(
            keccak(self.receiver + self.sender + encode_single("uint256", self.expiration_block))
        ) 
Example #11
Source File: base.py    From clove with GNU General Public License v3.0 4 votes vote down vote up
def find_transaction_details_in_redeem_event(
        self,
        recipient_address: str,
        secret_hash: str,
        block_number: int,
    ) -> Optional[dict]:
        '''
        Searching for transaction details of redeem transaction in Atomic Swap contract events.

        Args:
            recipient_address (str): recipient address
            secret_hash (str): hash of the secret
            block_number (int): number of the block from which filtering should be started

        Returns:
            dict, None: dictionary with secret and transaction hash, None if no redeem transaction where found

        Raises:
            NotImplementedError: if the network doesn't support event filtering
        '''
        if not self.filtering_supported:
            raise NotImplementedError

        event_signature_hash = self.web3.sha3(text="RedeemSwap(address,bytes20,bytes32)").hex()
        filter_options = {
            'fromBlock': block_number,
            'address': self.contract_address,
            'topics': [
                event_signature_hash,
                '0x' + encode_single('address', recipient_address).hex(),
                '0x' + encode_single('bytes20', bytes.fromhex(secret_hash)).hex()
            ]
        }

        event_filter = self.web3.eth.filter(filter_options)

        for _ in range(ETH_FILTER_MAX_ATTEMPTS):
            events = event_filter.get_all_entries()
            if events:
                return {
                    'secret': events[0]['data'][2:],
                    'transaction_hash': events[0]['transactionHash'].hex()
                } 
Example #12
Source File: test_logging.py    From vyper with Apache License 2.0 4 votes vote down vote up
def test_hashed_indexed_topics_memory(tester, keccak, get_contract):
    loggy_code = """
event MyLog:
    arg1: indexed(Bytes[10])
    arg2: indexed(int128[3])
    arg3: indexed(String[44])

@external
def foo():
    a: Bytes[10] = b"potato"
    b: int128[3] = [-777, 42, 8008135]
    c: String[44] = "why hello, neighbor! how are you today?"
    log MyLog(a, b, c)
    """

    c = get_contract(loggy_code)
    tx_hash = c.foo(transact={})
    receipt = tester.get_transaction_receipt(tx_hash.hex())

    # Event id is always the first topic
    event_id = keccak(b"MyLog(bytes,int128[3],string)")
    assert receipt["logs"][0]["topics"][0] == event_id.hex()

    topic1 = f"0x{keccak256(b'potato').hex()}"
    assert receipt["logs"][0]["topics"][1] == topic1

    topic2 = f"0x{keccak256(eth_abi.encode_single('int128[3]', [-777,42,8008135])).hex()}"
    assert receipt["logs"][0]["topics"][2] == topic2

    topic3 = f"0x{keccak256(b'why hello, neighbor! how are you today?').hex()}"
    assert receipt["logs"][0]["topics"][3] == topic3

    # Event abi is created correctly
    assert c._classic_contract.abi[0] == {
        "name": "MyLog",
        "inputs": [
            {"type": "bytes", "name": "arg1", "indexed": True},
            {"type": "int128[3]", "name": "arg2", "indexed": True},
            {"type": "string", "name": "arg3", "indexed": True},
        ],
        "anonymous": False,
        "type": "event",
    } 
Example #13
Source File: test_logging.py    From vyper with Apache License 2.0 4 votes vote down vote up
def test_hashed_indexed_topics_storage(tester, keccak, get_contract):
    loggy_code = """
event MyLog:
    arg1: indexed(Bytes[32])
    arg2: indexed(int128[2])
    arg3: indexed(String[6])

a: Bytes[32]
b: int128[2]
c: String[6]


@external
def setter(_a: Bytes[32], _b: int128[2], _c: String[6]):
    self.a = _a
    self.b = _b
    self.c = _c

@external
def foo():
    log MyLog(self.a, self.b, self.c)
    """

    c = get_contract(loggy_code)
    c.setter(b"zonk", [838, -2109], "yessir", transact={})
    tx_hash = c.foo(transact={})
    receipt = tester.get_transaction_receipt(tx_hash.hex())

    # Event id is always the first topic
    event_id = keccak(b"MyLog(bytes,int128[2],string)")
    assert receipt["logs"][0]["topics"][0] == event_id.hex()

    topic1 = f"0x{keccak256(b'zonk').hex()}"
    assert receipt["logs"][0]["topics"][1] == topic1

    topic2 = f"0x{keccak256(eth_abi.encode_single('int128[2]', [838,-2109])).hex()}"
    assert receipt["logs"][0]["topics"][2] == topic2

    topic3 = f"0x{keccak256(b'yessir').hex()}"
    assert receipt["logs"][0]["topics"][3] == topic3

    # Event abi is created correctly
    assert c._classic_contract.abi[0] == {
        "name": "MyLog",
        "inputs": [
            {"type": "bytes", "name": "arg1", "indexed": True},
            {"type": "int128[2]", "name": "arg2", "indexed": True},
            {"type": "string", "name": "arg3", "indexed": True},
        ],
        "anonymous": False,
        "type": "event",
    }