Zebec Network 백서

Zebec Network

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 20쪽 중 8쪽

ansactionPayload>` Removes a single token contract address from the whitelist. #### `setFrequencies(admin, frequencies, options?): Promise<TransactionPayload>` Updates the list of allowed accrual frequencies (in seconds) that streams can use. #### `updateConfig(admin, params, options?): Promise<TransactionPayload>` Bulk-updates the fee config **and** the allowed frequencies in a single transaction. * `params: UpdateConfigParams` — same as `SetFeeConfigParams` plus `frequencies`, `admin_signer`, and `xlm_token_contract_id`. ### Tenant methods Tenant configs let the admin set custom fee rules for a specific sender, overriding the global config for that sender's streams. #### `getTenantConfig(sender: string): Promise<TenantConfig>` Reads the tenant configuration assigned to a sender address: fee recipient, withdraw account, platform/base/stream-token fees, and fee tiers. #### `setTenantConfig(admin, params, options?): Promise<TransactionPayload>` Creates or updates the tenant config for `params.sender`. The wallet must match `admin`. #### `removeTenantConfig(admin, sender, options?): Promise<TransactionPayload>` Removes a tenant config, reverting the sender to the global fee defaults. ### Token methods #### `approveTokenSpending(caller, token, spender, amount, options?): Promise<TransactionPayload>` Approves a `spender` to transfer up to `amount` of `token` on behalf of `caller` (SEP-41 allowance). Required before invoking flows that pull funds via allowance, such as `triggerTopup`. * `amount` is in display units; the SDK scales it to raw units using the token's on-chain decimals. * The allowance lifetime is pinned to the network-enforced maximum entry TTL (fetched via `getMaxEntryTtl`), so the approval persists for the largest value the network will accept. * The wallet's public key must match `caller`. #### `establishTrustline(caller, assets, options?): Promise<TransactionPayload>` Establishes classic Stellar trustlines for the caller for one or more assets in a single transaction. Each asset becomes one `changeTrust` operation, using the default maximum trustline limit. Soroban contracts cannot invoke classic Stellar operations, so trustlines (a `ChangeTrust` op) cannot be opened from inside the streaming contract — they have to be opened SDK-side. This method bypasses the Soroban `prepareTransaction` step internally since the underlying operation is classic, not a host-function call. * `assets: Asset[]` — classic assets to trust. Construct with `new Asset(code, issuer)` from `@stellar/stellar-sdk` (also re-exported from this package). * The wallet's public key must match `caller`. * Submitting against an already-trusted asset is a no-op on the network — safe to call again. ```ts import { Asset } from "@zebec-network/stellar-payroll-sdk"; const usdc = new Asset( "USDC", "GA5ZSEFYNTRECNZXVT7AYG5WDXJWFEYDKHYZQ3LZWNK3RIEGBHV4QHGN", ); const eurc = new Asset( "EURC", "GB3Q6QDZYTHWT7E5PVS3W7FUT5GVAFC5KSZFFLPU234JZTKLATKSEPCV", ); const payload = await service.establishTrustline(caller, [usdc, eurc]); await payload.signAndSubmit(); ``` #### `checkTrustline(caller, assets): Promise<{ asset: Asset; exists: boolean }[]>` Checks whether `caller` has established classic Stellar trustlines for the provided assets. Looks up the corresponding `trustLine` ledger entries via the Soroban RPC in a single batched call and returns one `{ asset, exists }` entry per input asset, **in the same order**. * `assets: Asset[]` — classic assets to check. Construct with `new Asset(code, issuer)`. * Read-only — does not submit a transaction and does not require the caller's wallet to match the SDK's wallet. * Throws if `assets` is empty or if any entry is `Asset.native()`; every Stellar account implicitly trusts XLM, so a native trustline check is a programming error rather than a meaningful query. Typical pairing with `establishTrustline` — only sign for the missing trustlines: ```ts import { Asset } from "@zebec-network/stellar-payroll-sdk"; const want = [ new Asset("USDC", "GA5ZSEFYNTRECNZXVT7AYG5WDXJWFEYDKHYZQ3LZWNK3RIEGBHV4QHGN"), new Asset("EURC", "GB3Q6QDZYTHWT7E5PVS3W7FUT5GVAFC5KSZFFLPU234JZTKLATKSEPCV"), ]; const statuses = await service.checkTrustline(caller, want); const missing = statuses.filter((s) => !s.exists).map((s) => s.asset); if (missing.length > 0) { const payload = await service.establishTrustline(caller, missing); await payload.signAndSubmit(); } ``` #### `bulkTransfer(sender, asset, recipients, options?): Promise<TransactionPayload>` Executes a bulk transfer to multiple recipients using classic Stellar `Payment` operations. This bypasses Soroban contract invocation entirely, making it suitable for simple token distributions (e.g. payroll bonuses, airdrops, mass payouts) without interacting with the streaming contract. * `asset: Asset` — classic asset to transfer. Construct with `new Asset(code, issuer)` from `@stellar/stellar-sdk` (also re-exported from this package). For SAC tokens, derive the asset from the token's code and issuer; the SDK automatically computes the SAC contract ID to query on-chain decimals and adjust amounts correctly. * `recipients` — array of `{ destination: string; amount: string }`. Each `amount` is in display units (e.g. `"100.5"`). The SDK converts each amount to the token's atomic units, accounting for the difference between the token's on-chain decimals and Stellar classic's 7-decimal precision. * The wallet's public key must match `sender`. * This method bypasses Soroban `prepareTransaction` internally because classic `Payment` operations are not host-function calls. * Every destination account must exist on the ledger and must have established a trustline for the asset (unless the destination is the sender itself). ```ts import { Asset } from "@zebec-network/stellar-payroll-sdk"; const usdc = new Asset( "USDC", "GA5ZSEFYNTRECNZXVT7AYG5WDXJWFEYDKHYZQ3LZWNK3RIEGBHV4QHGN", ); const payload = await service.bulkTransfer(sender, usdc, [ { destination: "GBR...RECEIVER_1", amount: "100" }, { destination: "GBR...RECEIVER_2", amount: "250.5" }, { destination: "GBR...RECEIVER_3", amount: "75" }, ]); const result = await payload.signAndSubmit(); console.log("Bulk transfer tx:", result.txHash); ``` ### Stream methods #### `createStream(sender, receiver, streamId, token, params, options?): Promise<TransactionPayload>` Creates a new payment stream from `sender` to `receiver`. * `streamId` — 32-byte hex string. The SDK encodes it as a `BytesN`. * `token` — token contract address (Stellar Asset Contract or custom). * `params: CreateStreamParams` — full stream configuration (see [Data types](#data-types)). The amount in `params.amount` is scaled to the token's decimals automatically. The wallet must match `sender`. #### `createMultipleStreams(sender, entries, options?): Promise<TransactionPayload>` Creates multiple payment streams from `sender` in a single transaction. * `entries: CreateStreamEntry[]` — one entry per stream, each carrying its own `stream_id`, `receiver`, `token`, and `params`. * Each entry's `params.amount` and `params.initial_buffer_amount` are scaled to the entry's token decimals. Decimals are fetched once per unique token across the batch. * The wallet must match `sender`. #### `createMultipleStreamsBatch(sender, entries, options?): Promise<BatchChunk<string[]>[]>` Creates multiple payment streams split across several transactions to stay within Soroban resource limits. * `entries: CreateStreamEntry[]` — same as `createMultipleStreams`. * `options.chunkSize` — optional, defaults to `5`. Number of streams per chunk. * Returns an array of `BatchChunk<string[]>`. Each chunk carries a `payload` (a `TransactionPayload`) and `meta` (the list of `stream_id`s in that chunk). * The chunks can be signed and submitted all at once via [`TransactionPayload.signAndSubmitBatch`](#batch-submission). * **Not atomic** across chunks. If a chunk fails, earlier chunks may already be committed on-chain. Inspect the responses (or catch `BatchTransactionError`) to determine partial success. ```ts const chunks = await service.createMultipleStreamsBatch( sender.publicKey(), entries, { chunkSize: 7 }, ); const results = await TransactionPayload.signAndSubmitBatch(chunks, { abortOnFailure: false, }); for (const result of results) { if (result.response?.status === "SUCCESS") { console.log("Created streams:", result.meta); } else { console.error("Failed chunk:", result.meta, result.buildError); } } ``` #### `getStream(caller, streamId): Promise<Stream>` Reads the full state of a stream by its ID. Amounts are returned as human-readable strings (scaled down by token decimals); timestamps as numbers; status as an array of strings. #### `getWithdrawableAmount(caller, streamId): Promise<string>` Returns the currently-vested, withdrawable amount as a human-readable decimal string. Internally fetches the stream first to determine the token decimals. #### `pauseResumeStream(caller, streamId, options?): Promise<TransactionPayload>` Toggles the paused/active state of a stream. `caller` must be the stream's sender, and the stream must have `pausable: true`. #### `pauseResumeAllStreams(caller, streamIds, options?): Promise<TransactionPayload>` Toggles the paused/active state of multiple streams in a single transaction. * `streamIds` — array of 32-byte hex-encoded stream IDs. * `caller` must be the sender of every stream in the batch. Streams that are non-pausable, terminal, or whose sender does not match `caller` are silently skipped by the contract. #### `pauseResumeAllStreamsBatch(caller, streamIds, options?): Promise<BatchChunk<string[]>[]>` Toggles the paused/active state of multiple streams split across several transactions to stay within Soroban resource limits. * `streamIds` — array of 32-byte hex-encoded stream IDs. * `options.chunkSize` — optional, defaults to `5`. Number of stream IDs per chunk. * Returns an array of `BatchChunk<string[]>`. Each chunk carries a `payload` and `meta` (the list of `streamId`s in that chunk). * The chunks can be signed and submitted all at once via [`TransactionPayload.signAndSubmitBatch`](#batch-submission). * **Not atomic** across chunks. If a chunk fails, earlier chunks may already be committed on-chain. #### `cancelStream(caller, streamId, options?): Promise<TransactionPayload>` Cancels a stream. `caller` must be the sender (if `cancelable_by_sender`) or the receiver (if `cancelable_by_recipient`). Unvested funds are refunded to the sender. #### `cancelAllStreams(caller, streamIds, options?): Promise<TransactionPayload>` Cancels multiple streams in a single transaction. * `streamIds` — array of 32-byte hex-encoded stream IDs. * The caller-eligibility rule for `cancelStream` applies to each stream individually (sender with `cancelable_by_sender`, or receiver with `cancelable_by_recipient`). Streams that fail authorization, are terminal, or lack the vault balance to cover vested debt are silently skipped by the contract. #### `cancelAllStreamsBatch(caller, streamIds, options?): Promise<BatchChunk<string[]>[]>` Cancels multiple streams split across several transactions to stay within Soroban resource limits. * `streamIds` — array of 32-byte hex-encoded stream IDs. * `options.chunkSize` — optional, defaults to `5`. Number of stream IDs per chunk. * Returns an array of `BatchChunk<string[]>`. Each chunk carries a `payload` and `meta` (the list of `streamId`s in that chunk). * The chunks can be signed and submitted all at once via [`TransactionPayload.signAndSubmitBatch`](#batch-submission). * **Not atomic** across chunks. If a chunk fails, earlier chunks may already be committed on-chain. #### `withdrawStream(caller, streamId, options?): Promise<TransactionPayload>` Withdraws the vested amount. * If `automatic_withdrawal == true`, `caller` must be `stream.withdraw_account`. * If `automatic_withdrawal == false`, `caller` must be `stream.receiver`. #### `withdrawAllStreams(caller, streamIds, options?): Promise<TransactionPayload>` Withdraws the vested amount from multiple streams in a single transaction. * `streamIds` — array of 32-byte hex-encoded stream IDs. * The caller-eligibility rule for `withdrawStream` applies to each stream individually (`stream.withdraw_account` if `automatic_withdrawal == true`, otherwise `stream.receiver`); the same `caller` must satisfy this for every stream in the batch. #### `changeRecipient(caller, streamId, newReceiver, options?): Promise<TransactionPayload>` Reassigns the stream's receiver. `caller` must be the sender (if `transferable_by_sender`) or the current receiver (if `transferable_by_recipient`). #### `topupStream(caller, streamId, amount, options?): Promise<TransactionPayload>` Manually deposits additional funds into a stream. `caller` must be the stream's sender. `amount` is in display units; the SDK fetches the stream's token decimals and scales it to atomic units automatically. #### `triggerTopup(caller, streamId, amount, options?): Promise<TransactionPayload>` Triggers an automated top-up for a stream that has `auto_topup_enabled`. Callable by anyone (subject to contract rules). `amount` is in display units and is auto-scaled to the stream token's decimals. Requires a prior `approveTokenSpending` call so the contract can pull funds via allowance. #### `topupAllStreams(caller, entries, options?): Promise<TransactionPayload>` Top-ups multiple streams in a single transaction. `caller` must be the sender of every stream; entries owned by a different sender are silently skipped by the contract. No prior `approveTokenSpending` is needed because auth is collected once from `caller`. * `entries: TopupEntry[]` — one entry per stream (see [Data types](#data-types)). Each `amount` is in display units; the SDK looks up each stream's token, fetches its decimals, and scales the amount to atomic units automatically. Duplicate stream IDs are deduplicated internally. #### `triggerTopupAllStreams(caller, entries, options?): Promise<TransactionPayload>` Triggers automated top-ups for multiple streams in a single transaction. Callable by anyone (subject to contract rules). Streams with `auto_topup_enabled == false` are silently skipped by the contract. * `entries: TopupEntry[]` — one entry per stream. Each `amount` is in display units and is auto-scaled to the stream token's decimals. Requires a prior `approveTokenSpending` call for each stream's token so the contract can pull funds via allowance. ### TTL methods Soroban contract data has a time-to-live (TTL) for persistent storage. These methods extend it. #### `bumpStreamTtl(caller, streamId, options?): Promise<TransactionPayload>` Extends the TTL of a specific stream's persistent storage entry. Callable by anyone. #### `bumpConfigTtl(caller, options?): Promise<TransactionPayload>` Extends the TTL of the protocol's config instance storage. Callable by anyone. ## Data types All types are exported from the package root. ### `StellarStreamingSDKConfig` SDK constructor configuration. | Field | Type | Description | | ------------------- | -------- | ------------------------------------------------------------------------- | | `contractId` | `string` | Soroban contract address of the streaming contract. | | `networkPassphrase` | `string` | Stellar network passphrase (`Networks.TESTNET`, `Networks.PUBLIC`, etc.). | | `rpcUrl` | `string` | URL of a Soroban RPC endpoint. | ### `WalletAdapter` Interface every wallet implementation must satisfy. | Field | Type | Description | | --------------------- | ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `getPublicKey` | `() => Promise<string>` | Returns the source account's public key (G…). | | `signTransaction` | `(txXDR: string) => Promise<string>` | Signs a transaction in XDR format and returns the signed XDR. | | `signAllTransactions` | `(txXDRs: string[]) => Promise<string[]>` *(optional)* | Signs an array of transaction XDRs and returns the signed XDRs in the same order. Used by batch / multi-sign flows. Optional — only needed if you intend to use multi-sign helpers. | ### `TransactionOptions` Optional overrides for transaction building. | Field | Type | Description | | --------- | --------- | -------------------------------------------------- | | `fee` | `string?` | Custom fee (stroops). Defaults to `BASE_FEE`. | | `timeout` | `number?` | Transaction timeout in seconds. Defaults to `180`. | ### `FeeTier` A single fee tier band, expressed in human-readable units. | Field | Type | Description | | ------------- | ------------------ | -------------------------------------- | | `min_amount` | `string \| number` | Lower bound (inclusive) for this tier. | | `max_amount` | `string \| number` | Upper bound (exclusive) for this tier. | | `fee_percent` | `number` | Fee percentage (e.g. `0.5` for 0.5%). | ### `ParsedFeeTier` Internal representation after scaling: amounts in atomic units and fee converted to basis points. Returned by the conversion utilities. | Field | Type | | ------------ | -------- | | `min_amount` | `string` | | `max_amount` | `string` | | `fee_bps` | `string` | ### `TenantConfig` Read shape returned by `getTenantConfig`, and base shape for fee-related parameter types. | Field | Type | Description | | ------------------ | ----------- | -------------------------------------------- | | `fee_recipient` | `string` | Address that receives collected fees. | | `withdraw_account` | `string` | Address that performs automatic withdrawals. | | `platform_fee` | `number` | Platform-level fee percent. | | `base_fee` | `number` | Base fee percent applied to every stream. | | `stream_token_fee` | `number` | Fee percent charged in the stream token. | | `fee_tiers` | `FeeTier[]` | Amount-banded percentage fees. | ### `SetFeeConfigParams` Parameters for `setFeeConfig`. Same fields as `TenantConfig`, plus: | Field | Type | Description | | ------------ | --------- | --------------------------------------- | | `xlm_as_fee` | `boolean` | Whether XLM is accepted as a fee token. | ### `UpdateConfigParams` Parameters for `updateConfig`. Same fields as `SetFeeConfigParams`, plus: | Field | Type | Description | | ----------------------- | ---------- | ----------------------------------------------- | | `frequencies` | `number[]` | Allowed accrual frequencies in seconds. | | `admin_signer` | `string` | Hex-encoded admin signer public key (32 bytes). | | `xlm_token_contract_id` | `string` | Hex-encoded XLM token contract ID (32 bytes). | ### `SetTenantConfigParams` Parameters for `setTenantConfig`. Same shape as `TenantConfig`, plus: | Field | Type | Description | | -------- | -------- | ------------------------------------------------ | | `sender` | `string` | The sender address the tenant config applies to. | ### `Config` Read shape returned by `getConfig`. Extends `TenantConfig` with: | Field | Type | Description | | ----------------------- | ---------- | ----------------------------------------------- | | `frequencies` | `number[]` | Allowed accrual frequencies in seconds. | | `whitelisted_tokens` | `string[]` | Token contract addresses permitted for streams. | | `xlm_token` | `string` | Canonical XLM (Stellar Asset Contract) address. | | `admin_signer` | `string` | Hex-encoded admin signer public key. | | `xlm_token_contract_id` | `string` | Hex-encoded XLM token contract ID. | | `xlm_as_fee` | `boolean` | Whether XLM is accepted as a fee token. | ### `CreateStreamParams` Full parameters for creating a stream. | Field | Type | Description | | --------------------------- | --------- | ------------------------------------------------------------------------ | | `amount` | `string` | Total stream amount (human-readable; scaled by token decimals). | |
프로젝트로 돌아가기