> For the complete documentation index, see [llms.txt](https://velora-1.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://velora-1.gitbook.io/docs/guides/integration.md). Agents can also search and read this documentation through its [MCP server](https://velora-1.gitbook.io/docs/~gitbook/mcp).

# Integration Guide

This guide walks an external developer through creating a stream, claiming from it, and cancelling it — using the Anchor TypeScript client. The snippets are adapted from the program's own integration test suite (`backend/tests/backend.ts`), so they reflect exactly how the program is called on-chain.

By the end you will have:

1. Connected to the program.
2. Derived the stream and vault PDAs.
3. Created a linear stream that locks tokens in the vault.
4. Withdrawn the unlocked portion as the recipient.
5. (Optionally) cancelled and settled the stream.

## 1. Install dependencies

```bash
npm install @coral-xyz/anchor @solana/spl-token @solana/web3.js
```

You also need the program's IDL and types. After `anchor build` they are at `target/idl/backend.json` and `target/types/backend.ts`. Copy them into your client project, or import them from the workspace.

## 2. Connect to the program

```ts
import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { Backend } from "./types/backend"; // generated by anchor build
import idl from "./idl/backend.json";

const connection = new anchor.web3.Connection(
  anchor.web3.clusterApiUrl("devnet"),
  "confirmed"
);

// `wallet` is any Anchor-compatible wallet (e.g. NodeWallet or a browser adapter)
const provider = new anchor.AnchorProvider(connection, wallet, {
  commitment: "confirmed",
});
anchor.setProvider(provider);

const program = new Program<Backend>(idl as any, provider);
```

## 3. Derive the PDAs

Both PDAs are deterministic — no index or RPC lookup needed.

```ts
function deriveStream(
  creator: anchor.web3.PublicKey,
  recipient: anchor.web3.PublicKey,
  streamId: anchor.BN
) {
  return anchor.web3.PublicKey.findProgramAddressSync(
    [
      Buffer.from("stream"),
      creator.toBuffer(),
      recipient.toBuffer(),
      streamId.toArrayLike(Buffer, "le", 8),
    ],
    program.programId
  )[0];
}

function deriveVault(streamConfig: anchor.web3.PublicKey) {
  return anchor.web3.PublicKey.findProgramAddressSync(
    [Buffer.from("vault"), streamConfig.toBuffer()],
    program.programId
  )[0];
}
```

## 4. Prepare token accounts

The creator must hold the tokens to lock, and the recipient needs an account to receive them. With a fresh mint for testing:

```ts
import {
  createMint,
  createAccount,
  mintTo,
  TOKEN_PROGRAM_ID,
} from "@solana/spl-token";

const mint = await createMint(connection, payer, payer.publicKey, null, 0);

const creatorTokenAccount = await createAccount(
  connection, payer, mint, creator.publicKey
);
const recipientTokenAccount = await createAccount(
  connection, payer, mint, recipient.publicKey
);

await mintTo(connection, payer, mint, creatorTokenAccount, payer, 1_000);
```

In production the recipient's associated token account is the usual choice (`getAssociatedTokenAddress` + `createAssociatedTokenAccountInstruction`).

## 5. Create the stream

A linear stream over 1000 seconds, locking 1000 base units:

```ts
const streamId = new anchor.BN(1);
const streamConfig = deriveStream(creator.publicKey, recipient.publicKey, streamId);
const vault = deriveVault(streamConfig);

const now = Math.floor(Date.now() / 1000);

await program.methods
  .createStream({
    streamId,
    totalAmount: new anchor.BN(1_000),
    startTimestamp: new anchor.BN(now),
    endTimestamp: new anchor.BN(now + 1_000),
    cliffTimestamp: new anchor.BN(0),
    cliffAmount: new anchor.BN(0),
    scheduleType: { linear: {} },
    authorityType: { none: {} },
    releaseAuthority: null,
    milestoneDescription: Array(128).fill(0),
    isCancellable: true,
    cancelAuthority: { creatorOnly: {} },
  })
  .accounts({
    creator: creator.publicKey,
    recipient: recipient.publicKey,
    mint,
    streamConfig,
    vault,
    creatorTokenAccount,
    tokenProgram: TOKEN_PROGRAM_ID,
    systemProgram: anchor.web3.SystemProgram.programId,
    rent: anchor.web3.SYSVAR_RENT_PUBKEY,
  })
  .signers([creator])
  .rpc();
```

After this, the vault holds 1000 tokens and the creator's account holds 0.

## 6. Withdraw as the recipient

The recipient claims whatever has unlocked. For a linear stream, wait until some time has passed, then:

```ts
await program.methods
  .withdraw()
  .accounts({
    recipient: recipient.publicKey,
    streamConfig,
    vault,
    recipientTokenAccount,
    tokenProgram: TOKEN_PROGRAM_ID,
  })
  .signers([recipient])
  .rpc();

const state = await program.account.streamConfig.fetch(streamConfig);
console.log("claimed so far:", state.amountClaimed.toString());
```

Calling `withdraw` again before more tokens unlock fails with `NothingToWithdraw` — that is expected, not an error in your code.

## 7. Cancel (optional)

If the stream was created with `isCancellable: true`, the cancel authority can settle it early. Vested-but-unclaimed tokens go to the recipient; the locked remainder is refunded to the creator.

```ts
await program.methods
  .cancel()
  .accounts({
    authority: creator.publicKey,
    streamConfig,
    vault,
    recipientTokenAccount,
    creatorTokenAccount,
    tokenProgram: TOKEN_PROGRAM_ID,
  })
  .signers([creator])
  .rpc();
```

## Reading stream state

To display a stream in a UI, fetch the account and compute progress client-side:

```ts
const s = await program.account.streamConfig.fetch(streamConfig);
// s.totalAmount, s.amountClaimed, s.startTimestamp, s.endTimestamp,
// s.scheduleType, s.status, ...
```

Mirror the [schedule math](https://velora-1.gitbook.io/docs/reference/schedule-types.md) off-chain to show a live "unlocked so far" figure; the on-chain `withdraw` is the source of truth for what is actually claimable.

## Common pitfalls

* **`stream_id` reuse.** The same `(creator, recipient, stream_id)` maps to one PDA. Reusing it after a stream exists fails on `init`. Use a fresh id per stream.
* **`recipient == creator`.** Rejected with `SameRecipientCreator`.
* **Decimals.** All amounts are base units. Scale by the mint's decimals before calling.
* **Milestone streams** unlock nothing until [`release_milestone`](https://velora-1.gitbook.io/docs/instruction-reference/release-milestone.md) is called.
* See the full [error code table](https://velora-1.gitbook.io/docs/reference/errors.md) for handling failures.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://velora-1.gitbook.io/docs/guides/integration.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
