### Install Arweave via NPM
Source: https://github.com/arweaveteam/arweave-js/blob/master/README.md
Use this command to install the Arweave SDK for Node.js projects.
```bash
npm install --save arweave
```
--------------------------------
### Example Log Output
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/errors.md
When logging is enabled, Arweave JS outputs details about network requests and responses. This example shows the format for a request to the `/info` endpoint.
```text
[Arweave] Requesting: https://arweave.net:443/info
[Arweave] Response: https://arweave.net/info - 200
```
--------------------------------
### Common Encoding Chains
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/utils.md
Provides examples of common encoding and decoding chains between text, binary, and Base64URL formats.
```APIDOC
## Common Encoding Chains
### Text → Arweave Format
```typescript
// Text to base64url (for tag values)
const tagValue = Arweave.utils.stringToB64Url('My-Value');
// Text to binary to base64url (for data)
const buffer = Arweave.utils.stringToBuffer('Hello');
const b64url = Arweave.utils.bufferTob64Url(buffer);
```
### Arweave Format → Text
```typescript
// Base64url back to text (from tag values)
const decoded = Arweave.utils.b64UrlToString('TXktVmFsdWU');
// Binary (base64url) back to text (from data field)
const buffer = Arweave.utils.b64UrlToBuffer('SGVsbG8');
const text = Arweave.utils.bufferToString(buffer);
// Or in one step
const text = Arweave.utils.b64UrlToString('SGVsbG8');
```
```
--------------------------------
### get
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/transaction.md
Retrieves a field value with optional decoding from base64url format.
```APIDOC
## get(field, options)
### Description
Retrieves a field value with optional decoding from base64url format.
### Method Signature
```typescript
get(field: string): string;
get(field: string, options: { decode: true; string: false }): Uint8Array;
get(field: string, options: { decode: true; string: true }): string;
```
### Parameters
#### Path Parameters
- **field** (string) - Required - Property name to retrieve
#### Query Parameters
- **options.decode** (boolean) - Optional - Decode from base64url (for string fields)
- **options.string** (boolean) - Optional - Convert to UTF-8 string (requires `decode: true`)
### Returns
Field value as string (default), Uint8Array, or string depending on options.
### Example
```typescript
const tx = await arweave.transactions.get('bNbA...');
// Get base64url encoded data
const b64Data = tx.get('data');
// Get as binary
const binaryData = tx.get('data', { decode: true, string: false });
// Get as UTF-8 string
const textData = tx.get('data', { decode: true, string: true });
// Get owner public key as string
const owner = tx.get('owner');
```
```
--------------------------------
### Complete Large File Upload Example
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/uploader.md
Demonstrates how to upload a large file using Arweave JS, including reading the file, creating and signing a transaction, and uploading chunks with progress monitoring and error handling.
```typescript
import Arweave from 'arweave';
import * as fs from 'fs';
const arweave = Arweave.init({
host: 'arweave.net',
port: 443,
protocol: 'https'
});
async function uploadLargeFile(filePath, jwk) {
// Read file
const data = fs.readFileSync(filePath);
// Create and sign transaction
const tx = await arweave.createTransaction({ data }, jwk);
tx.addTag('Content-Type', 'application/octet-stream');
tx.addTag('File-Name', filePath);
await arweave.transactions.sign(tx, jwk);
// Create uploader
const uploader = await arweave.transactions.getUploader(tx);
console.log(`Uploading ${uploader.totalChunks} chunks...`);
// Upload with progress
while (!uploader.isComplete) {
try {
await uploader.uploadChunk();
console.log(`${uploader.pctComplete}% - ${uploader.uploadedChunks}/${uploader.totalChunks}`);
} catch (error) {
if (uploader.lastResponseStatus === 402) {
console.error('Insufficient account balance');
throw error;
}
// Network error or other, will retry automatically
console.error(`Chunk upload failed: ${uploader.lastResponseError}`);
}
}
console.log(`Upload complete! Transaction ID: ${tx.id}`);
return tx.id;
}
// Usage
const jwk = await arweave.wallets.generate();
const txId = await uploadLargeFile('/path/to/large-file.bin', jwk);
```
--------------------------------
### Initialize Arweave in Web (NPM)
Source: https://github.com/arweaveteam/arweave-js/blob/master/README.md
Initialize the Arweave client in a web application when using the NPM installation method. The init function can be called without options to use the current URL path, which is recommended for gateways.
```javascript
import Arweave from 'arweave';
// Since v1.5.1 you're now able to call the init function for the web version without options. The current URL path will be used by default. This is recommended when running from a gateway.
const arweave = Arweave.init({});
```
```javascript
// Or manually specify a host
const arweave = Arweave.init({
host: '127.0.0.1',
port: 1984,
protocol: 'http'
});
```
--------------------------------
### Generate Wallet and Get Address
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/INDEX.md
Generate a new Arweave wallet (JWK) and derive its public address.
```typescript
const jwk = await arweave.wallets.generate();
const address = await arweave.wallets.jwkToAddress(jwk);
```
--------------------------------
### Retrieve Transaction Fields with Decoding Options
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/transaction.md
The `get` method retrieves transaction fields. Use options to decode from base64url and specify output as Uint8Array or string.
```typescript
const tx = await arweave.transactions.get('bNbA...');
// Get base64url encoded data
const b64Data = tx.get('data');
// Get as binary
const binaryData = tx.get('data', { decode: true, string: false });
// Get as UTF-8 string
const textData = tx.get('data', { decode: true, string: true });
// Get owner public key as string
const owner = tx.get('owner');
```
--------------------------------
### List Stored Silos using GraphQL Query
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/silo.md
Provides a conceptual TypeScript example for listing stored Silos by constructing a GraphQL query. This query targets transactions tagged with 'Silo-Name' and owned by a specific wallet address.
```typescript
async function listMyMessages(walletAddress) {
// Note: Requires GraphQL query
// This is a conceptual example - actual implementation uses GraphQL
const query = `
query {
transactions(first: 100, owners: ["${walletAddress}"])
where: { tags: [{ name: "Silo-Name", values: ["*"] }] }
{
edges {
node {
id
tags {
name
value
}
}
}
}
}
`;
return query;
}
```
--------------------------------
### Handling BLOCK_NOT_FOUND Error
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/errors.md
Provides an example of catching and handling a BLOCK_NOT_FOUND error when a block does not exist at a specified height or hash. This is useful for verifying block existence.
```typescript
try {
const block = await arweave.blocks.get('invalid-hash');
} catch (error) {
if (error instanceof ArweaveError && error.type === ArweaveErrorType.BLOCK_NOT_FOUND) {
console.log('Block not found');
}
}
```
--------------------------------
### Browser (Bundle) Arweave Initialization
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/INDEX.md
Initialize the Arweave SDK in a browser using a pre-bundled script.
```html
```
--------------------------------
### Get Tag Name and Value
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/transaction.md
Retrieves the name or value of a tag. Supports getting the raw base64url-encoded string or a decoded UTF-8 string.
```typescript
// Get base64url encoded value
const encodedName = tag.get('name');
// Get decoded UTF-8 value
const name = tag.get('name', { decode: true, string: true });
```
```typescript
const tag = new Tag('Content-Type', 'text/html');
console.log(tag.get('name')); // base64url encoded
console.log(tag.get('name', { decode: true, string: true })); // "Content-Type"
```
--------------------------------
### Arweave Initialization Options
Source: https://github.com/arweaveteam/arweave-js/blob/master/README.md
Configuration options for initializing the Arweave client. These include network details, timeouts, and logging preferences.
```javascript
{
host: 'arweave.net',// Hostname or IP address for a Arweave host
port: 443, // Port
protocol: 'https', // Network protocol http or https
timeout: 20000, // Network request timeouts in milliseconds
logging: false, // Enable network request logging
}
```
--------------------------------
### Initialize Arweave SDK Configuration
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/INDEX.md
Configure the Arweave SDK with connection settings such as host, port, protocol, timeout, and logging preferences.
```typescript
const arweave = Arweave.init({
host: 'arweave.net',
port: 443,
protocol: 'https',
timeout: 20000,
logging: false
});
```
--------------------------------
### Get Current Block Data
Source: https://github.com/arweaveteam/arweave-js/blob/master/README.md
Retrieves the data for the current block on the Arweave network. This requires first fetching network info to get the current block's hash.
```javascript
const {current} = await arweave.network.getInfo();
```
```javascript
const result = await arweave.blocks.getCurrent();
console.log(result)
// {
// "indep_hash": "qoJwHSpzl6Ouo140HW2DTv1rGOrgfBEnHi5sHv-fJt_TsK7xA70F2QbjMCopLiMd",
// ...
```
--------------------------------
### Get Current Block
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/blocks.md
Retrieves the most recent block in the Arweave blockweave. This method is ideal for getting the latest state of the network without needing to know a specific height or hash.
```typescript
async getCurrent(): Promise
```
```typescript
const currentBlock = await arweave.blocks.getCurrent();
console.log(`Current height: ${currentBlock.height}`);
console.log(`Transactions in latest block: ${currentBlock.txs.length}`);
console.log(`Block time: ${currentBlock.timestamp}`);
```
--------------------------------
### Create and Upload New Transaction
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/transactions.md
Use `getUploader` to create a TransactionUploader for a new transaction. This allows for chunked uploading with progress tracking. You must first create and sign the transaction.
```typescript
const tx = await arweave.createTransaction({ data: largeBuffer }, jwk);
await arweave.transactions.sign(tx, jwk);
const uploader = await arweave.transactions.getUploader(tx);
while (!uploader.isComplete) {
await uploader.uploadChunk();
console.log(`${uploader.pctComplete}% complete (${uploader.uploadedChunks}/${uploader.totalChunks})`);
}
```
--------------------------------
### Initialize Arweave for Local Node
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/configuration.md
Set up Arweave JS to connect to a locally running Arweave node. Uses 'http' protocol and a non-standard port.
```typescript
const arweave = Arweave.init({
host: '127.0.0.1',
port: 1984,
protocol: 'http',
timeout: 20000
});
```
--------------------------------
### Initialize Arweave for Production Gateway (Web)
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/configuration.md
Configure Arweave JS to connect to the production gateway from a web environment. Ensure correct protocol, host, and port are set.
```typescript
const arweave = Arweave.init({
host: 'arweave.net',
port: 443,
protocol: 'https',
timeout: 30000,
logging: false
});
```
--------------------------------
### Get Block Data
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/README.md
Fetches details of a specific block from the Arweave blockchain.
```APIDOC
## Get Block
### Description
Retrieves the data for a specific Arweave block, identified by its ID.
### Method
GET
### Endpoint
`/api/v1/blocks/{block_id}`
### Parameters
#### Path Parameters
- **block_id** (string) - Required - The ID of the block to retrieve.
### Response
#### Success Response (200)
- **block** (object) - An object containing the block's data.
- **indicie** (string) - The block's indicie.
- **height** (integer) - The block's height.
- **hash** (string) - The block's hash.
- **timestamp** (integer) - The block's timestamp.
- **last_tx** (string) - The ID of the last transaction in the block.
- **tx_root** (string) - The root hash of the transactions in the block.
- **previous_block** (string) - The hash of the previous block.
- **nonce** (string) - The nonce of the block.
- **difficulty** (string) - The difficulty of the block.
- **min_gas_price** (string) - The minimum gas price for the block.
- **total_ar_ குறைக்க** (string) - The total AR staked in the block.
- **block_reward** (string) - The block reward.
- **weave_size** (string) - The size of the weave.
- **cumulative_diff** (string) - The cumulative difficulty.
- **hash_list_root** (string) - The root of the hash list.
- **hash_list** (array) - A list of hashes.
- **parent_offset** (integer) - The offset of the parent block.
- **parent_hash** (string) - The hash of the parent block.
- **edges** (array) - Edges related to the block.
#### Response Example
```json
{
"block": {
"indicie": "12345",
"height": 100000,
"hash": "block_hash_value",
"timestamp": 1678886400,
"last_tx": "last_tx_id_value",
"tx_root": "tx_root_hash_value",
"previous_block": "previous_block_hash_value",
"nonce": "nonce_value",
"difficulty": "difficulty_value",
"min_gas_price": "1000000000",
"total_ar_ குறைக்க": "50000000000000000000",
"block_reward": "20000000000000000",
"weave_size": "1000000000",
"cumulative_diff": "cumulative_diff_value",
"hash_list_root": "hash_list_root_value",
"hash_list": ["hash1", "hash2"],
"parent_offset": 0,
"parent_hash": "parent_hash_value",
"edges": []
}
}
```
```
--------------------------------
### Sign a Transaction
Source: https://github.com/arweaveteam/arweave-js/blob/master/README.md
Creates a transaction and then signs it using the provided wallet key. Signing is a necessary step before broadcasting a transaction.
```javascript
let key = await arweave.wallets.generate();
let transaction = await arweave.createTransaction({
target: '1seRanklLU_1VTGkEk7P0xAwMJfA7owA1JHW5KyZKlY',
quantity: arweave.ar.arToWinston('10.5')
}, key);
await arweave.transactions.sign(transaction, key);
console.log(transaction);
```
--------------------------------
### Get Current Arweave Block Data
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/network.md
Retrieves the current block's data from the Arweave network using its identifier. This snippet first fetches the network info to get the current block's hash, then uses that hash to fetch the block details. Useful for inspecting the latest block's contents.
```typescript
const info = await arweave.network.getInfo();
const currentBlock = await arweave.blocks.get(info.current);
console.log(`Block height: ${currentBlock.height}`);
console.log(`Transactions in block: ${currentBlock.txs.length}`);
```
--------------------------------
### Get Number of Uploaded Chunks
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/uploader.md
The `uploadedChunks` property indicates how many chunks have been successfully uploaded so far.
```typescript
get uploadedChunks(): number
```
--------------------------------
### Arweave Wallet Generation and Transaction Workflow
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/wallets.md
This snippet demonstrates the complete workflow for Arweave wallet management. It covers generating a new wallet, retrieving its address, checking the balance, obtaining the last transaction ID, creating and signing a transaction, and finally submitting it. Ensure you have initialized the Arweave SDK before running this code.
```typescript
import Arweave from 'arweave';
const arweave = Arweave.init({
host: 'arweave.net',
port: 443,
protocol: 'https'
});
// 1. Generate new wallet
const jwk = await arweave.wallets.generate();
// 2. Get wallet address
const address = await arweave.wallets.jwkToAddress(jwk);
console.log('New address:', address);
// 3. Check balance (after sending AR to the address)
const balance = await arweave.wallets.getBalance(address);
const ar = arweave.ar.winstonToAr(balance);
console.log(`Balance: ${ar} AR`);
// 4. Get last transaction for creating new transactions
const lastTx = await arweave.wallets.getLastTransactionID(address);
// 5. Create and sign transaction
const tx = await arweave.createTransaction({
data: 'Hello Arweave!'
}, jwk);
await arweave.transactions.sign(tx, jwk);
// 6. Submit transaction
const response = await arweave.transactions.post(tx);
console.log('Transaction ID:', tx.id);
```
--------------------------------
### Get Upload Progress Percentage
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/uploader.md
The `pctComplete` property returns the upload progress as a percentage, ranging from 0 to 100.
```typescript
get pctComplete(): number
```
--------------------------------
### Arweave.init(apiConfig)
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/arweave-main.md
Static factory method for creating and initializing an Arweave instance. It allows configuration of connection details to an Arweave node.
```APIDOC
## Arweave.init(apiConfig)
### Description
Static factory method for creating and initializing an Arweave instance. It allows configuration of connection details to an Arweave node.
### Method
Static factory method
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **apiConfig** (`ApiConfig`) - Optional - Configuration object for the Arweave node connection.
- **host** (`string`) - Optional - Hostname or IP address of the Arweave node. Defaults to `arweave.net` (web) or `127.0.0.1` (Node).
- **port** (`string | number`) - Optional - Port number for the connection. Defaults to `443` (web) or `80` (Node).
- **protocol** (`string`) - Optional - Network protocol (`http` or `https`). Defaults to `https` (web) or `http` (Node).
- **timeout** (`number`) - Optional - Network request timeout in milliseconds. Defaults to `20000`.
- **logging** (`boolean`) - Optional - Enable network request logging to console. Defaults to `false`.
- **logger** (`Function`) - Optional - Custom logging function for network requests. Defaults to `console.log`.
- **network** (`string`) - Optional - Optional network identifier header.
### Returns
A new `Arweave` instance configured with the provided settings.
### Example
```typescript
import Arweave from 'arweave';
// Node.js - connect to a local node
const arweave = Arweave.init({
host: '127.0.0.1',
port: 1984,
protocol: 'http',
timeout: 20000
});
// Web - connect to default gateway
const arweaveWeb = Arweave.init({
host: 'arweave.net',
port: 443,
protocol: 'https'
});
// Web - use current page location (recommended in browser)
const arweaveAuto = Arweave.init({});
```
```
--------------------------------
### Browser (ES Module) Arweave Initialization
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/INDEX.md
Initialize the Arweave SDK in a browser environment using ES Modules.
```typescript
import Arweave from 'arweave';
const arweave = Arweave.init({});
```
--------------------------------
### Get Last Transaction ID from Wallet
Source: https://github.com/arweaveteam/arweave-js/blob/master/README.md
Fetches the ID of the most recent transaction associated with a given Arweave wallet address.
```javascript
arweave.wallets.getLastTransactionID('1seRanklLU_1VTGkEk7P0xAwMJfA7owA1JHW5KyZKlY').then((transactionId) => {
console.log(transactionId);
//3pXpj43Tk8QzDAoERjHE3ED7oEKLKephjnVakvkiHF8
});
```
--------------------------------
### Get Total Number of Chunks
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/uploader.md
The `totalChunks` property provides the total count of data chunks the transaction has been divided into for uploading.
```typescript
get totalChunks(): number
```
--------------------------------
### Arweave Main Class
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/INDEX.md
Initialization and root entry point for the Arweave JS SDK.
```APIDOC
## Arweave Main Class
### Description
Provides the main entry point for interacting with the Arweave network using the Arweave JS SDK. This class handles initialization and configuration.
### Endpoint
N/A (SDK Class)
### Usage
```javascript
import Arweave from 'arweave';
const arweave = new Arweave({
host: 'arweave.net',
port: 443,
protocol: 'https'
});
```
```
--------------------------------
### Initialize Arweave Node with Explicit Configuration
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/configuration.md
Configure the Arweave.js SDK with explicit host, port, and protocol settings for a specific node. This is useful for setting up your initial connection.
```typescript
import Arweave from 'arweave';
// Explicit node configuration
const arweave = Arweave.init({
host: 'arweave.net',
port: 443,
protocol: 'https'
});
```
--------------------------------
### get
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/transactions.md
Retrieves a complete transaction object from the Arweave network using its unique ID. This includes all populated properties of the transaction.
```APIDOC
## get(id)
### Description
Retrieves a complete transaction object from the network.
### Method
`async get(id: string): Promise`
### Parameters
#### Path Parameters
- **id** (`string`) - Required - Base64url-encoded transaction ID
### Returns
`Transaction` object with all properties populated.
### Throws
- `ArweaveError` with type `TX_NOT_FOUND` if transaction doesn't exist (HTTP 404)
- `ArweaveError` with type `TX_FAILED` if transaction failed (HTTP 410)
- `ArweaveError` with type `TX_INVALID` for other errors
### Example
```typescript
const tx = await arweave.transactions.get('bNbA3TEQVL60xlgCcqdz4ZPHFZ711cZ3hmkpGttDt_U');
console.log(tx.id);
console.log(tx.owner);
console.log(tx.data); // Automatically fetched if available
```
```
--------------------------------
### Initialize Arweave with Environment Variables
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/configuration.md
Configure the Arweave library by reading settings from environment variables. Provides fallback values if environment variables are not set. Ensure port numbers are parsed as integers.
```typescript
const arweave = Arweave.init({
host: process.env.ARWEAVE_HOST || 'arweave.net',
port: parseInt(process.env.ARWEAVE_PORT || '443'),
protocol: process.env.ARWEAVE_PROTOCOL || 'https',
timeout: parseInt(process.env.REQUEST_TIMEOUT || '20000'),
logging: process.env.DEBUG_ARWEAVE === 'true'
});
```
--------------------------------
### Get Block by Independent Hash
Source: https://github.com/arweaveteam/arweave-js/blob/master/README.md
Retrieves block data using its independent hash. This is useful for accessing specific historical blocks.
```javascript
const result = await arweave.blocks.get("zbUPQFA4ybnd8h99KI9Iqh4mogXJibr0syEwuJPrFHhOhld7XBMOUDeXfsIGvYDp");
console.log(result)
// {
// "nonce": "6jdzO4FzS4EVaQVcLBEmxm6uN5-1tqBXW24Pzp6JsRQ",
// "previous_block": "iNgEv6vf9nIrxLWeEu-vPNHFftEh0kfOnx0qd6NKUOc8Z3WeMeOmAmdOHwSUFAGn",
// "timestamp": 1624183433,
// "last_retarget": 1624183433,
// "diff": "115792089220940710686296942055695413965527953310049630981189590430430626054144",
// "height": 711150,
// "hash": "_____8V8BkM8Cyja5ZFJcc7HfX33eM4BKDAvcEBn22s",
// "indep_hash": "zbUPQFA4ybnd8h99KI9Iqh4mogXJibr0syEwuJPrFHhOhld7XBMOUDeXfsIGvYDp",
// "txs": [ ...
```
--------------------------------
### Get Network Info and Block Data
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/INDEX.md
Retrieve current network information and fetch data for a specific block using its ID.
```typescript
const info = await arweave.network.getInfo();
const block = await arweave.blocks.get(info.current);
```
--------------------------------
### RequestInitWithAxios
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/types.md
Extends the standard `RequestInit` with Arweave-specific options, such as `responseType`. This type is used for parameters in API request methods like `Api.get()`, `Api.post()`, and `Api.request()`.
```APIDOC
## RequestInitWithAxios
### Description
HTTP request options with Arweave extensions.
### Type Definition
```typescript
interface RequestInitWithAxios extends RequestInit {
responseType?: "arraybuffer" | "json" | "text" | "webstream";
}
```
### Used by:
- `Api.get()`, `Api.post()`, `Api.request()` parameters
```
--------------------------------
### Get Transaction Anchor
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/transactions.md
Fetches the current transaction anchor, which is the hash of the last transaction on the network. This is required for creating valid transactions.
```typescript
async getTransactionAnchor(): Promise
```
```typescript
const anchor = await arweave.transactions.getTransactionAnchor();
console.log(anchor); // "Tk-0c7260Ya5zjfjzl4f6-W-vRO94qiqZMAScKBcYXc68v1Pd8b..."
```
--------------------------------
### Get Address (Alias)
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/wallets.md
An alias for `jwkToAddress()`, providing the same functionality to convert a JWK or use the browser wallet to derive an Arweave address.
```APIDOC
## getAddress(jwk)
### Description
Alias for `jwkToAddress()` with identical behavior.
### Method
```typescript
async getAddress(jwk?: JWKInterface | "use_wallet"): Promise
```
### Example
```typescript
const address = await arweave.wallets.getAddress(jwk);
```
```
--------------------------------
### Node.js Arweave Initialization
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/INDEX.md
Initialize the Arweave SDK for Node.js environments using CommonJS or ES Modules.
```typescript
import Arweave from 'arweave';
// Or CommonJS
const Arweave = require('arweave');
// Initialize
const arweave = Arweave.init({
host: 'arweave.net',
port: 443,
protocol: 'https'
});
```
--------------------------------
### Initialize Arweave for Production Gateway (Node.js)
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/configuration.md
Configure Arweave JS for the production gateway in a Node.js environment. Defaults for port and protocol are often used.
```typescript
const arweave = Arweave.init({
host: 'arweave.net',
port: 443,
protocol: 'https',
timeout: 30000
});
```
--------------------------------
### Get Wallet Balance
Source: https://github.com/arweaveteam/arweave-js/blob/master/README.md
Retrieves the balance of a specified Arweave wallet address. Balances are returned in Winston by default; conversion to AR is provided.
```javascript
arweave.wallets.getBalance('1seRanklLU_1VTGkEk7P0xAwMJfA7owA1JHW5KyZKlY').then((balance) => {
let winston = balance;
let ar = arweave.ar.winstonToAr(balance);
console.log(winston);
//125213858712
console.log(ar);
//0.125213858712
});
```
--------------------------------
### Arweave Class Methods
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/METHODS-SUMMARY.md
Methods for initializing the SDK and managing core Arweave functionalities.
```APIDOC
## Arweave Class
### Description
Provides methods for initializing the Arweave SDK and performing core operations.
### Methods
#### `init(config)`
- **Purpose**: Initialize SDK with connection config.
- **Returns**: `Arweave` instance.
#### `createTransaction(attrs, jwk)`
- **Purpose**: Create a new transaction.
- **Returns**: `Promise`.
#### `createSiloTransaction(attrs, jwk, uri)`
- **Purpose**: Create an encrypted Silo transaction.
- **Returns**: `Promise`.
#### `arql(query)`
- **Purpose**: Execute ARQL query (deprecated).
- **Returns**: `Promise`.
#### `getConfig()`
- **Purpose**: Get current configuration.
- **Returns**: `Config`.
```
--------------------------------
### Get Transaction Status
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/transactions.md
Retrieves the confirmation status of a transaction using its ID. Returns the HTTP status code and confirmation details if available.
```typescript
async getStatus(id: string): Promise
```
```typescript
const status = await arweave.transactions.getStatus('bNbA3TEQVL60xlgCcqdz4ZPHFZ711cZ3hmkpGttDt_U');
if (status.confirmed && status.confirmed.number_of_confirmations > 10) {
console.log('Transaction confirmed with 10+ blocks');
}
```
--------------------------------
### Get Wallet Balance
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/wallets.md
Retrieves the AR balance of a given Arweave wallet address. The balance is returned in winston, the smallest unit of AR.
```APIDOC
## getBalance(address)
### Description
Retrieves the AR balance of a wallet address.
### Method
```typescript
getBalance(address: string): Promise
```
### Parameters
#### Path Parameters
- **address** (string) - Required - Base64url-encoded Arweave wallet address
### Returns
Balance as a string in winston (smallest unit of AR).
### Example
```typescript
const balance = await arweave.wallets.getBalance('1seRanklLU_1VTGkEk7P0xAwMJfA7owA1JHW5KyZKlY');
console.log(balance); // "125213858712"
// Convert to AR
const arBalance = arweave.ar.winstonToAr(balance);
console.log(arBalance); // "0.125213858712"
```
```
--------------------------------
### Get Last Transaction ID
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/wallets.md
Retrieves the transaction ID of the most recent transaction from a specified wallet address. This is necessary for creating new transactions.
```typescript
const lastTxId = await arweave.wallets.getLastTransactionID('1seRanklLU_1VTGkEk7P0xAwMJfA7owA1JHW5KyZKlY');
console.log(lastTxId); // "Tk-0c7260Ya5zjfjzl4f6-W-vRO94qiqZMAScKBcYXc68v1Pd8bYfTbKWi7pepUF"
```
--------------------------------
### RequestInitWithAxios Interface
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/types.md
Extends standard HTTP request initialization options with Arweave-specific extensions like responseType.
```typescript
interface RequestInitWithAxios extends RequestInit {
responseType?: "arraybuffer" | "json" | "text" | "webstream";
}
```
--------------------------------
### Initialize Arweave with Web Bundles
Source: https://github.com/arweaveteam/arweave-js/blob/master/README.md
Initialize the Arweave client within an HTML file after including the web bundle. The init function can be called without options to use the current URL path.
```javascript
const arweave = Arweave.init({});
arweave.network.getInfo().then(console.log);
```
--------------------------------
### Get Wallet Balance
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/wallets.md
Retrieves the AR balance of a given wallet address. The balance is returned as a string in winston (the smallest unit of AR).
```typescript
const balance = await arweave.wallets.getBalance('1seRanklLU_1VTGkEk7P0xAwMJfA7owA1JHW5KyZKlY');
console.log(balance); // "125213858712"
// Convert to AR
const arBalance = arweave.ar.winstonToAr(balance);
console.log(arBalance); // "0.125213858712"
```
--------------------------------
### Get Arweave Configuration
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/arweave-main.md
Retrieves the current Arweave configuration, including API host and port. Useful for understanding the SDK's network settings.
```typescript
const config = arweave.getConfig();
console.log(config.api.host); // arweave.net
console.log(config.api.port); // 443
```
--------------------------------
### getUploader
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/transactions.md
Creates a TransactionUploader for chunked uploading with progress tracking and resumability. This is useful for large transactions where you need to monitor upload progress or resume an interrupted upload.
```APIDOC
## getUploader(upload, data)
### Description
Creates a `TransactionUploader` for chunked uploading with progress tracking and resumability.
### Method Signature
```typescript
async getUploader(
upload: Transaction | SerializedUploader | string,
data?: Uint8Array | ArrayBuffer
): Promise
```
### Parameters
#### upload
- **Type**: `Transaction | SerializedUploader | string`
- **Required**: Yes
- **Description**: Transaction, serialized uploader state, or transaction ID to resume
#### data
- **Type**: `Uint8Array | ArrayBuffer`
- **Required**: No
- **Description**: Transaction data (required when resuming from ID or serialized state)
### Returns
- **Type**: `TransactionUploader`
- **Description**: `TransactionUploader` instance for managing chunked uploads.
### Example - Upload New Transaction
```javascript
const tx = await arweave.createTransaction({ data: largeBuffer }, jwk);
await arweave.transactions.sign(tx, jwk);
const uploader = await arweave.transactions.getUploader(tx);
while (!uploader.isComplete) {
await uploader.uploadChunk();
console.log(`${uploader.pctComplete}% complete (${uploader.uploadedChunks}/${uploader.totalChunks})`);
}
```
### Example - Resume Upload from Saved State
```javascript
// Save state after partial upload
const savedState = JSON.stringify(uploader);
localStorage.setItem('upload-state', savedState);
// Later: resume
const resumeState = JSON.parse(localStorage.getItem('upload-state'));
const data = await readFile('large-file.bin'); // Get original data
const uploader = await arweave.transactions.getUploader(resumeState, data);
while (!uploader.isComplete) {
await uploader.uploadChunk();
}
```
### Example - Resume from Transaction ID
```javascript
// If you know the transaction ID but don't have the uploader state
const txId = 'bNbA3TEQVL60xlgCcqdz4ZPHFZ711cZ3hmkpGttDt_U';
const data = await readFile('large-file.bin');
const uploader = await arweave.transactions.getUploader(txId, data);
while (!uploader.isComplete) {
await uploader.uploadChunk();
}
```
```
--------------------------------
### Get Transaction Data
Source: https://github.com/arweaveteam/arweave-js/blob/master/README.md
Retrieves the data associated with a transaction ID. This method can return the data as a base64url encoded string, a decoded Uint8Array, or a decoded string.
```APIDOC
## Get Transaction Data
### Description
Retrieves the data associated with a transaction ID. This method can return the data as a base64url encoded string, a decoded Uint8Array, or a decoded string.
### Method
```js
arweave.transactions.getData(transactionId: string, options?: { decode?: boolean, string?: boolean })
```
### Parameters
#### Path Parameters
- **transactionId** (string) - Required - The ID of the transaction whose data is to be retrieved.
#### Query Parameters
- **options** (object) - Optional - Configuration for data retrieval.
- **decode** (boolean) - Optional - If true, decodes the data. Defaults to false.
- **string** (boolean) - Optional - If true and `decode` is true, decodes the data as a string. Defaults to false.
### Response
#### Success Response (200)
- **data** (string | Uint8Array) - The transaction data, either base64url encoded, as a Uint8Array, or as a string, depending on the options provided.
### Request Example
```js
// Get the base64url encoded string
arweave.transactions.getData('bNbA3TEQVL60xlgCcqdz4ZPHFZ711cZ3hmkpGttDt_U').then(data => {
console.log(data);
// CjwhRE9DVFlQRSBodG1sPgo...
});
// Get the data decoded to a Uint8Array for binary data
arweave.transactions.getData('bNbA3TEQVL60xlgCcqdz4ZPHFZ711cZ3hmkpGttDt_U', {decode: true}).then(data => {
console.log(data);
// Uint8Array [10, 60, 33, 68, ...]
});
// Get the data decode as string data
arweave.transactions.getData('bNbA3TEQVL60xlgCcqdz4ZPHFZ711cZ3hmkpGttDt_U', {decode: true, string: true}).then(data => {
console.log(data);
// ...
});
```
```
--------------------------------
### Initialize Arweave with Custom Node and Logging
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/configuration.md
Connect to a custom Arweave node with extended timeout and enable detailed logging using a custom logger function.
```typescript
const arweave = Arweave.init({
host: 'my-node.example.com',
port: 1984,
protocol: 'https',
timeout: 60000,
logging: true,
logger: (message) => {
console.log(`[${new Date().toISOString()}] ${message}`);
}
});
```
--------------------------------
### prepareChunks
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/transaction.md
Generates merkle tree chunks for large transaction data and sets the `data_root` field.
```APIDOC
## prepareChunks(data)
### Description
Generates merkle tree chunks for large transaction data and sets the `data_root` field.
### Method Signature
```typescript
async prepareChunks(data: Uint8Array): Promise
```
### Parameters
#### Path Parameters
- **data** (Uint8Array) - Required - Binary data to chunk (typically `this.data`)
### Throws
Error if chunk generation fails.
### Note
Called automatically during transaction creation and signing. Manual use is rare.
### Example
```typescript
const data = new Uint8Array(5 * 1024 * 1024); // 5MB
await tx.prepareChunks(data);
console.log(tx.data_root); // Now set to merkle root
```
```
--------------------------------
### Get Transaction
Source: https://github.com/arweaveteam/arweave-js/blob/master/README.md
Fetches a transaction from the connected Arweave node. Note that the `data` field is no longer guaranteed to be returned and `arweave.transactions.getData()` is recommended for fetching transaction data.
```APIDOC
## Get Transaction
### Description
Fetches a transaction from the connected Arweave node. Note that the `data` field is no longer guaranteed to be returned and `arweave.transactions.getData()` is recommended for fetching transaction data.
### Method
```js
arweave.transactions.get(transactionId: string)
```
### Parameters
#### Path Parameters
- **transactionId** (string) - Required - The ID of the transaction to fetch.
### Response
#### Success Response (200)
- **Transaction** (object) - An object representing the transaction with fields like `format`, `id`, `last_tx`, `owner`, `tags`, `target`, `quantity`, `data`, `data_size`, `data_tree`, `data_root`, `reward`, `signature`.
### Request Example
```js
arweave.transactions.get('hKMMPNh_emBf8v_at1tFzNYACisyMQNcKzeeE1QE9p8').then(transaction => {
console.log(transaction);
// Transaction { format: 1, id: 'hKMMPNh_emBf8v_at1tFzNYACisyMQNcKzeeE1QE9p8', last_tx: 'GW7p6NoGJ495tAoUjU5GLxIH52gqOgk5j78gQv3j0ebvldAlw6VgIUv_lrMNGI72', owner: 'warLaSbicZm1nx9ucf-_5i91CWgmNOcnFJfyJdloCtsbenBhLrcGH472kKTZyuEAp2lSKlZ0NFCT2r2z-0...', tags: [ { name: 'QXBwLU5hbWU', value: 'd2VpYm90LXNlYXJjaC13ZWlicw' } ], target: ', quantity: '0', data: 'iVBORw0KGgoAAAANSUhEUgAAArIAAADGCAYAAAAuVWN-AAAACXBIWXMAAAsSAAA...', data_size: '36795', data_tree: [], data_root: ', reward: '93077980', signature: 'RpohCHVl5vzGlG4R5ybeEuhs556Jv7rWOGaZCT69cpIei_j9b9sAetBlr0...' }
});
```
```
--------------------------------
### Get Current Arweave Configuration
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/configuration.md
Retrieve the current configuration settings of the Arweave instance using `getConfig()`. This allows you to inspect the active host, port, and protocol.
```typescript
const config = arweave.getConfig();
console.log(config.api.host); // Current host
console.log(config.api.port); // Current port
console.log(config.api.protocol); // Current protocol
```
--------------------------------
### compare(winstonStringA, winstonStringB)
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/ar.md
Compares two winston amounts using BigNumber arithmetic.
```APIDOC
## compare(winstonStringA, winstonStringB)
### Description
Compares two winston amounts using BigNumber arithmetic.
### Method
`compare`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **winstonStringA** (`string`) - Required - First amount in winston
- **winstonStringB** (`string`) - Required - Second amount in winston
### Returns
- `-1` if A < B
- `0` if A = B
- `1` if A > B
### Example
```javascript
const result = arweave.ar.compare('1000000000000', '500000000000');
console.log(result); // 1 (first is greater)
// if (arweave.ar.compare(balance, price) >= 0) {
// console.log('Sufficient balance to transact');
// }
```
```
--------------------------------
### Arweave.init() Static Factory Method
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/arweave-main.md
Use this static factory method to create and initialize an Arweave instance. It accepts an optional configuration object for connecting to an Arweave node.
```typescript
static init(apiConfig?: ApiConfig): Arweave
```
```typescript
import Arweave from 'arweave';
// Node.js - connect to a local node
const arweave = Arweave.init({
host: '127.0.0.1',
port: 1984,
protocol: 'http',
timeout: 20000
});
// Web - connect to default gateway
const arweaveWeb = Arweave.init({
host: 'arweave.net',
port: 443,
protocol: 'https'
});
// Web - use current page location (recommended in browser)
const arweaveAuto = Arweave.init({});
```
--------------------------------
### Get Transaction by ID
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/transactions.md
Retrieves a complete transaction object from the network using its Base64url-encoded transaction ID. Handles errors for non-existent, failed, or invalid transactions.
```typescript
async get(id: string): Promise
```
```typescript
const tx = await arweave.transactions.get('bNbA3TEQVL60xlgCcqdz4ZPHFZ711cZ3hmkpGttDt_U');
console.log(tx.id);
console.log(tx.owner);
console.log(tx.data); // Automatically fetched if available
```
--------------------------------
### Create Transaction Uploader
Source: https://github.com/arweaveteam/arweave-js/blob/master/_autodocs/api-reference/uploader.md
Instantiate the TransactionUploader by passing the transaction object to `arweave.transactions.getUploader()`. This is the primary method for initiating a chunked upload.
```typescript
const uploader = await arweave.transactions.getUploader(transaction);
```