bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 20쪽 중 9쪽
`start_time` | `string` | Unix timestamp (seconds) when streaming begins (ignored if `start_now`). |
| `duration` | `string` | Stream duration in seconds. |
| `cliff_percentage` | `string` | Percent of total that vests at start (basis-point–like input). |
| `start_now` | `boolean` | If `true`, streaming starts at on-chain submission time. |
| `payroll_run_id` | `string` | Off-chain identifier linking the stream to a payroll run. |
| `accrual_frequency` | `string` | Vesting tick interval, in seconds. Must be in the allowed `frequencies`. |
| `pausable` | `boolean` | Whether the stream supports pause/resume. |
| `cancelable_by_sender` | `boolean` | Whether the sender may cancel. |
| `cancelable_by_recipient` | `boolean` | Whether the receiver may cancel. |
| `transferable_by_sender` | `boolean` | Whether the sender may reassign the receiver. |
| `transferable_by_recipient` | `boolean` | Whether the receiver may reassign themselves. |
| `automatic_withdrawal` | `boolean` | If `true`, the configured `withdraw_account` performs withdrawals. |
| `initial_buffer_amount` | `string` | Optional buffer amount (human-readable; scaled by token decimals). |
| `auto_topup` | `boolean` | If `true`, the stream supports automated top-ups. |
| `sender_id` | `string` | Off-chain identifier for the sender (e.g. employer ref). |
| `receiver_id` | `string` | Off-chain identifier for the receiver (e.g. employee ref). |
| `token_price` | `string` | Token price in USD. |
| `price_expiry` | `string` | Unix timestamp when the token price signature expires. |
| `price_signature` | `string` | Hex-encoded admin signature over the token price data. |
| `token_contract_id` | `string` | Hex-encoded token contract ID (32 bytes). |
| `xlm_price` | `string` | XLM price in USD. |
| `xlm_price_expiry` | `string` | Unix timestamp when the XLM price signature expires. |
| `xlm_price_signature` | `string` | Hex-encoded admin signature over the XLM price data. |
### `CreateStreamEntry`
One entry in a `createMultipleStreams` batch. Carries everything `createStream` would otherwise take as positional arguments.
| Field | Type | Description |
| ----------- | -------------------- | --------------------------------------------------------------- |
| `stream_id` | `string` | 32-byte hex-encoded stream identifier (`BytesN`). |
| `receiver` | `string` | Receiver account address. |
| `token` | `string` | Token contract address (SAC or custom) for this stream. |
| `params` | `CreateStreamParams` | Full stream configuration; amounts are in human-readable units. |
### `TopupEntry`
One entry in a `topupAllStreams` or `triggerTopupAllStreams` batch.
| Field | Type | Description |
| ----------- | -------- | ------------------------------------------------------------------------- |
| `stream_id` | `string` | 32-byte hex-encoded stream identifier (`BytesN`). |
| `amount` | `string` | Top-up amount in human-readable display units (scaled by token decimals). |
### `BatchChunk<T>`
A single chunk in a batch submission, pairing a deferred payload with caller-defined metadata (e.g. the stream IDs contained in the chunk).
| Field | Type | Description |
| --------- | -------------------- | --------------------------------------------------------------- |
| `payload` | `TransactionPayload` | The deferred transaction payload for this chunk. |
| `meta` | `T` | Caller-defined metadata — for batch methods this is `string[]`. |
### `BatchChunkResult<T>`
Result of processing one chunk in a batch.
| Field | Type | Description |
| ------------ | ----------------------------- | ------------------------------------------------------------------------ |
| `meta` | `T` | The same metadata from the original `BatchChunk`. |
| `response` | `Api.GetTransactionResponse?` | Present when the chunk was successfully built **and** submitted. |
| `buildError` | `Error?` | Present when the chunk failed during `buildTransactionXDR` (simulation). |
Exactly one of `response` or `buildError` will be set.
## TransactionPayload
All write methods return a `TransactionPayload` rather than submitting directly, giving consumers control over the signing/submission flow.
```ts
class TransactionPayload {
readonly server: Server;
readonly sourcePublicKey: string;
readonly operations: xdr.Operation[];
readonly networkPassphrase: string;
readonly memo?: string;
buildTransaction(
options?: TransactionOptions,
): Promise<Transaction | FeeBumpTransaction>;
buildTransactionXDR(options?: TransactionOptions): Promise<string>;
signAndSubmit(
options?: TransactionOptions,
): Promise<Api.GetTransactionResponse>;
}
```
Build + simulate work is deferred until one of these methods is called, so the source account's sequence number and Soroban resource fees stay fresh even if the user pauses between the SDK call and the wallet popup.
* **`buildTransaction(options?)`** — Fetches a fresh sequence number, simulates the operation, applies the Soroban footprint and resource fees, and returns the prepared transaction (unsigned). Throws `"Simulation failed: ..."` if the RPC reports a simulation error.
* **`buildTransactionXDR(options?)`** — Convenience wrapper that returns the prepared transaction's base64 XDR string. Useful for handing to an external signer (hardware wallet, multi-sig coordinator, browser wallet).
* **`signAndSubmit(options?)`** — Builds, signs via the configured `WalletAdapter`, submits to the network, and polls until a final status is available.
`options` (`TransactionOptions`) shallow-merges on top of any construction-time options; per-call values win.
This separation lets you, for example, build the payload server-side and submit it client-side, or sign with multiple parties before submission.
### Batch submission
`TransactionPayload` also exposes a static `signAndSubmitBatch` method for executing multiple chunks as a single batch. All payloads must share the same server, source public key, and network passphrase. Sequence numbers are assigned contiguously starting from the current ledger sequence, so the transactions can be signed all at once (via `WalletAdapter.signAllTransactions`) and then submitted sequentially.
#### `TransactionPayload.signAndSubmitBatch(chunks, options?): Promise<BatchChunkResult<T>[]>`
* `chunks: BatchChunk<T>[]` — array of chunks to execute.
* `options.abortOnFailure` — optional, defaults to `true`. When `true`, the first failing chunk aborts the entire batch and throws a `BatchTransactionError`.
* Returns an array of `BatchChunkResult<T>` in the same order as `chunks`.
When `abortOnFailure` is `false`, failed chunks are included in the results with their error or non-success status, letting you inspect partial success:
```ts
const results = await TransactionPayload.signAndSubmitBatch(chunks, {
abortOnFailure: false,
});
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (result.buildError) {
console.error(`Chunk ${i + 1} failed to build:`, result.buildError.message);
} else if (result.response?.status !== "SUCCESS") {
console.error(`Chunk ${i + 1} failed on-chain:`, result.response?.txHash);
} else {
console.log(`Chunk ${i + 1} succeeded:`, result.response.txHash);
}
}
```
### `BatchTransactionError`
Thrown by `signAndSubmitBatch` when `abortOnFailure` is `true` and a chunk fails.
| Property | Type | Description |
| ------------- | -------------------- | -------------------------------------------------- |
| `results` | `BatchChunkResult[]` | Every result processed so far, including failures. |
| `failedIndex` | `number` | Index of the first failing chunk. |
| `meta` | `unknown` | Metadata of the first failing chunk. |
## Wallet adapter
The SDK is signer-agnostic. Any object satisfying the `WalletAdapter` interface works — Freighter, Albedo, Rabet, a `Keypair`-backed local signer, or a custom remote signer.
### Example with a local `Keypair`
```ts
import { Keypair, Networks, TransactionBuilder } from "@stellar/stellar-sdk";
const keypair = Keypair.fromSecret(process.env.SECRET!);
const wallet: WalletAdapter = {
getPublicKey: async () => keypair.publicKey(),
signTransaction: async (txXDR) => {
const tx = TransactionBuilder.fromXDR(txXDR, Networks.TESTNET);
tx.sign(keypair);
return tx.toXDR();
},
signAllTransactions: async (txXDRs) =>
txXDRs.map((txXDR) => {
const tx = TransactionBuilder.fromXDR(txXDR, Networks.TESTNET);
tx.sign(keypair);
return tx.toXDR();
}),
};
```
### Example with Freighter (browser)
```ts
import freighter from "@stellar/freighter-api";
const wallet: WalletAdapter = {
getPublicKey: () => freighter.getPublicKey(),
signTransaction: (txXDR) =>
freighter.signTransaction(txXDR, { networkPassphrase: Networks.PUBLIC }),
signAllTransactions: async (txXDRs) =>
Promise.all(
txXDRs.map((txXDR) =>
freighter.signTransaction(txXDR, {
networkPassphrase: Networks.PUBLIC,
}),
),
),
};
```
## Error handling
The SDK distinguishes three classes of errors:
1. **Wallet / caller mismatch** — thrown immediately when the supplied `admin`/`sender`/`caller` does not match the wallet's public key.
2. **Simulation errors** — returned by the Soroban RPC during transaction simulation. If the raw error contains a recognized contract error code, a `ContractError` is thrown instead of a plain `Error`.
3. **Transaction failures** — on-chain `FAILED` status. The SDK inspects `diagnosticEvents` for a typed `StreamError` code and throws a `ContractError` when one is found.
### `ContractError`
When the streaming contract rejects an operation it returns a `StreamError` (a numeric code). The SDK decodes this into a `ContractError` so you can react programmatically instead of parsing strings.
```ts
import {
ContractError,
StreamErrorCode,
} from "@zebec-network/stellar-payroll-sdk";
try {
const payload = await service.cancelStream(caller, streamId);
await payload.signAndSubmit();
} catch (err) {
if (err instanceof ContractError) {
console.error(`Contract rejected: ${err.errorName} (code ${err.code})`);
if (err.code === StreamErrorCode.StreamNotCancelable) {
// show user-friendly "this stream cannot be cancelled" message
}
} else {
console.error("Unexpected error:", (err as Error).message);
}
}
```
| Property | Type | Description |
| ----------- | -------- | ----------------------------------------------------- |
| `code` | `number` | Numeric error code returned by the contract. |
| `errorName` | `string` | Human-readable enum name (e.g. `"StreamNotStarted"`). |
| `message` | `string` | `"Contract error #2: StreamNotStarted"` |
### `StreamErrorCode`
All known contract error codes are exported as a typed enum:
```ts
enum StreamErrorCode {
StreamAlreadyCanceled = 1,
StreamNotStarted = 2,
StreamAlreadyEnded = 3,
StreamNotPausable = 4,
InsufficientFundsToWithdraw = 5,
StreamNotCancelable = 6,
SenderCannotBeReceiver = 7,
InvalidStartTime = 8,
InvalidDuration = 9,
InvalidAmount = 10,
InvalidCliffPercentage = 11,
FeesExceedAmount = 12,
InvalidTopupAmount = 14,
AutoTopupNotEnabled = 15,
TopupNotAvailable = 16,
StreamNotCancelableByRecipient = 17,
RecipientTransferNotAllowed = 18,
UnauthorizedWithdrawal = 19,
StreamAlreadyExists = 20,
StreamNameTooLong = 21,
InsufficientAllowanceForTopup = 22,
MaxWhitelistedTokensExceeded = 30,
TokenNotWhitelisted = 31,
InvalidFeeConfig = 32,
MaxFeetiersExceeded = 35,
InvalidFrequency = 36,
MaxFrequenciesExceeded = 37,
PriceExpired = 38,
TokenMismatch = 39,
InvalidPriceSignature = 40,
FeeTiersNotSet = 41,
}
```
### Polling timeout
`signAndSubmit` polls the RPC until the transaction is final. To prevent infinite loops, polling stops after **30 attempts** (roughly 30 seconds) and throws:
```
Transaction polling timed out after 30 attempts. Hash: <hash>
```
### Utilities
The following helpers are exported for advanced use cases:
* `parseContractError(error)` — tries to extract a `ContractError` from a raw string, number, or SDK error object.
* `parseContractErrorFromDiagnosticEvents(events)` — scans Soroban `DiagnosticEvent[]` for a contract error topic.
* `formatSimulationError(context, rawError)` — wraps a simulation error; returns `ContractError` when a code is detected, otherwise a plain `Error`.
* `formatTransactionError(resultXdr, diagnosticEvents?)` — wraps an on-chain failure; decodes diagnostic events first, then falls back to the raw `resultXdr`.
## Related
* [Streaming SDK overview](/developer-docs/sdks/streaming-sdk)
* [Enterprise Payroll streaming guide](/zebec-application-suite/enterprise-payroll/streaming-payroll)
* [Partner API overview](/developer-docs/partner-api)
# Solana
Solana Streaming SDK - TypeScript SDK for Zebec payment streams on Solana via Anchor.
A TypeScript SDK for interacting with the Zebec Stream protocol on Solana. This SDK provides a comprehensive interface for creating, managing, and interacting with payment streams on the Zebec Network.
## Overview
The Solana Streaming SDK enables developers to build applications that leverage continuous, programmable SPL-token streams on Solana. It wraps the underlying Anchor program interactions, handling instruction building, associated token account (ATA) resolution, fee quoting, and transaction composition while exposing strongly-typed, ergonomic APIs.
Typical use cases include:
* **Payroll** — Stream salaries to employees continuously per second / minute / hour.
* **Vesting** — Distribute tokens over time with configurable cliffs.
* **Subscriptions** — Recurring payments and metered billing.
* **Grants & Bounties** — Time-locked, cancelable token distribution.
## Installation
Install the package using npm or yarn:
```bash
npm install @zebec-network/zebec-stream-sdk
```
```bash
yarn add @zebec-network/zebec-stream-sdk
```
### Peer dependencies
The SDK relies on the following runtime dependencies (installed automatically):
* [`@coral-xyz/anchor`](https://www.npmjs.com/package/@coral-xyz/anchor) — Anchor framework for Solana program interaction
* [`@solana/web3.js`](https://www.npmjs.com/package/@solana/web3.js) — Solana Web3 JavaScript API
* [`@solana/spl-token`](https://www.npmjs.com/package/@solana/spl-token) — SPL token utilities
* [`@metaplex-foundation/mpl-token-metadata`](https://www.npmjs.com/package/@metaplex-foundation/mpl-token-metadata) — On-chain token metadata resolution
* [`@zebec-network/core-utils`](https://www.npmjs.com/package/@zebec-network/core-utils) — Zebec core utility functions
* [`@zebec-network/solana-common`](https://www.npmjs.com/package/@zebec-network/solana-common) — Common Solana helpers
* [`bignumber.js`](https://www.npmjs.com/package/bignumber.js) — Arbitrary-precision arithmetic
### Requirements
* Node.js 18+ recommended
* TypeScript 5+ (when consuming from TS projects)
## Quick start
```ts
import { Connection } from "@solana/web3.js";
import { ZebecStreamService, createAnchorProvider } from "@zebec-network/zebec-stream-sdk";
// 1. Create a connection to devnet or mainnet-beta
const connection = new Connection("https://api.devnet.solana.com");
// 2. Create an AnchorProvider using your wallet
const provider = createAnchorProvider(connection, wallet);
// 3. Initialize the service with a config name and network
const streamService = ZebecStreamService.create("my-app-config", provider, "devnet");
// 4. Create a stream
const tx = await streamService.createStream({
sender: "SenderPublicKeyHere",
receiver: "ReceiverPublicKeyHere",
streamToken: "TokenMintAddressHere",
amount: "1000", // Amount in human-readable token units
duration: 86400, // Total stream duration in seconds (1 day)
autoWithdrawFrequency: 3600, // Auto-withdrawal interval in seconds (1 hour)
streamName: "Monthly Salary",
startNow: true,
startTime: Math.floor(Date.now() / 1000),
cliffPercentage: 0,
automaticWithdrawal: true,
cancelableByRecipient: true,
cancelableBySender: true,
isPausable: true,
transferableByRecipient: false,
transferableBySender: false,
canTopup: true,
rateUpdatable: false,
});
const signature = await tx.execute();
console.log("Stream created:", signature);
```
## Core concepts
### Streams
A **stream** is an on-chain agreement to transfer SPL tokens from a sender to a receiver over a defined duration. Streams can be paused, resumed, canceled, transferred, and topped up depending on the permissions set at creation.
### Stream config
Every stream belongs to a named **stream config** PDA that holds the global protocol state: admin, fee tiers, allowed frequencies, withdraw account, fee vault, and whitelisted tokens. The config name is passed when creating the `ZebecStreamService`.
### Fee model
Fees are configured globally per stream config:
* **Platform fee** — a percentage charged on every stream.
* **Base fee** — a flat percentage applied to every stream.
* **Fee tiers** — amount-banded percentage fees based on the USD value of the stream amount.
Fees are quoted dynamically from the Zebec backend at stream creation time. The SDK fetches the fee quote, computes the fee token and amount, and includes the fee transfer instruction automatically.
### Decimals
The SDK automatically converts human-readable amounts to raw token units using the SPL token's on-chain decimals. Inputs like `"1000"` are scaled correctly before being passed to the program.
## SDK methods
All write methods return a [`TransactionPayload`](#transactionpayload) that must be executed. All read methods return parsed, human-readable values directly.
The service is constructed as:
```ts
ZebecStreamService.create(streamConfigName: string, provider: Provider, network: RpcNetwork)
```
| Parameter | Type | Description |
| ------------------ | ---------------------------- | ----------------------------------------------------------------- |
| `streamConfigName` | `string` | Unique name identifying the stream config PDA. |
| `provider` | `Provider` | Anchor provider (read/write) or read-only provider. |
| `network` | `"mainnet-beta" \| "devnet"` | Target network. Must match the connection's RPC endpoint network. |
### Admin methods
These methods configure the global protocol state and require the caller to be the config admin.
#### `initializeStreamConfig(params): Promise<TransactionPayload>`
Initializes the global stream configuration (admin only, one-time setup per `streamConfigName`).
* `params.admin?` — optional admin address (defaults to provider wallet).
* `params.config.baseFeePercent` — base fee as a percent string (e.g. `"0.1"`).
* `params.config.platformFeePercent` — platform fee as a percent string (e.g. `"0.05"`).
* `params.config.frequencies` — allowed auto-withdraw frequencies in seconds (e.g. `[3600, 86400, 604800]`).
* `params.config.withdrawAccount` — address that performs automatic withdrawals.
* `params.config.feeVault` — address that collects fees.
* `params.config.feeTiers` — array of `FeeTier` objects defining amount-banded fees.
```ts
await streamService.initializeStreamConfig({
admin: adminAddress,
config: {
baseFeePercent: "0.1",
platformFeePercent: "0.05",
frequencies: [3600, 86400, 604800],
withdrawAccount: "WithdrawAccountAddressHere",
feeVault: "FeeVaultAddressHere",
feeTiers: [
{ minThreshold: "0", maxThreshold: "1000", feeRateInPercent: "1.0" },
{ minThreshold: "1000", maxThreshold: "10000", feeRateInPercent: "0.75" },
{ minThreshold: "10000", maxThreshold: "99999999", feeRateInPercent: "0.5" },
],
},
});
```
#### `updateStreamConfig(params): Promise<TransactionPayload>`
Updates an existing stream configuration (admin only). Same parameter shape as `initializeStreamConfig`.
#### `whiteListTokens(params): Promise<TransactionPayload>`
Adds token mint addresses to the whitelist of streamable tokens (admin only).
| Field | Type | Description |
| -------- | ----------- | ------------------------------------------- |
| `admin` | `Address` | Admin public key. |
| `tokens` | `Address[]` | Array of token mint addresses to whitelist. |
### Stream methods
#### `createStream(params): Pro프로젝트로 돌아가기