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:
1pip install aelf-sdk
After installation, you need to create an instance of AElf using a node’s URL:
1from aelf import AElf23chain = 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.
1from aelf import AElf23# Create a new instance of AElf4aelf = 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:
1from aelf import AElf23aelf = AElf('http://127.0.0.1:8000')45# Get the genesis contract address6genesis_contract_address = aelf.get_genesis_contract_address_string()78# Get the contract address9# The get_system_contract_address method calls 'GetContractAddressByName' in the genesis contract to get other contracts' addresses10multi_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:
1from aelf import AElf, PrivateKey, CrossChainTransferInput23url = 'http://127.0.0.1:8000'45# Create a new instance of AElf6aelf = AElf(url)78# Generate the private key9private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa'10private_key = PrivateKey(bytes(bytearray.fromhex(private_key_string)))1112# Create input, the type is generated by protoc13cross_chain_transfer_input = CrossChainTransferInput()1415# Generate the transaction16transaction = aelf.create_transaction(to_address, method_name, params.SerializeToString())1718# Sign the transaction with the user's private key19aelf.sign_transaction(private_key, transaction)2021# Execute the transaction22aelf.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:
1from aelf import AElf23# Create a new instance of AElf, change the URL if needed4aelf = AElf('http://127.0.0.1:8000')
Get Chain Status#
Web API Path: /api/blockChain/chainStatus
Parameters: None
Returns:
Example:
1aelf = AElf(url)2chain_status = aelf.get_chain_status()3print('# get_chain_status', chain_status)
Get Block Height#
Web API Path: /api/blockChain/blockHeight
Parameters: None
Returns: Number
Example:
1aelf = AElf(url)2block_height = aelf.get_block_height()3print('# get_block_height', block_height)
Get Block#
Web API Path: /api/blockChain/block
Parameters: None
Returns:
Example:
1aelf = AElf(url)2block = aelf.get_block(blockHash)3print('# get_block', block)
Get Block by Height#
Web API Path: /api/blockChain/blockByHeight
Parameters:
Returns:
Example:
1aelf = AElf(url)2block_by_height = aelf.get_block_by_height(12, False)3print('# get_block_by_height', block_by_height)
Get Transaction Result#
Web API Path: /api/blockChain/transactionResult
Parameters:
Returns:
Example:
1aelf = AElf(url)2transaction_result = aelf.get_transaction_result(transactionId)3print('# get_transaction_result', transaction_result)
Get Transaction Results#
Web API Path: /api/blockChain/transactionResults
Parameters:
Returns: List of transaction result objects
Example:
1aelf = AElf(url)2transaction_results = aelf.get_transaction_results(blockHash, 0, 2)3print('# get_transaction_results', transaction_results)
Get Transaction Pool Status#
Web API Path: /api/blockChain/transactionPoolStatus
Example:
1aelf = AElf(url)2tx_pool_status = aelf.get_transaction_pool_status()3print('# get_transaction_pool_status', tx_pool_status)
Send Transaction#
Web API Path: /api/blockChain/sendTransaction
Method: POST
Parameters:
Example:
1aelf = AElf(url)2current_height = aelf.get_block_height()3block = aelf.get_block_by_height(current_height, include_transactions=False)4transaction = Transaction()5transaction.to_address.CopyFrom(aelf.get_system_contract_address("AElf.ContractNames.Consensus"))6transaction.ref_block_number = current_height7transaction.ref_block_prefix = bytes.fromhex(block['BlockHash'])[0:4]8transaction.method_name = 'GetCurrentMinerList'9transaction = aelf.sign_transaction(private_key, transaction)10result = aelf.send_transaction(transaction.SerializePartialToString().hex())11print('# send_transaction', result)
Send Transactions#
Web API Path: /api/blockChain/sendTransaction
Method: POST
Parameters:
Example:
1aelf = AElf(url)2current_height = aelf.get_block_height()3block = aelf.get_block_by_height(current_height, include_transactions=False)4transaction1 = Transaction().SerializePartialToString().hex()5transaction2 = Transaction().SerializePartialToString().hex()6result = aelf.send_transaction(transaction1 + ',' + transaction2)7print('# send_transactions', result)
Get Peers#
Web API Path: /api/net/peers
Example:
1aelf = AElf(url)2peers = aelf.get_peers()3print('# get_peers', peers)
Add Peer#
Web API Path: /api/net/peers
Method: POST
Parameters:
Example:
1aelf = AElf(url)2add_peer = aelf.add_peer(endpoint)3print('# add_peer', add_peer)
Remove Peer#
Web API Path: /api/net/peer?address=
Method: POST
Parameters:
Example:
1aelf = AElf(url)2remove_peer = aelf.remove_peer(address)3print('# remove_peer', remove_peer)
Create Raw Transaction#
Web API Path: /api/blockchain/rawTransaction
Method: POST
Parameters:
Returns:
Example:
1aelf = AElf(url)2transaction = {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}10raw_transaction = aelf.create_raw_transaction(transaction)11print('# create_raw_transaction', raw_transaction)
Send Raw Transaction#
Web API Path: /api/blockchain/sendRawTransaction
Method: POST
Parameters:
Example:
1aelf = AElf(url)23# Create the raw transaction4raw_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})1213# Sign the raw transaction14signature = private_key.sign_recoverable(bytes.fromhex(raw_transaction['RawTransaction']))1516# Create the transaction payload17transaction_2 = {18"Transaction": raw_transaction['RawTransaction'],19'Signature': signature.hex(),20'ReturnTransaction': True21}2223# Send the raw transaction24result = aelf.send_raw_transaction(transaction_2)25print('# send_raw_transaction', result)
Execute Raw Transaction#
Web API Path: /api/blockchain/executeRawTransaction
Method: POST
Parameters:
Example:
1aelf = AElf(url)23# Create the raw transaction4raw_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})1213# Sign the raw transaction14signature = private_key.sign_recoverable(bytes.fromhex(raw_transaction['RawTransaction']))1516# Create the transaction payload17transaction_1 = {18"RawTransaction": raw_transaction['RawTransaction'],19"Signature": signature.hex()20}2122# Execute the raw transaction23result = aelf.execute_raw_transaction(transaction_1)24print('# execute_raw_transaction', result)
Get Merkle Path#
Web API Path: /api/blockchain/merklePathByTransactionId?transactionId=
Method: POST
Parameters:
Example:
1aelf = AElf(url)23transaction_id = "your-transaction-id"4merkle_path = aelf.get_merkle_path(transaction_id)5print('# get_merkle_path', merkle_path)
Calculate Transaction Fee#
Web API Path: /api/blockchain/calculateTransactionFee
Method: POST
Parameters:
Returns:
Example:
1aelf = AElf(url)23calculate_transaction_fee_input = {4"RawTransaction": raw_transaction['RawTransaction']5}67calculate_transaction_fee_output = aelf.calculate_transaction_fee(calculate_transaction_fee_input)8print('# calculate_transaction_fee', calculate_transaction_fee_output)
Get Network Info#
Web API Path: /api/net/networkInfo
Method: POST
Example:
1aelf = AElf(url)23network_info = aelf.get_network_info()4print('# 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:
1aelf = AElf(url)23genesis_contract_address = aelf.get_genesis_contract_address_string()
get_system_contract_address#
Parameters:
Returns:
Example:
1aelf = AElf(url)23multi_token_contract_address = aelf.get_system_contract_address('AElf.ContractNames.Token')
get_system_contract_address_string#
Parameters:
Returns:
Example:
1aelf = AElf(url)23multi_token_contract_address_string = aelf.get_system_contract_address_string('AElf.ContractNames.Token')
create_transaction#
Parameters:
Example:
1aelf = AElf(url)23params = Hash()4params.value = hashlib.sha256(contract_name.encode('utf8')).digest()5transaction = aelf.create_transaction(genesisContractAddress, 'GetContractAddressByName', params.SerializeToString())
sign_transaction#
Sign a transaction with the user’s private key.
Parameters:
Example:
1aelf = AElf(url)23to_address_string = aelf.get_genesis_contract_address_string()4params = Hash()5params.value = hashlib.sha256(contract_name.encode('utf8')).digest()6transaction = aelf.create_transaction(to_address_string, 'GetContractAddressByName', params.SerializeToString())7transaction = aelf.sign_transaction(private_key, transaction)
get_address_from_public_key#
Generate an address from a public key.
Parameters:
Returns:
Example:
1aelf = AElf(url)2address = aelf.get_address_from_public_key(public_key)
get_address_string_from_public_key#
Generate an address string from a public key.
Parameters:
Returns:
Example:
1aelf = AElf(url)2address = aelf.get_address_string_from_public_key(public_key)
get_chain_id#
Returns:
Example:
1aelf = AElf(url)23chain_id = aelf.get_chain_id()4print('# get_chain_id', chain_id)
get_formatted_address#
Parameters:
Returns:
Example:
1aelf = AElf(url)2address = aelf.chain.get_system_contract_address("AElf.ContractNames.Consensus")3formatted_address = aelf.get_formatted_address(address)4print('formatted address', formatted_address)
Check whether the node is connected.
Example:
1aelf = AElf(url)2is_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.
1from aelf import AElfToolkit23# generate the private key4private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa'5private_key = PrivateKey(bytes(bytearray.fromhex(private_key_string)))67# create a toolkit8toolkit = AElfToolkit('http://127.0.0.1:8000', private_key)
Send a Transaction#
Send a CrossChainTransfer transaction using AElfToolkit.
1from aelf import AElfToolkit23# generate the private key4private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa'5private_key = PrivateKey(bytes(bytearray.fromhex(private_key_string)))67# create input, the type is generated by protoc8cross_chain_transfer_input = CrossChainTransferInput()910# AElfToolkit simplifies this transaction execution.11# create a toolkit12toolkit = AElfToolkit('http://127.0.0.1:8000', private_key)13toolkit.cross_chain_transfer(to_address_string, symbol, amount, memo, to_chain_id)
Requirements#
Support#
About Contributing#
Read out [contributing guide].
About Version#
Edited on: 16 July 2024 05:02:10 GMT+0