### Quick Start: Connect to Algorand Node
Source: https://github.com/algorand/js-algorand-sdk/blob/main/README.md
Initialize the Algod client to communicate with an Algorand node. Replace placeholders with your actual API token, server address, and port. This example demonstrates fetching the node's status.
```javascript
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);
});
```
--------------------------------
### Install algosdk with npm
Source: https://github.com/algorand/js-algorand-sdk/blob/main/README.md
Install the SDK for use in Node.js projects. Ensure you have Node.js and npm installed.
```bash
npm install algosdk
```
--------------------------------
### Algodv2 Client Initialization and Usage
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Demonstrates how to initialize the Algodv2 client to connect to an Algorand node and perform common operations such as checking node health, getting status, fetching suggested transaction parameters, account information, asset details, application data, block data, and compiling TEAL code.
```APIDOC
## Algodv2 Client
`new algosdk.Algodv2(token, server, port)` creates the primary client used to submit transactions, query accounts, compile TEAL, and read blockchain state. Every method returns a builder object; call `.do()` to execute the HTTP request and receive a typed response.
### Usage Example
```typescript
import algosdk from 'algosdk';
// Connect to a local sandbox node (default sandbox credentials)
const algodClient = new algosdk.Algodv2(
'a'.repeat(64), // API token
'http://localhost',
4001
);
// Check node health
await algodClient.healthCheck().do();
// Get node status
const status = await algodClient.status().do();
console.log('Last round:', status.lastRound);
// Fetch suggested transaction parameters (required for every transaction)
const sp = await algodClient.getTransactionParams().do();
console.log('Min fee:', sp.minFee); // bigint, e.g. 1000n
// Fetch account information
const acctInfo = await algodClient.accountInformation('XBYLS2E6YI6XXL5BWCAMOA4GTWHXWENZMX5UHXMRNWWUQ7BXCY5WC5TEPA').do();
console.log('Balance (microAlgos):', acctInfo.amount);
// Fetch asset info
const asset = await algodClient.getAssetByID(163650n).do();
console.log('Asset name:', asset.params.name);
// Fetch application info and box storage
const app = await algodClient.getApplicationByID(60553466n).do();
const box = await algodClient.getApplicationBoxByName(60553466n, algosdk.coerceToBytes('mybox')).do();
console.log('Box value:', box.value);
// Get block data
const block = await algodClient.block(18038133n).do();
// Compile TEAL source
const compiled = await algodClient.compile('#pragma version 8\nint 1').do();
const programBytes = algosdk.base64ToBytes(compiled.result);
```
### Methods
- **healthCheck()**: Checks the health of the Algorand node.
- **status()**: Retrieves the current status of the Algorand node.
- **getTransactionParams()**: Fetches suggested transaction parameters.
- **accountInformation(address)**: Retrieves information for a given Algorand account address.
- **getAssetByID(assetId)**: Fetches details for a specific asset ID.
- **getApplicationByID(appId)**: Retrieves information for a specific application ID.
- **getApplicationBoxByName(appId, boxName)**: Fetches the content of a specific application box.
- **block(roundNumber)**: Retrieves block data for a given round number.
- **compile(tealSourceCode)**: Compiles TEAL source code into program bytes.
```
--------------------------------
### Install algosdk for Node.js or Browser
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Install the algosdk package using npm for Node.js environments or include it via a CDN for browser usage.
```bash
# Node.js
npm install algosdk
# Browser (CDN)
#
```
--------------------------------
### Setup Mocha for Browser Testing
Source: https://github.com/algorand/js-algorand-sdk/blob/main/tests/browser/index.html
This code is necessary to enable the assert functionality in a browser environment by mocking the Node.js process object. It also initializes Mocha's 'bdd' mode.
```javascript
window.process = { env: {} };
mocha.setup('bdd');
```
--------------------------------
### Kmd Client Initialization and Usage
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Demonstrates how to initialize the Kmd client, list wallets, open a wallet session, list keys, export a private key, sign a transaction, and release the wallet session.
```APIDOC
## Kmd Client
`new algosdk.Kmd(token, server, port)` connects to the Algorand Key Management Daemon.
### Initialization
```typescript
const kmdClient = new algosdk.Kmd(
'a'.repeat(64), // KMD API token
'http://localhost',
7833
);
```
### Operations
#### List Wallets
```typescript
const { wallets } = await kmdClient.listWallets();
const defaultWallet = wallets.find((w: any) => w.name === 'unencrypted-default-wallet');
```
#### Initialize Wallet Handle
```typescript
const { wallet_handle_token: handle } = await kmdClient.initWalletHandle(
defaultWallet.id,
'' // empty password for sandbox default wallet
);
```
#### List Keys
```typescript
const { addresses } = await kmdClient.listKeys(handle);
console.log('Wallet addresses:', addresses);
```
#### Export Key
```typescript
const { private_key: sk } = await kmdClient.exportKey(handle, '', addresses[0]);
```
#### Sign Transaction
```typescript
const sp = { fee: 1000n, firstValid: 100n, lastValid: 200n, genesisHash: new Uint8Array(32), minFee: 1000n, flatFee: true };
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
sender: addresses[0],
receiver: addresses[1],
amount: 500_000n,
suggestedParams: sp,
});
const { signed_transaction } = await kmdClient.signTransaction(handle, '', txn);
```
#### Release Wallet Handle
```typescript
await kmdClient.releaseWalletHandle(handle);
```
```
--------------------------------
### Generate SDK Documentation
Source: https://github.com/algorand/js-algorand-sdk/blob/main/README.md
Generate the documentation website for the SDK. The output will be located in the 'docs/' directory.
```bash
npm run docs
```
--------------------------------
### Create, Opt-in, Call, Update, and Delete Algorand Applications
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Demonstrates the lifecycle of an Algorand application, from creation and opt-in to calling methods, updating the program, and finally deleting the application. Ensure TEAL programs are compiled and accounts are generated before execution.
```typescript
import algosdk from 'algosdk';
const algodClient = new algosdk.Algodv2('a'.repeat(64), 'http://localhost', 4001);
const creator = algosdk.generateAccount();
const sp = await algosdk.Algodv2.prototype; // illustrative — use real client
// const sp = await algodClient.getTransactionParams().do();
// Compile TEAL programs
const approvalResp = await algodClient.compile(approvalTeal).do();
const clearResp = await algodClient.compile(clearTeal).do();
const approvalProgram = algosdk.base64ToBytes(approvalResp.result);
const clearProgram = algosdk.base64ToBytes(clearResp.result);
// Create the application
const createTxn = algosdk.makeApplicationCreateTxnFromObject({
sender: creator.addr,
approvalProgram,
clearProgram,
numGlobalByteSlices: 1,
numGlobalInts: 1,
numLocalByteSlices: 1,
numLocalInts: 1,
suggestedParams: sp,
onComplete: algosdk.OnApplicationComplete.NoOpOC,
});
await algodClient.sendRawTransaction(createTxn.signTxn(creator.sk)).do();
const createResult = await algosdk.waitForConfirmation(algodClient, createTxn.txID(), 4);
const appId = createResult.applicationIndex!;
// Opt-in an account to the app (enables local state)
const optInTxn = algosdk.makeApplicationOptInTxnFromObject({
sender: creator.addr,
appIndex: appId,
suggestedParams: sp,
});
// NoOp call with arguments
const callTxn = algosdk.makeApplicationNoOpTxnFromObject({
sender: creator.addr,
appIndex: appId,
suggestedParams: sp,
appArgs: [algosdk.coerceToBytes('store'), algosdk.encodeUint64(42n)],
});
// Read global state
const appInfo = await algodClient.getApplicationByID(appId).do();
const globalState = appInfo.params.globalState ?? [];
for (const kv of globalState) {
console.log(algosdk.bytesToBase64(kv.key), '->', kv.value.bytes ?? kv.value.uint);
}
// Update the approval program
const updateTxn = algosdk.makeApplicationUpdateTxnFromObject({
sender: creator.addr,
appIndex: appId,
approvalProgram: newApprovalProgram,
clearProgram,
suggestedParams: sp,
});
// Delete the application
const deleteTxn = algosdk.makeApplicationDeleteTxnFromObject({
sender: creator.addr,
appIndex: appId,
suggestedParams: sp,
});
```
--------------------------------
### Run Algorand SDK Test Suite in Node.js
Source: https://github.com/algorand/js-algorand-sdk/blob/main/README.md
Execute the Algorand SDK test suite using Docker. This command ensures compatibility with the official testing framework.
```bash
make docker-test
```
--------------------------------
### Connect and Use Kmd Client
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Connects to the KMD daemon, lists wallets, opens a session, lists keys, exports a private key, signs a transaction, and releases the wallet session. Ensure KMD is running and accessible.
```typescript
import algosdk from 'algosdk';
const kmdClient = new algosdk.Kmd(
'a'.repeat(64), // KMD API token (found in kmd.token file)
'http://localhost',
7833
);
// List wallets
const { wallets } = await kmdClient.listWallets();
const defaultWallet = wallets.find((w: any) => w.name === 'unencrypted-default-wallet');
// Open a wallet session
const { wallet_handle_token: handle } = await kmdClient.initWalletHandle(
defaultWallet.id,
'' // empty password for the sandbox default wallet
);
// List keys in the wallet
const { addresses } = await kmdClient.listKeys(handle);
console.log('Wallet addresses:', addresses);
// Export a key (secret key as Uint8Array)
const { private_key: sk } = await kmdClient.exportKey(handle, '', addresses[0]);
// Sign a transaction using KMD (key never leaves KMD process)
const sp = { fee: 1000n, firstValid: 100n, lastValid: 200n, genesisHash: new Uint8Array(32), minFee: 1000n, flatFee: true };
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
sender: addresses[0],
receiver: addresses[1],
amount: 500_000n,
suggestedParams: sp,
});
const { signed_transaction } = await kmdClient.signTransaction(handle, '', txn);
// Release the session
await kmdClient.releaseWalletHandle(handle);
```
--------------------------------
### Build js-algorand-sdk
Source: https://github.com/algorand/js-algorand-sdk/blob/main/README.md
Build a new version of the library from the source code. This command is typically used by developers contributing to the SDK.
```bash
npm run build
```
--------------------------------
### makeApplicationOptInTxnFromObject
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Creates a transaction to opt an account into an application. This is necessary for an account to interact with an application's local state.
```APIDOC
## makeApplicationOptInTxnFromObject — Opt-in to an Application
### Method Signature
```typescript
algosdk.makeApplicationOptInTxnFromObject(parameters: {
sender: string;
appIndex: number;
suggestedParams?: SuggestedParams;
}): Transaction
```
### Parameters
- **sender** (string) - The address of the account opting in.
- **appIndex** (number) - The ID of the application to opt into.
- **suggestedParams** (SuggestedParams) - Optional. Transaction parameters obtained from the network.
### Example Usage
```typescript
// Opt-in an account to the app (enables local state)
const optInTxn = algosdk.makeApplicationOptInTxnFromObject({
sender: creator.addr,
appIndex: appId,
suggestedParams: sp,
});
```
```
--------------------------------
### Run SDK Test Suite in Firefox
Source: https://github.com/algorand/js-algorand-sdk/blob/main/README.md
Execute the Algorand SDK test suite using Docker within a Firefox browser. This requires setting the TEST_BROWSER environment variable.
```bash
TEST_BROWSER=firefox make docker-test
```
--------------------------------
### makeApplicationCreateTxnFromObject
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Creates a transaction to deploy a new application (smart contract) on Algorand. This function takes an object with transaction parameters, including the compiled approval and clear state TEAL programs.
```APIDOC
## makeApplicationCreateTxnFromObject — Deploy a Smart Contract
Application (smart contract) lifecycle transactions create, update, opt-in, call, close-out, clear-state, and delete smart contracts on Algorand.
### Method Signature
```typescript
algosdk.makeApplicationCreateTxnFromObject(parameters: {
sender: string;
approvalProgram: Uint8Array;
clearProgram: Uint8Array;
numGlobalByteSlices?: number;
numGlobalInts?: number;
numLocalByteSlices?: number;
numLocalInts?: number;
suggestedParams?: SuggestedParams;
onComplete?: OnApplicationComplete;
extraPages?: number;
}): Transaction
```
### Parameters
- **sender** (string) - The address of the account creating the application.
- **approvalProgram** (Uint8Array) - The compiled TEAL logic for the application's approval program.
- **clearProgram** (Uint8Array) - The compiled TEAL logic for the application's clear state program.
- **numGlobalByteSlices** (number) - Optional. The number of global byte slices for the application state.
- **numGlobalInts** (number) - Optional. The number of global integers for the application state.
- **numLocalByteSlices** (number) - Optional. The number of local byte slices for each account's state.
- **numLocalInts** (number) - Optional. The number of local integers for each account's state.
- **suggestedParams** (SuggestedParams) - Optional. Transaction parameters obtained from the network.
- **onComplete** (OnApplicationComplete) - Optional. Specifies the onComplete behavior for the application.
- **extraPages** (number) - Optional. The number of extra pages for the application's TEAL program.
### Example Usage
```typescript
// Compile TEAL programs
const approvalResp = await algodClient.compile(approvalTeal).do();
const clearResp = await algodClient.compile(clearTeal).do();
const approvalProgram = algosdk.base64ToBytes(approvalResp.result);
const clearProgram = algosdk.base64ToBytes(clearResp.result);
// Create the application
const createTxn = algosdk.makeApplicationCreateTxnFromObject({
sender: creator.addr,
approvalProgram,
clearProgram,
numGlobalByteSlices: 1,
numGlobalInts: 1,
numLocalByteSlices: 1,
numLocalInts: 1,
suggestedParams: sp,
onComplete: algosdk.OnApplicationComplete.NoOpOC,
});
```
```
--------------------------------
### Connect to Algorand Node and Query Data
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Initialize an Algodv2 client to interact with an Algorand node. Use .do() to execute requests and retrieve typed responses. Fetch suggested transaction parameters before creating transactions.
```typescript
import algosdk from 'algosdk';
// Connect to a local sandbox node (default sandbox credentials)
const algodClient = new algosdk.Algodv2(
'a'.repeat(64), // API token
'http://localhost',
4001
);
// Check node health
await algodClient.healthCheck().do();
// Get node status
const status = await algodClient.status().do();
console.log('Last round:', status.lastRound);
// Fetch suggested transaction parameters (required for every transaction)
const sp = await algodClient.getTransactionParams().do();
console.log('Min fee:', sp.minFee); // bigint, e.g. 1000n
// Fetch account information
const acctInfo = await algodClient.accountInformation('XBYLS2E6YI6XXL5BWCAMOA4GTWHXWENZMX5UHXMRNWWUQ7BXCY5WC5TEPA').do();
console.log('Balance (microAlgos):', acctInfo.amount);
// Fetch asset info
const asset = await algodClient.getAssetByID(163650n).do();
console.log('Asset name:', asset.params.name);
// Fetch application info and box storage
const app = await algodClient.getApplicationByID(60553466n).do();
const box = await algodClient.getApplicationBoxByName(60553466n, algosdk.coerceToBytes('mybox')).do();
console.log('Box value:', box.value);
// Get block data
const block = await algodClient.block(18038133n).do();
// Compile TEAL source
const compiled = await algodClient.compile('#pragma version 8\nint 1').do();
const programBytes = algosdk.base64ToBytes(compiled.result);
```
--------------------------------
### Include algosdk in HTML for Browser
Source: https://github.com/algorand/js-algorand-sdk/blob/main/README.md
Include the minified browser bundle directly in your HTML file using a CDN. Ensure the integrity hash and crossorigin attributes are correctly set.
```html
```
```html
```
--------------------------------
### LogicSig Signing
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
This section explains how to use LogicSigs, which represent compiled TEAL programs, to authorize transactions without a private key. It covers creating LogicSigs, LogicSigAccounts for delegated signing, and signing transactions with them.
```APIDOC
## LogicSig / LogicSigAccount — Smart Signature Signing
`LogicSig` holds a compiled TEAL program (and optional arguments) that authorizes transactions without a traditional private key. `LogicSigAccount` is the safe, general-purpose variant that supports delegated signing by an ed25519 key or multisig.
```typescript
import algosdk from 'algosdk';
const algodClient = new algosdk.Algodv2('a'.repeat(64), 'http://localhost', 4001);
const sp = await algodClient.getTransactionParams().do();
// 1. Compile a TEAL program
const tealSource = '#pragma version 8\nint 1'; // always approves
const compiled = await algodClient.compile(tealSource).do();
const programBytes = algosdk.base64ToBytes(compiled.result);
// 2. Create a LogicSig (contract account — not delegated)
const lsig = new algosdk.LogicSig(programBytes);
// Create a LogicSigAccount (delegation: signed by an ed25519 key)
const delegateAccount = algosdk.generateAccount();
const lsigAccount = new algosdk.LogicSigAccount(programBytes);
lsigAccount.sign(delegateAccount.sk); // delegate to delegateAccount
// 3. Sign a transaction with the LogicSigAccount
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
sender: lsigAccount.address().toString(), // the lsig's own address
receiver: delegateAccount.addr,
amount: 1000n,
suggestedParams: sp,
});
const { blob } = algosdk.signLogicSigTransactionObject(txn, lsigAccount);
await algodClient.sendRawTransaction(blob).do();
await algosdk.waitForConfirmation(algodClient, txn.txID(), 4);
// Teal sign: sign arbitrary bytes with a program (for verification off-chain)
const data = new TextEncoder().encode('hello');
const sig = algosdk.tealSign(delegateAccount.sk, data, programBytes);
const valid = algosdk.verifyTealSign(data, sig, lsigAccount.address());
console.log('Teal signature valid:', valid);
```
```
--------------------------------
### Create Basic, LogicSig, Multisig, and Empty Transaction Signers
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Factory functions for creating transaction signers. `makeBasicAccountTransactionSigner` is for standard accounts. `makeLogicSigAccountTransactionSigner` requires a pre-signed LogicSig. `makeMultiSigAccountTransactionSigner` handles multisignature accounts. `makeEmptyTransactionSigner` is for simulations.
```typescript
import algosdk from 'algosdk';
const account = algosdk.generateAccount();
// Basic account signer (most common)
const basicSigner = algosdk.makeBasicAccountTransactionSigner(account);
// LogicSig account signer
const lsigAccount = new algosdk.LogicSigAccount(compiledProgramBytes);
lsigAccount.sign(account.sk);
const lsigSigner = algosdk.makeLogicSigAccountTransactionSigner(lsigAccount);
// Multisig signer (uses multiple secret keys)
const msigParams: algosdk.MultisigMetadata = {
version: 1,
threshold: 2,
addrs: [acct1.addr, acct2.addr, acct3.addr],
};
const msigSigner = algosdk.makeMultiSigAccountTransactionSigner(msigParams, [acct1.sk, acct2.sk]);
// Empty signer — for simulation without actual keys
const emptySigner = algosdk.makeEmptyTransactionSigner();
// Use with AtomicTransactionComposer
const atc = new algosdk.AtomicTransactionComposer();
atc.addTransaction({
txn: algosdk.makePaymentTxnWithSuggestedParamsFromObject({
sender: account.addr,
receiver: account.addr,
amount: 0n,
suggestedParams: sp,
}),
signer: basicSigner,
});
// Simulate without submitting (uses makeEmptyTransactionSigner)
const simAtc = atc.clone();
const simResult = await simAtc.simulate(algodClient);
console.log('Simulation failed at:', simResult.failedAt);
```
--------------------------------
### Enable Node.js Util in Browser
Source: https://github.com/algorand/js-algorand-sdk/blob/main/tests/cucumber/browser/index.html
This code is necessary to make the 'assert' module work in a browser environment by mocking 'process.env.NODE_DEBUG'.
```javascript
window.process = { env: {} };
```
--------------------------------
### Encoding Utilities
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Provides low-level encoding and decoding helpers for Algorand's msgpack wire format, Base64 data, addresses, and uint64 values.
```APIDOC
## Encoding Utilities — msgpack, Base64, Address
The SDK exposes low-level encoding helpers for working with Algorand's msgpack wire format, base64 data, addresses, and uint64 values.
```typescript
import algosdk from 'algosdk';
// Address encoding / decoding
const addr = 'XBYLS2E6YI6XXL5BWCAMOA4GTWHXWENZMX5UHXMRNWWUQ7BXCY5WC5TEPA';
console.log('Valid address:', algosdk.isValidAddress(addr)); // true
const decoded = algosdk.decodeAddress(addr);
console.log('Public key bytes:', decoded.publicKey);
console.log('Re-encoded:', algosdk.encodeAddress(decoded.publicKey)); // same addr
// Application address: deterministic from app ID
const appAddr = algosdk.getApplicationAddress(1234n);
console.log('App address:', appAddr.toString());
// ALGO conversion
console.log(algosdk.algosToMicroalgos(2)); // 2000000n
console.log(algosdk.microalgosToAlgos(2_000_000n)); // 2
// Binary data helpers
const bytes = new Uint8Array([72, 101, 108, 108, 111]);
console.log(algosdk.bytesToBase64(bytes)); // "SGVsbG8="
console.log(algosdk.bytesToHex(bytes)); // "48656c6c6f"
console.log(algosdk.bytesToString(bytes)); // "Hello"
const b64 = 'SGVsbG8=';
console.log(algosdk.base64ToBytes(b64)); // Uint8Array [72, 101, ...]
// Coerce strings/arrays/buffers to Uint8Array
const note = algosdk.coerceToBytes('my note');
// Uint64 encode/decode (big-endian 8 bytes)
const encoded64 = algosdk.encodeUint64(12345678901234n);
const decoded64 = algosdk.decodeUint64(encoded64, 'bigint');
// msgpack encode/decode (Algorand canonical rules)
const data = { name: 'Alice', balance: 1000000 };
const packed = algosdk.msgpackRawEncode(data);
const unpacked = algosdk.msgpackRawDecode(packed);
// JSON with BigInt support (Algorand responses use bigint for uint64 fields)
const jsonStr = algosdk.stringifyJSON({ amount: 9007199254740993n }); // handles bigint
const parsed = algosdk.parseJSON(jsonStr, { intDecoding: algosdk.IntDecoding.BIGINT });
```
```
--------------------------------
### Address Handling: v2 vs v3
Source: https://github.com/algorand/js-algorand-sdk/blob/main/v2_TO_v3_MIGRATION_GUIDE.md
Compares address handling between v2 and v3. In v2, `decodeAddress` and `encodeAddress` were used. In v3, the `Address` class is preferred, with `Address.fromString` and `address.toString()` for conversions.
```typescript
// v2
const address = algosdk.decodeAddress(
'MO2H6ZU47Q36GJ6GVHUKGEBEQINN7ZWVACMWZQGIYUOE3RBSRVYHV4ACJI'
);
console.log('Address 32-byte public key component:', address.publicKey);
console.log('Address checksum:', address.checksum);
console.log('Address string:', algosdk.encodeAddress(address.publicKey));
// v3
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());
```
--------------------------------
### makeAssetCreateTxnWithSuggestedParamsFromObject
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Creates an ASA (Algorand Standard Asset) creation transaction. The returned asset ID is found in the `waitForConfirmation` result's `assetIndex` field.
```APIDOC
## makeAssetCreateTxnWithSuggestedParamsFromObject — Create an Algorand Standard Asset
Creates an ASA (Algorand Standard Asset) creation transaction. The returned asset ID is found in the `waitForConfirmation` result's `assetIndex` field.
```typescript
import algosdk from 'algosdk';
const algodClient = new algosdk.Algodv2('a'.repeat(64), 'http://localhost', 4001);
const creator = algosdk.generateAccount();
const sp = await algodClient.getTransactionParams().do();
// Create an ASA
const createTxn = algosdk.makeAssetCreateTxnWithSuggestedParamsFromObject({
sender: creator.addr,
suggestedParams: sp,
defaultFrozen: false,
unitName: 'USDC',
assetName: 'USD Coin',
manager: creator.addr,
reserve: creator.addr,
freeze: creator.addr,
clawback: creator.addr,
assetURL: 'https://centre.io/usdc',
total: 1_000_000_000n, // total supply
decimals: 6,
});
await algodClient.sendRawTransaction(createTxn.signTxn(creator.sk)).do();
const result = await algosdk.waitForConfirmation(algodClient, createTxn.txID(), 4);
const assetId = result.assetIndex!;
console.log('Created ASA with ID:', assetId);
// Opt-in: a zero-amount self-transfer
const receiver = algosdk.generateAccount();
const optInTxn = algosdk.makeAssetTransferTxnWithSuggestedParamsFromObject({
sender: receiver.addr,
receiver: receiver.addr,
suggestedParams: sp,
assetIndex: assetId,
amount: 0n,
});
// Transfer ASA after opt-in
const xferTxn = algosdk.makeAssetTransferTxnWithSuggestedParamsFromObject({
sender: creator.addr,
receiver: receiver.addr,
suggestedParams: sp,
assetIndex: assetId,
amount: 1_000_000n, // 1 USDC (6 decimals)
});
// Freeze an account's asset holding
const freezeTxn = algosdk.makeAssetFreezeTxnWithSuggestedParamsFromObject({
sender: creator.addr,
suggestedParams: sp,
assetIndex: assetId,
freezeTarget: receiver.addr,
frozen: true,
});
// Clawback from a frozen/any account back to creator
const clawbackTxn = algosdk.makeAssetTransferTxnWithSuggestedParamsFromObject({
sender: creator.addr, // must be the clawback address
receiver: creator.addr,
assetSender: receiver.addr, // the account being clawed back
suggestedParams: sp,
assetIndex: assetId,
amount: 1_000_000n,
});
// Destroy the asset (only manager can do this; all supply must be in creator's account)
const deleteTxn = algosdk.makeAssetDestroyTxnWithSuggestedParamsFromObject({
sender: creator.addr,
suggestedParams: sp,
assetIndex: assetId,
});
```
```
--------------------------------
### Multisig Transaction Signing with Algorand SDK
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Use `signMultisigTransaction` to create the first partial signature and `appendSignMultisigTransaction` to add subsequent signatures for M-of-N multisig accounts. The merged blob can be submitted once the threshold is met. Ensure correct multisig parameters are provided.
```typescript
import algosdk from 'algosdk';
const algodClient = new algosdk.Algodv2('a'.repeat(64), 'http://localhost', 4001);
const sp = await algodClient.getTransactionParams().do();
// Generate 3 signer accounts
const signer1 = algosdk.generateAccount();
const signer2 = algosdk.generateAccount();
const signer3 = algosdk.generateAccount();
// Define the multisig parameters: version 1, threshold 2-of-3
const msigParams: algosdk.MultisigMetadata = {
version: 1,
threshold: 2,
addrs: [signer1.addr, signer2.addr, signer3.addr],
};
// Derive the multisig account address from the parameters
const multisigAddr = algosdk.multisigAddress(msigParams);
console.log('Multisig address:', multisigAddr.toString());
// Build a payment from the multisig address
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
sender: multisigAddr,
receiver: signer1.addr,
amount: 100n,
suggestedParams: sp,
});
// First signer creates the initial partial multisig blob
const { blob: partialSig1 } = algosdk.signMultisigTransaction(txn, msigParams, signer1.sk);
// Second signer appends their signature (threshold reached: 2-of-3)
const { blob: fullSig } = algosdk.appendSignMultisigTransaction(partialSig1, msigParams, signer2.sk);
// Submit the fully signed multisig transaction
await algodClient.sendRawTransaction(fullSig).do();
await algosdk.waitForConfirmation(algodClient, txn.txID(), 4);
console.log('Multisig transaction confirmed');
// Verify a multisig signature
const isValid = algosdk.verifyMultisig(txn.bytesToSign(), algosdk.decodeSignedTransaction(fullSig).msig!, msigParams);
```
--------------------------------
### Connect to Algorand Indexer
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Connects to the Algorand Indexer REST API for historical data search. All query builder methods are chainable before .do().
```typescript
import algosdk from 'algosdk';
const indexer = new algosdk.Indexer('', 'http://localhost', 8980);
// Look up a single account
const acct = await indexer.lookupAccountByID('XBYLS2E6YI6XXL5BWCAMOA4GTWHXWENZMX5UHXMRNWWUQ7BXCY5WC5TEPA').do();
// Search transactions for a specific account with filters
const txns = await indexer
.lookupAccountTransactions('XBYLS2E6YI6XXL5BWCAMOA4GTWHXWENZMX5UHXMRNWWUQ7BXCY5WC5TEPA')
.limit(10)
.do();
// Search all transactions with type filter
const payTxns = await indexer
.searchForTransactions()
.txType('pay')
.currencyGreaterThan(1_000_000n)
.do();
// Look up asset holders
const holders = await indexer.lookupAssetBalances(163650n).do();
// Look up asset by ID (also available via algod)
const assetInfo = await indexer.lookupAssetByID(163650n).do();
console.log('Asset info:', assetInfo);
// Search for application boxes (paginated)
const page1 = await indexer.searchForApplicationBoxes(1234n).limit(20).do();
const boxNames = page1.boxes.map((box) => box.name);
const page2 = await indexer
.searchForApplicationBoxes(1234n)
.limit(20)
.nextToken(page1.nextToken!)
.do();
// Look up transaction by ID
const txn = await indexer.lookupTransactionByID('MEUOC4RQJB23CQZRFRKYEI6WBO73VTTPST5A7B3S5OKBUY6LFUDA').do();
```
--------------------------------
### Encoding and Decoding Transactions (v2 vs v3)
Source: https://github.com/algorand/js-algorand-sdk/blob/main/v2_TO_v3_MIGRATION_GUIDE.md
Compares the v2 and v3 methods for encoding and decoding transactions using msgpack. v3 simplifies this process with direct functions for Encodable objects.
```typescript
// Encoding a transaction to msgpack, then decoding it back
// v2
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({...});
const encoded = algosdk.encodeObj(txn.get_obj_for_encoding());
const decoded = algosdk.Transaction.from_obj_for_encoding(
algosdk.decodeObj(encoded) as algosdk.EncodedTransaction
);
assert.deepStrictEqual(txn, decoded);
// v3
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({...});
const encoded = algosdk.encodeMsgpack(txn); // Uint8Array of msgpack-encoded transaction
const decoded = algosdk.decodeMsgpack(encoded, algosdk.Transaction); // Decoded Transaction instance
assert.deepStrictEqual(txn, decoded);
```
--------------------------------
### Create Algorand Standard Asset (ASA)
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Creates an ASA with specified parameters. The returned asset ID is available in the confirmation result. This function requires suggested transaction parameters.
```typescript
import algosdk from 'algosdk';
const algodClient = new algosdk.Algodv2('a'.repeat(64), 'http://localhost', 4001);
const creator = algosdk.generateAccount();
const sp = await algodClient.getTransactionParams().do();
// Create an ASA
const createTxn = algosdk.makeAssetCreateTxnWithSuggestedParamsFromObject({
sender: creator.addr,
suggestedParams: sp,
defaultFrozen: false,
unitName: 'USDC',
assetName: 'USD Coin',
manager: creator.addr,
reserve: creator.addr,
freeze: creator.addr,
clawback: creator.addr,
assetURL: 'https://centre.io/usdc',
total: 1_000_000_000n, // total supply
decimals: 6,
});
await algodClient.sendRawTransaction(createTxn.signTxn(creator.sk)).do();
const result = await algosdk.waitForConfirmation(algodClient, createTxn.txID(), 4);
const assetId = result.assetIndex!;
console.log('Created ASA with ID:', assetId);
```
--------------------------------
### Generate SRI Hash for algosdk.min.js
Source: https://github.com/algorand/js-algorand-sdk/blob/main/FAQ.md
Use this command to compute the SHA384 SRI hash for the minified algosdk.min.js browser bundle. This is useful for verifying the integrity of the script when hosting it yourself.
```bash
cat dist/browser/algosdk.min.js | openssl dgst -sha384 -binary | openssl base64 -A
```
--------------------------------
### LogicSig and LogicSigAccount Signing with Algorand SDK
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Use `LogicSig` for compiled TEAL programs that authorize transactions without a private key. `LogicSigAccount` supports delegated signing via ed25519 keys or multisig. Ensure the TEAL program is compiled before creating the LogicSig object.
```typescript
import algosdk from 'algosdk';
const algodClient = new algosdk.Algodv2('a'.repeat(64), 'http://localhost', 4001);
const sp = await algodClient.getTransactionParams().do();
// 1. Compile a TEAL program
const tealSource = '#pragma version 8
int 1'; // always approves
const compiled = await algodClient.compile(tealSource).do();
const programBytes = algosdk.base64ToBytes(compiled.result);
// 2. Create a LogicSig (contract account — not delegated)
const lsig = new algosdk.LogicSig(programBytes);
// Create a LogicSigAccount (delegation: signed by an ed25519 key)
const delegateAccount = algosdk.generateAccount();
const lsigAccount = new algosdk.LogicSigAccount(programBytes);
lsigAccount.sign(delegateAccount.sk); // delegate to delegateAccount
// 3. Sign a transaction with the LogicSigAccount
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
sender: lsigAccount.address().toString(), // the lsig's own address
receiver: delegateAccount.addr,
amount: 1000n,
suggestedParams: sp,
});
const { blob } = algosdk.signLogicSigTransactionObject(txn, lsigAccount);
await algodClient.sendRawTransaction(blob).do();
await algosdk.waitForConfirmation(algodClient, txn.txID(), 4);
// Teal sign: sign arbitrary bytes with a program (for verification off-chain)
const data = new TextEncoder().encode('hello');
const sig = algosdk.tealSign(delegateAccount.sk, data, programBytes);
const valid = algosdk.verifyTealSign(data, sig, lsigAccount.address());
console.log('Teal signature valid:', valid);
```
--------------------------------
### makeApplicationDeleteTxnFromObject
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
Creates a transaction to delete an application from the Algorand network.
```APIDOC
## makeApplicationDeleteTxnFromObject — Delete Application
### Method Signature
```typescript
algosdk.makeApplicationDeleteTxnFromObject(parameters: {
sender: string;
appIndex: number;
suggestedParams?: SuggestedParams;
}): Transaction
```
### Parameters
- **sender** (string) - The address of the account initiating the deletion.
- **appIndex** (number) - The ID of the application to delete.
- **suggestedParams** (SuggestedParams) - Optional. Transaction parameters obtained from the network.
### Example Usage
```typescript
// Delete the application
const deleteTxn = algosdk.makeApplicationDeleteTxnFromObject({
sender: creator.addr,
appIndex: appId,
suggestedParams: sp,
});
```
```
--------------------------------
### v2 Transaction Construction Methods
Source: https://github.com/algorand/js-algorand-sdk/blob/main/v2_TO_v3_MIGRATION_GUIDE.md
Illustrates the two methods for constructing payment transactions in v2: using individual arguments or a parameter object. The v3 SDK deprecates the first method.
```typescript
// Warning: This is v2 code. Code for v3 is shown later in this section.
const suggestedParams = await client.getTransactionParams().do();
// Method 1: Using the "standard" version of the maker function for a specific transaction type.
// This standard version passes parameters as individual arguments.
const txn = algosdk.makePaymentTxnWithSuggestedParams(
'MO2H6ZU47Q36GJ6GVHUKGEBEQINN7ZWVACMWZQGIYUOE3RBSRVYHV4ACJI',
'7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q',
1000,
undefined,
Uint8Array.from([1, 2, 3]),
suggestedParams,
undefined
);
// Method 2: Using the "FromObject" variant of the function, which takes a single parameter object.
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
from: 'MO2H6ZU47Q36GJ6GVHUKGEBEQINN7ZWVACMWZQGIYUOE3RBSRVYHV4ACJI',
to: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q',
amount: 1000,
note: Uint8Array.from([1, 2, 3]),
suggestedParams,
});
```
--------------------------------
### Multisig Signing
Source: https://context7.com/algorand/js-algorand-sdk/llms.txt
This section covers creating partial signatures for multisig transactions and appending subsequent signatures until the required threshold is met. It also shows how to verify multisig signatures.
```APIDOC
## signMultisigTransaction / appendSignMultisigTransaction — Multisig Signing
Algorand multisig accounts require M-of-N signatures. `signMultisigTransaction` creates the first partial signature blob, and `appendSignMultisigTransaction` adds each subsequent signature. Once the threshold is met, the merged blob can be submitted.
```typescript
import algosdk from 'algosdk';
const algodClient = new algosdk.Algodv2('a'.repeat(64), 'http://localhost', 4001);
const sp = await algodClient.getTransactionParams().do();
// Generate 3 signer accounts
const signer1 = algosdk.generateAccount();
const signer2 = algosdk.generateAccount();
const signer3 = algosdk.generateAccount();
// Define the multisig parameters: version 1, threshold 2-of-3
const msigParams: algosdk.MultisigMetadata = {
version: 1,
threshold: 2,
addrs: [signer1.addr, signer2.addr, signer3.addr],
};
// Derive the multisig account address from the parameters
const multisigAddr = algosdk.multisigAddress(msigParams);
console.log('Multisig address:', multisigAddr.toString());
// Build a payment from the multisig address
const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
sender: multisigAddr,
receiver: signer1.addr,
amount: 100n,
suggestedParams: sp,
});
// First signer creates the initial partial multisig blob
const { blob: partialSig1 } = algosdk.signMultisigTransaction(txn, msigParams, signer1.sk);
// Second signer appends their signature (threshold reached: 2-of-3)
const { blob: fullSig } = algosdk.appendSignMultisigTransaction(partialSig1, msigParams, signer2.sk);
// Submit the fully signed multisig transaction
await algodClient.sendRawTransaction(fullSig).do();
await algosdk.waitForConfirmation(algodClient, txn.txID(), 4);
console.log('Multisig transaction confirmed');
// Verify a multisig signature
const isValid = algosdk.verifyMultisig(txn.bytesToSign(), algosdk.decodeSignedTransaction(fullSig).msig!, msigParams);
```
```