# Introduction to Arweave Wallet Kit

Hooks and Components for unified interaction with Arweave wallets

<figure><img src="/files/FJyOFL420qsQcjhlTk2P" alt=""><figcaption></figcaption></figure>

The Arweave Wallet Kit simplifies interactions between Arweave wallets and dApps, offering a unified API that supports any Arweave wallet. Users can easily interact with apps using their preferred wallet.

The Kit is divided into multiple packages for modularity and extensibility:

* A core package that is foundation for all functionality.
* A set of React hooks and components built on the core package.
* A styles package that complements the React hooks and components.

Support for other frameworks can be developed using the core package.

The support for various wallets is modular as well. It is broken down into “strategies”, with each having its own package.

## Terminology

In Arweave Wallet Kit, a *strategy* is an implementation of an Arweave wallet within the kit. These strategies allow the user to communicate with all wallets in a standard way and with a common API.

## Supported wallets

The library currently supports the following wallets:

* [Wander.app](https://www.wander.app)
* [Arweave.app](https://arweave.app)
* [Othent](https://othent.io/)
* General Browser Wallets

*Note: Othent will be deprecated by the end of 2025.  If you are integrating Arweave Wallet Kit into your dApp, it is recommended that you do NOT include the Othent strategy.* \
\
*For an Othent alternative, please check out Wander Connect:* [*https://wander.app/connect*](https://wander.app/connect)


# Setup

Setup the Arweave Wallet Kit in React applications

As seen in the introduction, the Arweave Wallet Kit utility is distributed across a few packages for modularity. The three main packages for using Arweave Wallet Kit with React apps are `@arweave-wallet-kit/core`, `@arweave-wallet-kit/react`, `@arweave-wallet-kit/styles`. The `core` and `styles` package are peer dependencies for the `react` package.

Alongside these, the strategies for each wallet have their own dedicated packages as well:

* `@arweave-wallet-kit/wander-strategy`
* `@arweave-wallet-kit/browser-wallet-strategy`
* `@arweave-wallet-kit/othent-strategy`
* `@arweave-wallet-kit/webwallet-strategy`

*Note: Othent will be deprecated by the end of 2025.  If you are integrating Arweave Wallet Kit into your dApp, it is recommended that you do NOT include the Othent strategy.* \
\
*For an Othent alternative, please check out Wander Connect:* [*https://wander.app/connect*](https://wander.app/connect)

You can configure one or more strategies depending on the wallets you wish to add support for.

{% hint style="info" %}
Note: Currently, Arweave Wallet Kit works out of the box with ReactJS and Vite applications. Support for NextJS is in the works.
{% endhint %}

## Installation

We’ll be demonstrating the installation and setup for all 4 strategies. The Wallet Kit can be installed with any of the popular package managers as follows:

```sh
npm install @arweave-wallet-kit/core @arweave-wallet-kit/react @arweave-wallet-kit/styles @arweave-wallet-kit/wander-strategy @arweave-wallet-kit/browser-wallet-strategy @arweave-wallet-kit/othent-strategy @arweave-wallet-kit/webwallet-strategy
```

or

```sh
yarn add @arweave-wallet-kit/core @arweave-wallet-kit/react @arweave-wallet-kit/styles @arweave-wallet-kit/wander-strategy @arweave-wallet-kit/browser-wallet-strategy @arweave-wallet-kit/othent-strategy @arweave-wallet-kit/webwallet-strategy
```

or

```sh
pnpm add @arweave-wallet-kit/core @arweave-wallet-kit/react @arweave-wallet-kit/styles @arweave-wallet-kit/wander-strategy @arweave-wallet-kit/browser-wallet-strategy @arweave-wallet-kit/othent-strategy @arweave-wallet-kit/webwallet-strategy
```

or

```sh
bun install @arweave-wallet-kit/core @arweave-wallet-kit/react @arweave-wallet-kit/styles @arweave-wallet-kit/wander-strategy @arweave-wallet-kit/browser-wallet-strategy @arweave-wallet-kit/othent-strategy @arweave-wallet-kit/webwallet-strategy
```

## Setting Up the Provider

To use the library, you need to wrap your application with the Kit Provider. We’ll be using a React Vite app as an example.

```tsx
// main.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { ArweaveWalletKit } from "@arweave-wallet-kit/react";
import WanderStrategy from "@arweave-wallet-kit/wander-strategy";
import OthentStrategy from "@arweave-wallet-kit/othent-strategy";
import BrowserWalletStrategy from "@arweave-wallet-kit/browser-wallet-strategy";
import WebWalletStrategy from "@arweave-wallet-kit/webwallet-strategy";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <ArweaveWalletKit
      config={{
        permissions: [
          "ACCESS_ADDRESS",
          "ACCESS_PUBLIC_KEY",
          "SIGN_TRANSACTION",
          "DISPATCH",
        ],
        ensurePermissions: true,
        strategies: [
          new WanderStrategy(),
          new OthentStrategy(),
          new BrowserWalletStrategy(),
          new WebWalletStrategy(),
        ],
      }}
    >
      <App />
    </ArweaveWalletKit>
  </React.StrictMode>
);
```

In the example above, the application is wrapped with the Arweave Wallet Kit Provider, passing it a `config` object as parameter with the desired wallet strategies and permissions based on the application requirements.

Once the provider is setup, you can either use the Wallet Kit’s functionality through its custom [components](/arweave-wallet-kit/connect-button) or [hooks](/arweave-wallet-kit/hooks).


# Connect Button

The Connect Button provides an option to easily integrate the Wallet Kit

The `<ConnectButton>` component is a highly customizable button that supports the [ANS](https://ans.gg) protocol to display information about the connected wallet. It comes as part of the `@arweave-wallet-kit/react` package.

## Usage

You can import and use the component anywhere in your React application as follows:

```tsx
<ConnectButton
  accent="rgb(255, 0, 0)"
  profileModal={false}
  showBalance={true}
  ...
/>
```

## Configuration

You can configure the Connect Button through its props:

| Props                | Type      | Description                                                                             |
| -------------------- | --------- | --------------------------------------------------------------------------------------- |
| `accent`             | `string`  | A theme color for the button                                                            |
| `showBalance`        | `boolean` | Show user balance when connected                                                        |
| `showProfilePicture` | `boolean` | Show user profile picture when connected                                                |
| `useAns`             | `boolean` | Use ANS to grab profile information                                                     |
| `profileModal`       | `boolean` | Show profile modal on click (if disabled, clicking the button will disconnect the user) |


# Hooks

React hooks that provide deeper access into the wallet APIs

Inside the [`<ArweaveWalletKit>`](/arweave-wallet-kit/setup#setup-provider), you can use all kinds of hooks that are reactive to the different [strategies](/#terminology). Some of the hooks and/or api functions might not be supported by all wallets.

## `useConnection`

This is the core hook for connecting / disconnecting a [strategy](/#terminology).

To use the different functionalities the various Arweave wallets provide, you need to request permissions from the user to interact with their wallets. This can be done with the `connect()` function.

To end the current Wander session for the user, you can disconnect from the extension, using the `disconnect()` function. This removes all permissions from your application.

The `connected` function is simply a boolean for checking whether the user is connected with the application.

### Usage

```ts
const { connected, connect, disconnect } = useConnection();

// initiate connection
await connect();

// disconnect the connected strategy
await disconnect();

// is there a strategy connected?
connected ? "wallet connected" : "no connected wallet";
```

## `useApi`

The API hook returns the active [strategy](/#terminology)'s API as an intractable object. Can be used to sign/encrypt, etc.

### Usage

```ts
const api = useApi();

// sign
await api.sign(transaction);

// encrypt
await api.encrypt(...)
```

{% hint style="warning" %}
The available API functions may vary depending on the chosen strategy.
{% endhint %}

## `useProfileModal`

Toggle visibility (display/ hide) a modal with the connected user’s profile information and a disconnect button.

```ts
const profileModal = useProfileModal();

profileModal.setOpen(true);
```

## `useActiveAddress`

The Active address hook returns the address that is currently connected with the application. It requires the [`ACCESS_ADDRESS`](https://docs.wander.app/api/connect#permissions) and the [`ACCESS_ALL_ADDRESSES`](https://docs.wander.app/api/connect#permissions) permission.

### Usage

```ts
const address = useActiveAddress();
```

## `usePublicKey`

The Active address hook returns the public key that is currently connected with the application. It requires the [`ACCESS_PUBLIC_KEY`](https://docs.wander.app/api/connect#permissions) permission.

### Usage

```ts
const publicKey = usePublicKey();
```

## `usePermissions`

The Permissions hook returns the permissions given to the application by the connected user.

### Usage

```ts
const permissions = usePermissions();
```

## `useAddresses`

This hook returns all the addresses in the connected wallet, known by Arweave Wallet Kit. This is useful for fetching all the addresses a connected user may have. It requires the [`ACCESS_ALL_ADDRESSES`](https://docs.wander.app/api/connect#permissions) permission.

### Usage

```ts
const addresses = useAddresses();
```

## `useWalletNames`

This hook returns any names associated with all the addresses the connected user may have. An example of these names are ANS names that can be associated with any Arweave wallet addresses. It requires the [`ACCESS_ALL_ADDRESSES`](https://docs.wander.app/api/connect#permissions) permission.

### Usage

```ts
const walletNames = useWalletNames();
```

## `useStrategy`

Active [strategy](/#terminology) hook. Returns the currently used strategy's ID ([`"wander"`](https://www.wander.app/), [`"webwallet"`](https://arweave.app), etc.)

### Usage

```ts
const strategy = useStrategy();
```


# Customization

Apply various customizations to the Wallet Kit UI

## Manage customizations

Custom configuration can be applied using the Wallet Kit Provider:

```tsx
...
   <ArweaveWalletKit
      theme={{
        displayTheme: "light",
        accent: {
          r: 0,
          g: 0,
          b: 0
        },
        titleHighlight: {
          r: 0,
          g: 122,
          b: 255
        },
        radius: "default"
      }}
      config={{
        strategies: [
          new WanderStrategy(),
          new WebWalletStrategy(),
          new OthentStrategy(),
          new BrowserWalletStrategy()
        ],
        permissions: ["ACCESS_ADDRESS", "ACCESS_ALL_ADDRESSES"],
        ensurePermissions: true,
        appInfo: {
          name: "Test App",
          logo: "https://arweave.net/tQUcL4wlNj_NED2VjUGUhfCTJ6pDN9P0e3CbnHo3vUE"
        },
        gatewayConfig: {
          host: "arweave.net",
          port: 443,
          protocol: "https"
        }
      }}
    >
    <YourApp />
  </ArweaveWalletKit>
...
```

## Application info

Using the `config` field of the [`<ArweaveWalletKit>`](/arweave-wallet-kit/setup#setup-provider) provider component, you can define a name, a logo or the required permissions for your app. The following options are available:

| Prop                | Type                                                                                | Default             | Description                                                                                                |
| ------------------- | ----------------------------------------------------------------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------- |
| `permissions`       | [`PermissionType[]`](https://docs.wander.app/api/connect#permissions)               | `[]`                | Permissions to connect with.                                                                               |
| `ensurePermissions` | `boolean`                                                                           | `false`             | Ensure that all required permissions are present. If false, it only checks if the app has any permissions. |
| `appInfo`           | [`AppInfo`](https://docs.wander.app/api/connect#additional-application-information) | `{}`                | Information about your app (name/logo).                                                                    |
| `gatewayConfig`     | [`GatewayConfig`](https://docs.wander.app/api/connect#custom-gateway-config)        | arweave.net gateway | Configuration for the Arweave gateway to use.                                                              |

## Theming

With the `theme` field, you can define a custom theme configuration for the Arweave Wallet Kit modals and buttons. The following options are available:

| Prop             | Type                               | Description                                                            |
| ---------------- | ---------------------------------- | ---------------------------------------------------------------------- |
| `displayTheme`   | `"dark"`, `"light"`                | UI display theme to use                                                |
| `accent`         | `RGBObject`                        | RGB accent color for the UI                                            |
| `titleHighlight` | `RGBObject`                        | RGB accent color for the subscreen titles (like the connection screen) |
| `radius`         | `"default"`, `"minimal"`, `"none"` | Border radius level used throughout the Kit UI                         |


# Introduction to the Arweave Data Storage SDK

The **Arweave Data Storage SDK** is a comprehensive toolkit designed to easily store any type of data permanently, facilitating seamless file and folder management on the Arweave blockchain. It leverages Arweave's decentralized permanent storage capabilities and ArFS specification to offer a robust solution for managing drives, folders, and files in a secure and immutable manner. With built-in encryption support, Arweave Data Storage SDK allows you to store files privately ensuring only authorized parties can access the content.

For seamless data storage and retrieval on [Arweave](https://www.arweave.org/), use the [`Arweave Data Storage SDK`](https://www.npmjs.com/package/arweave-storage-sdk) .

**Documentation**

The SDK is structured around several key services and models that produce Arweave compatible transactions:

* **Drives** – Create, list, and manage Arweave Data Storage SDK’s drives.
* **Folders** – Organize files in a hierarchical folder system.
* **Files** – Create, download, and manage file data.
* **Query** – Get uploaded file links, search for files using tags.

**Requirements**

* Node 18 or higher

*The library makes use of modern JavaScript/TypeScript features that require at least Node 18.*


# Installation

Install the package with:

```

npm install arweave-storage-sdk

# or

yarn add arweave-storage-sdk

```

This simple installation command adds Arweave Data Storage SDK to your project. It’s designed to integrate quickly, whether you’re building a prototype or a production-level application.


# Usage

Below is a quick example of how to initialize the Arweave Data Storage SDK,create a drive, a folder, and a file, or quickly upload a file. For more detailed use-cases, refer to the [Examples](https://github.com/) section.

#### Basic Setup

To use the SDK, initialize StorageApi with a configuration object. This will create a new Arweave Data Storage SDK client. You may also specify the application name (`appName`) and optional configurations.

```
const { Configuration, StorageApi, Token, Network } = require('arweave-storage-sdk');

const config = new Configuration({
	appName: '<Name of your App>'
	privateKey: '<ENV to private key or use_web_wallet>',
	network: Network.BASE_MAINNET,
	token: Token.USDC
})

const storageClient = new StorageApi(config);
await storageApiInstance.ready
```

#### Authentication

Once you have the storage client initialized and before you go ahead to upload any files, its really important to create a secured session by authenticating yourself. This allows you to track or query your uploads, receipts. It is easy and can be done in one line.

```
  //Login
  await storageApiInstance.api.login()
```

And that's it. You’re ready to make authenticated requests with the service.

#### Upload cost estimates

Assuming you have a valid session post login, the next step is to query for file upload prices. This is an optional step, in-case you are interested in setting up uploads conditionally or to check your wallet for enough balance before your upload. Based on your selected token and network, estimates will be provided to you in the same token and also in USD.

```
export interface GetEstimatesResponse {
  size: number
  usd: number
  usdc: {
    amount: string
    amountInSubUnits: string
  }
  payAddress: string
}
const size = file.size // 200000 bytes
const estimates = await storageClient.getEstimates(size) // size of type number

console.log(estimates)
{ 
  "data": { 
"size": 200000, 
"usd": 0.008599242237052303, 
"usdc": { 
"amount": "0.0086", 
"amountInSubUnits": "8600" 
}, 
"payAddress": "<USDC ADDRESS OF THE SERVICE>" 
  } 
}
```

#### Quick file upload

Upload a file (or buffer) quickly using the quickUpload method.

The `quickUpload` method simplifies the process of uploading a file to Arweave. It automatically handles the creation of the transaction, including setting metadata such as content type, visibility, and tags. The receipt returned includes the unique ID, to query and confirm the file upload.

```
const file = <web File object, file path, buffer or stream>�const receipt = await storageClient.quickUpload(file, {
	name: file.name || "test.txt",
	dataContentType: 'text/plain', // content type of the file
	visibility: '<public|private>',
	tags: [{name: "Collection-Type", value: "ART"}],�	size: file.size // size in bytes of type number
});

console.log('File has been uploaded. receipt:', receipt.id);
```

#### Creating a Drive

Create a new drive to manage your files on Arweave.

Drives act as containers for your files and folders. The additional parameters such as visibility and tags help you categorize and control access to your content. This context is useful if you’re new to managing storage on decentralized platforms.

```
const drive = await storageClient.drive.create('My Drive', { 
visibility: 'public',
tags: [{name: "Collection-Type", value: "ART"}] 
});

console.log('Drive created with ID:', drive.id);
```

#### Creating a Folder

Organize your files by creating folders within a drive.

Folders help you structure your files within a drive. In this example, you can see how to specify the parent drive and (optionally) a parent folder to build a hierarchical file system.

```
const folder = await storageClient.folder.create('My Folder', {
driveId: '<driveId>',
parentFolderId: '<parentFolderId>',
visibility: 'public',
tags: [{name: "Collection-Type", value: "ART"}]
});

console.log('Folder created with ID:', folder.id);
```

#### Creating a File

Store a file on Arweave by creating a file transaction.

This snippet creates a file by converting a string into a buffer and then sending it as a transaction to Arweave. The parameters include metadata like file name, size, and content type.

```
const fileData = Buffer.from('Hello, Arweave!');

const file = await storageClient.file.create({
	name: 'My File',
	size: fileData.length,
	dataContentType: 'text/plain',
	driveId: '<driveId>',
	parentFolderId: '<parentFolderId>',
	file: fileData,
	visibility: 'public',
	tags: [{name: "Collection-Type", value: "ART"}]
});

console.log('File uploaded; transaction ID:', file.txId);
```

*Note: The `visibility` field can be set to `public` or `private`.*


# Wallet

Arweave Data Storage SDK’s `WalletService` is designed to help you interact with your stored files and manage your funds. Whether you need to fetch a list of files or check your wallet balance, this service simplifies those tasks.&#x20;

Here’s what you can do with this WalletService:

* **Get all Files:** Retrieve all uploaded file links.
* **SearchFile:** Search for files using tags.
* **Balances:** Read wallet balances.


# Configuration

Initialize the **Arweave Data Storage SDK** object with various configuration options. The `appName` is recommended as it helps in organizing and searching your transactions on Arweave. The `privateKey` can either be your account’s key or a flag to use a browser wallet. Other parameters like `network`, `token`, and `gateway` let you tailor the SDK to your specific environment.

```
const { Configuration, Network, Token} = require('arweave-storage-sdk');

const config = new Configuration({
	appName: 'My cool project'
	privateKey: process.env.PRIVATE_KEY,
	network: Network.BASE_MAINNET,
	token: Token.USDC
})
```

| Option       | Optional | Description                                                                                                                                          |
| ------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `appName`    | true     | App name to be used in Arweave transactions. Recommended to use since it makes searching all your app files easier.                                  |
| `privateKey` | false    | Private key of your account. JWK in case of Arweave. if `'use_web_wallet'` is used, sdk will rely on browser wallets.                                |
| `network`    | true     | Network of your payment token. Eg: 'SOL\_MAINNET'. Simply use the Network object provided by the sdk to see supported networks. Defaults to Arweave. |
| `token`      | true     | Token to use for payments. Eg: 'USDT'. Use the Token object provided by the sdk to see all supported tokens. Defaults to AR.                         |

* **Encryption:** For private drives or file storage, use the built-in Crypto utilities to manage encryption.
* **API Calls:** The SDK uses the ArFSApi internally to interact with the Arweave network. You can override or customize gateway endpoints if needed.


# Data Upload Service

This service is used with Arweave Data Storage SDK to upload data to Arweave and pay for the storage using other chain's stablecoin tokens.

***Supported chains and stablecoins***

*Ethereum and EVM:* USDC and USDT

*Solana:* USDC and USDT

*Cosmos:* Noble

*If you would like to request support for a stablecoin payment on a different chain, please open an issue in the github repo* [*here*](/data-upload-service)

### Prerequisites

* Docker
* Node.js (>= v20.18.3)
* pnpm (>= v9.14.2)

### Installation

```
pnpm install
```

### Running the service

```
pnpm start:dev
```

### Running the service in production mode

```
pnpm start:prod
```

### Prisma migrations

```
pnpm db:migrate:dev
```

```
pnpm db:migrate:prod
```

### Prisma Studio

```
pnpm db:studio

```


# Introduction

What is ArweaveKit

***ArweaveKit aims to lower the barrier of onboarding and building on Arweave by creating a well documented one-stop library.***

### Installing the Package

For using any functions from the library, the package must be installed in the application.

```bash
npm install arweavekit
# or
yarn add arweavekit 
```

{% hint style="success" %}
The latest stable version of ArweaveKit is <mark style="color:red;">`1.5.1`</mark>.
{% endhint %}

### Using the Library

After installation, individual functions from specific function types can be imported as follows:

<pre class="language-javascript"><code class="lang-javascript"><strong>import { createWallet } from 'arweavekit/wallet';
</strong>
const wallet = await createWallet({params});
</code></pre>

### Types of functions available&#x20;

In this library, the following types of functions are available:

* **Wallet Functions**: Functions associated with creating and using wallets. Read more [here](/wallets/introduction).
* **Transaction Functions**: Functions associated with creating and interacting with transactions. Read more [here](/transactions/introduction).
* **Contract Functions**: Functions associated with creating and interacting with contracts. Read more [here](broken://pages/lzU5iWI44UA4187OvgvV).
* **Auth Functions**: Functions associated with authentication. Read more [here](/auth/introduction-to-auth).
* **Encryption Functions**: Functions associated with encryption. Read more [here](/encryption/introduction-to-encryption).
* **GraphQL query functions**: Functions to query on-chain data using GraphQL. Read more [here](/graphql/introduction-to-graphql).

### Compatibility

ArweaveKit is compatible with both Node.js and Browser environments. Node.js has deprecated for `v16` and suggest upgrading applications to `v18` and above, as per this [announcement](https://x.com/nodejs/status/1701309614263001569?s=20).

While ArweaveKit continues to support Node.js `v16`, a few flags must be passed in while running any scripts in order to optimally use some of ArweaveKit's latest features. If using Node.js `v16` we recommend using the following format:

```bash
node --experimental-fetch --no-warnings file-path
```

### Guide for understanding the docs

Every function has a dedicated page with the following information associated with it:

* A **brief description** of the function
* The **basic syntax** for function calls
* Any **input parameters** for the function
  * The syntax format for input parameters is `name: type`. Some parameters have the `optional` keyword which means they are optional. Parameters that do not have this keyword are required and must be passed in for successful function calls.
* The **returned data** for function calls
  * The syntax format for returned data is `name: type`. Data returned can be different different depending on the combination of input parameters used.

Links provided in data type descriptions may themselves link to other data types in cases of complex data objects. The most relevant bits have been explained throughout these docs but for a further understanding feel free to jump in to the rabbit hole.

### Example Application Ideas

Here's a list of example ideas for full-stack, end-user-facing applications you could build with `arweavekit`. These concepts leverage features of Arweave, such as decentralised data storage, pay-once store-forever pricing, transaction support, and smart contract and serverless function capabilities (using SmartWeave).

* **Decentralised Blogging Platform**: Users could write and publish blog posts that are stored permanently on Arweave. It could have an interactive frontend for easy post creation, browsing, and reading.
* **Decentralised Social Media**: A social media application where users can post text, images, and videos, create their profiles, and follow other users. All user data and interactions can be stored on Arweave.
* **Decentralised Document Collaboration**: A collaborative document editing platform that lets users create, edit, and share documents in real-time with other collaborators. It securely stores all document data on Arweave so that multiple copies are accessible and maintained indefinitely.

### Happy Building!


# Introduction to Wallets

Introduction to wallets on Arweave

### What is a wallet for blockchains?

A wallet on a blockchain is a device, program or service that stores public and private keys which in turn enable transactions with the blockchain.

The public key can be thought of as the username and the private key is like a password that must be kept safe at all times.

Any change to the state of the blockchain (information stored on chain) is considered a transaction and requires a wallet to complete.

### Wallets on Arweave

Arweave is a blockchain-like system that focuses on permanent and decentralised low-cost storage solutions. It can be thought of as a blockchain database.

All kinds of data like images, videos, documents, JSON objects, even web applications, among other types, can be stored on Arweave.

For uploading this data on Arweave we need a wallet. Additionally, a wallet is needed for interacting with applications that rely on Arweave.

### Wallets from a development perspective

As developers, we need to handle wallets for various uses right from providing users the ability to create transactions using these wallets on Arweave to interacting with other applications built on Arweave.

### Libraries used

The functions associated with wallets leverage the following libraries:

* [Arweave JS](https://github.com/ArweaveTeam/arweave-js)

### Wallet based functions

In this section, we will look at the following functions:

* creating a new wallet
* getting a wallet address using the private key
* getting the balance of a wallet address

###


# Create Wallet

Creating an Arweave wallet

The `createWallet` function creates a new wallet capable of interacting with Arweave and Arweave based applications.

{% hint style="info" %}
The created wallet does not have any tokens or assets in it. For transactions, the wallet may need to be supplied with funds.
{% endhint %}

### Basic Syntax

The function is called as follows:

```javascript
import { createWallet } from 'arweavekit/wallet'

const wallet = await createWallet({params});
```

### Input Parameters

The following params are available for this function and they must be passed in as an object:

* `seedPhrase: boolean` (optional) : Returns the seed phrase of the newly created wallet if set to `true`.
* `environment: 'local' | 'mainnet'` (optional) : The environment for creating the wallet. The wallet created is funded with `1000000000000 Winston` for the `local` environment. Wallets created on the `mainnet` need to be funded separately.

{% hint style="info" %}
An `arlocal` instance must be running on port <mark style="color:red;">`1984`</mark> for the function to work with the `local` environment. And any funds in the wallet will be available only as long as the same instance of `arlocal` is running.  To create one, simply run `npx arlocal` in the command line. Learn more about `arlocal` [here](https://cookbook.arweave.dev/guides/testing/arlocal.html).
{% endhint %}

{% hint style="info" %}
**Winston** is the smallest possible unit of **AR**, similar to a [satoshi](https://en.bitcoin.it/wiki/Satoshi_%28unit%29) in Bitcoin, or [wei](http://ethdocs.org/en/latest/ether.html#denominations) in Ethereum.

**1 AR** = 1000000000000 Winston (12 zeros) and **1 Winston** = 0.000000000001 AR.
{% endhint %}

<details>

<summary>Example</summary>

```javascript
const wallet = await createWallet({
    seedPhrase: true,
    environment: 'local',
});
```

This creates a new wallet on the local network that is pre-funded with `1000000000000 Winston (1 AR)` and returns the seedPhrase for the same along with the private key and wallet address.

</details>

### Returned Data

The function call returns the following data:

```bash
{
key: { KEY_OBJECT },
walletAddress: 'WALLET_ADDRESS',
seedPhrase: '12_WORD_SEED_PHRASE'
}
```

* `key: JWKInterface` : The private key is a JSON object. Read more about the Arweave compatible key format [here](https://docs.arweave.org/developers/server/http-api#key-format).

{% hint style="danger" %}
The key provides access to a wallet and any assets associated with it. It is crucial to keep the key secure and not publish it anywhere.
{% endhint %}

{% hint style="info" %}
Store the value of `key` in a file with the `.json` extension for later use.
{% endhint %}

* `walletAddress: string`: The wallet address is derived from the public key by truncating it down to 43 characters.
* `seedPhrase: string` (optional) : This is a 12 word `string` that can be used to recover a wallet and any assets associated with it.

{% hint style="danger" %}
It is is crucial to keep the seed phrase secure and not publish it anywhere.
{% endhint %}

{% hint style="info" %}
The seed phrase is returned only if the input parameter is set to true.
{% endhint %}


# Get Wallet Address

Fetching a wallet address

The `getWallet` function returns the wallet address for a given private key.

### Basic Syntax

The function is called as follows:

```javascript
import { getAddress } from 'arweavekit/wallet'

const address = await getAddress({params});
```

### Input Parameters

The following params are available for this function:

* `key: JWKInterface` : The private key for the wallet address to be fetched. The wallet key file can be loaded as follows:

```javascript
import { readFileSync } from 'fs';

const key = JSON.parse(readFileSync('wallet.json').toString());
```

{% hint style="danger" %}
Private keys must be kept secure at all times. Please ensure that the `wallet.json` file is not pushed to a version control (eg. GitHub).
{% endhint %}

{% hint style="info" %}
It is important to `JSON.parse` the read file as this returns the `key` in the correct format (`object`) for further use.
{% endhint %}

* `environment: 'local' | 'mainnet'` : The active environment on which the wallet is interacting with.

{% hint style="info" %}
An `arlocal` instance must be running on port <mark style="color:red;">`1984`</mark> for the function to work with the local environment. To create one, simply run `npx arlocal` in the command line. Learn more about `arlocal` [here](https://cookbook.arweave.dev/guides/testing/arlocal.html).
{% endhint %}

<details>

<summary>Example</summary>

```javascript
const walletAddress = await getAddress({
    key: { KEY_OBJECT },
    environment: 'local',
});
```

This returns the wallet address of the key entered as part of the parameters for the chosen environment.

</details>

### Returned Data

The function call returns the following data:

<pre class="language-bash"><code class="lang-bash"><strong>'WALLET_ADDRESS'
</strong></code></pre>

* `address: string` : The wallet address corresponding to the private key input is returned as type `string`.


# Get Wallet Balance

Get the balance of an address

The `getBalance` function returns the AR token balance in Winston (smallest possible unit of the AR token) for a given wallet address. The AR token is the native token in the Arweave ecosystem.

### Basic Syntax

The function is called as follows:

```javascript
import { getBalance } from 'arweavekit/wallet'

const address = await getBalance({params});
```

### Input Parameters

The following params are available for this function:

* `address: string` : The wallet address passed in as type `string`.
* `environment: 'local' | 'mainnet'` (optional) : The environment on which the wallet balance must be fetched.

{% hint style="info" %}
The `local` environment is configured to port <mark style="color:red;">`1984`</mark> and must have an `arlocal` instance running on the same port in the background for the function to work successfully. To create one, simply run `npx arlocal` in the command line. Learn more about `arlocal` [here](https://cookbook.arweave.dev/guides/testing/arlocal.html).
{% endhint %}

`options` : Additional options can be passed in as a JSON object.&#x20;

* &#x20;`winstonToAr: boolean` (optional) : Set this to `true` in order to receive wallet ballance in `Ar` instead of `Winston`.

{% hint style="info" %}
**Winston** is the smallest possible unit of **AR**, similar to a [satoshi](https://en.bitcoin.it/wiki/Satoshi_%28unit%29) in Bitcoin, or [wei](http://ethdocs.org/en/latest/ether.html#denominations) in Ethereum.

**1 AR** = 1000000000000 Winston (12 zeros) and **1 Winston** = 0.000000000001 AR.
{% endhint %}

<details>

<summary>Example</summary>

```javascript
const walletBalance = await getBalance({
    address: string,
    environment: 'local',
});
```

This returns the `AR` token balance of the entered wallet address in `Winston` for the chosen environment.

</details>

### Returned Data

The function call returns the following data:

```bash
'100000000000'
```

* `walletBalance: string` : Wallet balance in `Winston` returned as type `string` when the `winston` parameter is set to `true`.


# Wallet Plugins

Plug in a external package to arweavekit/wallet

The `use` function exposed via the ArweaveKit object from `arweavekit/wallet` package allows you to plugin external packages into arweave kit package.

### Basic Syntax

The function is called as follows:

{% code title="usage.js" %}

```javascript
import * as externalPackage from 'externalPackage';
import { ArweaveKit } from 'arweavekit/wallet';

const arweaveKit = ArweaveKit.use({ name: 'MyPlugIn', plugin: externalPackage });

console.log(arweavekit.functionFromExternalPackage())
```

{% endcode %}

{% hint style="info" %}
The ArweaveKit object imported also contains all functions from the ArweaveKit package for ease of use.
{% endhint %}

### Create a Plugin

Most existing packages in Arweave will already be supported without any additional work, the functions just need to be defined and exported in the external package:

{% code title="externalPackage.js" %}

```javascript
import * as ExternalPackage from 'package'
export function PackagePlugIn() {
    return ExternalPackage
}
```

{% endcode %}


# Introduction to Transactions

Introduction to transactions on Arweave

### Transactions on Arweave

Any change to the state of the blockchain (information stored on chain) is considered a transaction.

The two common types of transactions on Arweave are uploading data on chain and transfer of assets between wallets.

The transaction process on Arweave is split into 3 steps for convenience,  customisation and reduction in compute time. Namely, creating the transaction, signing it and then posting it on Arweave. The next pages look at these in depth.

### Transactions from a development perspective

Developers need to create user friendly tools, applications and interfaces that let users perform transactions like uploading data on chain or sending tokens without the need for writing code for it.

### Libraries used

The functions associated with transactions leverage the following libraries:

* [Arweave JS](https://github.com/ArweaveTeam/arweave-js)
* [Bundlr Network SDK](https://docs.bundlr.network/category/basic-features)
* [Othent](https://othent.io/)

### Transaction based functions

In this section, we will look at the following features:

* creating a transaction
* signing a transaction
* posting the transaction on chain
* getting the status of a transaction
* getting an existing transaction from the network
* creating and posting a transaction to the network with Othent


# Create Transaction

Create a transaction on Arweave

The `createTransaction` function creates a transaction based on the input parameters. The transaction can either be a data upload transaction or a wallet to wallet (token transfer) transaction.

### Basic Syntax

The function is called as follows:

<pre class="language-javascript"><code class="lang-javascript"><strong>import { createTransaction } from 'arweavekit/transaction'
</strong>
const transaction = await createTransaction({params});
</code></pre>

### Input Parameters

The following params are available for this function and they must be passed in as an object:

* `type: 'data' | 'wallet'` : The type of transaction to be created. A `data` type transaction uploads data on Arweave whereas a `wallet` type transaction transfers tokens from one wallet to another.
* `key: JWKInterface` (optional) : The private key for the wallet address to be fetched. The wallet key is optional for default transaction creation as no key is needed until signing a transaction, however, it must be passed in if the `useBundlr` or `signAndPost` option is set to `true`. The wallet key file can be loaded as follows:

```javascript
import { readFileSync } from 'fs';

const key = JSON.parse(readFileSync('wallet.json').toString());
```

{% hint style="danger" %}
Private keys must be kept secure at all times. Please ensure that the `wallet.json` file is not pushed to a version control (eg. GitHub).
{% endhint %}

{% hint style="info" %}
It is important to `JSON.parse` the read file as this returns the `key` in the correct format (`object`) for further use.
{% endhint %}

* `environment: 'local' | 'mainnet'` : The environment for creating transactions. As this is only one part of the three step process of uploading transactions to Arweave, it is important that the transaction is signed and posted in the same environment it is created on.

{% hint style="info" %}
An `arlocal` instance must be running on port <mark style="color:red;">`1984`</mark> for the function to work with the local environment. To create one, simply run `npx arlocal` in the command line. Learn more about `arlocal` [here](https://cookbook.arweave.dev/guides/testing/arlocal.html).
{% endhint %}

{% hint style="warning" %}
Currently, the Bundlr SDK only supports the `mainnet` environment.
{% endhint %}

* `target: string` (optional) : The wallet address to which the wallet to wallet transaction must be sent.

{% hint style="info" %}
The `target` must be accompanied with a `quantity` , else it sends a transaction with `0` tokens by default.
{% endhint %}

* `quantity: string` (optional) : The quantity specifies the units of **Winston** to be sent in a wallet to wallet transaction.

{% hint style="info" %}
The `quantity` must be accompanied with a `target` wallet address.
{% endhint %}

{% hint style="info" %}
**Winston** is the smallest possible unit of **AR**, similar to a [satoshi](https://en.bitcoin.it/wiki/Satoshi_%28unit%29) in Bitcoin, or [wei](http://ethdocs.org/en/latest/ether.html#denominations) in Ethereum.

**1 AR** = 1000000000000 Winston (12 zeros) and **1 Winston** = 0.000000000001 AR.
{% endhint %}

* `data: string | Uint8Array | ArrayBuffer` (optional) : To create a data type transaction, this optional parameter can be passed in. The data can be passed as a `string`, `Uint8Array` or an `ArrayBuffer` (as preferred by the network).
* `options` : Additional options can be passed in as a JSON object.&#x20;
  * &#x20;`tags: array` (optional) : Tags can be added to any transaction for ease of indexing and querying. The syntax for adding tags is as follows:

    ```javascript
    tags: [{ 'name': key_name, 'value': some_value},
            { 'name': key_name2, 'value': some_value2}]
    ```

    The `name` is the key for a given `value` that can be used for querying the   transaction in the future. By default the library adds the `'ArweaveKit' : '1.5.1'` tag on the backend to help identify the library and version used to deploy the function.
  * `signAndPost: boolean` (optional) : By default, the transaction process on Arweave has three steps to reduce the computation time, and provide convenience and customisation. However, by setting this option to `true`, the function signs and posts the transaction on chain in the same function call.
  * `useBundlr: boolean` (optional) : Creates the transaction using [bundlr network](https://docs.bundlr.network/docs/client/transactions). Only `data` type transactions can use this option. If the data size is under 100kB the transaction does not require any fees for processing through Bundlr.

{% hint style="warning" %}
Currently, the Bundlr SDK only supports data based transactions and only on the `mainnet`.
{% endhint %}

{% hint style="warning" %}
The `option` to `signAndPost` must be set to `true` for using `Bundlr`. Transactions using Bundlr will be signed and posted to the network by default as there is no support for signing and uploading Bundlr transactions in separate steps.
{% endhint %}

{% hint style="warning" %}
Web Transactions using Bundlr will fallback on Arweave in case of failure.
{% endhint %}

<details>

<summary>Example</summary>

<pre class="language-javascript"><code class="lang-javascript"><strong>const transaction = await createTransaction({
</strong><strong>    key: { KEY_OBJECT },
</strong><strong>    type: 'wallet',
</strong>    quantity: '1000000',
    target: 'TARGET_WALLET_ADDRESS',
    environment: 'mainnet',
    options: {
        tags: [{ 'name': 'key_name', 'value': 'some_value'}],
    },
});
</code></pre>

This call creates `wallet` type transaction on the `mainnet`  and adds the tags that we have defined. This needs to be signed and posted in the consequent steps to successfully upload on Arweave.

</details>

### Returned Data

The function call returns the following data depending on input parameters:

* Default transaction (when `useBundlr` is `false`):
  * An object of type [Transaction](https://docs.arweave.org/developers/server/http-api#field-definitions) is returned by Arweave.
  * The data related key value pairs hold information when `data` prop is passed in.
  * The target and quantity fields have in formation for wallet-to-wallet transactions.
  * The `signature` key has no information until the transaction is signed.
  * The `id` of a transaction is only received after calling the `postTransaction` function (basically, when the transaction is posted on Arweave).
  * On selecting the `signAndPost` option the function returns a status object along with the transaction object. `status: 200` and `statusText: 'OK'` indicates a successful post request on Arweave.
  * The transaction is created on the selected `environment` (`local` or `mainnet`).
* When the `useBundlr` option is set to `true:`
  * An object of type [Bundlr Transaction](https://github.com/Bundlr-Network/js-sdk/blob/12d5e57df8d82ca277106ca08e4787909ee3eede/src/common/transaction.ts#L11) and an object containing the `id` of the posted transaction and the `timestamp` are returned.
  * The `Bundlr Transaction` object consists information regarding the network, currency, data to be posted, tags, etc.
  * The `environment` is always `mainnet`.
* A few errors help identify the correct parameters in case any might be missing or not as expected.&#x20;


# Sign Transaction

Sign a created transaction

As seen earlier, the transaction process has been split in 3 steps. Once a transaction has been created, it must be signed. The signature is a unique identifier created by hashing the input parameters provided while creating the transaction and wallet information of the signer. This is useful for verification purposes and prevention of forgery.

The `signTransaction` function creates a signature for a transaction.

### Basic Syntax

The function is called as follows:

```javascript
import { signTransaction } from 'arweavekit/transaction'

const signedTransaction = await signTransaction({params}) 
```

### Input Parameters

The following params are available for this function and they must be passed in as an object:

* `key: JWKInterface` (optional): The private key for the wallet signing the transaction. When using in web apps, this field can be left empty or the `use_wallet` string can be passed in to trigger a web wallet. The wallet key file can be loaded as follows:

```javascript
import { readFileSync } from 'fs';

const key = JSON.parse(readFileSync('wallet.json').toString());
```

* `environment: 'local' | 'mainnet'` (optional) : The environment on which the transaction was created.

{% hint style="info" %}
An `arlocal` instance must be running on port <mark style="color:red;">`1984`</mark> for the function to work with the local environment. To create one, simply run `npx arlocal` in the command line. Learn more about `arlocal` [here](https://cookbook.arweave.dev/guides/testing/arlocal.html).
{% endhint %}

* `createdTransaction: object` : The transaction object created in the earlier step.
* `postTransaction: boolean` (optional): This boolean enables the posting of the transaction to Arweave using the `signTransaction` function itself.

<details>

<summary>Example</summary>

```javascript
const signedTransaction = await signTransaction({
    createdTransaction: createdTransaction,
    key: { KEY_OBJECT },
    environment: 'mainnet',
});
```

This call signs a created transaction on `mainnet` on a node environment.

</details>

### Returned Data

The function call returns the following data depending on input parameters:

* A signed object of type [Transaction](https://docs.arweave.org/developers/server/http-api#field-definitions) is returned by Arweave.
  * The `signature` key will be populated with a base64URL encoded signature hash with the help of the RSA algorithm.
  * The `id` of a transaction is only received after posting the transaction on Arweave.
  * On selecting the `postTransaction` option the function returns a status object along with the transaction object. `status: 200` and `statusText: 'OK'` indicates a successful post request on Arweave.
  * The transaction is signed on the selected `environment` (`local` or `mainnet`).


# Post Transaction

Post a signed transaction on Arweave

This is the final step of the transaction process on Arweave.

The `postTransaction` function uploads the previously signed transaction on Arweave.

### Basic Syntax

The function is called as follows:

```javascript
import { postTransaction } from 'arweavekit/transaction'

const postedTransaction = await postTransaction({params}) 
```

### Input Parameters

The following params are available for this function and they must be passed in as an object:

* `key: JWKInterface` (optional): The private key for the wallet posting the transaction. The wallet key file can be loaded as follows:

```javascript
import { readFileSync } from 'fs';

const key = JSON.parse(readFileSync('wallet.json').toString());
```

{% hint style="info" %}
Make sure to use the same private key used in the `signTransaction` function.
{% endhint %}

* `environment: 'local' | 'mainnet'` (optional) : The environment on which the transaction was created and signed.

{% hint style="info" %}
An `arlocal` instance must be running on port <mark style="color:red;">`1984`</mark> for the function to work with the local environment. To create one, simply run `npx arlocal` in the command line. Learn more about `arlocal` [here](https://cookbook.arweave.dev/guides/testing/arlocal.html).
{% endhint %}

* `transaction: object` : The transaction object signed previously.

<details>

<summary>Example</summary>

```javascript
const postedTransaction = await postTransaction({
    transaction: transaction,
    key: { KEY_OBJECT },
    environment: 'mainnet',
});
```

This function call posts the signed transaction on Arweave's `mainnet`.

</details>

### Returned Data

The function call returns the following data depending on input parameters:

* A signed object of type [Transaction](https://docs.arweave.org/developers/server/http-api#field-definitions) is returned by Arweave.
* A status object is also returned. `status: 200` and `statusText: 'OK'` indicates a successful post request on Arweave.
  * The transaction is posted on the selected `environment` (`local` or `mainnet`).


# Get Transaction Status

Get the transaction status of a posted transaction

There is a wait time involved between requesting to post a transaction on chain and it actually being posted.

The `getTransactionStatus` functions provides the status for a given transaction on whether it has been successfully posted on chain or is amidst processing.

{% hint style="info" %}
This function is only valid for transactions for which the post request has already been sent to the network. Additionally, this function only works with transactions generated with the default param for network (i.e. the `arweave-js` library. Support for the Bundlr SDK is not available currently.
{% endhint %}

### Basic Syntax

The function is called as follows:

```javascript
import { getTransactionStatus } from 'arweavekit/transaction'

const status = await getTransactionStatus({params});
```

### Input Parameters

The following params are available for this function and they must be passed in as an object:

* `transactionId: string` : The unique identification Id associated with a transaction.
* `environment: 'local' | 'mainnet'` : The environment on which the transaction was posted.

{% hint style="info" %}
An `arlocal` instance must be running on port <mark style="color:red;">`1984`</mark> for the function to work with the local environment. To create one, simply run `npx arlocal` in the command line. Learn more about `arlocal` [here](https://cookbook.arweave.dev/guides/testing/arlocal.html).
{% endhint %}

### Returned Data

The function call returns the following data:

```javascript
{
  status: 200,
  confirmed: {
    block_height: 1107205,
    block_indep_hash: 'O0VduHn7GsBx0jsLVKXSPpx_ue-GRXpX56_1hfmIOrVI9sQFVe1ABb8iDDLJBzlu',
    number_of_confirmations: 18358
  }
}
```

* `status: number` : The `status` is an indicator on whether the transaction has been successfully processed. It must return the value `200` for the same.
* `confirmed: object` :  The `confirmed` object contains additional information regarding the successful processing of the transaction.
  * `block_height: number` : The height or block number in which the transaction has been processed.
  * `block_indep_hash: string` : &#x20;
  * `number_of_confirmations: number` :  The number of blocks in the network that have been mined since processing of the given transaction.


# Get Transaction

Get the details for a posted transaction

Get details about a transaction that has already been posted to the network with the help of the `getTransaction` function.

{% hint style="info" %}
This function is only valid for transactions for which the post request has already been sent to the network. Additionally, this function only works with transactions generated with the default param for network (i.e. the `arweave-js` library. Support for the Bundlr SDK is not available currently.
{% endhint %}

### Basic Syntax

The function is called as follows:

```javascript
import { getTransaction } from 'arweavekit/transaction'

const data = await getTransaction({params});
```

### Input Parameters

The following params are available for this function and they must be passed in as an object:

* `transactionId: string` : The unique identification Id associated with a transaction.
* `environment: 'local' | 'mainnet'` : The environment on which the transaction was posted.

{% hint style="info" %}
An `arlocal` instance must be running on port <mark style="color:red;">`1984`</mark> for the function to work with the local environment. To create one, simply run `npx arlocal` in the command line. Learn more about `arlocal` [here](https://cookbook.arweave.dev/guides/testing/arlocal.html).
{% endhint %}

### Returned Data

The function call returns the following data:

```bash
{
    transaction: [TransactionObject]
}
```

* `transaction: Transaction` : An object of type [Transaction](https://docs.arweave.org/developers/server/http-api#field-definitions) is returned by Arweave.


# Create and Post Transaction with Othent

Post a transaction on Arweave with Othent

[Othent](https://docs.othent.io/developers/sdk) is library facilitating the onboarding of users from web2 to web3 through account abstraction. The authentication protocol offers a number of "wallet-less" functions for the same. Users can connect and interact with applications using web2 technologies like email accounts with the help of Othent.

The `createAndPostTransactionWOthent` function enables interacting with a deployed contract based on the input parameters.

### Basic Syntax

{% hint style="info" %}
Ensure you have pop-ups enabled in your browser for the URL you'll be using this function in.
{% endhint %}

The function is called as follows:

```javascript
import { createAndPostTransactionWOthent } from 'arweavekit/transaction'

const transaction = await createAndPostTransactionWOthent({params});
```

### Input Parameters

The following params are available for this function and they must be passed in as an object:

* `apiId: string` : Use of any Othent function requires an `apiId` which can be fetched from [othent.io](https://othent.io/). Towards the bottom of the linked page, the `Get your API ID` button provides the same.
* `othentFunction: string` : The `othentFunction` param informs the protocol's backend on the type of interaction to network. For the `createAndPostTransactionWOthent` function, the required input is `'uploadData'`.
* `data: object` : The `data` field is the data to be uploaded on the network. Currently, the function supports data uploads of type `File`. This can be a file of any format.
* `tags : array` (optional) : Tags can be added to any data for ease of indexing and querying. Every tag must be passed in as an object in the tags array. The syntax for adding tags is as follows:

  ```javascript
  tags: [{ 'name': key_name, 'value': some_value},
          { 'name': key_name2, 'value': some_value2}]
  ```
* `useBundlr: boolean` (optional) : Creates and posts the transaction using [bundlr network](https://docs.bundlr.network/docs/client/transactions). Only data type transactions can use this option. If the data size is under 100kB the transaction does not require any fees for processing through Bundlr.

{% hint style="info" %}
The `environment` does not need to be specified for `createAndPostTransactionWOthent` as it only supports `mainnet` interactions, currently.
{% endhint %}

<details>

<summary>Example</summary>

```javascript
const postedTransaction = await createAndPostTransactionWOthent({
  apiId: string,
  othentFunction: 'uploadData', 
  data: image.png, 
  tags: [ {name: 'Test', value: 'Tag'} ]
});
```

This function uploads the input data (image) to the network along with the tags, after verifying the `apiId`.

</details>

### Returned Data

The function call returns the following data:

* `success: boolean` : The `success` status of the data upload request.
* `transactionId: string` : The unique identifier for the upload request. As every upload request is a transaction, it has a corresponding `transactionId` associated with it for future reference.


# Transaction Plugins

Plug in a external package to arweavekit/transaction

The `use` function exposed via the ArweaveKit object from `arweavekit/transaction` package allows you to plugin external packages into arweave kit package.

### Basic Syntax

The function is called as follows:

{% code title="usage.js" %}

```javascript
import * as externalPackage from 'externalPackage';
import { ArweaveKit } from 'arweavekit/transaction';

const arweaveKit = ArweaveKit.use({ name: 'MyPlugIn', plugin: externalPackage });

console.log(arweavekit.functionFromExternalPackage())
```

{% endcode %}

{% hint style="info" %}
The ArweaveKit object imported also contains all functions from the ArweaveKit package for ease of use.
{% endhint %}

### Create a Plugin

Most existing packages in Arweave will already be supported without any additional work, the functions just need to be defined and exported in the external package:

{% code title="externalPackage.js" %}

```javascript
import * as ExternalPackage from 'package'
export function PackagePlugIn() {
    return ExternalPackage
}
```

{% endcode %}


# Introduction to Auth

Introduction to authentication on Arweave

### Authentication on Arweave

To interact with applications, a user must be authenticated and the application in-turn must have permissions from the user to interact with the network on the users behalf.&#x20;

Additionally, every interaction (transaction) on the network has a unique signature. The signature is a hash of the various input parameters as well as the users key that helps authenticate the transaction and point it to a particular user.

### Authentication from a development perspective

Developers need to create user friendly tools and interfaces that verify user wallet connection to applications, use wallet addressed and request permissions from users to perform actions on their behalf.

### Libraries used

The functions associated with authentication leverage the following libraries:

* [ArConnect](https://github.com/arconnectio/ArConnect)
* [Othent](https://docs.othent.io/)

{% hint style="info" %}
Currently the library only supports the ArConnect extension for compatibility reasons. Support for additional browser based wallets will be added in the future.
{% endhint %}

### Auth based functions

In this section, we will look at the following features:

* connecting a web wallet
* disconnecting a web wallet
* getting address of connected web wallet
* getting permissions from user to use connected web wallet
* getting names associated with wallet addresses
* getting all addresses from web wallet extension
* getting a users active public key from web wallet
* checking if web wallet is installed
* connecting to applications using email ids
* disconnecting email ids from applications
* fetching user details of


# Connect

Connecting a web wallet on Arweave

The `connect` function connects an application to a web wallet and gives the application appropriate permissions based on the input parameters.

### Basic Syntax

The function is called as follows:

```javascript
import { ArConnect } from 'arweavekit/auth'

const response = await ArConnect.connect({params});
```

### Input Parameters

The following params are available for this function and they must be passed in as an object:

* `permissions: array` : The permissions array consists of specific permissions that the application requires to perform actions on behalf of the user. Currently there are 8 permissions available. Read more [here](https://github.com/arconnectio/ArConnect#permissions).
* `appInfo: object` (optional) : Additional information about application like `name` and `logo`. This is suitable for custom applications trying to make a connection.
* `gateway: object` (optional) : The gateway configuration to be used while connecting web wallet to application.
  * `host: string` : The Hostname or IP address for a Arweave Host.
  * `port: number` : The port for the gateway.
  * `protocol: 'http' | 'https'` : The network protocol for the gateway.

### Returned Data

The function call returns a `void`. However, the function can be coupled with conditionals to perform user authentication and display gated information.


# Disconnect

Disconnecting a web wallet on Arweave

The `disconnect` function disconnects a wallet from an applications and rescinds any provided permissions from the application.

### Basic Syntax

The function is called as follows:

```javascript
import { ArConnect } from 'arweavekit/auth'

const response = await ArConnect.disconnect();
```


# Get Active Address

Getting address of active web wallet on Arweave

The `getActiveAddress` function fetches the address of the active web wallet.

{% hint style="info" %}
The `ACCESS_ADDRESS` permission must be granted either while calling `connect()` or `getPermissions()` in order to successfully use this function. Read more about permissions [here](https://github.com/arconnectio/ArConnect#permissions).&#x20;
{% endhint %}

### Basic Syntax

The function is called as follows:

```javascript
import { ArConnect } from 'arweavekit/auth'

const address = await ArConnect.getActiveAddress();
```

### Returned Data

The function call returns the following data:

```bash
'WALLET_ADDRESS'
```

* `address: string` : The wallet address of the active web wallet.


# Get Permissions

Getting permissions from web wallet on Arweave

The `getPermissions` function requests the active web wallet for permissions on behalf of the application.

### Basic Syntax

The function is called as follows:

```javascript
import { ArConnect } from 'arweavekit/auth'

const response = await ArConnect.getPermissions();
```

### Returned Data

The function call returns the following data:

```bash
[
    'PERMISSION_1',
    'PERMISSION_2'
]
```

* `permissions: array`: A list of all the permissions provided to the application. Read more about the available permissions [here](https://github.com/arconnectio/ArConnect#permissions).


# Get Wallet Names

Get wallet names of web wallets on Arweave

The `getWalletNames` function fetches the wallet names of the web wallets in the browser extension.

{% hint style="info" %}
The ACCESS\_ALL\_ADDRESSES permission must be granted either while calling `connect()` or `getPermissions()` in order to successfully use this function. Read more about permissions [here](https://github.com/arconnectio/ArConnect#permissions).&#x20;
{% endhint %}

### Basic Syntax

The function is called as follows:

```javascript
import { ArConnect } from 'arweavekit/auth'

const response = await ArConnect.getWalletNames();
```

### Returned Data

The function call returns the following data:

```bash
{
    'WALLET_ADDRESS_1': 'WALLET_NAME_1',
    'WALLET_ADDRESS_2': 'WALLET_NAME_2'
}
```

* `walletNames: object`: An object consisting of key-value pairs of the wallet addresses and associated wallet names.


# Get All Addresses

Get addresses of web wallets on Arweave

The `getAllAddresses` function fetches the wallet addresses of the web wallets in the browser extension.

{% hint style="info" %}
The ACCESS\_ALL\_ADDRESSES permission must be granted either while calling `connect()` or `getPermissions()` in order to successfully use this function. Read more about permissions [here](https://github.com/arconnectio/ArConnect#permissions).&#x20;
{% endhint %}

### Basic Syntax

The function is called as follows:

```javascript
import { ArConnect } from 'arweavekit/auth'

const response = await ArConnect.getAllAddresses();
```

### Returned Data

The function call returns the following data:

```bash
[
    'WALLET_ADDRESS_1',
    'WALLET_ADDRESS_2'
]
```

* `walletAddresses: array`: A list of all the added wallet addresses.


# Get Active Public Key

Get public key of active web wallet on Arweave

The `getActivePublicKey` function fetches the public key of the active web wallet.

{% hint style="info" %}
The ACCESS\_PUBLIC\_KEY permission must be granted either while calling `connect()` or `getPermissions()` in order to successfully use this function. Read more about permissions [here](https://github.com/arconnectio/ArConnect#permissions).&#x20;
{% endhint %}

### Basic Syntax

The function is called as follows:

```javascript
import { ArConnect } from 'arweavekit/auth'

const response = await ArConnect.getActivePublicKey();
```

### Returned Data

The function call returns the following data:

```bash
[
    'ACTIVE_PUBLIC_KEY'
]
```

* `activePublicKey: array`: The key of the active web wallet.


# Is Installed

Checks for injected web wallet

The `isInstalled` function checks if the ArConnect global object (extension) is injected into the application. Else it points to the installation page for the same.

### Basic Syntax

The function is called as follows:

```javascript
import { ArConnect } from 'arweavekit/auth'

const response = await ArConnect.isInstalled();
```


# Log In with Othent

Log In with web2 accounts on Arweave

[Othent](https://docs.othent.io/developers/sdk) is library facilitating the onboarding of users from web2 to web3 by through authentication. The authentication protocol offers a number of "wallet-less" functions for the same.

The `logIn` function lets users log in to applications built on Arweave using web2 technologies like email addresses. This helps eliminate the need for or knowledge of web3 technologies like wallets and tokens and opens up avenues for building widely inclusive applications.

{% hint style="info" %}
Ensure you have pop-ups enabled in your browser for the URL you'll be using this function in.
{% endhint %}

### Basic Syntax

The function is called as follows:

```javascript
import { Othent } from 'arweavekit/auth'

const result = await Othent.logIn({params});
```

### Input Parameters

* `apiId: string` : Use of any Othent function requires an `apiId` which can be fetched from [othent.io](https://othent.io/). Towards the bottom of the linked page, the `Get your API ID` button provides the same.

<details>

<summary>Example</summary>

```javascript
const result = await Othent.logIn({
    apiId: string
});
```

This function enables a user to log In to an Arweave application using web2 technologies like email addresses after verifying the `apiId`. Upon successful login, the function call returns the connected user's details fetched from their email address.

</details>

### Returned Data

The function call returns the following data:

```bash
{
    contract_id: string,
    given_name: string,
    family_name: string,
    nickname: string,
    name: string,
    picture: string,
    locale: string,
    email: string,
    email_verified: string,
    sub: string,
    success?: string,
    message?: string
}
```

* `contract_id: string` : The `contract_id` is the wallet address associated with a user's email account, provided to the user at the time of registration with Othent.
* `given_name: string` : The `given_name` is the connected user's first name associated with the email account.
* `family_name: string` : The `family_name` is the connected user's last name associated with the email account.
* `nickname: string` : The `nickname` is the connected user's initials associated with the email account.
* `name: string` : The `name` is the connected user's given\_name and family\_name joined together.
* `picture: string` : The `picture` is the connected user's profile picture associated with the email account.
* `locale: string` : The `locale` is the connected user's preferred language associated with the email account.
* `email: string` : The `email` is the connected user's email address.
* `email_verified: string` : The `email_verified` holds information the confirmation status of the email.
* `sub: string` : The `sub` is a unique id for Othent's reference.
* `success: string` (optional) : The `success` status of function call.
* `message: string` (optional) : Any `message` to be returned with function call.


# Log Out with Othent

Log out of Arweave applications using Othent

The `logOut` function lets users log out of applications built on Arweave using web2 technologies like email addresses.

{% hint style="info" %}
Ensure you have pop-ups enabled in your browser for the URL you'll be using this function in.
{% endhint %}

### Basic Syntax

The function is called as follows:

```javascript
import { Othent } from 'arweavekit/auth'

const result = await Othent.logOut({params});
```

### Input Parameters

* `apiId: string` : Use of any Othent function requires an `apiId` which can be fetched from [othent.io](https://othent.io/). Towards the bottom of the linked page, the `Get your API ID` button provides the same.

<details>

<summary>Example</summary>

```javascript
const result = await Othent.logOut({
    apiId: string
});
```

This function logs out users from the connected application.

</details>

### Returned Data

The function call returns the following data:

```bash
{
    response: string
}
```

* `response: string` : The `response` returned on function call.


# Get User Details with Othent

Getting details of user logged in using Othent

The `userDetails` function returns details of the logged in user associated with their user account.

{% hint style="info" %}
Ensure you have pop-ups enabled in your browser for the URL you'll be using this function in.
{% endhint %}

### Basic Syntax

The function is called as follows:

```javascript
import { Othent } from 'arweavekit/auth'

const result = await Othent.userDetails({params});
```

### Input Parameters

* `apiId: string` : Use of any Othent function requires an `apiId` which can be fetched from [othent.io](https://othent.io/). Towards the bottom of the linked page, the `Get your API ID` button provides the same.

<details>

<summary>Example</summary>

```javascript
const result = await Othent.userDetails({
    apiId: string
});
```

This function get the details of the connected user associated with their connected account.

</details>

### Returned Data

The function call returns the following data:

```bash
{
    contract_id: string,
    given_name: string,
    family_name: string,
    nickname: string,
    name: string,
    picture: string,
    locale: string,
    email: string,
    email_verified: string,
    sub: string,
    success?: string,
    message?: string
}
```

* `contract_id: string` : The `contract_id` is the wallet address associated with a user's email account, provided to the user at the time of registration with Othent.
* `given_name: string` : The `given_name` is the connected user's first name associated with the email account.
* `family_name: string` : The `family_name` is the connected user's last name associated with the email account.
* `nickname: string` : The `nickname` is the connected user's initials associated with the email account.
* `name: string` : The `name` is the connected user's given\_name and family\_name joined together.
* `picture: string` : The `picture` is the connected user's profile picture associated with the email account.
* `locale: string` : The `locale` is the connected user's preferred language associated with the email account.
* `email: string` : The `email` is the connected user's email address.
* `email_verified: string` : The `email_verified` holds information the confirmation status of the email.
* `sub: string` : The `sub` is a unique id for Othent's reference.
* `success: string` (optional) : The `success` status of function call.
* `message: string` (optional) : Any `message` to be returned with function call.


# Auth Plugins

Plug in a external package to arweavekit/auth

The `use` function exposed via the ArweaveKit object from `arweavekit/auth` package allows you to plugin external packages into arweave kit package.

### Basic Syntax

The function is called as follows:

{% code title="usage.js" %}

```javascript
import * as externalPackage from 'externalPackage';
import { ArweaveKit } from 'arweavekit/auth';

const arweaveKit = ArweaveKit.use({ name: 'MyPlugIn', plugin: externalPackage });

console.log(arweavekit.functionFromExternalPackage())
```

{% endcode %}

{% hint style="info" %}
The ArweaveKit object imported also contains all functions from the ArweaveKit package for ease of use.
{% endhint %}

### Create a Plugin

Most existing packages in Arweave will already be supported without any additional work, the functions just need to be defined and exported in the external package:

{% code title="externalPackage.js" %}

```javascript
import * as ExternalPackage from 'package'
export function PackagePlugIn() {
    return ExternalPackage
}
```

{% endcode %}


# Introduction to Encryption

Introduction to encryption and decryption on Arweave

### Need for encryption

Arweave has brought forth the ability to "permanently" store data at a low cost leveraging the benefits of decentralization.

Arising from the benefits of immutability and openness, however, is a need to ensure adequate data protection for sensitive and private information.

With the help of encryption and decryption features, users can seek the benefits of permanent data storage and rest assured that their data is confidential and secure.

### How does encryption work?

On a high level, data that must be secured, is locked cryptographically and the key for unlocking it is only provided to the user that encrypts this information. This ensures that only the user encrypting the data can securely decrypt and access it again.

### Encryption from a development perspective

Developers can create user interfaces for users to securely encrypt and decrypt their data easily.&#x20;

{% hint style="danger" %}
It is important that developers handle the process with end-to-end encryption, where in no one (including the developers), except the end user has access to the keys.
{% endhint %}

### Tools used

The functions associated with smart contracts leverage the following tools:

* [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API)
* [Arweave Wallet (Window Object)](https://docs.arconnect.io/api/intro)

### Encryption based functions

In this section, we will look at the following features:

* encrypt data with AES
* decrypt data with AES
* encrypt AES key with RSA
* decrypt AES key with RSA


# Encrypt Data with AES

Encrypt Data with the Advanced Encryption Standard (AES)

The `encryptDataWithAES` performs symmetric encryption using the [Advanced Encryption Standard (AES)](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt#aes-gcm), specifically the Galois/ Counter Mode (GCM). Symmetric encryption is optimal for data encryption and performs the encryption and decryption of data with a single key.

A new `AES` key is generated each time the function is called. The data is encrypted using this key and a randomly generated initialized vector (`iv`).

The `iv` is required for decryption as well, hence it is returned prepended to the encrypted data as a combined `Array Buffer`. The encryption key is returned as well, as part of the return object. The key is generated as a `CryptoKey object` however it is converted to a `base64` encoded `string` before being returned.

### Basic Syntax

The function is called as follows:

```javascript
import { encryptDataWithAES } from 'arweavekit/encryption';

const encryptedDataObject = await encryptDataWithAES({params});
```

### Input Parameters

The following params are available for this function and they must be passed in as an object:

* `data: ArrayBuffer` : The data to be encrypted passed in as an `ArrayBuffer`. The `ArrayBuffer` is optimal for data encryption using `AES-GCM` and is one of the preferred types for uploading data on Arweave.

<details>

<summary>Example</summary>

```javascript
const encryptedDataObject = await encryptDataWithAES({
    data: ArrayBuffer,
});
```

This encrypts the provided `ArrayBuffer` using the `AES-GCM` encryption method.

</details>

### Returned Data

The function call returns the following data:

```bash
{
    rawEncryptedKeyAsBase64: Base64 string,
    combinedArrayBuffer: ArrayBuffer,
}
```

* `rawEncryptedKeyAsBase64: string` : The encryption key generated at the time of data encryption using `AES-GCM` and encoded using `Base64` format.
* `combinedArrayBuffer: ArrayBuffer` : The combination of the random initialized vector prepended to the encrypted data as an `ArrayBuffer`.


# Decrypt Data with AES

Decrypt Data with the Advanced Encryption Standard (AES)

The `decryptDataWithAES` performs symmetric encryption using the [Advanced Encryption Standard (AES)](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt#aes-gcm), specifically the Galois/ Counter Mode (GCM).

The `AES` key and the random initialized vector (`iv`) used at the time of encryption are needed to decrypt the data.

The `iv` is part of the `combinedArrayBuffer` returned as the encrypted data from the `encryptDataWithAES` function. The `decryptDataWithAES` functions splits this into the `iv` and actual `encryptedData` on the backend before decrypting the latter.

### Basic Syntax

The function is called as follows:

```javascript
import { decryptDataWithAES } from 'arweavekit/encryption';

const decryptedDataObject = await decryptDataWithAES({params});
```

### Input Parameters

The following params are available for this function and they must be passed in as an object:

* `data: ArrayBuffer` : The combination of the random initialized vector prepended to the encrypted data as an `ArrayBuffer` generated at the time of encryption.
* `key: string` : The encryption key generated at the time of data encryption using `AES-GCM` and used for encrypting the data.

<details>

<summary>Example</summary>

```javascript
const decryptedDataObject = await decryptDataWithAES({
    data: ArrayBuffer,
    key: string,
});
```

This encrypts the provided `ArrayBuffer` using the `AES-GCM` encryption method.

</details>

### Returned Data

The function call returns the following data:

```bash
decryptedData: ArrayBuffer
```

* `decryptedData: ArrayBuffer` : The decrypted data returned as an `ArrayBuffer`.


# Encrypt AES Key with RSA

Encrypt an AES Key with an RSA Public Key

The `encryptAESKeyWithRSA` performs asymmetric encryption using an `RSA Public Key` and the `RSA-OAEP` algorithm. The permissions are requested with the help of the `Arweave Wallet (Window Object)` in a browser environment if no wallet or `use_wallet` is passed. The node environment expects Arweave JWK to be passed.

{% hint style="info" %}
Installation of [`ArConnect`](https://www.arconnect.io/) is suggested for successful use of this function in a browser environment.
{% endhint %}

Asymmetric encryption is optimal for the encryption of strings (such as the `AES` key received in the previous function).

### Basic Syntax

The function is called as follows:

```javascript
import { encryptAESKeyWithRSA } from 'arweavekit/encryption';

const encryptedAESKey = await encryptAESKeyWithRSA({params});
```

### Input Parameters

The following params are available for this function and they must be passed in as an object:

* `key: string` : The `AES` key used to encrypt data using the `encryptDataWithAES` function.
* `wallet: ArWallet`(optional): A value of type `JWKInterface` or `use_wallet` can be passed. If `use_wallet` or nothing is passed to this param, it expects `ArConnect` to be installed to run the encryption successfully.

<details>

<summary>Example</summary>

<pre class="language-javascript"><code class="lang-javascript"><strong>// In a browser environment, use_wallet or nothing can be passed.
</strong><strong>const wallet = "use_wallet"
</strong>// In a node environment, Arweave wallet JWK can be used.
const wallet = JSON.parse(fs.readFileSync('wallet.json').toString());

const encryptedAESKey = await encryptAESKeyWithRSA({
    key: string,
    wallet
});
</code></pre>

This encrypts the provided `AES Key` using the `RSA-OAEP` algorithm.

</details>

### Returned Data

The function call returns the following data:

```bash
{
    encryptedKey: Uint8Array,
}
```

* `encryptedKey: Uint8Array` : The `AES` key encrypted using an `RSA Public Key`.


# Decrypt AES Key with RSA

Decrypt an AES Key with an RSA Private Key

The `decryptAESKeyWithRSA` performs asymmetric decryption using an `RSA Private Key` and the `RSA-OAEP` algorithm. The permissions are requested with the help of the `Arweave Wallet (Window Object)` in a browser environment if no wallet or `use_wallet` is passed. The node environment expects Arweave JWK to be passed.

{% hint style="info" %}
Installation of [`ArConnect`](https://www.arconnect.io/) is suggested for successful use of this function in a browser environment.
{% endhint %}

### Basic Syntax

The function is called as follows:

```javascript
import { decryptAESKeyWithRSA } from 'arweavekit/encryption';

const decryptedAESKey = await decryptAESKeyWithRSA({params});
```

### Input Parameters

The following params are available for this function and they must be passed in as an object:

* `key: Uint8Array` : Th`e encrypted AES key received from the encryptAESKeyWithRSA function.`
* `wallet: ArWallet`(optional): A value of type `JWKInterface` or `use_wallet` can be passed. If `use_wallet` or nothing is passed to this param, it expects `ArConnect` to be installed to run the decryption successfully.

<details>

<summary>Example</summary>

```javascript
// In a browser environment, use_wallet or nothing can be passed.
const wallet = "use_wallet"
// In a node environment, Arweave wallet JWK can be passed.
const wallet = JSON.parse(fs.readFileSync('wallet.json').toString());

const decryptedAESKey = await decryptAESKeyWithRSA({
    key: Uint8Array,
});
```

This decrypts the provided `AES Key` using the `RSA-OAEP` algorithm.

</details>

### Returned Data

The function call returns the following data:

```bash
{
    decryptedKey: string,
}
```

* `decryptedKey: string` : The `AES` key decrypted using an `RSA Public Key` returned as a `Base64 string`.


# Encryption Plugins

Plug in a external package to arweavekit/encryption

The `use` function exposed via the ArweaveKit object from `arweavekit/encryption` package allows you to plugin external packages into arweave kit package.

### Basic Syntax

The function is called as follows:

{% code title="usage.js" %}

```javascript
import * as externalPackage from 'externalPackage';
import { ArweaveKit } from 'arweavekit/encryption';

const arweaveKit = ArweaveKit.use({ name: 'MyPlugIn', plugin: externalPackage });

console.log(arweavekit.functionFromExternalPackage())
```

{% endcode %}

{% hint style="info" %}
The ArweaveKit object imported also contains all functions from the ArweaveKit package for ease of use.
{% endhint %}

### Create a Plugin

Most existing packages in Arweave will already be supported without any additional work, the functions just need to be defined and exported in the external package:

{% code title="externalPackage.js" %}

```javascript
import * as ExternalPackage from 'package'
export function PackagePlugIn() {
    return ExternalPackage
}
```

{% endcode %}


# Introduction to GraphQL

Introduction to querying transaction data on Arweave using GraphQL

### Querying transaction data on Arweave

As a user or developer interacting with the Arweave blockchain, there are several compelling reasons why you may need access to transaction data. For example if you're working on analytics, dApps, user interaction monitoring, verifying a transaction, smart contract interaction and the list goes on. Now accessing on-chain transactions data using REST APIs is a straight forward way to go but with GraphQL and its precise data retrieval, reduced overfetching and underfetching, batching capabilities, and real-time updates, GraphQL offers a more efficient and flexible way to interact with the Arweave blockchain. \
\
By embracing this powerful querying technology, developers can build performant and user-friendly applications, while keeping their codebase future-proof and adaptable to the evolving blockchain landscape.

In this section, we will look at the following features:

* Querying GraphQL endpoint for any Arweave supported blockchain data
* Querying for transactions with GraphQL and cursor based pagination
* Querying for all transactions with GraphQL iteratively


# Query All Arweave Transactions

Query GraphQL for all Arweave Transactions data iteratively

You can query for all transactions on GraphQL endpoint using the method thats described here.&#x20;

### Basic Syntax

The function that we will be using is `queryAllTransactionsGQL`. For implementation details, see below.

```typescript
import { queryAllTransactionsGQL } from 'arweavekit/graphql';

const response = await queryAllTransactionsGQL(queryString, options);
```

### Input Parameters

You must supply `queryAllTransactionsGQL` with two inputs.

* `QueryString:`` `<mark style="color:red;">`string`</mark> - A valid GraphQL query string with the `first` filter.
* `Options:`` `<mark style="color:red;">`object`</mark> - An options object.
  * `gateway:`` `<mark style="color:red;">`string`</mark> - Gateway url like `arweave.net`
  * `filters:`` `<mark style="color:red;">`object`</mark> - Filters object like `first: 100`.

### Returned Data

The expected response will be a list of `GraphQLEdge`&#x20;


# Query Arweave Data

Query GraphQL for Arweave Blocks and Transactions data

You can query for everything that Arweave GraphQL endpoint supports. For instance, single transaction, more than one transaction, single block, more than one block.

### Basic Syntax

The function that we will be using is `queryGQL`. For implementation details, see below.

```typescript
import { queryGQL } from 'arweavekit/graphql';

const response = await queryGQL(queryString, options);
```

### Input Parameters

You must supply `queryGQL` with two inputs.

* `QueryString:`` `<mark style="color:red;">`string`</mark> - A valid GraphQL query string.
* `Options:`` `<mark style="color:red;">`object`</mark> - An options object.
  * `gateway:`` `<mark style="color:red;">`string`</mark> - Gateway url like `arweave.net`
  * `filters:`` `<mark style="color:red;">`object`</mark> - Filters object like `first: 100` . In case of no filters, pass an empty object.

### Returned Data

The expected response will be an object with following fields.

* `status:`` `<mark style="color:green;">`number`</mark> - Query HTTP status code. Example, 200.
* `data:`` `<mark style="color:green;">`object | null`</mark> - Successful response will return GraphQL node or list of GraphQL edges and in case of failure null will be returned here.
* `errors:`` `<mark style="color:green;">`GraphQLError[] | null`</mark> - Incase of failure you can expect this field to be non-nullish and a list of GraphQLError is provided.&#x20;
  * `GraphQLError:`` `<mark style="color:green;">`object`</mark> - GraphQL error object contains following fields:
    * `message:`` `<mark style="color:green;">`string`</mark> - Error message in string format
    * `extensions:`` `<mark style="color:green;">`object`</mark> - This object has a field `code` and its supposed to provide you with error code.


# Query Arweave Transactions

Query GraphQL for Arweave Transactions data with pagination support

You can query for transactions data with support for cursor based pagination on GraphQL endpoint. It is expected from consumer of this method to write the logic for storing the cursor returned and looping until the last page.

### Basic Syntax

The function that we will be using is `queryTransactionsGQL`. For implementation details, see below.

```typescript
import { queryTransactionsGQL } from 'arweavekit/graphql';

const response = await queryTransactionsGQL(queryString, options);
```

### Input Parameters

You must supply `queryTransactionsGQL` with two inputs.

* `QueryString:`` `<mark style="color:red;">`string`</mark> - A valid GraphQL query string with `cursor` and `first` filter.
* `Options:`` `<mark style="color:red;">`object`</mark> - An options object.
  * `gateway:`` `<mark style="color:red;">`string`</mark> - Gateway url like `arweave.net`
  * `filters:`` `<mark style="color:red;">`object`</mark> - Filters object like `first: 100` . In case of no filters, pass an empty object. `cursor` filter is not optional. A persisted `cursor` filter must be supplied in the filters.

### Returned Data

The expected response will be an object with following fields.

* `status:`` `<mark style="color:green;">`number`</mark> - Query HTTP status code. Example, 200.
* `data:`` `<mark style="color:green;">`GraphQLEdge[]`</mark> - Successful response will return a list of GraphQL edges and in case of failure empty list will be returned here.
* `cursor:`` `<mark style="color:green;">`string`</mark>  - cursor id of last GraphQLEdge.
* `hasNextPage:`` `<mark style="color:green;">`boolean`</mark> - if the next page exist this will be true.
* `errors:`` `<mark style="color:green;">`GraphQLError[] | null`</mark> - Incase of failure you can expect this field to be non-nullish and a list of GraphQLError is provided.&#x20;
  * `GraphQLError:`` `<mark style="color:green;">`object`</mark> - GraphQL error object contains following fields:
    * `message:`` `<mark style="color:green;">`string`</mark> - Error message in string format
    * `extensions:`` `<mark style="color:green;">`object`</mark> - This object has a field `code` and its supposed to provide you with error code.


# GraphQL Plugins

Plug in a external package to arweavekit/graphql

The `use` function exposed via the ArweaveKit object from `arweavekit/graphql` package allows you to plugin external packages into arweave kit package.

### Basic Syntax

The function is called as follows:

{% code title="usage.js" %}

```javascript
import * as externalPackage from 'externalPackage';
import { ArweaveKit } from 'arweavekit/graphql';

const arweaveKit = ArweaveKit.use({ name: 'MyPlugIn', plugin: externalPackage });

console.log(arweavekit.functionFromExternalPackage())
```

{% endcode %}

{% hint style="info" %}
The ArweaveKit object imported also contains all functions from the ArweaveKit package for ease of use.
{% endhint %}

### Create a Plugin

Most existing packages in Arweave will already be supported without any additional work, the functions just need to be defined and exported in the external package:

{% code title="externalPackage.js" %}

```javascript
import * as ExternalPackage from 'package'
export function PackagePlugIn() {
    return ExternalPackage
}
```

{% endcode %}


# ArweaveKit in Browser Environments

Sample configurations needed for using ArweaveKit in Browser Environments

In today's web development landscape, module bundlers and frameworks play a pivotal role in optimizing and deploying code for browser environments. Despite their numerous advantages, it's important to note that these bundlers often require separate polyfill configurations to ensure support for Node's [Core Modules](https://nodejs.org/dist/latest-v16.x/docs/api/modules.html#core-modules) across different browsers.

### NextJS

NextJS is compatible with ArweaveKit out of the box and does not require separate polyfills for the modules.

### NuxtJS

Nuxt 3 requires the implementation of polyfills in order to use the core modules in browser environments. Since Nuxt ships with Vite by default, we can use the Vite plugin for the same.

#### Setup

Here's a sample setup to successfully polyfill required modules and use the functionality from arweavekit in a Nuxt app.

The first step is installing the dependency:

```bash
npm install --save-dev vite-plugin-node-polyfills
# or
yarn add --dev vite-plugin-node-polyfills
```

Then this polyfill plugin must be added to the `nuxt.config.ts` file and the nuxt config should look similar to the config below:

{% code title="nuxt.config.ts" %}

```javascript
import { nodePolyfills } from "vite-plugin-node-polyfills";

export default defineNuxtConfig({
  // other configs
  vite: {
    plugins: [
      nodePolyfills({
        include: ["buffer", "crypto", "stream", "util", "vm"],
        globals: {
          process: false,
        },
      }),
    ],
    resolve: {
      alias: [
        {
          find: "ethers",
          replacement:
            "https://cdnjs.cloudflare.com/ajax/libs/ethers/6.7.0/ethers.min.js",
        },
      ],
    },
  },
});

```

{% endcode %}

{% hint style="warning" %}
This is a sample config. For more advanced options visit [here](https://github.com/davidmyersdev/vite-plugin-node-polyfills).
{% endhint %}

Now, add arweavekit plugin named `arweavekit.client.ts` to the `plugins` directory in the root directory of the nuxt project. And, import and return the essential functions from arweavekit in this plugin.

{% code title="arweavekit.client.ts" %}

```typescript
import {
  createTransaction,
  signTransaction,
  postTransaction,
  queryAllTransactionsGQL,
  createContract,
  writeContract,
} from "arweavekit";

export default defineNuxtPlugin(() => {
  return {
    provide: {
      createTransaction,
      signTransaction,
      postTransaction,
      queryAllTransactionsGQL,
      createContract,
      writeContract,
    },
  };
});

```

{% endcode %}

Now, you can use the functions from this plugin in your vue files as below.

{% code title="app.vue" %}

```tsx
<script setup lang="ts">
const {
  $createTransaction: createTransaction,
  $signTransaction: signTransaction,
  $postTransaction: postTransaction,
  $queryAllTransactionsGQL: queryAllTransactionsGQL,
  $createContract: createContract,
  $writeContract: writeContract,
} = useNuxtApp();

// An example function to write to a contract in testnet
async function writeContractTestNet() {
  const response = await writeContract({
    environment: "testnet",
    contractTxId: "CO7NkmEVj4wEwPySxYUY0_ElrEqU4IeTglU2IilCnLA",
    options: {
      function: "increment",
    },
  });
  console.log(response);
}
</script>

<template>
  <div class="container mx-auto flex justify-center h-screen pt-12">
    <div class="flex flex-col gap-4 w-1/2">
      <button class="border-4" @click="writeContractTestNet">
        Write Contract Testnet
      </button>
    </div>
  </div>
</template>
```

{% endcode %}

### Vite

In an attempt to prevent runtime errors, Vite produces [errors](https://github.com/vitejs/vite/issues/9200) or [warnings](https://github.com/vitejs/vite/pull/9837) when your code references built-in modules such as `fs` or `path`. These must be polyfilled separately to utilize the core modules in browser environments.

#### Setup

Here's a sample setup to successfully polyfill required modules in a Vite app.

The first step is installing the dependency:

```bash
npm install --save-dev vite-plugin-node-polyfills
# or
yarn add --dev vite-plugin-node-polyfills
```

Then the plugin must be added to the `vite.config.js` file:

```javascript
import { defineConfig } from 'vite'
import { nodePolyfills } from 'vite-plugin-node-polyfills'

// https://vitejs.dev/config/
export default defineConfig({
  // other configs
  plugins: [
    // other plugins
    nodePolyfills({
        include: ["buffer", "crypto", "stream", "util", "http"],
    }),
  ],
})
```

{% hint style="warning" %}
This is a sample config. For more advanced options visit [here](https://github.com/davidmyersdev/vite-plugin-node-polyfills).
{% endhint %}

{% hint style="info" %}
This config is compatible with all Vite-supported frameworks. Read more about the supported frameworks [here](https://vitejs.dev/guide/).
{% endhint %}

### Webpack

Webpack versions < 5 used to include polyfills by default, however, this must be implemented separately for Webpack versions > 5 in order to use the core modules in browser environments.

#### Setup

Here's a sample setup to successfully polyfill required modules in an app using Webpack as a bundler.

The first step is installing the dependency:

```bash
npm install --save-dev @craco/craco node-polyfill-webpack-plugin
# or
yarn add --dev @craco/craco node-polyfill-webpack-plugin
```

Then the setups must be added to a `craco.config.js` file:

```javascript
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");

module.exports = {
  webpack: {
    // Using craco to import files from outside the src/ directory
    configure: (webpackConfig) => {
      const scopePluginIndex = webpackConfig.resolve.plugins.findIndex(
        ({ constructor }) =>
          constructor && constructor.name === "ModuleScopePlugin"
      );

      webpackConfig.resolve.plugins.splice(scopePluginIndex, 1);
      return webpackConfig;
    },
    plugins: {
      add: [
        new NodePolyfillPlugin({
          includeAliases: ["buffer", "Buffer", "crypto", "stream"],
        }),
      ],
    },
  },
};
```

And finally, replace the default scripts in `package.json` as follows:

```json
"scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject"
}
```

{% hint style="warning" %}
This is a sample config. For more advanced options visit [here](https://www.npmjs.com/package/node-polyfill-webpack-plugin).
{% endhint %}

{% hint style="info" %}
This config is compatible with React applications. Learn more about React applications [here](https://create-react-app.dev/).
{% endhint %}


# Arweave StarterKit

Fast track your journey to building decentralized applications on Arweave with the Arweave StarterKit. A CLI tool that effortlessly sets up an entire application, harnessing the power of [NextJS](https://nextjs.org/) as the framework, [Shadcn UI](https://ui.shadcn.com/) for a sleek and aesthetic interface, and [ArweaveKit](https://arweavekit.com/?utm_source=Github\&utm_medium=StarterKit+Repo\&utm_campaign=Create-Arweave-App+StarterKit+Docs\&utm_id=Create-Arweave-App+StarterKit+Docs) to seamlessly interact with the Arweave ecosystem.

## Usage

### Interactive

To scaffold an Arweave app interactively, run the following command based on your package manager of choice:

### npm

```bash
npx create-arweave-app@latest
# or
npm create arweave-app@latest
```

### yarn

```bash
yarn create arweave-app
```

### pnpm

```bash
pnpm create arweave-app@latest
```

### bun

```bash
bunx create-arweave-app@latest
# or
bun create arweave-app@latest
```

During the interactive setup, you'll be prompted for your project's name and other configuration options. Provide your choices to create a new Arweave application.

> **Note:** For windows users using a secure shell, ensure your ssh-agent is running as expected for successfull installation of dependencies.

### Non-interactive

For a non-interactive setup, use command line arguments. You can view available options with:

```bash
create-arweave-app --help
```

```bash
Usage: create-arweave-app [dir] [options]

A CLI for creating full-stack Arweave web applications

Arguments:
  dir                         The name of the application, as well as the name of the directory to create

Options:
  --noGit                     Explicitely tell the CLI to not initialize a new git repo in the project (default: false)
  --noInstall                 Explicitely tell the CLI to not run the package manager's install command (default: false)
  -y, --default               Bypass the CLI and Use default options to bootstrap a new Arweave app. Note: Default options can be overridden by user-provided options. (default: false)
  -l, --language <type>       Initialize project as a Typescript or JavaScript project (choices: "typescript", "javascript", "ts", "js", default: "typescript")
  -i, --import-alias <alias>  Explicitly tell the CLI to use a custom import alias (default: "@/")
  --appRouter [boolean]       Explicitly tell the CLI to use the new Next.js app router (default: true)
  -v, --version               Display the version number
  -h, --help                  display help for command
```

You can quickly scaffold an Arweave app using the starter kit with the default options by running:

```bash
npx create-arweave-app@latest -y
# or
yarn create arweave-app -y
# or
pnpm create arweave-app@latest -y
# or
bunx create-arweave-app@latest -y
```

You can also quickly scaffold by overriding the default options by passing the other options as well:

```bash
npx create-arweave-app@latest my-arweave-app --noGit --default
# or
yarn create arweave-app my-arweave-app --noGit --default
# or
pnpm create arweave-app@latest my-arweave-app --noGit --default
# or
bunx create-arweave-app@latest my-arweave-app --noGit --default
```

## Getting Started

After creating a new project and installing the dependencies, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

## Preview

Open <http://localhost:3000> in your browser to see the result.

**Landing Page:** A form that allows users to upload Atomic assets on Arweave, complete with various metadata configurations.

![Landing Page Form Preview](/files/FtdX9R5LaUARMEaxmLzX)

**View Page:** A dedicated space to view the uploaded assets and engage with them through on-chain likes (known as stamps) and comments.

![View Page Preview](/files/IlfMWUikd2tIc3lwv0zL)

Start editing the page by modifying `app/page.tsx` or `pages/index.ts`, as per your NextJS config.

## Why use a StarterKit?

Building DApps from scratch can be a daunting task. From setting up the environment to ensuring compatibility across different components, the process can be time-consuming. A starter kit provides a pre-configured foundation, enabling developers to focus on building unique features and functionalities rather than the underlying setup.

## What are the key components of the StarterKit?

* **Navbar:** A built-in navigation bar that integrates with [Arweave Wallet Kit](https://docs.arweavekit.com/wallets/wallet-kit?utm_source=Github\&utm_medium=StarterKit+Repo\&utm_campaign=Create-Arweave-App+StarterKit+Docs\&utm_id=Create-Arweave-App+StarterKit+Docs), enabling users to connect to and interact with the DApp effortlessly.
* **Landing Page:** A landing page featuring a form, typesafed with [Zod](https://zod.dev/) schemas. Users can upload images and add metadata, which is then posted to the Arweave network as an [atomic asset](https://cookbook.arweave.dev/concepts/atomic-tokens.html).
* **Atomic Assets and Contracts:** Each asset is paired with an associated contract, enabling alterations to the metadata and transfer of ownership.

  The created project is initialized with a contract which is located at `src/contracts`. You can make necessary modifications to the contract code according to your needs and run the script `deploy-contracts` to automatically update the contract linked functionality to the new one.<br>

  ```bash
  # With wallet.json keyfile present at root
  yarn deploy-contracts
  # With keyfile present at a custom path
  yarn deploy-contracts /Users/arweave/Documents/keys/wallet.json
  ```
* **View Page:** A space to showcase assets and metadata, augmented with features like [Stamps](https://stamps.arweave.dev/#/en/main) (Arweave's version of 'likes') and [on-chain comments](https://specs.ar-io.dev/#/view/SYCrxZYzhP_L_iwmxS7niejyeJ_XhJtN4EArplCPHGQ).

## Leverage Modularity

The true strength of this kit lies in its modularity. Simply interchange the core asset from image to music and transform an image sharing application to a music hub. Or swap in for videos to create a streaming service. As any form of data can be uploaded to the Arweave network, the possibilities are limitless.

## Credits

For a complete list of contributors and credits, please see the [CREDITS](https://github.com/labscommunity/starterkit/blob/main/CREDITS.md) file.

## License

This project is licensed under the [MIT License](https://github.com/labscommunity/starterkit/blob/main/LICENSE).


