@streamflow/stream 11.0.4 → 11.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -82,6 +82,9 @@ interface IGetAllData {
82
82
  address: string;
83
83
  type?: StreamType;
84
84
  direction?: StreamDirection;
85
+ filters?: {
86
+ closed?: boolean;
87
+ };
85
88
  }
86
89
  interface ICreateMultiError {
87
90
  recipient: string;
@@ -501,6 +504,7 @@ declare class SolanaStreamClient {
501
504
  private readonly commitment;
502
505
  readonly alignedProxyProgram: Program<StreamflowAlignedUnlocks>;
503
506
  private readonly schedulingParams;
507
+ private readonly apiClient;
504
508
  /**
505
509
  * Create Stream instance with flat arguments
506
510
  */
@@ -750,7 +754,7 @@ declare class SolanaStreamClient {
750
754
  * @param {IGetAllData} getData - Query parameters including address, stream type filter, and direction filter
751
755
  * @returns Record of stream data
752
756
  */
753
- get({ address, type, direction, }: IGetAllData): Promise<[string, Stream][]>;
757
+ get({ address, type, direction, filters, }: IGetAllData): Promise<[string, Stream][]>;
754
758
  /**
755
759
  * Searches for streams/contracts by providing filters.
756
760
  * @param {ISearchStreams} data - Search by mint, sender, recipient or closed status
@@ -808,8 +812,15 @@ declare class SolanaStreamClient {
808
812
  * Utility function that checks whether the associated stream address is an aligned unlock contract, indicated by whether the sender/creator is a PDA.
809
813
  * For migrated streams, the PDA was derived from the old metadata key.
810
814
  */
811
- isAlignedUnlock(streamPublicKey: PublicKey, senderPublicKey: PublicKey, oldMetadata?: PublicKey): boolean;
815
+ isAlignedUnlock(streamPublicKey: PublicKey, senderPublicKey: PublicKey): boolean;
812
816
  private flatBuildCreateMultipleTransactionInstructions;
817
+ /**
818
+ * Gets closed streams for a given owner and direction
819
+ * @param owner - Owner address
820
+ * @param direction - Stream direction
821
+ * @returns Record of closed streams
822
+ */
823
+ getClosedStreams(owner: string, direction?: StreamDirection): Promise<Record<string, Stream>>;
813
824
  /**
814
825
  * Utility function to generate metadata for a Contract or return existing Pubkey
815
826
  */
@@ -1185,4 +1196,169 @@ declare const _default: {
1185
1196
  }[];
1186
1197
  };
1187
1198
 
1188
- export { AIRDROP_AMOUNT, AIRDROP_TEST_TOKEN, ALIGNED_COMPUTE_LIMIT, ALIGNED_PRECISION_FACTOR_POW, ALIGNED_UNLOCKS_PROGRAM_ID, type Account, AlignedContract, AlignedProxyErrorCode, type AlignedStream, type AlignedStreamData, type AlignedUnlocksContract, type BatchItem, type BatchItemError, type BatchItemResult, type BatchItemSuccess, CONTRACT_DISCRIMINATOR, CONTRACT_SEED, CREATE_PARAMS_PADDING, type ChangeOracleParams, type ClientCreationOptions, Contract, ContractErrorCode, type CreateParams, type CreateTestOracleParams, DEFAULT_AUTO_CLAIM_FEE_SOL, DEFAULT_CREATION_FEE_SOL, DEFAULT_STREAMFLOW_FEE, type DecodedStream, ESCROW_SEED, FEES_METADATA_SEED, FEE_ORACLE_PUBLIC_KEY, type IAlignedStreamConfig, type IBaseStreamConfig, type ICancelData, type ICreateAlignedStreamData, type ICreateExt, type ICreateLinearStreamData, type ICreateMultiError, type ICreateMultipleAlignedStreamData, type ICreateMultipleLinearStreamData, type ICreateMultipleStreamData, type ICreateResult, type ICreateStreamData, type ICreateStreamExt, type ICreateStreamInstructions, type IFees, type IGetAllData, type IGetFeesData, type IGetOneData, type IInteractData, type IInteractStreamExt, type IMultiTransactionResult, type IPrepareCreateStreamExt, type IPrepareStreamExt, type IRecipient, type ISearchStreams, type ITopUpData, type ITopUpStreamExt, type ITransactionExtWithInstructions, type ITransactionResult, type ITransferData, type IUpdateData, type IWithdrawData, type InstructionGenerator, type LinearStream, MAX_SAFE_UNIX_TIME_VALUE, type MetadataRecipientHashMap, ORIGINAL_CONTRACT_SENDER_OFFSET, type OracleType, type OracleTypeName, PARTNERS_SCHEMA, PARTNER_ORACLE_PROGRAM_ID, PARTNER_SCHEMA, PROGRAM_ID, REPOPULATED_METADATA_SEED, SOLANA_ERROR_MAP, SOLANA_ERROR_MATCH_REGEX, STREAMFLOW_TREASURY_PUBLIC_KEY, STREAM_STRUCT_OFFSETS, STREAM_STRUCT_OFFSET_CLOSED, STREAM_STRUCT_OFFSET_MINT, STREAM_STRUCT_OFFSET_OLD_METADATA_KEY, STREAM_STRUCT_OFFSET_RECIPIENT, STREAM_STRUCT_OFFSET_SENDER, SolanaStreamClient, type Stream, type StreamClientOptions, StreamDirection, StreamType, TEST_ORACLE_DISCRIMINATOR, TEST_ORACLE_SEED, TX_FINALITY_CONFIRMED, type TestOracle, type TransactionSchedulingOptions, type UpdateTestOracleParams, WITHDRAWOR, WITHDRAWOR_PUBLIC_KEY, WITHDRAW_AVAILABLE_AMOUNT, buildStreamType, calculateTotalAmountToDeposit, calculateUnlockedAmount, cancelStreamInstruction, createStreamInstruction, createUncheckedStreamInstruction, decodeEndTime, decodeStream, deriveContractPDA, deriveEscrowPDA, deriveRepopulatedMetadataPDA, deriveTestOraclePDA, extractSolanaErrorCode, getMetadataKey, handleContractError, isAligned, isCliffCloseToDepositedAmount, isCreateAlignedStreamData, isDynamicLock, isTokenLock, isVesting, sendAndConfirmStreamRawTransaction, signAllTransactionWithRecipients, _default as timelockIDL, topupStreamInstruction, transferStreamInstruction, updateStreamInstruction, withdrawStreamInstruction };
1199
+ /**
1200
+ * Chain identifiers supported by Streamflow protocol
1201
+ */
1202
+ type Chain = "SOLANA" | "APTOS" | "ETHEREUM" | "BNB" | "POLYGON" | "SUI";
1203
+ /**
1204
+ * Contract types supported by Streamflow protocol
1205
+ */
1206
+ type ContractType = "VESTING" | "PAYMENT" | "TOKEN_LOCK" | "DYNAMIC_VESTING" | "DYNAMIC_LOCK";
1207
+ /**
1208
+ * Price oracle types for dynamic contracts
1209
+ */
1210
+ type PriceOracleType = "TEST" | "SWITCHBOARD" | "PYTH";
1211
+ /**
1212
+ * Contract schema matching OpenAPI specification
1213
+ * Used for API responses
1214
+ */
1215
+ interface ContractSchema {
1216
+ chain: Chain;
1217
+ programId: string;
1218
+ address: string;
1219
+ oldAddress: string | null;
1220
+ name: string;
1221
+ contractType: ContractType;
1222
+ sender: string;
1223
+ recipient: string;
1224
+ partner: string | null;
1225
+ mint: string;
1226
+ escrow: string | null;
1227
+ amount: string;
1228
+ cliffAmount: string;
1229
+ amountPerPeriod: string;
1230
+ claimedAmount: string;
1231
+ amountUnlockedAtLastRateUpdate: string;
1232
+ period: number;
1233
+ autoClaimPeriod: number;
1234
+ createdDt: string;
1235
+ startDt: string;
1236
+ endDt: string;
1237
+ canceledDt: string | null;
1238
+ pausedDt: string | null;
1239
+ lastClaimedDt: string | null;
1240
+ lastRateUpdateDt: string | null;
1241
+ isClosed: boolean;
1242
+ isFucked: boolean;
1243
+ isPausable: boolean;
1244
+ canTopup: boolean;
1245
+ hasAutoClaim: boolean;
1246
+ isCancelableBySender: boolean;
1247
+ isCancelableByRecipient: boolean;
1248
+ isTransferableBySender: boolean;
1249
+ isTransferableByRecipient: boolean;
1250
+ canUpdateRate: boolean | null;
1251
+ streamflowFee: string;
1252
+ streamflowFeeWithdrawn: string;
1253
+ streamflowFeePercentage: string;
1254
+ partnerFee: string;
1255
+ partnerFeeWithdrawn: string;
1256
+ partnerFeePercentage: string;
1257
+ txFee: string;
1258
+ pauseCumulative: number;
1259
+ creationFee: number | null;
1260
+ creationFeeClaimed: boolean | null;
1261
+ autoClaimFee: number | null;
1262
+ autoClaimFeeClaimed: boolean | null;
1263
+ lastUpdateSlot: number | null;
1264
+ dynamicContract: DynamicContractSchema | null;
1265
+ }
1266
+ /**
1267
+ * Dynamic contract schema for aligned stream data
1268
+ * Used for API responses with price-based streams
1269
+ */
1270
+ interface DynamicContractSchema {
1271
+ chain: Chain;
1272
+ programId: string;
1273
+ address: string;
1274
+ contractAddress: string;
1275
+ sender: string;
1276
+ priceOracleType: PriceOracleType | null;
1277
+ priceOracleAddress: string | null;
1278
+ minPrice: string;
1279
+ maxPrice: string;
1280
+ minPercentage: string;
1281
+ maxPercentage: string;
1282
+ tickSize: string;
1283
+ expiryDt: string | null;
1284
+ expiryPercentage: string;
1285
+ floorPrice: string;
1286
+ lastPrice: string;
1287
+ initialAmountPerPeriod: string;
1288
+ initialPrice: string;
1289
+ initialAmount: string;
1290
+ lastUpdateSlot: number | null;
1291
+ streamCanceledTime: string | number | null;
1292
+ }
1293
+ /**
1294
+ * TabulariumContract interface
1295
+ * Mirrors LinearStream with primitive types for API/public usage
1296
+ * All addresses are strings, timestamps are numbers, amounts are BN
1297
+ */
1298
+ interface TabulariumContract {
1299
+ address: string;
1300
+ sender: string;
1301
+ senderTokens: string;
1302
+ recipient: string;
1303
+ recipientTokens: string;
1304
+ partner: string;
1305
+ partnerTokens: string;
1306
+ mint: string;
1307
+ escrowTokens: string;
1308
+ streamflowTreasury: string;
1309
+ streamflowTreasuryTokens: string;
1310
+ depositedAmount: BN;
1311
+ withdrawnAmount: BN;
1312
+ cliffAmount: BN;
1313
+ amountPerPeriod: BN;
1314
+ streamflowFeeTotal: BN;
1315
+ streamflowFeeWithdrawn: BN;
1316
+ partnerFeeTotal: BN;
1317
+ partnerFeeWithdrawn: BN;
1318
+ pauseCumulative: BN;
1319
+ fundsUnlockedAtLastRateChange: BN;
1320
+ start: number;
1321
+ end: number;
1322
+ cliff: number;
1323
+ createdAt: number;
1324
+ canceledAt: number;
1325
+ lastWithdrawnAt: number;
1326
+ lastRateChangeTime: number;
1327
+ currentPauseStart: number;
1328
+ period: number;
1329
+ withdrawalFrequency: number;
1330
+ streamflowFeePercent: number;
1331
+ partnerFeePercent: number;
1332
+ cancelableBySender: boolean;
1333
+ cancelableByRecipient: boolean;
1334
+ transferableBySender: boolean;
1335
+ transferableByRecipient: boolean;
1336
+ canTopup: boolean;
1337
+ automaticWithdrawal: boolean;
1338
+ closed: boolean;
1339
+ name: string;
1340
+ type: StreamType;
1341
+ isAligned: boolean;
1342
+ magic: number;
1343
+ version: number;
1344
+ oldMetadata: string;
1345
+ }
1346
+
1347
+ interface ApiClientOptions {
1348
+ apiUrl?: string;
1349
+ cluster?: "mainnet" | "devnet";
1350
+ fetchFn?: typeof fetch;
1351
+ }
1352
+ interface GetContractsOptions {
1353
+ sender?: string;
1354
+ recipient?: string;
1355
+ }
1356
+ interface ApiClient {
1357
+ getContracts: (opts?: GetContractsOptions) => Promise<ContractSchema[]>;
1358
+ getContract: (address: string) => Promise<ContractSchema>;
1359
+ }
1360
+ declare const createClient: (options?: ApiClientOptions) => ApiClient;
1361
+
1362
+ declare const transformContract: (schema: ContractSchema) => Promise<Stream>;
1363
+
1364
+ export { AIRDROP_AMOUNT, AIRDROP_TEST_TOKEN, ALIGNED_COMPUTE_LIMIT, ALIGNED_PRECISION_FACTOR_POW, ALIGNED_UNLOCKS_PROGRAM_ID, type Account, AlignedContract, AlignedProxyErrorCode, type AlignedStream, type AlignedStreamData, type AlignedUnlocksContract, type ApiClient, type ApiClientOptions, type BatchItem, type BatchItemError, type BatchItemResult, type BatchItemSuccess, CONTRACT_DISCRIMINATOR, CONTRACT_SEED, CREATE_PARAMS_PADDING, type Chain, type ChangeOracleParams, type ClientCreationOptions, Contract, ContractErrorCode, type ContractSchema, type ContractType, type CreateParams, type CreateTestOracleParams, DEFAULT_AUTO_CLAIM_FEE_SOL, DEFAULT_CREATION_FEE_SOL, DEFAULT_STREAMFLOW_FEE, type DecodedStream, type DynamicContractSchema, ESCROW_SEED, FEES_METADATA_SEED, FEE_ORACLE_PUBLIC_KEY, type GetContractsOptions, type IAlignedStreamConfig, type IBaseStreamConfig, type ICancelData, type ICreateAlignedStreamData, type ICreateExt, type ICreateLinearStreamData, type ICreateMultiError, type ICreateMultipleAlignedStreamData, type ICreateMultipleLinearStreamData, type ICreateMultipleStreamData, type ICreateResult, type ICreateStreamData, type ICreateStreamExt, type ICreateStreamInstructions, type IFees, type IGetAllData, type IGetFeesData, type IGetOneData, type IInteractData, type IInteractStreamExt, type IMultiTransactionResult, type IPrepareCreateStreamExt, type IPrepareStreamExt, type IRecipient, type ISearchStreams, type ITopUpData, type ITopUpStreamExt, type ITransactionExtWithInstructions, type ITransactionResult, type ITransferData, type IUpdateData, type IWithdrawData, type InstructionGenerator, type LinearStream, MAX_SAFE_UNIX_TIME_VALUE, type MetadataRecipientHashMap, ORIGINAL_CONTRACT_SENDER_OFFSET, type OracleType, type OracleTypeName, PARTNERS_SCHEMA, PARTNER_ORACLE_PROGRAM_ID, PARTNER_SCHEMA, PROGRAM_ID, type PriceOracleType, REPOPULATED_METADATA_SEED, SOLANA_ERROR_MAP, SOLANA_ERROR_MATCH_REGEX, STREAMFLOW_TREASURY_PUBLIC_KEY, STREAM_STRUCT_OFFSETS, STREAM_STRUCT_OFFSET_CLOSED, STREAM_STRUCT_OFFSET_MINT, STREAM_STRUCT_OFFSET_OLD_METADATA_KEY, STREAM_STRUCT_OFFSET_RECIPIENT, STREAM_STRUCT_OFFSET_SENDER, SolanaStreamClient, type Stream, type StreamClientOptions, StreamDirection, StreamType, TEST_ORACLE_DISCRIMINATOR, TEST_ORACLE_SEED, TX_FINALITY_CONFIRMED, type TabulariumContract, type TestOracle, type TransactionSchedulingOptions, type UpdateTestOracleParams, WITHDRAWOR, WITHDRAWOR_PUBLIC_KEY, WITHDRAW_AVAILABLE_AMOUNT, buildStreamType, calculateTotalAmountToDeposit, calculateUnlockedAmount, cancelStreamInstruction, createClient, createStreamInstruction, createUncheckedStreamInstruction, decodeEndTime, decodeStream, deriveContractPDA, deriveEscrowPDA, deriveRepopulatedMetadataPDA, deriveTestOraclePDA, extractSolanaErrorCode, getMetadataKey, handleContractError, isAligned, isCliffCloseToDepositedAmount, isCreateAlignedStreamData, isDynamicLock, isTokenLock, isVesting, sendAndConfirmStreamRawTransaction, signAllTransactionWithRecipients, _default as timelockIDL, topupStreamInstruction, transferStreamInstruction, transformContract, updateStreamInstruction, withdrawStreamInstruction };
@@ -3,7 +3,7 @@ import bs58 from 'bs58';
3
3
  import { Buffer } from 'buffer';
4
4
  import { NATIVE_MINT, ASSOCIATED_TOKEN_PROGRAM_ID } from '@solana/spl-token';
5
5
  import { PublicKey, TransactionInstruction, Connection, Keypair, SYSVAR_RENT_PUBKEY, SystemProgram, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
6
- import { ICluster, getNumberFromBN, isSignerKeypair, isSignerWallet, executeTransaction, ContractError, buildSendThrottler, assertHasPublicKey, prepareWrappedAccount, prepareTransaction, signAndExecuteTransaction, invariant, getMintAndProgram, prepareBaseInstructions, getBN, ata, createVersionedTransaction, executeMultipleTransactions, getMultipleAccountsInfoBatched, getProgramAccounts, checkOrCreateAtaBatch } from '@streamflow/common';
6
+ import { ICluster, getNumberFromBN, isSignerKeypair, isSignerWallet, executeTransaction, ContractError, buildSendThrottler, assertHasPublicKey, prepareWrappedAccount, prepareTransaction, signAndExecuteTransaction, invariant, getMintAndProgram, prepareBaseInstructions, getBN, ata, createVersionedTransaction, executeMultipleTransactions, getMultipleAccountsInfoBatched, getProgramAccounts, isDev, checkOrCreateAtaBatch, pk } from '@streamflow/common';
7
7
  export { ContractError, ICluster, getBN, getNumberFromBN } from '@streamflow/common';
8
8
  import * as borsh from 'borsh';
9
9
  import { Program } from '@coral-xyz/anchor';
@@ -2517,6 +2517,146 @@ var deriveRepopulatedMetadataPDA = (programId, streamMetadata) => {
2517
2517
  return PublicKey.findProgramAddressSync([REPOPULATED_METADATA_SEED, streamMetadata.toBuffer()], programId)[0];
2518
2518
  };
2519
2519
 
2520
+ // solana/api-public/client.ts
2521
+ var DEFAULT_API_URL = "https://api-public.streamflow.finance";
2522
+ var DEFAULT_DEVNET_API_URL = "https://api-public-staging.streamflow.finance";
2523
+ var createClient = (options) => {
2524
+ const apiUrl = options?.apiUrl ?? options?.cluster === "mainnet" ? DEFAULT_API_URL : DEFAULT_DEVNET_API_URL;
2525
+ const fetchFn = options?.fetchFn ?? fetch;
2526
+ const fetchResource = async (url, options2) => {
2527
+ const res = await fetchFn(url, {
2528
+ method: "GET",
2529
+ headers: { "Content-Type": "application/json" },
2530
+ ...{}
2531
+ });
2532
+ if (!res.ok) {
2533
+ const text = await res.text().catch(() => "");
2534
+ throw new Error(`Tabularium API error`, {
2535
+ cause: new Error(`: ${res.status} ${res.statusText}${text ? ` - ${text}` : ""}`)
2536
+ });
2537
+ }
2538
+ return res.json();
2539
+ };
2540
+ return {
2541
+ getContracts: async (opts) => {
2542
+ const params = new URLSearchParams();
2543
+ if (opts?.sender) params.set("sender", opts.sender);
2544
+ if (opts?.recipient) params.set("recipient", opts.recipient);
2545
+ const url = `${apiUrl}/v2/api/contracts/tabularium/${params.toString() ? `?${params.toString()}` : ""}`;
2546
+ return fetchResource(url);
2547
+ },
2548
+ getContract: async (address) => {
2549
+ const url = `${apiUrl}/v2/api/contracts/tabularium/${encodeURIComponent(address)}`;
2550
+ return fetchResource(url);
2551
+ }
2552
+ };
2553
+ };
2554
+ var isoToUnix = (iso) => {
2555
+ if (!iso) return 0;
2556
+ const time = new Date(iso).getTime();
2557
+ return Number.isNaN(time) ? 0 : Math.floor(time / 1e3);
2558
+ };
2559
+ var toBN = (value) => new BN3(value);
2560
+ var mapOracleType = (apiType) => {
2561
+ if (!apiType) return { none: {} };
2562
+ const mapping = {
2563
+ TEST: { test: {} },
2564
+ PYTH: { pyth: {} },
2565
+ SWITCHBOARD: { switchboard: {} }
2566
+ };
2567
+ return mapping[apiType] ?? { none: {} };
2568
+ };
2569
+ async function toDecodedStream(schema) {
2570
+ const mint = pk(schema.mint);
2571
+ const sender = pk(schema.sender);
2572
+ const recipient = pk(schema.recipient);
2573
+ const partner = schema.partner ? pk(schema.partner) : sender;
2574
+ const [senderTokens, recipientTokens, partnerTokens, streamflowTreasuryTokens] = await Promise.all([
2575
+ ata(mint, sender),
2576
+ ata(mint, recipient),
2577
+ ata(mint, partner),
2578
+ ata(mint, STREAMFLOW_TREASURY_PUBLIC_KEY)
2579
+ ]);
2580
+ return {
2581
+ magic: toBN(4),
2582
+ version: toBN(4),
2583
+ createdAt: toBN(isoToUnix(schema.createdDt)),
2584
+ withdrawnAmount: toBN(schema.claimedAmount),
2585
+ canceledAt: toBN(isoToUnix(schema.canceledDt)),
2586
+ end: toBN(isoToUnix(schema.endDt)),
2587
+ lastWithdrawnAt: toBN(isoToUnix(schema.lastClaimedDt)),
2588
+ sender,
2589
+ senderTokens,
2590
+ recipient,
2591
+ recipientTokens,
2592
+ mint,
2593
+ escrowTokens: schema.escrow ? pk(schema.escrow) : PublicKey.default,
2594
+ streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
2595
+ streamflowTreasuryTokens,
2596
+ streamflowFeeTotal: toBN(schema.streamflowFee),
2597
+ streamflowFeeWithdrawn: toBN(schema.streamflowFeeWithdrawn),
2598
+ streamflowFeePercent: parseFloat(schema.streamflowFeePercentage) || 0,
2599
+ partnerFeeTotal: toBN(schema.partnerFee),
2600
+ partnerFeeWithdrawn: toBN(schema.partnerFeeWithdrawn),
2601
+ partnerFeePercent: parseFloat(schema.partnerFeePercentage) || 0,
2602
+ partner,
2603
+ partnerTokens,
2604
+ start: toBN(isoToUnix(schema.startDt)),
2605
+ depositedAmount: toBN(schema.amount),
2606
+ period: toBN(schema.period),
2607
+ amountPerPeriod: toBN(schema.amountPerPeriod),
2608
+ cliff: toBN(isoToUnix(schema.startDt)),
2609
+ cliffAmount: toBN(schema.cliffAmount),
2610
+ cancelableBySender: schema.isCancelableBySender,
2611
+ cancelableByRecipient: schema.isCancelableByRecipient,
2612
+ automaticWithdrawal: schema.hasAutoClaim,
2613
+ transferableBySender: schema.isTransferableBySender,
2614
+ transferableByRecipient: schema.isTransferableByRecipient,
2615
+ canTopup: schema.canTopup,
2616
+ name: schema.name,
2617
+ withdrawFrequency: toBN(schema.autoClaimPeriod),
2618
+ closed: schema.isClosed,
2619
+ currentPauseStart: toBN(0),
2620
+ pauseCumulative: toBN(schema.pauseCumulative),
2621
+ lastRateChangeTime: toBN(isoToUnix(schema.lastRateUpdateDt)),
2622
+ fundsUnlockedAtLastRateChange: toBN(schema.amountUnlockedAtLastRateUpdate),
2623
+ oldMetadata: PublicKey.default
2624
+ };
2625
+ }
2626
+ function toPrecisionBN(value, precision = ALIGNED_PRECISION_FACTOR_POW2) {
2627
+ return getBN(typeof value === "number" ? value : parseFloat(value), precision);
2628
+ }
2629
+ function toAlignedProxy(dynamic) {
2630
+ const proxy = {
2631
+ sender: pk(dynamic.sender),
2632
+ minPrice: toPrecisionBN(dynamic.minPrice),
2633
+ maxPrice: toPrecisionBN(dynamic.maxPrice),
2634
+ minPercentage: toPrecisionBN(dynamic.minPercentage),
2635
+ maxPercentage: toPrecisionBN(dynamic.maxPercentage),
2636
+ priceOracleType: mapOracleType(dynamic.priceOracleType),
2637
+ priceOracle: dynamic.priceOracleAddress ? pk(dynamic.priceOracleAddress) : PublicKey.default,
2638
+ tickSize: toPrecisionBN(dynamic.tickSize),
2639
+ initialAmountPerPeriod: toBN(dynamic.initialAmountPerPeriod),
2640
+ initialPrice: toPrecisionBN(dynamic.initialPrice),
2641
+ lastPrice: toPrecisionBN(dynamic.lastPrice),
2642
+ lastAmountUpdateTime: toBN(isoToUnix(dynamic.expiryDt)),
2643
+ initialNetAmount: toBN(dynamic.initialAmount),
2644
+ expiryTime: toBN(isoToUnix(dynamic.expiryDt)),
2645
+ expiryPercentage: toPrecisionBN(dynamic.expiryPercentage),
2646
+ floorPrice: toPrecisionBN(dynamic.floorPrice),
2647
+ streamCanceledTime: dynamic.streamCanceledTime ? toBN(dynamic.streamCanceledTime) : toBN(0)
2648
+ };
2649
+ return proxy;
2650
+ }
2651
+ var transformContract = async (schema) => {
2652
+ const decodedStream = await toDecodedStream(schema);
2653
+ if (schema.dynamicContract) {
2654
+ const alignedProxy = toAlignedProxy(schema.dynamicContract);
2655
+ return new AlignedContract(decodedStream, alignedProxy);
2656
+ }
2657
+ return new Contract(decodedStream);
2658
+ };
2659
+
2520
2660
  // solana/StreamClient.ts
2521
2661
  var METADATA_ACC_SIZE = 1104;
2522
2662
  var ALIGNED_METADATA_ACC_SIZE = 320;
@@ -2559,6 +2699,9 @@ var SolanaStreamClient = class {
2559
2699
  address: streamflow_aligned_unlocks_default.address
2560
2700
  };
2561
2701
  this.alignedProxyProgram = new Program(alignedUnlocksProgram, { connection: this.connection });
2702
+ this.apiClient = createClient(
2703
+ typeof optionsOrClusterUrl === "object" && optionsOrClusterUrl.cluster !== ICluster.Mainnet ? { cluster: "devnet" } : { cluster: "mainnet" }
2704
+ );
2562
2705
  }
2563
2706
  getConnection() {
2564
2707
  return this.connection;
@@ -3338,7 +3481,7 @@ var SolanaStreamClient = class {
3338
3481
  throw new Error("Impossible to cancel a stream contract that does not exist");
3339
3482
  }
3340
3483
  const decoded = decodeStream(account.data);
3341
- const isAlignedUnlock = this.isAlignedUnlock(streamPublicKey, decoded.sender, decoded.oldMetadata);
3484
+ const isAlignedUnlock = this.isAlignedUnlock(streamPublicKey, decoded.sender);
3342
3485
  const ixs = isAlignedUnlock ? await this.prepareCancelAlignedUnlockInstructions(cancelData, extParams) : await this.prepareCancelLinearStream(cancelData, extParams);
3343
3486
  return ixs;
3344
3487
  }
@@ -3574,17 +3717,21 @@ var SolanaStreamClient = class {
3574
3717
  }
3575
3718
  ]
3576
3719
  });
3577
- if (migrated.length === 0) {
3578
- throw new Error("Couldn't get account info.");
3720
+ if (migrated.length > 0) {
3721
+ return this.decodeStreamAccount(migrated[0].pubkey, migrated[0].account.data);
3722
+ }
3723
+ try {
3724
+ const contract = await this.apiClient.getContract(id);
3725
+ return await transformContract(contract);
3726
+ } catch (cause) {
3727
+ throw new Error(`Couldn't get account info from chain or Tabularium`, { cause });
3579
3728
  }
3580
- return this.decodeStreamAccount(migrated[0].pubkey, migrated[0].account.data);
3581
3729
  }
3582
3730
  async decodeStreamAccount(pubkey, data) {
3583
3731
  const stream = decodeStream(data);
3584
- const metadataKey = getMetadataKey(pubkey, stream.oldMetadata);
3585
- if (this.isAlignedUnlock(pubkey, stream.sender, stream.oldMetadata)) {
3732
+ if (this.isAlignedUnlock(pubkey, stream.sender)) {
3586
3733
  const alignedProxy = await this.alignedProxyProgram.account.contract.fetch(
3587
- deriveContractPDA(this.alignedProxyProgram.programId, metadataKey)
3734
+ deriveContractPDA(this.alignedProxyProgram.programId, pubkey)
3588
3735
  );
3589
3736
  if (!alignedProxy) {
3590
3737
  throw new Error("Couldn't get proxy account info.");
@@ -3625,9 +3772,7 @@ var SolanaStreamClient = class {
3625
3772
  const streams = {};
3626
3773
  const alignedStreamsPubKeys = Object.keys(streamRecord);
3627
3774
  const alignedProxyPDAs = alignedStreamsPubKeys.map((streamPubKey) => {
3628
- const pubkey = new PublicKey(streamPubKey);
3629
- const metadataKey = getMetadataKey(pubkey, streamRecord[streamPubKey].oldMetadata);
3630
- return deriveContractPDA(this.alignedProxyProgram.programId, metadataKey);
3775
+ return deriveContractPDA(this.alignedProxyProgram.programId, new PublicKey(streamPubKey));
3631
3776
  });
3632
3777
  const alignedProxyAccounts = await getMultipleAccountsInfoBatched(this.connection, alignedProxyPDAs);
3633
3778
  alignedProxyAccounts.forEach((account, index) => {
@@ -3650,7 +3795,8 @@ var SolanaStreamClient = class {
3650
3795
  async get({
3651
3796
  address,
3652
3797
  type = "all" /* All */,
3653
- direction = "all" /* All */
3798
+ direction = "all" /* All */,
3799
+ filters
3654
3800
  }) {
3655
3801
  const publicKey = new PublicKey(address);
3656
3802
  let streams = {};
@@ -3680,7 +3826,7 @@ var SolanaStreamClient = class {
3680
3826
  const allIncomingStreams = allIncomingAccounts.map((account) => decodeStream(account.account.data));
3681
3827
  const alignedDecoded = {};
3682
3828
  allIncomingAccounts.forEach((account, index) => {
3683
- if (this.isAlignedUnlock(account.pubkey, allIncomingStreams[index].sender, allIncomingStreams[index].oldMetadata)) {
3829
+ if (this.isAlignedUnlock(account.pubkey, allIncomingStreams[index].sender)) {
3684
3830
  alignedDecoded[account.pubkey.toBase58()] = allIncomingStreams[index];
3685
3831
  } else {
3686
3832
  streams[account.pubkey.toBase58()] = new Contract(allIncomingStreams[index]);
@@ -3691,6 +3837,10 @@ var SolanaStreamClient = class {
3691
3837
  streams = { ...streams, ...incomingAlignedStreams };
3692
3838
  }
3693
3839
  }
3840
+ if (filters?.closed) {
3841
+ const closedStreams = await this.getClosedStreams(address, direction);
3842
+ streams = { ...streams, ...closedStreams };
3843
+ }
3694
3844
  const sortedStreams = Object.entries(streams).sort(([, stream1], [, stream2]) => stream2.start - stream1.start);
3695
3845
  if (type === "all" /* All */) return sortedStreams;
3696
3846
  return sortedStreams.filter((stream) => stream[1].type === type);
@@ -3725,9 +3875,8 @@ var SolanaStreamClient = class {
3725
3875
  collectAlignedEntries(decoded) {
3726
3876
  const entries = [];
3727
3877
  decoded.forEach(({ pubkey, stream }, index) => {
3728
- if (this.isAlignedUnlock(pubkey, stream.sender, stream.oldMetadata)) {
3729
- const metadataKey = getMetadataKey(pubkey, stream.oldMetadata);
3730
- entries.push({ index, pda: deriveContractPDA(this.alignedProxyProgram.programId, metadataKey) });
3878
+ if (this.isAlignedUnlock(pubkey, stream.sender)) {
3879
+ entries.push({ index, pda: deriveContractPDA(this.alignedProxyProgram.programId, pubkey) });
3731
3880
  }
3732
3881
  });
3733
3882
  return entries;
@@ -3788,7 +3937,7 @@ var SolanaStreamClient = class {
3788
3937
  const escrow = await this.connection.getAccountInfo(streamPublicKey);
3789
3938
  invariant(escrow, "Couldn't get account info");
3790
3939
  const decoded = decodeStream(escrow.data);
3791
- const isAlignedUnlock = this.isAlignedUnlock(streamPublicKey, decoded.sender, decoded.oldMetadata);
3940
+ const isAlignedUnlock = this.isAlignedUnlock(streamPublicKey, decoded.sender);
3792
3941
  if (isAlignedUnlock && (data.enableAutomaticWithdrawal !== void 0 || data.amountPerPeriod !== void 0)) {
3793
3942
  throw new Error("Automatic withdrawal and rate update are not possible in price-based vesting!");
3794
3943
  }
@@ -3882,9 +4031,8 @@ var SolanaStreamClient = class {
3882
4031
  * Utility function that checks whether the associated stream address is an aligned unlock contract, indicated by whether the sender/creator is a PDA.
3883
4032
  * For migrated streams, the PDA was derived from the old metadata key.
3884
4033
  */
3885
- isAlignedUnlock(streamPublicKey, senderPublicKey, oldMetadata) {
3886
- const metadataKey = oldMetadata ? getMetadataKey(streamPublicKey, oldMetadata) : streamPublicKey;
3887
- const pda = deriveContractPDA(this.alignedProxyProgram.programId, metadataKey);
4034
+ isAlignedUnlock(streamPublicKey, senderPublicKey) {
4035
+ const pda = deriveContractPDA(this.alignedProxyProgram.programId, streamPublicKey);
3888
4036
  return senderPublicKey.equals(pda);
3889
4037
  }
3890
4038
  async flatBuildCreateMultipleTransactionInstructions(data, extParams) {
@@ -3902,6 +4050,40 @@ var SolanaStreamClient = class {
3902
4050
  )
3903
4051
  };
3904
4052
  }
4053
+ /**
4054
+ * Gets closed streams for a given owner and direction
4055
+ * @param owner - Owner address
4056
+ * @param direction - Stream direction
4057
+ * @returns Record of closed streams
4058
+ */
4059
+ async getClosedStreams(owner, direction = "all" /* All */) {
4060
+ const streams = {};
4061
+ try {
4062
+ const tabulariumContracts = await this.apiClient.getContracts({
4063
+ sender: direction !== "incoming" /* Incoming */ ? owner : void 0,
4064
+ recipient: direction !== "outgoing" /* Outgoing */ ? owner : void 0
4065
+ });
4066
+ for (const contract of tabulariumContracts) {
4067
+ if (!streams[contract.address]) {
4068
+ try {
4069
+ const transformed = await transformContract(contract);
4070
+ streams[contract.address] = transformed;
4071
+ } catch (cause) {
4072
+ if (isDev) {
4073
+ throw new Error(`Failed to transform contract ${contract.address}:`, { cause });
4074
+ }
4075
+ console.warn(new Error(`Failed to transform contract ${contract.address}:`, { cause }));
4076
+ }
4077
+ }
4078
+ }
4079
+ } catch (cause) {
4080
+ if (isDev) {
4081
+ throw new Error("Failed to get data from the service", { cause });
4082
+ }
4083
+ console.warn(new Error("Failed to get data from the service", { cause }));
4084
+ }
4085
+ return streams;
4086
+ }
3905
4087
  /**
3906
4088
  * Utility function to generate metadata for a Contract or return existing Pubkey
3907
4089
  */
@@ -4361,6 +4543,6 @@ var timelockIDL_default = {
4361
4543
  ]
4362
4544
  };
4363
4545
 
4364
- export { AIRDROP_AMOUNT, AIRDROP_TEST_TOKEN, ALIGNED_COMPUTE_LIMIT, ALIGNED_PRECISION_FACTOR_POW2 as ALIGNED_PRECISION_FACTOR_POW, ALIGNED_UNLOCKS_PROGRAM_ID, AlignedContract, AlignedProxyErrorCode, CONTRACT_DISCRIMINATOR, CONTRACT_SEED, CREATE_PARAMS_PADDING, Contract, ContractErrorCode, DEFAULT_AUTO_CLAIM_FEE_SOL, DEFAULT_CREATION_FEE_SOL, DEFAULT_STREAMFLOW_FEE, ESCROW_SEED, FEES_METADATA_SEED, FEE_ORACLE_PUBLIC_KEY, MAX_SAFE_UNIX_TIME_VALUE2 as MAX_SAFE_UNIX_TIME_VALUE, ORIGINAL_CONTRACT_SENDER_OFFSET, PARTNERS_SCHEMA, PARTNER_ORACLE_PROGRAM_ID, PARTNER_SCHEMA, PROGRAM_ID, REPOPULATED_METADATA_SEED, SOLANA_ERROR_MAP, SOLANA_ERROR_MATCH_REGEX, STREAMFLOW_TREASURY_PUBLIC_KEY, STREAM_STRUCT_OFFSETS, STREAM_STRUCT_OFFSET_CLOSED, STREAM_STRUCT_OFFSET_MINT, STREAM_STRUCT_OFFSET_OLD_METADATA_KEY, STREAM_STRUCT_OFFSET_RECIPIENT, STREAM_STRUCT_OFFSET_SENDER, SolanaStreamClient, StreamDirection, StreamType, TEST_ORACLE_DISCRIMINATOR, TEST_ORACLE_SEED, TX_FINALITY_CONFIRMED, WITHDRAWOR, WITHDRAWOR_PUBLIC_KEY, WITHDRAW_AVAILABLE_AMOUNT, buildStreamType, calculateTotalAmountToDeposit, calculateUnlockedAmount, cancelStreamInstruction, createStreamInstruction, createUncheckedStreamInstruction, decodeEndTime, decodeStream, deriveContractPDA, deriveEscrowPDA, deriveRepopulatedMetadataPDA, deriveTestOraclePDA, extractSolanaErrorCode, getMetadataKey, handleContractError, isAligned, isCliffCloseToDepositedAmount, isCreateAlignedStreamData, isDynamicLock, isTokenLock, isVesting, sendAndConfirmStreamRawTransaction, signAllTransactionWithRecipients, timelockIDL_default as timelockIDL, topupStreamInstruction, transferStreamInstruction, updateStreamInstruction, withdrawStreamInstruction };
4546
+ export { AIRDROP_AMOUNT, AIRDROP_TEST_TOKEN, ALIGNED_COMPUTE_LIMIT, ALIGNED_PRECISION_FACTOR_POW2 as ALIGNED_PRECISION_FACTOR_POW, ALIGNED_UNLOCKS_PROGRAM_ID, AlignedContract, AlignedProxyErrorCode, CONTRACT_DISCRIMINATOR, CONTRACT_SEED, CREATE_PARAMS_PADDING, Contract, ContractErrorCode, DEFAULT_AUTO_CLAIM_FEE_SOL, DEFAULT_CREATION_FEE_SOL, DEFAULT_STREAMFLOW_FEE, ESCROW_SEED, FEES_METADATA_SEED, FEE_ORACLE_PUBLIC_KEY, MAX_SAFE_UNIX_TIME_VALUE2 as MAX_SAFE_UNIX_TIME_VALUE, ORIGINAL_CONTRACT_SENDER_OFFSET, PARTNERS_SCHEMA, PARTNER_ORACLE_PROGRAM_ID, PARTNER_SCHEMA, PROGRAM_ID, REPOPULATED_METADATA_SEED, SOLANA_ERROR_MAP, SOLANA_ERROR_MATCH_REGEX, STREAMFLOW_TREASURY_PUBLIC_KEY, STREAM_STRUCT_OFFSETS, STREAM_STRUCT_OFFSET_CLOSED, STREAM_STRUCT_OFFSET_MINT, STREAM_STRUCT_OFFSET_OLD_METADATA_KEY, STREAM_STRUCT_OFFSET_RECIPIENT, STREAM_STRUCT_OFFSET_SENDER, SolanaStreamClient, StreamDirection, StreamType, TEST_ORACLE_DISCRIMINATOR, TEST_ORACLE_SEED, TX_FINALITY_CONFIRMED, WITHDRAWOR, WITHDRAWOR_PUBLIC_KEY, WITHDRAW_AVAILABLE_AMOUNT, buildStreamType, calculateTotalAmountToDeposit, calculateUnlockedAmount, cancelStreamInstruction, createClient, createStreamInstruction, createUncheckedStreamInstruction, decodeEndTime, decodeStream, deriveContractPDA, deriveEscrowPDA, deriveRepopulatedMetadataPDA, deriveTestOraclePDA, extractSolanaErrorCode, getMetadataKey, handleContractError, isAligned, isCliffCloseToDepositedAmount, isCreateAlignedStreamData, isDynamicLock, isTokenLock, isVesting, sendAndConfirmStreamRawTransaction, signAllTransactionWithRecipients, timelockIDL_default as timelockIDL, topupStreamInstruction, transferStreamInstruction, transformContract, updateStreamInstruction, withdrawStreamInstruction };
4365
4547
  //# sourceMappingURL=index.js.map
4366
4548
  //# sourceMappingURL=index.js.map