logo

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:

  • Install and use aelf-web3.js.
  • Understand the available API.
  • 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

    1
    npm install aelf-sdk

    Using Pure js

    1
    link dist/aelf.umd.js

    Create an AElf Instance#

    Set up your AElf instance and connect to a provider.

    Node.js

    1
    const AElf = require("aelf-sdk");
    2
    const aelf = new AElf(
    3
    new AElf.providers.HttpProvider("https://tdvw-test-node.aelf.io")
    4
    );

    Frontend (Using PureJs)

  • Include the script in your HTML file:
  • 1
    <script src="https://unpkg.com/aelf-sdk@latest/dist/aelf.umd.js"></script>
    2
    <script>
    3
    const 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.

    packagesusage
    dist/aelf.cjs.jsFor node.js, excludes node built-in modules like crypto.
    dist/aelf.umd.jsFor browsers, includes necessary node built-in modules.

    For Beginner in Frontend

  • Add the UMD package to your HTML:
  • 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)

  • Set up Webpack:
  • 1
    module.exports = {
    2
    resolve: {
    3
    alias: {
    4
    "aelf-sdk$": "aelf-sdk/dist/aelf.umd.js",
    5
    },
    6
    },
    7
    };
  • Set up Rollup:
  • 1
    const alias = require("rollup-plugin-alias");
    2
    3
    rollup({
    4
    // ...
    5
    plugins: [
    6
    alias({
    7
    "aelf-sdk": require.resolve("aelf-sdk/dist/aelf.umd.js"),
    8
    }),
    9
    ],
    10
    });

    For Node.js (Using CommonJS)

  • Set up Webpack:
  • 1
    module.exports = {
    2
    // ...
    3
    resolve: {
    4
    alias: {
    5
    "aelf-sdk$": "aelf-sdk/dist/aelf.cjs.js",
    6
    },
    7
    },
    8
    };
  • Set up Rollup:
  • 1
    const alias = require("rollup-plugin-alias");
    2
    3
    rollup({
    4
    // ...
    5
    plugins: [
    6
    alias({
    7
    "aelf-sdk": require.resolve("aelf-sdk/dist/aelf.cjs.js"),
    8
    }),
    9
    ],
    10
    });

    Note

  • aelf-web3.js is the same as aelf-sdk.
  • aelf-sdk is the package name on npm.
  • For more detailed usage and examples, refer to the aelf-web3.js repository.

    Development 🔨#

    Install Development Dependencies#

  • Install the required development dependencies:
  • 1
    yarn install

    Write Your Code#

  • Create your file under the src directory.
  • Write your logic in the newly created file.
  • Integrate Your Module#

  • Check src/index to see if you need to add your new module as an attribute to the AElf instance.
  • Execute yarn link in the root directory. This creates a global symbolic link to this package and stores it in the global node_modules directory.
  • 1
    yarn link
  • When using yarn link aelf-sdk in other directories, ensure the version of the package is correct. Inconsistent node versions can sometimes cause issues with linking the incorrect version of aelf-web3.js.
  • 1
    yarn link aelf-sdk

    Test Your Code#

  • Try out the logic you just wrote to make sure everything works as expected.
  • Linting#

  • To lint your code, run:
  • 1
    yarn lint

    Running Tests#

  • To run unit tests, execute:
  • Basic usage#

    Examples#

    You can also see full example here - Examples

    Create Instance

    1
    import AElf from "aelf-sdk";
    2
    3
    // Create a new instance of AElf
    4
    const aelf = new AElf(
    5
    new AElf.providers.HttpProvider("https://tdvw-test-node.aelf.io")
    6
    );

    Create or Load a Wallet

    1
    // Create a new wallet
    2
    const newWallet = AElf.wallet.createNewWallet();
    3
    4
    // Load a wallet by private key
    5
    const privateKeyWallet = AElf.wallet.getWalletByPrivateKey("your-private-key");
    6
    7
    // Load a wallet by mnemonic
    8
    const mnemonicWallet = AElf.wallet.getWalletByMnemonic("your-mnemonic");

    Get a System Contract Address

    1
    const tokenContractName = "AElf.ContractNames.Token";
    2
    let tokenContractAddress;
    3
    4
    (async () => {
    5
    // Get chain status
    6
    const chainStatus = await aelf.chain.getChainStatus();
    7
    // Get genesis contract address
    8
    const GenesisContractAddress = chainStatus.GenesisContractAddress;
    9
    // Get genesis contract instance
    10
    const zeroContract = await aelf.chain.contractAt(
    11
    GenesisContractAddress,
    12
    newWallet
    13
    );
    14
    // Get contract address by the read-only method 'GetContractAddressByName' of genesis contract
    15
    tokenContractAddress = await zeroContract.GetContractAddressByName.call(
    16
    AElf.utils.sha256(tokenContractName)
    17
    );
    18
    })();

    Get a Contract Instance

    1
    const wallet = AElf.wallet.createNewWallet();
    2
    let tokenContract;
    3
    4
    // Async method
    5
    (async () => {
    6
    tokenContract = await aelf.chain.contractAt(tokenContractAddress, wallet);
    7
    })();
    8
    9
    // Promise method
    10
    aelf.chain.contractAt(tokenContractAddress, wallet).then((result) => {
    11
    tokenContract = result;
    12
    });
    13
    14
    // Callback method
    15
    aelf.chain.contractAt(tokenContractAddress, wallet, (error, result) => {
    16
    if (error) throw error;
    17
    tokenContract = 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 address
    3
    const balanceResult = await tokenContract.GetBalance.call({
    4
    symbol: "ELF",
    5
    owner: "7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz",
    6
    });
    7
    console.log(balanceResult);
    8
    /**
    9
    {
    10
    "symbol": "ELF",
    11
    "owner": "7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz",
    12
    "balance": "1000000000000"
    13
    }
    14
    */
    15
    16
    // Send transaction method: Transfer tokens
    17
    const transactionId = await tokenContract.Transfer({
    18
    symbol: "ELF",
    19
    to: "7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz",
    20
    amount: "1000000000",
    21
    memo: "transfer in demo",
    22
    });
    23
    console.log(transactionId);
    24
    /**
    25
    {
    26
    "TransactionId": "123123"
    27
    }
    28
    */
    29
    })();

    Change the Node Endpoint#

    1
    import AElf from "aelf-sdk";
    2
    3
    const aelf = new AElf(
    4
    new AElf.providers.HttpProvider("https://tdvw-test-node.aelf.io")
    5
    );
    6
    aelf.setProvider(
    7
    new 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:

  • Local node: http://127.0.0.1:1235/swagger/index.html
  • Testnet nodes:
  • Setup:

    Create an instance of AElf:

    1
    import AElf from "aelf-sdk";
    2
    3
    // Change the URL if needed
    4
    const aelf = new AElf(new AElf.providers.HttpProvider("http://127.0.0.1:1235"));

    Get Chain Status#

    Get the current status of the blockchain.

  • Web API Path: /api/blockChain/chainStatus
  • Method: GET
  • Parameters: None
  • Returns: Object
  • Example:

    1
    aelf.chain.getChainStatus().then((res) => {
    2
    console.log(res);
    3
    });

    Get Contract File Descriptor Set#

    Get the protobuf definitions related to a contract.

  • Web API Path: /api/blockChain/contractFileDescriptorSet
  • Method: GET
  • Parameters: contractAddress (String)
  • Returns: String.
  • Example:

    1
    aelf.chain.getContractFileDescriptorSet(contractAddress).then((res) => {
    2
    console.log(res);
    3
    });

    Get Block Height#

    Get the current best height of the chain.

  • Web API Path: /api/blockChain/blockHeight
  • Method: GET
  • Parameters: None
  • Returns: Number.
  • Example:

    1
    aelf.chain.getBlockHeight().then((res) => {
    2
    console.log(res);
    3
    });

    Get Block#

    Get block information by block hash.

  • Web API Path: /api/blockChain/block
  • Method: GET
  • Parameters:
  • Returns: Object
  • Example:

    1
    aelf.chain.getBlock(blockHash, false).then((res) => {
    2
    console.log(res);
    3
    });

    Get Block By Height#

    Get block information by block height.

  • Web API Path: /api/blockChain/blockByHeight
  • Method: GET
  • Parameters:
  • Returns: Object
  • Example:

    1
    aelf.chain.getBlockByHeight(12, false).then((res) => {
    2
    console.log(res);
    3
    });

    Get Contract View Method List#

  • Web API Path: /api/blockChain/ContractViewMethodList
  • Method: GET
  • Parameters: address (String)
  • Returns: Array - The array of view method name
  • Example:

    1
    aelf.chain
    2
    .getContractViewMethodList("https://tdvw-test-node.aelf.io/")
    3
    .then((res) => {
    4
    console.log(res);
    5
    });

    Get Transaction Result#

  • Web API Path: /api/blockChain/transactionResult
  • Method: GET
  • Parameters: transactionId (String)
  • Returns: Object
  • Example:

    1
    aelf.chain.getTxResult(transactionId).then((res) => {
    2
    console.log(res);
    3
    });

    Get Merkle Path By TxId#

  • Web API Path: /api/blockChain/merklePathByTransactionId
  • Method: GET
  • Parameters:
  • Returns:
  • Example:

    1
    aelf.chain.merklePathByTransactionId(txId).then((res) => {
    2
    console.log(res);
    3
    });

    Get Multiple Transaction Results#

  • Web API Path: /api/blockChain/transactionResults
  • Method: GET
  • Parameters:
  • Returns:
  • Example:

    1
    aelf.chain.getTxResults(blockHash, 0, 2).then((res) => {
    2
    console.log(res);
    3
    });

    Get Transaction Pool Status#

  • Web API Path: /api/blockChain/transactionPoolStatus
  • Method: GET
  • Parameters: None
  • Send Transaction#

  • Web API Path: /api/blockChain/sendTransaction
  • Method: POST
  • Parameters: Object (Serialized protobuf data with RawTransaction string)
  • Send Multiple Transactions#

  • Web API Path: /api/blockChain/sendTransactions
  • Method: POST
  • Parameters: Object (Serialized protobuf data with RawTransaction string)
  • Call Read-Only Method#

    Call a read-only method on a contract.

  • Method: POST
  • Parameters: Object (Serialized protobuf data with RawTransaction string)
  • Returns: Method call result
  • Get Peers#

    Get peer info about the connected network nodes.

  • Method: GET
  • Parameters: withMetrics (Boolean)
  • Add Peer#

    Attempts to add a node to the connected network nodes

  • Method: POST
  • Parameters: Object The object with the following structure :
  • Remove Peer#

    Attempts to remove a node from the connected network nodes

  • Method: DELETE
  • Parameters: address (String)
  • Calculate Transaction Fee#

  • Web API Path: /api/blockChain/calculateTransactionFee
  • Method: POST
  • Parameters: CalculateTransactionFeeInput (Object with RawTransaction string):
  • Returns: CalculateTransactionFeeOutput (Object with fee details):
  • Example

    1
    aelf.chain.calculateTransactionFee(rawTransaction).then((res) => {
    2
    console.log(res);
    3
    });

    Network Info#

  • Method: GET
  • Parameters: None
  • Returns: Network connection info
  • AElf.wallet#

    AElf.wallet is a static property of AElf.

    createNewWallet#

    Returns:

  • Object
  • Example:

    1
    import AElf from "aelf-sdk";
    2
    const wallet = AElf.wallet.createNewWallet();
    3
    console.log(wallet);

    getWalletByMnemonic#

    Retrieves a wallet using a mnemonic phrase.

    Parameters:

  • mnemonic - String: The mnemonic phrase of the wallet.
  • Returns:

  • Object: The complete wallet object.
  • Example:

    1
    const wallet = AElf.wallet.getWalletByMnemonic(mnemonic);
    2
    console.log(wallet);

    getWalletByPrivateKey#

    Retrieves a wallet using a private key.

    Parameters:

  • privateKey - String: The mnemonic phrase of the wallet.
  • Returns:

  • Object: The complete wallet object, with an empty mnemonic.
  • Example:

    1
    const wallet = AElf.wallet.getWalletByPrivateKey(privateKey);
    2
    console.log(wallet);

    signTransaction#

    Signs a transaction using the wallet's key pair.

    Parameters:

  • rawTxn - String: The raw transaction data.
  • keyPair - String: The key pair to sign the transaction.
  • Returns:

  • Object: The signed transaction object.
  • Example:

    1
    const result = AElf.wallet.signTransaction(rawTxn, keyPair);
    2
    console.log(result);

    AESEncrypt#

    Encrypts a string using the AES algorithm.

    Parameters:

  • input - String: The input string to encrypt.
  • password - String: The password to use for encryption.
  • Returns:

  • String: The encrypted string.
  • AESDecrypt
  • Decrypts a string using the AES algorithm.

    Parameters:

  • input - String: The encrypted string.
  • password - String: The password used for encryption.
  • Returns:

  • String: The decrypted string.
  • 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:#

    1
    const AElf = require("aelf-sdk");
    2
    const { base58 } = AElf.utils;
    3
    4
    try {
    5
    base58.decode("$address"); // replace '$address' with actual address
    6
    console.log("Valid address");
    7
    } catch (error) {
    8
    console.error("Invalid address", error);
    9
    }

    AElf.version#

    1
    import AElf from "aelf-sdk";
    2
    console.log(AElf.version); // outputs the version, e.g., 3.2.23

    Requirements#

    To use aelf SDK, you need:

  • Node.js
  • NPM
  • 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