logo

Python SDK

aelf-sdk.py - aelf Python API

Introduction#

The aelf-sdk.py is the Python equivalent of web3.js for Ethereum. It is a collection of libraries that allow you to interact with a local or remote aelf node using an HTTP connection.

This documentation will guide you through the installation and usage of aelf-sdk.py, providing detailed API references with examples. For more information, you can check out the aelf-sdk.py repository.

Adding aelf-sdk.py#

To start using aelf-sdk.py in your project, you need to install the package. This can be done using pip:

1
pip install aelf-sdk

After installation, you need to create an instance of AElf using a node’s URL:

1
from aelf import AElf
2
3
chain = AElf('http://127.0.0.1:8000')

Examples#

You can find more examples in the ./test directory of the repository.

Create an Instance#

To create a new instance of AElf and connect to an aelf chain node, use the following code. With this instance, you can call various APIs on aelf.

1
from aelf import AElf
2
3
# Create a new instance of AElf
4
aelf = AElf('http://127.0.0.1:8000')

Get a System Contract Address#

To get a system contract address, for example, the AElf.ContractNames.Token, use the following code:

1
from aelf import AElf
2
3
aelf = AElf('http://127.0.0.1:8000')
4
5
# Get the genesis contract address
6
genesis_contract_address = aelf.get_genesis_contract_address_string()
7
8
# Get the contract address
9
# The get_system_contract_address method calls 'GetContractAddressByName' in the genesis contract to get other contracts' addresses
10
multi_token_contract_address = aelf.get_system_contract_address('AElf.ContractNames.Token')

Send a Transaction#

To send a transaction, first get the contract address and then use the following steps:

1
from aelf import AElf, PrivateKey, CrossChainTransferInput
2
3
url = 'http://127.0.0.1:8000'
4
5
# Create a new instance of AElf
6
aelf = AElf(url)
7
8
# Generate the private key
9
private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa'
10
private_key = PrivateKey(bytes(bytearray.fromhex(private_key_string)))
11
12
# Create input, the type is generated by protoc
13
cross_chain_transfer_input = CrossChainTransferInput()
14
15
# Generate the transaction
16
transaction = aelf.create_transaction(to_address, method_name, params.SerializeToString())
17
18
# Sign the transaction with the user's private key
19
aelf.sign_transaction(private_key, transaction)
20
21
# Execute the transaction
22
aelf.execute_transaction(transaction)

By following these instructions, you can effectively interact with the aelf blockchain using the aelf-sdk.py library. For more detailed examples and information, please refer to the aelf-sdk.py repository.

Web API#

You can view how the Web API of the node works at http://{chainAddress}/swagger/index.html.

For example, if your local address is http://127.0.0.1:1235, you can access it at http://127.0.0.1:1235/swagger/index.html.

Before using these methods, make sure you have an AElf instance. If not, create one as shown below:

1
from aelf import AElf
2
3
# Create a new instance of AElf, change the URL if needed
4
aelf = AElf('http://127.0.0.1:8000')

Get Chain Status#

Web API Path: /api/blockChain/chainStatus

Parameters: None

Returns:

  • JSON
  • Example:

    1
    aelf = AElf(url)
    2
    chain_status = aelf.get_chain_status()
    3
    print('# get_chain_status', chain_status)

    Get Block Height#

    Web API Path: /api/blockChain/blockHeight

    Parameters: None

    Returns: Number

    Example:

    1
    aelf = AElf(url)
    2
    block_height = aelf.get_block_height()
    3
    print('# get_block_height', block_height)

    Get Block#

    Web API Path: /api/blockChain/block

    Parameters: None

  • block_hash - String
  • include_transactions - Boolean (true to include transaction IDs list, false otherwise)
  • Returns:

  • JSON
  • BlockHash - String
  • Header - JSON
  • Body - JSON
  • Example:

    1
    aelf = AElf(url)
    2
    block = aelf.get_block(blockHash)
    3
    print('# get_block', block)

    Get Block by Height#

    Web API Path: /api/blockChain/blockByHeight

    Parameters:

  • block_height - Number
  • include_transactions - Boolean (true to include transaction IDs list, false otherwise)
  • Returns:

  • JSON
  • BlockHash - String
  • Header - JSON
  • Body - JSON
  • Example:

    1
    aelf = AElf(url)
    2
    block_by_height = aelf.get_block_by_height(12, False)
    3
    print('# get_block_by_height', block_by_height)

    Get Transaction Result#

    Web API Path: /api/blockChain/transactionResult

    Parameters:

  • transactionId - String
  • Returns:

  • JSON
  • Example:

    1
    aelf = AElf(url)
    2
    transaction_result = aelf.get_transaction_result(transactionId)
    3
    print('# get_transaction_result', transaction_result)

    Get Transaction Results#

    Web API Path: /api/blockChain/transactionResults

    Parameters:

  • blockHash - String
  • offset - Number
  • limit - Number
  • Returns: List of transaction result objects

    Example:

    1
    aelf = AElf(url)
    2
    transaction_results = aelf.get_transaction_results(blockHash, 0, 2)
    3
    print('# get_transaction_results', transaction_results)

    Get Transaction Pool Status#

    Web API Path: /api/blockChain/transactionPoolStatus

    Example:

    1
    aelf = AElf(url)
    2
    tx_pool_status = aelf.get_transaction_pool_status()
    3
    print('# get_transaction_pool_status', tx_pool_status)

    Send Transaction#

    Web API Path: /api/blockChain/sendTransaction

    Method: POST

    Parameters:

  • transaction - String (serialized data)
  • Example:

    1
    aelf = AElf(url)
    2
    current_height = aelf.get_block_height()
    3
    block = aelf.get_block_by_height(current_height, include_transactions=False)
    4
    transaction = Transaction()
    5
    transaction.to_address.CopyFrom(aelf.get_system_contract_address("AElf.ContractNames.Consensus"))
    6
    transaction.ref_block_number = current_height
    7
    transaction.ref_block_prefix = bytes.fromhex(block['BlockHash'])[0:4]
    8
    transaction.method_name = 'GetCurrentMinerList'
    9
    transaction = aelf.sign_transaction(private_key, transaction)
    10
    result = aelf.send_transaction(transaction.SerializePartialToString().hex())
    11
    print('# send_transaction', result)

    Send Transactions#

    Web API Path: /api/blockChain/sendTransaction

    Method: POST

    Parameters:

  • transactions - String (serialized data)
  • Example:

    1
    aelf = AElf(url)
    2
    current_height = aelf.get_block_height()
    3
    block = aelf.get_block_by_height(current_height, include_transactions=False)
    4
    transaction1 = Transaction().SerializePartialToString().hex()
    5
    transaction2 = Transaction().SerializePartialToString().hex()
    6
    result = aelf.send_transaction(transaction1 + ',' + transaction2)
    7
    print('# send_transactions', result)

    Get Peers#

    Web API Path: /api/net/peers

    Example:

    1
    aelf = AElf(url)
    2
    peers = aelf.get_peers()
    3
    print('# get_peers', peers)

    Add Peer#

    Web API Path: /api/net/peers

    Method: POST

    Parameters:

  • peer_address - String (peer’s endpoint)
  • Example:

    1
    aelf = AElf(url)
    2
    add_peer = aelf.add_peer(endpoint)
    3
    print('# add_peer', add_peer)

    Remove Peer#

    Web API Path: /api/net/peer?address=

    Method: POST

    Parameters:

  • peer_address - String (peer’s endpoint)
  • Example:

    1
    aelf = AElf(url)
    2
    remove_peer = aelf.remove_peer(address)
    3
    print('# remove_peer', remove_peer)

    Create Raw Transaction#

    Web API Path: /api/blockchain/rawTransaction

    Method: POST

    Parameters:

  • transaction - JSON format transaction
  • Returns:

  • JSON
  • Example:

    1
    aelf = AElf(url)
    2
    transaction = {
    3
    "From": aelf.get_address_string_from_public_key(public_key),
    4
    "To": aelf.get_system_contract_address_string("AElf.ContractNames.Consensus"),
    5
    "RefBlockNumber": 0,
    6
    "RefBlockHash": "b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa",
    7
    "MethodName": "GetCurrentMinerList",
    8
    "Params": '{}'
    9
    }
    10
    raw_transaction = aelf.create_raw_transaction(transaction)
    11
    print('# create_raw_transaction', raw_transaction)

    Send Raw Transaction#

    Web API Path: /api/blockchain/sendRawTransaction

    Method: POST

    Parameters:

  • Transaction - raw transaction
  • Signature - signature
  • ReturnTransaction - indicates whether to return the transaction
  • Example:

    1
    aelf = AElf(url)
    2
    3
    # Create the raw transaction
    4
    raw_transaction = aelf.create_raw_transaction({
    5
    "From": aelf.get_address_string_from_public_key(public_key),
    6
    "To": aelf.get_system_contract_address_string("AElf.ContractNames.Consensus"),
    7
    "RefBlockNumber": 0,
    8
    "RefBlockHash": "b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa",
    9
    "MethodName": "GetCurrentMinerList",
    10
    "Params": '{}'
    11
    })
    12
    13
    # Sign the raw transaction
    14
    signature = private_key.sign_recoverable(bytes.fromhex(raw_transaction['RawTransaction']))
    15
    16
    # Create the transaction payload
    17
    transaction_2 = {
    18
    "Transaction": raw_transaction['RawTransaction'],
    19
    'Signature': signature.hex(),
    20
    'ReturnTransaction': True
    21
    }
    22
    23
    # Send the raw transaction
    24
    result = aelf.send_raw_transaction(transaction_2)
    25
    print('# send_raw_transaction', result)

    Execute Raw Transaction#

    Web API Path: /api/blockchain/executeRawTransaction

    Method: POST

    Parameters:

  • RawTransaction - raw transaction
  • Signature - signature
  • Example:

    1
    aelf = AElf(url)
    2
    3
    # Create the raw transaction
    4
    raw_transaction = aelf.create_raw_transaction({
    5
    "From": aelf.get_address_string_from_public_key(public_key),
    6
    "To": aelf.get_system_contract_address_string("AElf.ContractNames.Consensus"),
    7
    "RefBlockNumber": 0,
    8
    "RefBlockHash": "b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa",
    9
    "MethodName": "GetCurrentMinerList",
    10
    "Params": '{}'
    11
    })
    12
    13
    # Sign the raw transaction
    14
    signature = private_key.sign_recoverable(bytes.fromhex(raw_transaction['RawTransaction']))
    15
    16
    # Create the transaction payload
    17
    transaction_1 = {
    18
    "RawTransaction": raw_transaction['RawTransaction'],
    19
    "Signature": signature.hex()
    20
    }
    21
    22
    # Execute the raw transaction
    23
    result = aelf.execute_raw_transaction(transaction_1)
    24
    print('# execute_raw_transaction', result)

    Get Merkle Path#

    Web API Path: /api/blockchain/merklePathByTransactionId?transactionId=

    Method: POST

    Parameters:

  • transactionId - String
  • Example:

    1
    aelf = AElf(url)
    2
    3
    transaction_id = "your-transaction-id"
    4
    merkle_path = aelf.get_merkle_path(transaction_id)
    5
    print('# get_merkle_path', merkle_path)

    Calculate Transaction Fee#

    Web API Path: /api/blockchain/calculateTransactionFee

    Method: POST

    Parameters:

  • CalculateTransactionFeeInput - JSON with the following structure:
  • Returns:

  • CalculateTransactionFeeOutput - json - The json with the following structure :
  • Example:

    1
    aelf = AElf(url)
    2
    3
    calculate_transaction_fee_input = {
    4
    "RawTransaction": raw_transaction['RawTransaction']
    5
    }
    6
    7
    calculate_transaction_fee_output = aelf.calculate_transaction_fee(calculate_transaction_fee_input)
    8
    print('# calculate_transaction_fee', calculate_transaction_fee_output)

    Get Network Info#

    Web API Path: /api/net/networkInfo

    Method: POST

    Example:

    1
    aelf = AElf(url)
    2
    3
    network_info = aelf.get_network_info()
    4
    print('# get_network_info', network_info)

    AElf.client#

    Use the API to see detailed results.

    get_genesis_contract_address_string#

    Returns the zero contract address.

    Example:

    1
    aelf = AElf(url)
    2
    3
    genesis_contract_address = aelf.get_genesis_contract_address_string()

    get_system_contract_address#

    Parameters:

  • contract_name - String: system contract’s name
  • Returns:

  • Address: system contract’s address
  • Example:

    1
    aelf = AElf(url)
    2
    3
    multi_token_contract_address = aelf.get_system_contract_address('AElf.ContractNames.Token')

    get_system_contract_address_string#

    Parameters:

  • contract_name - String: system contract’s name
  • Returns:

  • String: system contract’s address
  • Example:

    1
    aelf = AElf(url)
    2
    3
    multi_token_contract_address_string = aelf.get_system_contract_address_string('AElf.ContractNames.Token')

    create_transaction#

    Parameters:

  • to_address - Address or String: target contract’s address
  • method_name - String: method name
  • params - String: serialize parameters into String
  • Example:

    1
    aelf = AElf(url)
    2
    3
    params = Hash()
    4
    params.value = hashlib.sha256(contract_name.encode('utf8')).digest()
    5
    transaction = aelf.create_transaction(genesisContractAddress, 'GetContractAddressByName', params.SerializeToString())

    sign_transaction#

    Sign a transaction with the user’s private key.

    Parameters:

  • private_key - String: user’s private key
  • transaction - Transaction: transaction
  • Example:

    1
    aelf = AElf(url)
    2
    3
    to_address_string = aelf.get_genesis_contract_address_string()
    4
    params = Hash()
    5
    params.value = hashlib.sha256(contract_name.encode('utf8')).digest()
    6
    transaction = aelf.create_transaction(to_address_string, 'GetContractAddressByName', params.SerializeToString())
    7
    transaction = aelf.sign_transaction(private_key, transaction)

    get_address_from_public_key#

    Generate an address from a public key.

    Parameters:

  • public_key - bytes: user’s public key
  • Returns:

  • Address
  • Example:

    1
    aelf = AElf(url)
    2
    address = aelf.get_address_from_public_key(public_key)

    get_address_string_from_public_key#

    Generate an address string from a public key.

    Parameters:

  • public_key - bytes: user’s public key
  • Returns:

  • String
  • Example:

    1
    aelf = AElf(url)
    2
    address = aelf.get_address_string_from_public_key(public_key)

    get_chain_id#

    Returns:

  • Number
  • Example:

    1
    aelf = AElf(url)
    2
    3
    chain_id = aelf.get_chain_id()
    4
    print('# get_chain_id', chain_id)

    get_formatted_address#

    Parameters:

  • address - Address: address
  • Returns:

  • String
  • Example:

    1
    aelf = AElf(url)
    2
    address = aelf.chain.get_system_contract_address("AElf.ContractNames.Consensus")
    3
    formatted_address = aelf.get_formatted_address(address)
    4
    print('formatted address', formatted_address)
  • is_connected
  • Check whether the node is connected.

    Example:

    1
    aelf = AElf(url)
    2
    is_connected = aelf.is_connected()

    Tookkits.py#

    AElfToolkit Encapsulate AElf and user’s private key. It simplifies the procedures of sending some transactions. You can find it in src/aelf/toolkits.py.

    Create a Toolkit#

    Create a Toolkit with AElfToolkit.

    1
    from aelf import AElfToolkit
    2
    3
    # generate the private key
    4
    private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa'
    5
    private_key = PrivateKey(bytes(bytearray.fromhex(private_key_string)))
    6
    7
    # create a toolkit
    8
    toolkit = AElfToolkit('http://127.0.0.1:8000', private_key)

    Send a Transaction#

    Send a CrossChainTransfer transaction using AElfToolkit.

    1
    from aelf import AElfToolkit
    2
    3
    # generate the private key
    4
    private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa'
    5
    private_key = PrivateKey(bytes(bytearray.fromhex(private_key_string)))
    6
    7
    # create input, the type is generated by protoc
    8
    cross_chain_transfer_input = CrossChainTransferInput()
    9
    10
    # AElfToolkit simplifies this transaction execution.
    11
    # create a toolkit
    12
    toolkit = AElfToolkit('http://127.0.0.1:8000', private_key)
    13
    toolkit.cross_chain_transfer(to_address_string, symbol, amount, memo, to_chain_id)

    Requirements#

  • Python
  • Docker
  • Support#

  • Node
  • About Contributing#

    Read out [contributing guide].

    About Version#

    https://semver.org/

    Edited on: 16 July 2024 05:02:10 GMT+0