aelf-sdk.py - AELF Python API

Introduction

aelf-sdk.py for aelf is like web.js for ethereum.

aelf-sdk.py is a collection of libraries which allow you to interact with a local or remote aelf node, using a HTTP connection.

The following documentation will guide you through installing and running aelf-sdk.py, as well as providing a API reference documentation with examples.

If you need more information you can check out the repo : aelf-sdk.py

Adding aelf-sdk.js

First you need to get aelf-sdk package into your project. This can be done using the following methods:

pip: pip install aelf-sdk

After that you need to create a aelf instance by a node’s URL.

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

Examples

You can also see full examples in ./test;

1.Create instance

Create a new instance of AElf, connect to an AELF chain node. Using this instance, you can call the 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

Get a system contract address, take AElf.ContractNames.Token as an example

from aelf import AElf

aelf = AElf('http://127.0.0.1:8000')
// get genesis contract address
genesis_contract_address = aelf.get_genesis_contract_address_string()

// get contract address
// in fact, get_system_contract_address call the method 'GetContractAddressByName' in the genesis contract to get other contracts' address
multi_token_contract_address = aelf.get_system_contract_address('AElf.ContractNames.Token')

3.Send a transaction

Get the contract address, and then send the transaction.

from aelf import AElf

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 by user's private key
aelf.sign_transaction(private_key, transaction)

// execute the transaction
aelf.execute_transaction(transaction)

Web API

You can see how the Web Api of the node works in {chainAddress}/swagger/index.html tip: for an example, my local address: ‘http://127.0.0.1:1235/swagger/index.html’

The usage of these methods is based on the AElf instance, so if you don’t have one please create it:

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

Get the current status of the block chain.

Web API path

/api/blockChain/chainStatus

Parameters

Empty

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

Get current best height of the chain.

Web API path

/api/blockChain/blockHeight

Parameters

Empty

Returns

Number

Example

aelf = AElf(url)

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

3.get_block

Get block information by block hash.

Web API path

/api/blockChain/block

Parameters

  1. block_hash - String
  2. include_transactions - Boolean :
  • true require transaction ids list in the block
  • false Doesn’t require transaction ids list in the block

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

Get block information by block height.

Parameters

  1. block_height - Number
  2. include_transactions - Boolean :
  • true require transaction ids list in the block
  • false Doesn’t require transaction ids list in the block

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

Get the result of a transaction

Web API path

/api/blockChain/transactionResult

Parameters

  1. 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 - String
    • To - String
    • 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_results', transaction_result)

6.get_transaction_results

Get multiple transaction results in a block

Web API path

/api/blockChain/transactionResults

Parameters

  1. blockHash - String
  2. offset - Number
  3. limit - Number

Returns

List - The array of method descriptions:

  • the transaction result object

Example

aelf = AElf(url)

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

7.get_transaction_pool_status

Get the 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

Broadcast a transaction

Web API path

/api/blockChain/sendTransaction

POST

Parameters

transaction - String - Serialization of data into String

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

Broadcast multiple transactions

Web API path

/api/blockChain/sendTransaction

POST

Parameters

transactions - String - Serialization of data into String

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

Get peer info about the connected network nodes

Web API path

/api/net/peers

Example

aelf = AElf(url)

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

11.add_peer

Attempts to add a node to the connected network nodes

Web API path

/api/net/peer

POST

Parameters

peer_address - String - peer’s endpoint

Example

aelf = AElf(url)

add_peer = aelf.add_peer(endpoint)
print('# add_peers', add_peer)

12.remove_peer

Attempts to remove a node from the connected network nodes

Web API path

/api/net/peer?address=

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

create a raw transaction

Web API path

/api/blockchain/rawTransaction

POST

Parameters

  1. transaction - the 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)

14.send_raw_transaction

send raw transactions

Web API path

/api/blockchain/sendRawTransaction

Parameters

  1. Transaction - raw transaction
  2. Signature - signature
  3. ReturnTransaction - indicates whether to return transaction

Example

aelf = AElf(url)

raw_transaction = aelf.create_raw_transaction(transaction)
signature = private_key.sign_recoverable(bytes.fromhex(raw_transaction['RawTransaction']))
transaction_2 = {
  "Transaction": raw_transaction['RawTransaction'],
  'Signature': signature.hex(),
  'ReturnTransaction': True
}
print('# send_raw_transaction', aelf.send_raw_transaction(transaction_2))

15.execute_raw_transaction

execute raw transactions

Web API path

/api/blockchain/executeRawTransaction

Post

Parameters

  1. RawTransaction - raw transaction
  2. Signature - signature

Example

aelf = AElf(url)

raw_transaction = aelf.create_raw_transaction(transaction)
signature = private_key.sign_recoverable(bytes.fromhex(raw_transaction['RawTransaction']))
transaction_1 = {
  "RawTransaction": raw_transaction['RawTransaction'],
  "Signature": signature.hex()
}
print('# execute_raw_transaction', aelf.execute_raw_transaction(transaction_1))

16.get_merkle_path

get merkle path

Web API path

/api/blockchain/merklePathByTransactionId?transactionId=

Parameters

  1. transactionId - String

Example

aelf = AElf(url)

transaction_results = aelf.get_transaction_results(transactionId)
print('# get_transaction_results', transaction_results)

17.get_network_info

get network information

Web API path

/api/net/networkInfo

Example

aelf = AElf(url)

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

AElf.client

Use the api to see detailed results

1.get_genesis_contract_address_string

Returns

String: zero contract address

Example

aelf = AElf(url)

genesis_contract_address = aelf.get_genesis_contract_address_string()

2.get_system_contract_address

Parameters

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

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

create a transaction

Parameters

  1. to_address - Address or String : target contract’s address
  2. method_name - String : method name
  3. params - String : serilize paramters into String

Example

aelf = AElf(url)

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

5.sign_transaction

sign transaction with user’s private key

Parameters

  1. private_key - String : user’s private key
  2. 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 address from public key

Parameters

  1. public_key - bytes : user’s pubilc key

Returns

Address

Example_

aelf = AElf(url)

address = aelf.get_address_from_public_key(public_key)

7.get_address_string_from_public_key

generate address string from public key

Parameters

  1. public_key - bytes : user’s pubilc key

Returns

String

Example_

aelf = AElf(url)

address = aelf.get_address_string_from_public_key(public_key)

8.get_chain_id

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

get formatted address

Parameters

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

10.is_connected

check whether to connect the node

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

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 transcation 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

node

About contributing

Read out [contributing guide]

About Version

https://semver.org/