Skip to main content

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:

pip install aelf-sdk

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

from aelf import AElf

chain = AElf('http://127.0.0.1:8000')

Examples

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

1. 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.

from aelf import AElf

# Create a new instance of AElf
aelf = AElf('http://127.0.0.1:8000')

2. Get a System Contract Address

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

from aelf import AElf

aelf = AElf('http://127.0.0.1:8000')

# Get the genesis contract address
genesis_contract_address = aelf.get_genesis_contract_address_string()

# Get the contract address
# The get_system_contract_address method calls 'GetContractAddressByName' in the genesis contract to get other contracts' addresses
multi_token_contract_address = aelf.get_system_contract_address('AElf.ContractNames.Token')

3. Send a Transaction

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

from aelf import AElf, PrivateKey, CrossChainTransferInput

url = 'http://127.0.0.1:8000'

# Create a new instance of AElf
aelf = AElf(url)

# Generate the private key
private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa'
private_key = PrivateKey(bytes(bytearray.fromhex(private_key_string)))

# Create input, the type is generated by protoc
cross_chain_transfer_input = CrossChainTransferInput()

# Generate the transaction
transaction = aelf.create_transaction(to_address, method_name, params.SerializeToString())

# Sign the transaction with the user's private key
aelf.sign_transaction(private_key, transaction)

# Execute the transaction
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:

from aelf import AElf

# Create a new instance of AElf, change the URL if needed
aelf = AElf('http://127.0.0.1:8000')

1. Get Chain Status

Web API Path: /api/blockChain/chainStatus

Parameters: None

Returns:

  • JSON

    • ChainId - String
    • Branches - JSON
    • NotLinkedBlocks - JSON
    • LongestChainHeight - Number
    • LongestChainHash - String
    • GenesisBlockHash - String
    • GenesisContractAddress - String
    • LastIrreversibleBlockHash - String
    • LastIrreversibleBlockHeight - Number
    • BestChainHash - String
    • BestChainHeight - Number

Example:

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

2. Get Block Height

Web API Path: /api/blockChain/blockHeight

Parameters: None

Returns: Number

Example:

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

3. 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

    • PreviousBlockHash - String
    • MerkleTreeRootOfTransactions - String
    • MerkleTreeRootOfWorldState - String
    • Extra - List
    • Height - Number
    • Time - JSON
    • ChainId - String
    • Bloom - String
    • SignerPubkey - String
  • Body - JSON

    • TransactionsCount - Number
    • Transactions - List
      • transactionId - String

Example:

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

4. 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

    • PreviousBlockHash - String
    • MerkleTreeRootOfTransactions - String
    • MerkleTreeRootOfWorldState - String
    • Extra - List
    • Height - Number
    • Time - JSON
    • ChainId - String
    • Bloom - String
    • SignerPubkey - String
  • Body - JSON

    • TransactionsCount - Number
    • Transactions - List
      • transactionId - String

Example:

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

5. Get Transaction Result

Web API Path: /api/blockChain/transactionResult

Parameters:

  • transactionId - String

Returns:

  • JSON

    • TransactionId - String
    • Status - String
    • Logs - List
      • Address - String
      • Name - String
      • Indexed - List
      • NonIndexed - String
    • Bloom - String
    • BlockNumber - Number
    • Transaction - List
      • From - Number
      • To - Number
      • RefBlockNumber - Number
      • RefBlockPrefix - String
      • MethodName - String
      • Params - JSON
      • Signature - String
    • ReadableReturnValue - JSON
    • Error - String

Example:

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

6. Get Transaction Results

Web API Path: /api/blockChain/transactionResults

Parameters:

  • blockHash - String
  • offset - Number
  • limit - Number

Returns: List of transaction result objects

Example:

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

7. Get Transaction Pool Status

Web API Path: /api/blockChain/transactionPoolStatus

Example:

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

8. Send Transaction

Web API Path: /api/blockChain/sendTransaction

Method: POST

Parameters:

  • transaction - String (serialized data)

Example:

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

9. Send Transactions

Web API Path: /api/blockChain/sendTransaction

Method: POST

Parameters:

  • transactions - String (serialized data)

Example:

aelf = AElf(url)
current_height = aelf.get_block_height()
block = aelf.get_block_by_height(current_height, include_transactions=False)
transaction1 = Transaction().SerializePartialToString().hex()
transaction2 = Transaction().SerializePartialToString().hex()
result = aelf.send_transaction(transaction1 + ',' + transaction2)
print('# send_transactions', result)

10. Get Peers

Web API Path: /api/net/peers

Example:

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

11. Add Peer

Web API Path: /api/net/peers

Method: POST

Parameters:

  • peer_address - String (peer’s endpoint)

Example:

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

12. Remove Peer

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

Method: POST

Parameters:

  • peer_address - String (peer’s endpoint)

Example:

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

13. Create Raw Transaction

Web API Path: /api/blockchain/rawTransaction

Method: POST

Parameters:

  • transaction - JSON format transaction

Returns:

  • JSON
    • RawTransaction - hex string bytes generated by transaction information

Example:

aelf = AElf(url)
transaction = {
"From": aelf.get_address_string_from_public_key(public_key),
"To": aelf.get_system_contract_address_string("AElf.ContractNames.Consensus"),
"RefBlockNumber": 0,
"RefBlockHash": "b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa",
"MethodName": "GetCurrentMinerList",
"Params": '{}'
}
raw_transaction = aelf.create_raw_transaction(transaction)
print('# create_raw_transaction', raw_transaction)

14. 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:

aelf = AElf(url)

# Create the raw transaction
raw_transaction = aelf.create_raw_transaction({
"From": aelf.get_address_string_from_public_key(public_key),
"To": aelf.get_system_contract_address_string("AElf.ContractNames.Consensus"),
"RefBlockNumber": 0,
"RefBlockHash": "b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa",
"MethodName": "GetCurrentMinerList",
"Params": '{}'
})

# Sign the raw transaction
signature = private_key.sign_recoverable(bytes.fromhex(raw_transaction['RawTransaction']))

# Create the transaction payload
transaction_2 = {
"Transaction": raw_transaction['RawTransaction'],
'Signature': signature.hex(),
'ReturnTransaction': True
}

# Send the raw transaction
result = aelf.send_raw_transaction(transaction_2)
print('# send_raw_transaction', result)

15. Execute Raw Transaction

Web API Path: /api/blockchain/executeRawTransaction

Method: POST

Parameters:

  • RawTransaction - raw transaction
  • Signature - signature

Example:

aelf = AElf(url)

# Create the raw transaction
raw_transaction = aelf.create_raw_transaction({
"From": aelf.get_address_string_from_public_key(public_key),
"To": aelf.get_system_contract_address_string("AElf.ContractNames.Consensus"),
"RefBlockNumber": 0,
"RefBlockHash": "b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa",
"MethodName": "GetCurrentMinerList",
"Params": '{}'
})

# Sign the raw transaction
signature = private_key.sign_recoverable(bytes.fromhex(raw_transaction['RawTransaction']))

# Create the transaction payload
transaction_1 = {
"RawTransaction": raw_transaction['RawTransaction'],
"Signature": signature.hex()
}

# Execute the raw transaction
result = aelf.execute_raw_transaction(transaction_1)
print('# execute_raw_transaction', result)

16. Get Merkle Path

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

Method: POST

Parameters:

  • transactionId - String

Example:

aelf = AElf(url)

transaction_id = "your-transaction-id"
merkle_path = aelf.get_merkle_path(transaction_id)
print('# get_merkle_path', merkle_path)

17. Calculate Transaction Fee

Web API Path: /api/blockchain/calculateTransactionFee

Method: POST

Parameters:

  • CalculateTransactionFeeInput - JSON with the following structure:
    • RawTransaction - String

Returns:

  • CalculateTransactionFeeOutput - json - The json with the following structure :
    • Success - Boolean
    • TransactionFee - Array
    • ResourceFee - Array

Example:

aelf = AElf(url)

calculate_transaction_fee_input = {
"RawTransaction": raw_transaction['RawTransaction']
}

calculate_transaction_fee_output = aelf.calculate_transaction_fee(calculate_transaction_fee_input)
print('# calculate_transaction_fee', calculate_transaction_fee_output)

18. Get Network Info

Web API Path: /api/net/networkInfo

Method: POST

Example:

aelf = AElf(url)

network_info = aelf.get_network_info()
print('# get_network_info', network_info)

AElf.client

Use the API to see detailed results.

1. get_genesis_contract_address_string

Returns the zero contract address.

Example:

aelf = AElf(url)

genesis_contract_address = aelf.get_genesis_contract_address_string()

2. get_system_contract_address

Parameters:

  • contract_name - String: system contract’s name

Returns:

  • Address: system contract’s address

Example:

aelf = AElf(url)

multi_token_contract_address = aelf.get_system_contract_address('AElf.ContractNames.Token')

3. get_system_contract_address_string

Parameters:

  • contract_name - String: system contract’s name

Returns:

  • String: system contract’s address

Example:

aelf = AElf(url)

multi_token_contract_address_string = aelf.get_system_contract_address_string('AElf.ContractNames.Token')

4. create_transaction

Parameters:

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

Example:

aelf = AElf(url)

params = Hash()
params.value = hashlib.sha256(contract_name.encode('utf8')).digest()
transaction = aelf.create_transaction(genesisContractAddress, 'GetContractAddressByName', params.SerializeToString())

5. sign_transaction

Sign a transaction with the user’s private key.

Parameters:

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

Example:

aelf = AElf(url)

to_address_string = aelf.get_genesis_contract_address_string()
params = Hash()
params.value = hashlib.sha256(contract_name.encode('utf8')).digest()
transaction = aelf.create_transaction(to_address_string, 'GetContractAddressByName', params.SerializeToString())
transaction = aelf.sign_transaction(private_key, transaction)

6. get_address_from_public_key

Generate an address from a public key.

Parameters:

  • public_key - bytes: user’s public key

Returns:

  • Address

Example:

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

7. 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:

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

8. get_chain_id

Returns:

  • Number

Example:

aelf = AElf(url)

chain_id = aelf.get_chain_id()
print('# get_chain_id', chain_id)

9. get_formatted_address

Parameters:

  • address - Address: address

Returns:

  • String

Example:

aelf = AElf(url)
address = aelf.chain.get_system_contract_address("AElf.ContractNames.Consensus")
formatted_address = aelf.get_formatted_address(address)
print('formatted address', formatted_address)

9. is_connected

Check whether the node is connected.

Example:

aelf = AElf(url)
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.

from aelf import AElfToolkit

# generate the private key
private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa'
private_key = PrivateKey(bytes(bytearray.fromhex(private_key_string)))

# create a toolkit
toolkit = AElfToolkit('http://127.0.0.1:8000', private_key)

Send a Transaction

Send a CrossChainTransfer transaction using AElfToolkit.

from aelf import AElfToolkit

# generate the private key
private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa'
private_key = PrivateKey(bytes(bytearray.fromhex(private_key_string)))

# create input, the type is generated by protoc
cross_chain_transfer_input = CrossChainTransferInput()

# AElfToolkit simplifies this transaction execution.
# create a toolkit
toolkit = AElfToolkit('http://127.0.0.1:8000', private_key)
toolkit.cross_chain_transfer(to_address_string, symbol, amount, memo, to_chain_id)

Requirements

Support

About Contributing

Read out contributing guide.

About Version

https://semver.org/