Arweave JS

repository·master·Indexed 20 days ago

https://github.com/arweaveteam/arweave-js

A JavaScript/TypeScript SDK for interacting with the Arweave network. It enables developers to upload data to the permaweb, manage transactions, and handle wallets in both Node.js and browser environments. Key features include chunked uploading for large files, ARQL query execution, and utilities for managing private keys and transaction signatures.

Tokens
9.9K
Snippets
48
Records
49
Agent score
70%

What's inside arweave-js

  1. Create and Sign Transactions

    master

    Transactions are the building blocks of the Arweave permaweb. You can create data transactions (to store data) or wallet-to-wallet transactions (to transfer AR).

    Workflow:

    1. Call createTransaction to get an unsigned transaction object.
    2. (Optional) Add metadata using addTag.
    3. Call transactions.sign to sign the transaction with a key.
    4. Call transactions.submit or use an uploader to send it to the network.

    Important:

    • Modifying a transaction object after signing it will invalidate the signature.
    • If no key is passed to createTransaction, Arweave.js will attempt to use a browser-based wallet extension (like ArConnect).
    • For large data uploads, use ArBundles instead of standard transactions.
    let key = await arweave.wallets.generate();
    
    // Create a data transaction
    let transaction = await arweave.createTransaction({
        data: 'Hello World'
    }, key);
    
    // Add metadata tags
    transaction.addTag('Content-Type', 'text/plain');
    
    // Sign the transaction
    await arweave.transactions.sign(transaction, key);
    
    // Submit the transaction
    const response = await arweave.transactions.post(transaction);
  2. Manage Wallets and Private Keys

    master

    Arweave.js provides utilities to generate new wallets, derive addresses from private keys, and check wallet balances.

    Security Warning: Private keys (JWK format) must be stored securely. Anyone with the key can spend the funds in the wallet. They can never be recovered if lost.

    // Generate a new wallet and private key
    arweave.wallets.generate().then((key) => {
        console.log(key);
    });
    
    // Get the wallet address for a private key
    arweave.wallets.jwkToAddress(key).then((address) => {
        console.log(address);
    });
    
    // Get an address balance (returns value in winston)
    arweave.wallets.getBalance('ADDRESS').then((balance) => {
        let winston = balance;
        let ar = arweave.ar.winstonToAr(balance);
        console.log(winston, ar);
    });
    
    // Get the last transaction ID from a wallet
    arweave.wallets.getLastTransactionID('ADDRESS').then((transactionId) => {
        console.log(transactionId);
    });
  3. Upload Large Data via Chunked Uploading

    master

    For large files, use the getUploader method to perform chunked uploading. This allows for progress updates and the ability to resume interrupted uploads.

    Resuming an upload:

    • From a saved uploader: You can persist an uploader object using JSON.stringify(uploader) and resume it later by passing the parsed object and the original data to getUploader().
    • From a transaction ID: If an upload was interrupted and you didn't save the uploader, you can resume using the transaction ID and the original data (this will restart the upload from the beginning).
    • Async Iterator: You can also use the arweave.transactions.upload(tx) async iterator for a cleaner syntax.
    // Using the Uploader pattern
    let data = fs.readFileSync('path/to/file.pdf');
    let transaction = await arweave.createTransaction({ data: data }, key);
    transaction.addTag('Content-Type', 'application/pdf');
    await arweave.transactions.sign(transaction, key);
    
    let uploader = await arweave.transactions.getUploader(transaction);
    while (!uploader.isComplete) {
      await uploader.uploadChunk();
      console.log(`${uploader.pctComplete}% complete`);
    }
    
    // Using the Async Iterator pattern
    for await (const uploader of arweave.transactions.upload(transaction)) {
      console.log(`${uploader.pctComplete}% Complete`);
    }
  4. Install Arweave JS via Web Bundles

    master

    For direct usage in a browser without a bundler, you can include the Arweave web bundle via a <script> tag from unpkg. Use the minified version for production.

    <!-- Latest -->
    <script src="https://unpkg.com/arweave/bundles/web.bundle.js"></script>
    
    <!-- Latest, minified-->
    <script src="https://unpkg.com/arweave/bundles/web.bundle.min.js"></script>
    
    <!-- Specific version -->
    <script src="https://unpkg.com/arweave@1.2.0/bundles/web.bundle.js"></script>
    
    <!-- Specific version, minified -->
    <script src="https://unpkg.com/arweave@1.2.0/bundles/web.bundle.min.js"></script>
  5. Set up the WALLET_JSON environment variable for debug-cli

    master

    The debug-cli scripts require a wallet with sufficient funds to perform transactions. You must provide your wallet as a JSON string via the WALLET_JSON environment variable. You can do this by reading your keyfile into the variable using cat.

    export WALLET_JSON=$(cat path/to/keyfile.json)
  6. Access Arweave via the global Window object

    master

    When using the web entrypoint, the Arweave object is automatically attached to the global scope (window.Arweave or globalThis.Arweave). This allows you to access the SDK in environments where modules might not be explicitly imported, such as via a <script> tag.

    // If loaded via script tag, Arweave is available on the window
    const arweave = window.Arweave.init();
  7. Redo an upload using a file and a mined transaction ID

    master

    If an upload was previously attempted, you can use test-chunk-resume-id.js to redo the upload. This requires the original file and the transaction ID (txid) of a transaction that has already been mined.

    ./test-chunk-resume-id.js <file> <txid>
  8. Initialize Arweave using Web Bundles

    master

    When using the standalone <script> bundle in HTML, initialize the instance using Arweave.init({}).

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Hello world</title>
        <script src="https://unpkg.com/arweave@1.15.5/bundles/web.bundle.js"></script>
        <script>
        const arweave = Arweave.init({});
        arweave.network.getInfo().then(console.log);
        </script>
    </head>
    <body>
    </body>
    </html>