JavaScript SDK
aelf-web3.js - aelf JavaScript API#
Introduction#
The aelf-web3.js library for aelf is similar to web3.js for Ethereum. It allows you to interact with a local or remote aelf node using an HTTP connection.
This guide will help you:
For more details, check out the repository: aelf-web3.js.
Quickstart#
Adding aelf-web3.js#
Now, You can add aelf-web3.js using npm or directly in your HTML.
Using npm
1npm install aelf-sdk
Using Pure js
1link dist/aelf.umd.js
Create an AElf Instance#
Set up your AElf instance and connect to a provider.
Node.js
1const AElf = require("aelf-sdk");2const aelf = new AElf(3new AElf.providers.HttpProvider("https://tdvw-test-node.aelf.io")4);
Frontend (Using PureJs)
1<script src="https://unpkg.com/aelf-sdk@latest/dist/aelf.umd.js"></script>2<script>3const aelf = new AElf(new AElf.providers.HttpProvider('https://tdvw-test-node.aelf.io'));4</script>
Choose the Right Package#
You can skip this step, if Adding aelf-web3.js is enough
The dist directory provides packages for different environments.
packages | usage |
---|---|
dist/aelf.cjs.js | For node.js, excludes node built-in modules like crypto. |
dist/aelf.umd.js | For browsers, includes necessary node built-in modules. |
For Beginner in Frontend
1<!-- minified version with UMD module -->2<script src="https://unpkg.com/aelf-sdk@lastest/dist/aelf.umd.js"></script>
Use with Bundlers#
If you want to use a bundler like Webpack or Rollup, import the specified version of the package files.
For Browser (Using UMD)
1module.exports = {2resolve: {3alias: {4"aelf-sdk$": "aelf-sdk/dist/aelf.umd.js",5},6},7};
1const alias = require("rollup-plugin-alias");23rollup({4// ...5plugins: [6alias({7"aelf-sdk": require.resolve("aelf-sdk/dist/aelf.umd.js"),8}),9],10});
For Node.js (Using CommonJS)
1module.exports = {2// ...3resolve: {4alias: {5"aelf-sdk$": "aelf-sdk/dist/aelf.cjs.js",6},7},8};
1const alias = require("rollup-plugin-alias");23rollup({4// ...5plugins: [6alias({7"aelf-sdk": require.resolve("aelf-sdk/dist/aelf.cjs.js"),8}),9],10});
Note
For more detailed usage and examples, refer to the aelf-web3.js repository.
Development 🔨#
Install Development Dependencies#
1yarn install
Write Your Code#
Integrate Your Module#
Link the Package Globally#
1yarn link
Link the Package in Other Directories#
1yarn link aelf-sdk
Test Your Code#
Linting#
1yarn lint
Running Tests#
Basic usage#
Examples#
You can also see full example here - Examples
Create Instance
1import AElf from "aelf-sdk";23// Create a new instance of AElf4const aelf = new AElf(5new AElf.providers.HttpProvider("https://tdvw-test-node.aelf.io")6);
Create or Load a Wallet
1// Create a new wallet2const newWallet = AElf.wallet.createNewWallet();34// Load a wallet by private key5const privateKeyWallet = AElf.wallet.getWalletByPrivateKey("your-private-key");67// Load a wallet by mnemonic8const mnemonicWallet = AElf.wallet.getWalletByMnemonic("your-mnemonic");
Get a System Contract Address
1const tokenContractName = "AElf.ContractNames.Token";2let tokenContractAddress;34(async () => {5// Get chain status6const chainStatus = await aelf.chain.getChainStatus();7// Get genesis contract address8const GenesisContractAddress = chainStatus.GenesisContractAddress;9// Get genesis contract instance10const zeroContract = await aelf.chain.contractAt(11GenesisContractAddress,12newWallet13);14// Get contract address by the read-only method 'GetContractAddressByName' of genesis contract15tokenContractAddress = await zeroContract.GetContractAddressByName.call(16AElf.utils.sha256(tokenContractName)17);18})();
Get a Contract Instance
1const wallet = AElf.wallet.createNewWallet();2let tokenContract;34// Async method5(async () => {6tokenContract = await aelf.chain.contractAt(tokenContractAddress, wallet);7})();89// Promise method10aelf.chain.contractAt(tokenContractAddress, wallet).then((result) => {11tokenContract = result;12});1314// Callback method15aelf.chain.contractAt(tokenContractAddress, wallet, (error, result) => {16if (error) throw error;17tokenContract = result;18});
Use Contract Instance
How to use a contract instance. You can call methods in two ways: read-only and send transaction.
1(async () => {2// Read-only method: Get the balance of an address3const balanceResult = await tokenContract.GetBalance.call({4symbol: "ELF",5owner: "7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz",6});7console.log(balanceResult);8/**9{10"symbol": "ELF",11"owner": "7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz",12"balance": "1000000000000"13}14*/1516// Send transaction method: Transfer tokens17const transactionId = await tokenContract.Transfer({18symbol: "ELF",19to: "7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz",20amount: "1000000000",21memo: "transfer in demo",22});23console.log(transactionId);24/**25{26"TransactionId": "123123"27}28*/29})();
Change the Node Endpoint#
1import AElf from "aelf-sdk";23const aelf = new AElf(4new AElf.providers.HttpProvider("https://tdvw-test-node.aelf.io")5);6aelf.setProvider(7new AElf.providers.HttpProvider("https://tdvw-test-node.aelf.io")8);
Web API#
Access the Web API of your aelf node at {chainAddress}/swagger/index.html
Examples:
Setup:
Create an instance of AElf:
1import AElf from "aelf-sdk";23// Change the URL if needed4const aelf = new AElf(new AElf.providers.HttpProvider("http://127.0.0.1:1235"));
Get Chain Status#
Get the current status of the blockchain.
Example:
1aelf.chain.getChainStatus().then((res) => {2console.log(res);3});
Get Contract File Descriptor Set#
Get the protobuf definitions related to a contract.
Example:
1aelf.chain.getContractFileDescriptorSet(contractAddress).then((res) => {2console.log(res);3});
Get Block Height#
Get the current best height of the chain.
Example:
1aelf.chain.getBlockHeight().then((res) => {2console.log(res);3});
Get Block#
Get block information by block hash.
Example:
1aelf.chain.getBlock(blockHash, false).then((res) => {2console.log(res);3});
Get Block By Height#
Get block information by block height.
Example:
1aelf.chain.getBlockByHeight(12, false).then((res) => {2console.log(res);3});
Get Contract View Method List#
Example:
1aelf.chain2.getContractViewMethodList("https://tdvw-test-node.aelf.io/")3.then((res) => {4console.log(res);5});
Get Transaction Result#
Example:
1aelf.chain.getTxResult(transactionId).then((res) => {2console.log(res);3});
Get Merkle Path By TxId#
Example:
1aelf.chain.merklePathByTransactionId(txId).then((res) => {2console.log(res);3});
Get Multiple Transaction Results#
Example:
1aelf.chain.getTxResults(blockHash, 0, 2).then((res) => {2console.log(res);3});
Get Transaction Pool Status#
Send Transaction#
Send Multiple Transactions#
Call Read-Only Method#
Call a read-only method on a contract.
Get Peers#
Get peer info about the connected network nodes.
Add Peer#
Attempts to add a node to the connected network nodes
Remove Peer#
Attempts to remove a node from the connected network nodes
Calculate Transaction Fee#
Example
1aelf.chain.calculateTransactionFee(rawTransaction).then((res) => {2console.log(res);3});
Network Info#
AElf.wallet#
AElf.wallet is a static property of AElf.
createNewWallet#
Returns:
Example:
1import AElf from "aelf-sdk";2const wallet = AElf.wallet.createNewWallet();3console.log(wallet);
getWalletByMnemonic#
Retrieves a wallet using a mnemonic phrase.
Parameters:
Returns:
Example:
1const wallet = AElf.wallet.getWalletByMnemonic(mnemonic);2console.log(wallet);
getWalletByPrivateKey#
Retrieves a wallet using a private key.
Parameters:
Returns:
Example:
1const wallet = AElf.wallet.getWalletByPrivateKey(privateKey);2console.log(wallet);
signTransaction#
Signs a transaction using the wallet's key pair.
Parameters:
Returns:
Example:
1const result = AElf.wallet.signTransaction(rawTxn, keyPair);2console.log(result);
AESEncrypt#
Encrypts a string using the AES algorithm.
Parameters:
Returns:
Decrypts a string using the AES algorithm.
Parameters:
Returns:
These are the detailed functions and their usages for the AElf.wallet API. If you have any specific questions or need further clarification, feel free to ask!
AElf.pbjs#
Reference to protobuf.js. For detailed usage, refer to the protobuf.js documentation.
AElf.pbUtils#
Provides basic format methods for aelf. For detailed code, see src/utils/proto.js.
AElf.utils#
Contains utility methods for aelf. For detailed code, see src/utils/utils.js.
Check address#
Example to check if an address is valid using base58 utility from aelf.
Example:#
1const AElf = require("aelf-sdk");2const { base58 } = AElf.utils;34try {5base58.decode("$address"); // replace '$address' with actual address6console.log("Valid address");7} catch (error) {8console.error("Invalid address", error);9}
AElf.version#
1import AElf from "aelf-sdk";2console.log(AElf.version); // outputs the version, e.g., 3.2.23
Requirements#
To use aelf SDK, you need:
Support https://img.shields.io/badge/browsers-latest%202%20versions-brightgreen.svg
https://img.shields.io/badge/node-%3E=10-green.svg
About contributing#
Read out [contributing guide]
About Version#
AElf SDK follows Semantic Versioning. For more details, refer to semver.org.
Edited on: 15 July 2024 05:26:57 GMT+0