Algorand JavaScript SDK

repository·main·Indexed 43 days ago

https://github.com/algorand/js-algorand-sdk

The official JavaScript library (algosdk v3.7.0) for communicating with the Algorand network, supporting Node.js and modern browsers. It provides tools for interacting with Algod and Indexer services, ABI encoding/decoding for smart contracts, and utilities for managing accounts and transactions.

Tokens
21K
Snippets
79
Records
108
Agent score
55%

What's inside Algorand JS SDK

  1. Migrate SuggestedParams configuration

    main

    The SuggestedParams interface has changed. The SuggestedParamsWithMinFee interface was removed, and minFee is now a required field in the standard SuggestedParams interface.

    If you are manually constructing SuggestedParams objects (instead of fetching them from an Algod client), you must:

    1. Add a minFee field (type number | bigint).
    2. Convert genesisHash from a string to a Uint8Array (use algosdk.base64ToBytes if necessary).
    3. Note that genesisID is now optional.
  2. Quick Start: Connect to an Algod node

    main

    To get started, instantiate an algosdk.Algodv2 client with your API token, server address, and port. You can then call methods like .status().do() to interact with the network. Note that .do() is used to execute the request.

    const token = 'Your algod API token';
    const server = 'http://127.0.0.1';
    const port = 8080;
    const client = new algosdk.Algodv2(token, server, port);
    
    (async () => {
      console.log(await client.status().do());
    })().catch((e) => {
      console.log(e);
    });
  3. Install algosdk in the browser

    main

    To use the SDK directly in a browser, include a minified bundle via a <script> tag using a CDN like unpkg or jsdelivr. Ensure you include the integrity attribute for security.

    <script
      src="https://unpkg.com/algosdk@v3.7.0/dist/browser/algosdk.min.js"
      integrity="sha384-Ksil7tlB+Yp+9WUMjKpf0bQppKTfgLBzaJ++ckfV/lAuxfLP8T9ovUQ8Db3P3UsK"
      crossorigin="anonymous"
    ></script>
  4. Install algosdk via npm

    main

    To use the Algorand JavaScript SDK in a Node.js environment, install the algosdk package using npm. This package includes TypeScript types, but requires TypeScript version 4.2 or higher for proper type support.

    $ npm install algosdk
  5. Migrate Address usage from v2 to v3

    main

    In v3, the Address interface has been upgraded to a class. While decodeAddress and encodeAddress still exist, it is recommended to use the Address class directly.

    • Use Address.fromString(string) to create an instance from a string.
    • Use address.toString() to convert an instance back to a string.
    • Access the 32-byte public key via address.publicKey.
    • Access the checksum via the method address.checksum() (note: this is now a method, not a property).

    Most SDK functions that previously accepted address strings in v2 now accept either a string or an Address instance.

    // v3 recommended approach
    const address = algosdk.Address.fromString(
      'MO2H6ZU47Q36GJ6GVHUKGEBEQINN7ZWVACMWZQGIYUOE3RBSRVYHV4ACJI'
    );
    console.log('Address 32-byte public key component:', address.publicKey);
    console.log('Address checksum:', address.checksum());
    console.log('Address string:', address.toString());
  6. Handle BigInt with JSON and Msgpack

    main

    Because v3 uses bigint for many numeric fields (amounts, IDs, rounds, timestamps), standard JSON.parse and JSON.stringify may fail with TypeError: Do not know how to serialize a BigInt.

    JSON Operations:

    • Use algosdk.parseJSON(jsonString) to parse JSON with support for bigint fields.
    • Use algosdk.stringifyJSON(object) to serialize objects containing bigints.

    Msgpack Operations:

    • encodeObj and decodeObj are deprecated. Use msgpackRawEncode and msgpackRawDecode instead.
    • For preferred usage, use algosdk.encodeMsgpack(object) and algosdk.decodeMsgpack(buffer, Class).
  7. Migrate Transaction construction to FromObject variants

    main

    In v3, the standard make* functions that take individual arguments (e.g., makePaymentTxnWithSuggestedParams) have been removed. You must now use the FromObject variants which take a single parameter object.

    Example Migration:

    v2 (Deprecated):

    const txn = algosdk.makePaymentTxnWithSuggestedParams(
      'FROM_ADDR', 
      'TO_ADDR', 
      1000, 
      undefined, 
      note, 
      suggestedParams
    );

    v3 (Current):

    const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
      sender: 'FROM_ADDR',
      receiver: 'TO_ADDR',
      amount: 1000,
      note: Uint8Array.from([1, 2, 3]),
      suggestedParams,
    });

    Key Parameter Name Changes:

    • from $\rightarrow$ sender (for all transactions)
    • to $\rightarrow$ receiver (for Payment and Asset Transfer)
    • to $\rightarrow$ assetSender (for Asset Transfer revocationTarget replacement)
    • freezeState $\rightarrow$ frozen (for Asset Freeze)
    const suggestedParams = await client.getTransactionParams().do();
    
    const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
      sender: 'MO2H6ZU47Q36GJ6GVHUKGEBEQINN7ZWVACMWZQGIYUOE3RBSRVYHV4ACJI',
      receiver: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q',
      amount: 1000,
      note: Uint8Array.from([1, 2, 3]),
      suggestedParams,
    });
  8. Use ABI encoding and decoding utilities

    main

    The src/abi module provides the complete suite of tools for interacting with Algorand smart contracts using Application Binary Interface (ABI) standards. This includes utilities for defining contract interfaces, encoding method calls into transactions, decoding transaction results, and managing ABI types.

    Key functional areas include:

    • ABI Types: Defining and handling the data types used in smart contracts.
    • Contract Interfaces: Representing the structure of a smart contract.
    • Methods: Encoding specific contract method calls.
    • Transactions: Creating ABI-encoded transactions.
    • Reference/Decoding: Decoding data returned from the blockchain or provided in transaction references.
  9. Inspect transaction effects with ApplyData and EvalDelta

    main

    When a transaction is applied, ApplyData and EvalDelta describe the resulting state changes:

    ApplyData

    Contains high-level changes such as closingAmount, assetClosingAmount, senderRewards, receiverRewards, closeRewards, and newly created IDs for configAsset (ASA) or applicationID (App).

    EvalDelta

    Provides granular details on state changes, including:

    • globalDelta: A map of changes to global state.
    • localDeltas: A map of changes to local state for specific accounts.
    • sharedAccts: Accounts whose local state was modified by a non-sender.
    • logs: Application logs produced during execution.
    • innerTxns: A list of SignedTxnWithAD representing inner transactions.
  10. Define a full TransactionParams object

    main

    The TransactionParams interface is the top-level object used to construct any transaction. It combines common fields with type-specific parameters.

    Common fields:

    • type: A TransactionType enum (e.g., pay, appl, axfer).
    • sender: The Address of the transaction sender.
    • note: (Optional) Arbitrary Uint8Array data.
    • lease: (Optional) A 32-byte lease to prevent transaction replay.
    • rekeyTo: (Optional) The Address to authorize future transactions.
    • suggestedParams: The SuggestedParams for the transaction.

    Type-specific fields (only one should be populated based on type):

    • paymentParams (for pay)
    • keyregParams (for keyreg)
    • assetConfigParams (for acfg)
    • assetTransferParams (for axfer)
    • assetFreezeParams (for afrz)
    • appCallParams (for appl)
    • stateProofParams (for stpf)
    • heartbeatParams (for hb)
    const txnParams: TransactionParams = {
      type: TransactionType.pay,
      sender: 'SENDER_ADDRESS',
      suggestedParams: mySuggestedParams,
      paymentParams: {
        receiver: 'RECEIVER_ADDRESS',
        amount: 5000n
      }
    };