| Branch | Tests | Coverage |
|---|---|---|
master |
aelf-sdk.js for aelf is like web.js for ethereum.
aelf-sdk.js 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.js, as well as providing a API reference documentation with examples.
You can get some codes in the ./examples directory
First you need to get aelf-sdk.js into your project. This can be done using the following methods:
npm: npm install aelf-sdk
pure js: link dist/aelf.umd.js
After that you need to create a aelf instance and set a provider.
// 1.In node.js use: const AElf = require('aelf-sdk');
// 2.FrontEnd freshman, add following tag in html
// <script src="https://unpkg.com/aelf-sdk@lastest/dist/aelf.umd.js"></script>
const aelf = new AElf(new AElf.providers.HttpProvider('http://127.0.0.1:8000'));You can skip 2.2 as 2.1 is enough now.
In our dist directory, we supply two kinds of packages for different platforms, such as Node and Browser.
| packages | usage |
|---|---|
| dist/aelf.esm.js | built as an ES Module, optimized for modern bundlers and tree-shaking. Designed for use in modern JavaScript environments like webpack, Rollup, and Vite. |
| dist/aelf.cjs.js | built for node, remove node built-in modules such as crypto. |
| dist/aelf.umd.js | built for browser, add some node built-in modules by webpack |
You can choose any packages based on your need, for examples:
if you are new to FrontEnd, you can use AElf-sdk by add a script tag in your html files.
<!-- minified version with UMD module -->
<script src="https://unpkg.com/aelf-sdk@lastest/dist/aelf.umd.js"></script>if you want to use a bundle system such as webpack or rollup, and build your applications for Node.js and Browsers, just import the specified version of package files.
ESM
// ✅ Recommended: Use "exports" to enable Tree Shaking
import wallet from 'aelf-sdk/wallet';
// ✅ Also supported: Directly import from the "src" directory
import wallet from 'aelf-sdk/src/wallet/index.js';
// ✅ Backward compatibility: Traditional import method
import AElf from 'aelf-sdk';
const { wallet } = AElf;Webpack:
module.exports = {
// ...
resolve: {
alias: {
'aelf-sdk$': 'aelf-sdk/dist/aelf.umd.js'
}
}
};Rollup:
const alias = require('rollup-plugin-alias');
rollup({
// ...
plugins: [
alias({
'aelf-sdk': require.resolve('aelf-sdk/dist/aelf.umd.js')
})
]
});Webpack:
module.exports = {
// ...
resolve: {
alias: {
'aelf-sdk$': 'aelf-sdk/dist/aelf.cjs.js'
}
}
};Rollup:
const alias = require('rollup-plugin-alias');
rollup({
// ...
plugins: [
alias({
'aelf-sdk': require.resolve('aelf-sdk/dist/aelf.cjs.js')
})
]
});You can also see full examples in ./examples;
-
Create a new instance of AElf, connect to an AELF chain node.
import AElf from 'aelf-sdk'; // create a new instance of AElf const aelf = new AElf(new AElf.providers.HttpProvider('http://127.0.0.1:1235'));
-
Create or load a wallet with
AElf.wallet// create a new wallet const newWallet = AElf.wallet.createNewWallet(); // load a wallet by private key const priviteKeyWallet = AElf.wallet.getWalletByPrivateKey('xxxxxxx'); // load a wallet by mnemonic const mnemonicWallet = AElf.wallet.getWalletByMnemonic('set kite ...');
-
Get a system contract address, take
AElf.ContractNames.Tokenas an exampleconst tokenContractName = 'AElf.ContractNames.Token'; let tokenContractAddress; (async () => { // get chain status const chainStatus = await aelf.chain.getChainStatus(); // get genesis contract address const GenesisContractAddress = chainStatus.GenesisContractAddress; // get genesis contract instance const zeroContract = await aelf.chain.contractAt(GenesisContractAddress, newWallet); // Get contract address by the read only method `GetContractAddressByName` of genesis contract tokenContractAddress = await zeroContract.GetContractAddressByName.call(AElf.utils.sha256(tokenContractName)); })();
-
Get a contract instance by contract address
const wallet = AElf.wallet.createNewWallet(); let tokenContract; // Use token contract for examples to demonstrate how to get a contract instance in different ways // in async function (async () => { tokenContract = await aelf.chain.contractAt(tokenContractAddress, wallet); })(); // promise way aelf.chain.contractAt(tokenContractAddress, wallet).then(result => { tokenContract = result; }); // callback way aelf.chain.contractAt(tokenContractAddress, wallet, (error, result) => { if (error) throw error; tokenContract = result; });
-
How to use contract instance
A contract instance consists of several contract methods and methods can be called in two ways: read-only and send transaction.
(async () => { // get the balance of an address, this would not send a transaction, // or store any data on the chain, or required any transaction fee, only get the balance // with `.call` method, `aelf-sdk` will only call read-only method const result = await tokenContract.GetBalance.call({ symbol: 'ELF', owner: '7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz' }); console.log(result); /** { "symbol": "ELF", "owner": "2661mQaaPnzLCoqXPeys3Vzf2wtGM1kSrqVBgNY4JUaGBxEsX8", "balance": "1000000000000" }*/ // with no `.call`, `aelf-sdk` will sign and send a transaction to the chain, and return a transaction id. // make sure you have enough transaction fee `ELF` in your wallet const transactionId = await tokenContract.Transfer({ symbol: 'ELF', to: '7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz', amount: '1000000000', memo: 'transfer in demo' }); console.log(transactionId); /** { "TransactionId": "123123" } */ })();
-
Change the node endpoint by using
aelf.setProviderimport AElf from 'aelf-sdk'; const aelf = new AElf(new AElf.providers.HttpProvider('http://127.0.0.1:1235')); aelf.setProvider(new AElf.providers.HttpProvider('http://127.0.0.1:8000'));
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'
parameters and returns based on the URL: https://aelf-public-node.aelf.io/swagger/index.html
The usage of these methods is based on the AElf instance, so if you don't have one please create it:
import AElf from 'aelf-sdk';
// create a new instance of AElf, change the URL if needed
const aelf = new AElf(new AElf.providers.HttpProvider('http://127.0.0.1:1235'));Get the current status of the block chain.
Web API path
/api/blockChain/chainStatus
Parameters
Empty
Returns
Object
ChainId - StringBranches - ObjectNotLinkedBlocks - ObjectLongestChainHeight - NumberLongestChainHash - StringGenesisBlockHash - StringGenesisContractAddress - StringLastIrreversibleBlockHash - StringLastIrreversibleBlockHeight - NumberBestChainHash - StringBestChainHeight - Number
Example
aelf.chain.getChainStatus().then(res => {
console.log(res);
});Get the protobuf definitions related to a contract
Web API path
/api/blockChain/contractFileDescriptorSet
Parameters
contractAddress - Stringaddress of a contract
Returns
String
Example
aelf.chain.getContractFileDescriptorSet(contractAddress).then(res => {
console.log(res);
});Get current best height of the chain.
Web API path
/api/blockChain/blockHeight
Parameters
Empty
Returns
Number
Example
aelf.chain.getBlockHeight().then(res => {
console.log(res);
});Get block information by block hash.
Web API path
/api/blockChain/block
Parameters
blockHash - StringincludeTransactions - Boolean:
truerequire transaction ids list in the blockfalseDoesn't require transaction ids list in the block
Returns
Object
BlockHash - StringHeader - ObjectPreviousBlockHash - StringMerkleTreeRootOfTransactions - StringMerkleTreeRootOfWorldState - StringExtra - ArrayHeight - NumberTime - google.protobuf.TimestampChainId - StringBloom - StringSignerPubkey - String
Body - ObjectTransactionsCount - NumberTransactions - ArraytransactionId - String
Example
aelf.chain.getBlock(blockHash, false).then(res => {
console.log(res);
});Web API path
/api/blockChain/blockByHeight
Get block information by block height.
Parameters
blockHeight - NumberincludeTransactions - Boolean:
truerequire transaction ids list in the blockfalseDoesn't require transaction ids list in the block
Returns
Object
BlockHash - StringHeader - ObjectPreviousBlockHash - StringMerkleTreeRootOfTransactions - StringMerkleTreeRootOfWorldState - StringExtra - ArrayHeight - NumberTime - google.protobuf.TimestampChainId - StringBloom - StringSignerPubkey - String
Body - ObjectTransactionsCount - NumberTransactions - ArraytransactionId - String
Example
aelf.chain.getBlockByHeight(12, false).then(res => {
console.log(res);
});Get the result of a transaction
Web API path
/api/blockChain/transactionResult
Parameters
transactionId - String
Returns
Object
TransactionId - StringStatus - StringLogs - ArrayAddress - StringName - StringIndexed - ArrayNonIndexed - String
Bloom - StringBlockNumber - NumberTransaction - ObjectFrom - StringTo - StringRefBlockNumber - NumberRefBlockPrefix - StringMethodName - StringParams - ObjectSignature - String
ReadableReturnValue - ObjectError - String
Example
aelf.chain.getTxResult(transactionId).then(res => {
console.log(res);
});Get multiple transaction results in a block
Web API path
/api/blockChain/transactionResults
Parameters
blockHash - Stringoffset - Numberlimit - Number
Returns
Array - The array of method descriptions:
- the transaction result object
Example
aelf.chain.getTxResults(blockHash, 0, 2).then(res => {
console.log(res);
});Get the transaction pool status.
Web API path
/api/blockChain/transactionPoolStatus
Parameters
Empty
Broadcast a transaction
Web API path
/api/blockChain/sendTransaction
POST
Parameters
Object - Serialization of data into protobuf data, The object with the following structure :
RawTransaction - String:
usually developers don't need to use this function directly, just get a contract method and send transaction by call contract method:
Broadcast multiple transactions
POST
Parameters
Object - The object with the following structure :
RawTransaction - String
Estimate transaction fee
Web API path
/api/blockChain/calculateTransactionFee
POST
Parameters
Object - The object with the following structure :
RawTransaction - String
Call a read-only method on a contract.
POST
Parameters
Object - The object with the following structure :
RawTransaction - String
Get peer info about the connected network nodes
Attempts to add a node to the connected network nodes
you need to create a aelf authorization instance and set a provider
const aelf = new AElf(
new AElf.providers.HttpProvider('http://127.0.0.1:8000', 8000, {
Authorization: AElf.utils.getAuthorization('UseName', 'Password')
})
);Example
const aelf = new AElf(
new AElf.providers.HttpProvider('http://127.0.0.1:8000', 8000, {
Authorization: AElf.utils.getAuthorization('aelf', '12345678')
})
);
aelf.chain.addPeer('192.168.11.140:6801').then(res => {
console.log(res);
});Attempts to remove a node from the connected network nodes
you need to create a aelf authorization instance and set a provider
const aelf = new AElf(
new AElf.providers.HttpProvider('http://127.0.0.1:8000', 8000, {
Authorization: AElf.utils.getAuthorization('UseName', 'Password')
})
);Example
const aelf = new AElf(
new AElf.providers.HttpProvider('http://127.0.0.1:8000', 8000, {
Authorization: AElf.utils.getAuthorization('aelf', '12345678')
})
);
aelf.chain.removePeer('192.168.11.140:6801').then(res => {
console.log(res);
});Get information about the node’s connection to the network
AElf.wallet is a static property of AElf.
Use the api to see detailed results
Returns
Object
mnemonic - String: mnemonicBIP44Path - String: m/purpose'/coin_type'/account'/change/address_indexchildWallet - Object: HD WalletkeyPair - String: The EC key pair generated by ellipticprivateKey - String: private Keyaddress - String: address
Example
import AElf from 'aelf-sdk';
const wallet = AElf.wallet.createNewWallet();Parameters
mnemonic - String: wallet's mnemonic
Returns
Object: Complete wallet object.
Example
const wallet = AElf.wallet.getWalletByMnemonic(mnemonic);Parameters
privateKey: String: wallet's private key
Returns
Object: Complete wallet object, with empty mnemonic
Example
const wallet = AElf.wallet.getWalletByPrivateKey(privateKey);Use wallet keypair to sign a transaction
Parameters
rawTxn - StringkeyPair - String
Returns
Object: The object with the following structure :
Example
const result = AElf.wallet.signTransaction(rawTxn, keyPair);Encrypt a string by aes algorithm
Parameters
input - Stringpassword - String
Returns
String
Decrypt by aes algorithm
Parameters
input - Stringpassword - String
Returns
String
Simple example in how to use aelf.pbjs;
The reference to protobuf.js, read the documentation to see how to use.
Some basic format methods about proto for aelf.
For more information, please see the code in src/util/proto.js. It is simple and easy to understand.
Some methods for aelf.
For more information, please see the code in src/util/utils.js. It is simple and easy to understand.
const AElf = require('aelf-sdk');
const { base58 } = AElf.utils;
base58.decode('$addresss'); // throw error if invalidimport AElf from 'aelf-sdk';
AElf.version; // eg. 3.2.23sudo apt-get update
sudo apt-get install nodejs
sudo apt-get install npmBuild the web3.js package:
yarn run buildyarn run testCommit code will run test and lint automatically, and show the test result in readme.md, please make sure all test cases passed.
Read out contributing guide
https://semver.org/