@streamflow/stream 7.0.0-alpha.12 → 7.0.0-alpha.13

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.
Files changed (37) hide show
  1. package/README.md +10 -5
  2. package/dist/cjs/common/constants.js +2 -1
  3. package/dist/cjs/common/contractUtils.js +17 -1
  4. package/dist/cjs/common/types.js +30 -1
  5. package/dist/cjs/solana/StreamClient.js +244 -99
  6. package/dist/cjs/solana/constants.js +29 -1
  7. package/dist/cjs/solana/descriptor/idl/streamflow_aligned_unlocks.json +1471 -0
  8. package/dist/cjs/solana/descriptor/streamflow_aligned_unlocks.js +2 -0
  9. package/dist/cjs/solana/index.js +2 -1
  10. package/dist/cjs/solana/lib/derive-accounts.js +17 -0
  11. package/dist/cjs/solana/{utils.js → lib/utils.js} +2 -2
  12. package/dist/cjs/solana/types.js +25 -2
  13. package/dist/esm/aptos/types.d.ts +2 -2
  14. package/dist/esm/common/constants.d.ts +1 -0
  15. package/dist/esm/common/constants.js +1 -0
  16. package/dist/esm/common/contractUtils.d.ts +4 -1
  17. package/dist/esm/common/contractUtils.js +13 -0
  18. package/dist/esm/common/types.d.ts +104 -49
  19. package/dist/esm/common/types.js +29 -0
  20. package/dist/esm/evm/types.d.ts +2 -2
  21. package/dist/esm/solana/StreamClient.d.ts +20 -14
  22. package/dist/esm/solana/StreamClient.js +247 -101
  23. package/dist/esm/solana/constants.d.ts +14 -0
  24. package/dist/esm/solana/constants.js +29 -1
  25. package/dist/esm/solana/descriptor/idl/streamflow_aligned_unlocks.json +1471 -0
  26. package/dist/esm/solana/descriptor/streamflow_aligned_unlocks.d.ts +1272 -0
  27. package/dist/esm/solana/descriptor/streamflow_aligned_unlocks.js +1 -0
  28. package/dist/esm/solana/index.d.ts +2 -1
  29. package/dist/esm/solana/index.js +2 -1
  30. package/dist/esm/solana/lib/derive-accounts.d.ts +4 -0
  31. package/dist/esm/solana/lib/derive-accounts.js +11 -0
  32. package/dist/esm/solana/{utils.d.ts → lib/utils.d.ts} +1 -1
  33. package/dist/esm/solana/{utils.js → lib/utils.js} +2 -2
  34. package/dist/esm/solana/types.d.ts +31 -3
  35. package/dist/esm/solana/types.js +30 -2
  36. package/dist/esm/sui/types.d.ts +2 -2
  37. package/package.json +5 -4
@@ -5,20 +5,26 @@ import { ASSOCIATED_TOKEN_PROGRAM_ID, NATIVE_MINT } from "@solana/spl-token";
5
5
  import { Connection, Keypair, PublicKey, SystemProgram, SYSVAR_RENT_PUBKEY, TransactionMessage, VersionedTransaction, } from "@solana/web3.js";
6
6
  import { ata, checkOrCreateAtaBatch, signAndExecuteTransaction, getProgramAccounts, prepareWrappedAccount, prepareTransaction, prepareBaseInstructions, getMintAndProgram, executeTransaction, executeMultipleTransactions, buildSendThrottler, } from "@streamflow/common/solana";
7
7
  import * as borsh from "borsh";
8
- import { Contract, } from "./types.js";
9
- import { decodeStream, extractSolanaErrorCode, sendAndConfirmStreamRawTransaction, signAllTransactionWithRecipients, } from "./utils.js";
10
- import { PROGRAM_ID, STREAMFLOW_TREASURY_PUBLIC_KEY, STREAM_STRUCT_OFFSET_RECIPIENT, STREAM_STRUCT_OFFSET_SENDER, TX_FINALITY_CONFIRMED, WITHDRAWOR_PUBLIC_KEY, FEE_ORACLE_PUBLIC_KEY, DEFAULT_STREAMFLOW_FEE, PARTNER_ORACLE_PROGRAM_ID, FEES_METADATA_SEED, PARTNERS_SCHEMA, STREAM_STRUCT_OFFSETS, } from "./constants.js";
8
+ import { Program } from "@coral-xyz/anchor";
9
+ import { getBN } from "@streamflow/common";
10
+ import { Contract, AlignedContract, } from "./types.js";
11
+ import { decodeStream, extractSolanaErrorCode, sendAndConfirmStreamRawTransaction, signAllTransactionWithRecipients, } from "./lib/utils.js";
12
+ import { PROGRAM_ID, STREAMFLOW_TREASURY_PUBLIC_KEY, STREAM_STRUCT_OFFSET_RECIPIENT, STREAM_STRUCT_OFFSET_SENDER, TX_FINALITY_CONFIRMED, WITHDRAWOR_PUBLIC_KEY, FEE_ORACLE_PUBLIC_KEY, DEFAULT_STREAMFLOW_FEE, PARTNER_ORACLE_PROGRAM_ID, FEES_METADATA_SEED, PARTNERS_SCHEMA, STREAM_STRUCT_OFFSETS, ORIGINAL_CONTRACT_SENDER_OFFSET, ALIGNED_PRECISION_FACTOR_POW, ALIGNED_COMPUTE_LIMIT, } from "./constants.js";
11
13
  import { withdrawStreamInstruction, cancelStreamInstruction, transferStreamInstruction, topupStreamInstruction, createStreamInstruction, createUncheckedStreamInstruction, updateStreamInstruction, } from "./instructions.js";
12
14
  import { ICluster, StreamDirection, StreamType, } from "../common/types.js";
13
15
  import { BaseStreamClient } from "../common/BaseStreamClient.js";
14
16
  import { calculateTotalAmountToDeposit } from "../common/utils.js";
15
17
  import { WITHDRAW_AVAILABLE_AMOUNT } from "../common/constants.js";
18
+ import StreamflowAlignedUnlocksIDL from "./descriptor/idl/streamflow_aligned_unlocks.json";
19
+ import { deriveContractPDA, deriveEscrowPDA, deriveTestOraclePDA } from "./lib/derive-accounts.js";
20
+ import { isCreateAlignedStreamData } from "../common/contractUtils.js";
16
21
  const METADATA_ACC_SIZE = 1104;
17
22
  export class SolanaStreamClient extends BaseStreamClient {
18
23
  connection;
19
24
  programId;
20
25
  commitment;
21
26
  sendThrottler;
27
+ alignedProxyProgram;
22
28
  /**
23
29
  * Create Stream instance
24
30
  */
@@ -28,6 +34,11 @@ export class SolanaStreamClient extends BaseStreamClient {
28
34
  this.connection = new Connection(clusterUrl, this.commitment);
29
35
  this.programId = programId !== "" ? new PublicKey(programId) : new PublicKey(PROGRAM_ID[cluster]);
30
36
  this.sendThrottler = sendThrottler ?? buildSendThrottler(sendRate);
37
+ const alignedUnlocksProgram = {
38
+ ...StreamflowAlignedUnlocksIDL,
39
+ address: StreamflowAlignedUnlocksIDL.address,
40
+ };
41
+ this.alignedProxyProgram = new Program(alignedUnlocksProgram, { connection: this.connection });
31
42
  }
32
43
  getConnection() {
33
44
  return this.connection;
@@ -43,7 +54,20 @@ export class SolanaStreamClient extends BaseStreamClient {
43
54
  * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
44
55
  */
45
56
  async create(data, extParams) {
57
+ const { partner, amount } = data;
58
+ const { isNative, sender } = extParams;
59
+ const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
60
+ if (!sender.publicKey) {
61
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
62
+ }
46
63
  const { ixs, metadata, metadataPubKey } = await this.prepareCreateInstructions(data, extParams);
64
+ if (isNative) {
65
+ const totalFee = await this.getTotalFee({
66
+ address: partnerPublicKey.toString(),
67
+ });
68
+ const totalAmount = calculateTotalAmountToDeposit(amount, totalFee);
69
+ ixs.push(...(await prepareWrappedAccount(this.connection, sender.publicKey, totalAmount)));
70
+ }
47
71
  const { tx, hash, context } = await prepareTransaction(this.connection, ixs, extParams.sender.publicKey, undefined, metadata);
48
72
  const signature = await signAndExecuteTransaction(this.connection, extParams.sender, tx, {
49
73
  hash,
@@ -52,11 +76,80 @@ export class SolanaStreamClient extends BaseStreamClient {
52
76
  }, { sendThrottler: this.sendThrottler });
53
77
  return { ixs, txId: signature, metadataId: metadataPubKey.toBase58() };
54
78
  }
79
+ async prepareCreateInstructions(streamParams, extParams) {
80
+ const { ixs, metadata, metadataPubKey } = isCreateAlignedStreamData(streamParams)
81
+ ? await this.prepareCreateAlignedUnlockInstructions(streamParams, extParams)
82
+ : await this.prepareCreateStreamInstructions(streamParams, extParams);
83
+ return { ixs, metadata, metadataPubKey };
84
+ }
85
+ async prepareCreateAlignedUnlockInstructions(streamParams, extParams) {
86
+ const { tokenId: mint, start, period, cliff, canTopup, cancelableBySender, cancelableByRecipient, transferableBySender, transferableByRecipient, partner, recipient, cliffAmount, amountPerPeriod, amount: depositedAmount, name: streamName, minPrice, maxPercentage, minPercentage, maxPrice, skipInitial, tickSize, priceOracle, oracleType, } = streamParams;
87
+ const { isNative, sender, computeLimit, computePrice, metadataPubKeys } = extParams;
88
+ if (!sender.publicKey) {
89
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
90
+ }
91
+ if (!priceOracle && oracleType && oracleType !== "none") {
92
+ throw new Error("Price oracle is required for the specified oracle type");
93
+ }
94
+ const recipientPublicKey = new PublicKey(recipient);
95
+ const mintPublicKey = isNative ? NATIVE_MINT : new PublicKey(mint);
96
+ const metadata = !metadataPubKeys ? Keypair.generate() : undefined;
97
+ const metadataPubKey = metadata ? metadata.publicKey : metadataPubKeys[0];
98
+ const { tokenProgramId } = await getMintAndProgram(this.connection, mintPublicKey);
99
+ const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
100
+ const streamflowProgramPublicKey = new PublicKey(this.programId);
101
+ const escrowPDA = deriveEscrowPDA(streamflowProgramPublicKey, metadataPubKey);
102
+ const oracle = priceOracle ?? deriveTestOraclePDA(this.alignedProxyProgram.programId, mintPublicKey, sender.publicKey);
103
+ const ixs = prepareBaseInstructions(this.connection, {
104
+ computePrice,
105
+ computeLimit: computeLimit ?? ALIGNED_COMPUTE_LIMIT,
106
+ });
107
+ const encodedUIntArray = new TextEncoder().encode(streamName);
108
+ const streamNameArray = Array.from(encodedUIntArray);
109
+ const createIx = await this.alignedProxyProgram.methods
110
+ .create({
111
+ startTime: new BN(start),
112
+ netAmountDeposited: depositedAmount,
113
+ period: new BN(period),
114
+ amountPerPeriod: amountPerPeriod,
115
+ cliff: new BN(cliff),
116
+ cliffAmount: cliffAmount,
117
+ transferableBySender,
118
+ transferableByRecipient,
119
+ cancelableByRecipient,
120
+ cancelableBySender,
121
+ canTopup,
122
+ oracleType: (!!oracleType ? { [oracleType]: {} } : { none: {} }),
123
+ streamName: streamNameArray,
124
+ minPrice: getBN(minPrice, ALIGNED_PRECISION_FACTOR_POW),
125
+ maxPrice: getBN(maxPrice, ALIGNED_PRECISION_FACTOR_POW),
126
+ minPercentage: getBN(minPercentage, ALIGNED_PRECISION_FACTOR_POW),
127
+ maxPercentage: getBN(maxPercentage, ALIGNED_PRECISION_FACTOR_POW),
128
+ tickSize: new BN(tickSize || 1),
129
+ skipInitial: skipInitial ?? false,
130
+ })
131
+ .accountsPartial({
132
+ sender: sender.publicKey,
133
+ streamMetadata: metadataPubKey,
134
+ escrowTokens: escrowPDA,
135
+ mint: mintPublicKey,
136
+ partner: partnerPublicKey,
137
+ recipient: recipientPublicKey,
138
+ withdrawor: WITHDRAWOR_PUBLIC_KEY,
139
+ feeOracle: FEE_ORACLE_PUBLIC_KEY,
140
+ priceOracle: oracle,
141
+ tokenProgram: tokenProgramId,
142
+ streamflowProgram: this.programId,
143
+ })
144
+ .instruction();
145
+ ixs.push(createIx);
146
+ return { ixs, metadata, metadataPubKey };
147
+ }
55
148
  /**
56
149
  * Creates a new stream/vesting contract.
57
150
  * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
58
151
  */
59
- async prepareCreateInstructions({ recipient, tokenId: mint, start, amount: depositedAmount, period, cliff, cliffAmount, amountPerPeriod, name, canPause, canUpdateRate, canTopup, cancelableBySender, cancelableByRecipient, transferableBySender, transferableByRecipient, automaticWithdrawal = false, withdrawalFrequency = 0, partner, }, { sender, metadataPubKeys, isNative = false, computePrice, computeLimit }) {
152
+ async prepareCreateStreamInstructions({ recipient, tokenId: mint, start, amount: depositedAmount, period, cliff, cliffAmount, amountPerPeriod, name, canPause, canUpdateRate, canTopup, cancelableBySender, cancelableByRecipient, transferableBySender, transferableByRecipient, automaticWithdrawal = false, withdrawalFrequency = 0, partner, }, { sender, metadataPubKeys, isNative = false, computePrice, computeLimit }) {
60
153
  if (!sender.publicKey) {
61
154
  throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
62
155
  }
@@ -74,13 +167,6 @@ export class SolanaStreamClient extends BaseStreamClient {
74
167
  const streamflowTreasuryTokens = await ata(mintPublicKey, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
75
168
  const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
76
169
  const partnerTokens = await ata(mintPublicKey, partnerPublicKey, tokenProgramId);
77
- if (isNative) {
78
- const totalFee = await this.getTotalFee({
79
- address: partnerPublicKey.toString(),
80
- });
81
- const totalAmount = calculateTotalAmountToDeposit(depositedAmount, totalFee);
82
- ixs.push(...(await prepareWrappedAccount(this.connection, sender.publicKey, totalAmount)));
83
- }
84
170
  ixs.push(createStreamInstruction({
85
171
  start: new BN(start),
86
172
  depositedAmount,
@@ -210,26 +296,32 @@ export class SolanaStreamClient extends BaseStreamClient {
210
296
  * Creates multiple stream/vesting contracts.
211
297
  * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
212
298
  */
213
- async createMultiple(data, { sender, metadataPubKeys, isNative = false, computePrice, computeLimit }) {
214
- const { recipients } = data;
215
- if (!sender.publicKey) {
216
- throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
217
- }
299
+ async createMultiple(data, extParams) {
300
+ const { recipients, ...streamParams } = data;
301
+ const { sender, metadataPubKeys: metadataPubKeysExt, isNative, computePrice, computeLimit } = extParams;
218
302
  const metadatas = [];
219
303
  const metadataToRecipient = {};
220
304
  const errors = [];
221
305
  const signatures = [];
222
306
  const batch = [];
223
307
  const instructionsBatch = [];
224
- metadataPubKeys = metadataPubKeys || [];
308
+ const metadataPubKeys = metadataPubKeysExt || [];
309
+ if (recipients.length === 0) {
310
+ throw new Error("Recipients array is empty!");
311
+ }
312
+ if (!sender.publicKey) {
313
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
314
+ }
225
315
  for (let i = 0; i < recipients.length; i++) {
226
316
  const recipientData = recipients[i];
227
- const { ixs, metadata, metadataPubKey } = await this.prepareStreamInstructions(recipientData, data, {
317
+ const createStreamData = { ...streamParams, ...recipientData };
318
+ const createStreamExtParams = {
228
319
  sender,
229
320
  metadataPubKeys: metadataPubKeys[i] ? [metadataPubKeys[i]] : undefined,
230
321
  computePrice,
231
322
  computeLimit,
232
- });
323
+ };
324
+ const { ixs, metadata, metadataPubKey } = await this.prepareCreateInstructions(createStreamData, createStreamExtParams);
233
325
  metadataToRecipient[metadataPubKey.toBase58()] = recipientData;
234
326
  metadatas.push(metadataPubKey.toBase58());
235
327
  instructionsBatch.push({
@@ -352,8 +444,8 @@ export class SolanaStreamClient extends BaseStreamClient {
352
444
  /**
353
445
  * Attempts canceling the specified stream.
354
446
  */
355
- async cancel({ id }, extParams) {
356
- const ixs = await this.prepareCancelInstructions({ id }, extParams);
447
+ async cancel(cancelData, extParams) {
448
+ const ixs = await this.prepareCancelInstructions(cancelData, extParams);
357
449
  const { tx, hash, context } = await prepareTransaction(this.connection, ixs, extParams.invoker.publicKey);
358
450
  const signature = await signAndExecuteTransaction(this.connection, extParams.invoker, tx, {
359
451
  hash,
@@ -362,10 +454,59 @@ export class SolanaStreamClient extends BaseStreamClient {
362
454
  }, { sendThrottler: this.sendThrottler });
363
455
  return { ixs, txId: signature };
364
456
  }
457
+ async prepareCancelInstructions(cancelData, extParams) {
458
+ const streamPublicKey = new PublicKey(cancelData.id);
459
+ const account = await this.connection.getAccountInfo(streamPublicKey);
460
+ if (!account) {
461
+ throw new Error("Impossible to cancel a stream contract that does not exist");
462
+ }
463
+ const { sender: senderPublicKey } = decodeStream(account.data);
464
+ const isAlignedUnlock = this.isAlignedUnlock(streamPublicKey, senderPublicKey);
465
+ const ixs = isAlignedUnlock
466
+ ? await this.prepareCancelAlignedUnlockInstructions(cancelData, extParams)
467
+ : await this.prepareCancelStreamInstructions(cancelData, extParams);
468
+ return ixs;
469
+ }
470
+ async prepareCancelAlignedUnlockInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
471
+ if (!invoker.publicKey) {
472
+ throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
473
+ }
474
+ const streamPublicKey = new PublicKey(id);
475
+ const escrowAcc = await this.connection.getAccountInfo(streamPublicKey);
476
+ if (!escrowAcc?.data) {
477
+ throw new Error("Couldn't get account info");
478
+ }
479
+ const streamflowProgramPublicKey = new PublicKey(this.programId);
480
+ const streamData = decodeStream(escrowAcc?.data);
481
+ const escrowPDA = deriveEscrowPDA(streamflowProgramPublicKey, streamPublicKey);
482
+ const { tokenProgramId } = await getMintAndProgram(this.connection, streamData.mint);
483
+ const partnerPublicKey = streamData.partner;
484
+ const ixs = prepareBaseInstructions(this.connection, {
485
+ computePrice,
486
+ computeLimit: computeLimit ?? ALIGNED_COMPUTE_LIMIT,
487
+ });
488
+ await this.checkAssociatedTokenAccounts(streamData, { invoker, checkTokenAccounts }, ixs, tokenProgramId);
489
+ const cancelIx = await this.alignedProxyProgram.methods
490
+ .cancel()
491
+ .accountsPartial({
492
+ sender: invoker.publicKey,
493
+ streamMetadata: streamPublicKey,
494
+ escrowTokens: escrowPDA,
495
+ recipient: streamData.recipient,
496
+ partner: partnerPublicKey,
497
+ streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
498
+ mint: streamData.mint,
499
+ tokenProgram: tokenProgramId,
500
+ streamflowProgram: this.programId,
501
+ })
502
+ .instruction();
503
+ ixs.push(cancelIx);
504
+ return ixs;
505
+ }
365
506
  /**
366
507
  * Creates Transaction Instructions for cancel
367
508
  */
368
- async prepareCancelInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
509
+ async prepareCancelStreamInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
369
510
  if (!invoker.publicKey) {
370
511
  throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
371
512
  }
@@ -504,11 +645,56 @@ export class SolanaStreamClient extends BaseStreamClient {
504
645
  * Fetch stream data by its id (address).
505
646
  */
506
647
  async getOne({ id }) {
507
- const escrow = await this.connection.getAccountInfo(new PublicKey(id), TX_FINALITY_CONFIRMED);
648
+ const streamPublicKey = new PublicKey(id);
649
+ const escrow = await this.connection.getAccountInfo(streamPublicKey, TX_FINALITY_CONFIRMED);
508
650
  if (!escrow?.data) {
509
651
  throw new Error("Couldn't get account info.");
510
652
  }
511
- return new Contract(decodeStream(escrow?.data));
653
+ const stream = decodeStream(escrow.data);
654
+ if (this.isAlignedUnlock(streamPublicKey, stream.sender)) {
655
+ const alignedProxy = await this.alignedProxyProgram.account.contract.fetch(deriveContractPDA(this.alignedProxyProgram.programId, streamPublicKey));
656
+ if (!alignedProxy) {
657
+ throw new Error("Couldn't get proxy account info.");
658
+ }
659
+ return new AlignedContract(stream, alignedProxy);
660
+ }
661
+ return new Contract(stream);
662
+ }
663
+ /**
664
+ * Fetch all aligned outgoing streams/contracts by the provided public key.
665
+ */
666
+ async getOutgoingAlignedStreams(sender) {
667
+ const streams = {};
668
+ const alignedOutgoingProgramAccounts = await this.alignedProxyProgram.account.contract.all([
669
+ {
670
+ memcmp: {
671
+ offset: ORIGINAL_CONTRACT_SENDER_OFFSET,
672
+ bytes: sender,
673
+ },
674
+ },
675
+ ]);
676
+ const streamPubKeys = alignedOutgoingProgramAccounts.map((account) => account.account.stream);
677
+ const streamAccounts = await this.connection.getMultipleAccountsInfo(streamPubKeys, TX_FINALITY_CONFIRMED);
678
+ streamAccounts.forEach((account, index) => {
679
+ if (account) {
680
+ const alignedData = alignedOutgoingProgramAccounts[index].account;
681
+ streams[alignedData.sender.toBase58()] = new AlignedContract(decodeStream(account.data), alignedData);
682
+ }
683
+ });
684
+ return streams;
685
+ }
686
+ async getIncomingAlignedStreams(streamRecord) {
687
+ const streams = {};
688
+ const alignedStreamsPubKeys = Object.keys(streamRecord);
689
+ const alignedProxyPDAs = alignedStreamsPubKeys.map((streamPubKey) => deriveContractPDA(this.alignedProxyProgram.programId, new PublicKey(streamPubKey)));
690
+ const alignedProxyAccounts = await this.alignedProxyProgram.account.contract.fetchMultiple(alignedProxyPDAs);
691
+ alignedProxyAccounts.forEach((account, index) => {
692
+ if (account) {
693
+ const alignedData = streamRecord[alignedStreamsPubKeys[index]];
694
+ streams[alignedStreamsPubKeys[index]] = new AlignedContract(alignedData, account);
695
+ }
696
+ });
697
+ return streams;
512
698
  }
513
699
  /**
514
700
  * Fetch streams/contracts by providing direction.
@@ -516,24 +702,39 @@ export class SolanaStreamClient extends BaseStreamClient {
516
702
  */
517
703
  async get({ address, type = StreamType.All, direction = StreamDirection.All, }) {
518
704
  const publicKey = new PublicKey(address);
519
- let accounts = [];
520
- //todo: we need to be smart with our layout so we minimize rpc calls to the chain
521
- if (direction === "all") {
522
- const outgoingAccounts = await getProgramAccounts(this.connection, publicKey, STREAM_STRUCT_OFFSET_SENDER, this.programId);
523
- const incomingAccounts = await getProgramAccounts(this.connection, publicKey, STREAM_STRUCT_OFFSET_RECIPIENT, this.programId);
524
- accounts = [...outgoingAccounts, ...incomingAccounts];
705
+ let streams = {};
706
+ // don't do unnecessary rpc calls if we are not querying for vesting streams
707
+ const shouldFetchAligned = type === StreamType.All || type === StreamType.Vesting;
708
+ if (direction !== StreamDirection.Incoming) {
709
+ const outgoingStreamAccounts = await getProgramAccounts(this.connection, publicKey, STREAM_STRUCT_OFFSET_SENDER, this.programId);
710
+ outgoingStreamAccounts.forEach((account) => {
711
+ streams[account.pubkey.toBase58()] = new Contract(decodeStream(account.account.data));
712
+ });
713
+ if (shouldFetchAligned) {
714
+ const alignedStreams = await this.getOutgoingAlignedStreams(address);
715
+ streams = { ...streams, ...alignedStreams };
716
+ }
525
717
  }
526
- else {
527
- const offset = direction === "outgoing" ? STREAM_STRUCT_OFFSET_SENDER : STREAM_STRUCT_OFFSET_RECIPIENT;
528
- accounts = await getProgramAccounts(this.connection, publicKey, offset, this.programId);
718
+ if (direction !== StreamDirection.Outgoing) {
719
+ const allIncomingAccounts = await getProgramAccounts(this.connection, publicKey, STREAM_STRUCT_OFFSET_RECIPIENT, this.programId);
720
+ const allIncomingStreams = allIncomingAccounts.map((account) => decodeStream(account.account.data));
721
+ const alignedDecoded = {};
722
+ // filter out aligned unlocks and store them in a separate object
723
+ allIncomingAccounts.forEach((account, index) => {
724
+ if (this.isAlignedUnlock(account.pubkey, allIncomingStreams[index].sender)) {
725
+ alignedDecoded[account.pubkey.toBase58()] = allIncomingStreams[index];
726
+ }
727
+ else {
728
+ streams[account.pubkey.toBase58()] = new Contract(allIncomingStreams[index]);
729
+ }
730
+ });
731
+ if (shouldFetchAligned) {
732
+ const incomingAlignedStreams = await this.getIncomingAlignedStreams(alignedDecoded);
733
+ streams = { ...streams, ...incomingAlignedStreams };
734
+ }
529
735
  }
530
- let streams = {};
531
- accounts.forEach((account) => {
532
- const decoded = new Contract(decodeStream(account.account.data));
533
- streams = { ...streams, [account.pubkey.toBase58()]: decoded };
534
- });
535
736
  const sortedStreams = Object.entries(streams).sort(([, stream1], [, stream2]) => stream2.start - stream1.start);
536
- if (type === "all")
737
+ if (type === StreamType.All)
537
738
  return sortedStreams;
538
739
  return sortedStreams.filter((stream) => stream[1].type === type);
539
740
  }
@@ -616,68 +817,6 @@ export class SolanaStreamClient extends BaseStreamClient {
616
817
  const logs = "logs" in err && Array.isArray(err.logs) ? err.logs : undefined;
617
818
  return extractSolanaErrorCode(err.toString() ?? "Unknown error!", logs);
618
819
  }
619
- /**
620
- * Forms instructions from params, creates a raw transaction and fetch recent blockhash.
621
- */
622
- async prepareStreamInstructions(recipient, streamParams, extParams) {
623
- const { tokenId: mint, start, period, cliff, canTopup, canUpdateRate, canPause, cancelableBySender, cancelableByRecipient, transferableBySender, transferableByRecipient, automaticWithdrawal = false, withdrawalFrequency = 0, partner, } = streamParams;
624
- const { sender, metadataPubKeys, computeLimit, computePrice } = extParams;
625
- if (!sender.publicKey) {
626
- throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
627
- }
628
- const ixs = prepareBaseInstructions(this.connection, {
629
- computePrice,
630
- computeLimit,
631
- });
632
- const recipientPublicKey = new PublicKey(recipient.recipient);
633
- const mintPublicKey = new PublicKey(mint);
634
- const { metadata, metadataPubKey } = this.getOrCreateStreamMetadata(metadataPubKeys);
635
- const [escrowTokens] = PublicKey.findProgramAddressSync([Buffer.from("strm"), metadataPubKey.toBuffer()], this.programId);
636
- const { tokenProgramId } = await getMintAndProgram(this.connection, mintPublicKey);
637
- const senderTokens = await ata(mintPublicKey, sender.publicKey, tokenProgramId);
638
- const recipientTokens = await ata(mintPublicKey, recipientPublicKey, tokenProgramId);
639
- const streamflowTreasuryTokens = await ata(mintPublicKey, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
640
- const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
641
- const partnerTokens = await ata(mintPublicKey, partnerPublicKey, tokenProgramId);
642
- ixs.push(createStreamInstruction({
643
- start: new BN(start),
644
- depositedAmount: recipient.amount,
645
- period: new BN(period),
646
- amountPerPeriod: recipient.amountPerPeriod,
647
- cliff: new BN(cliff),
648
- cliffAmount: new BN(recipient.cliffAmount),
649
- cancelableBySender,
650
- cancelableByRecipient,
651
- automaticWithdrawal,
652
- transferableBySender,
653
- transferableByRecipient,
654
- canTopup,
655
- canUpdateRate: !!canUpdateRate,
656
- canPause: !!canPause,
657
- name: recipient.name,
658
- withdrawFrequency: new BN(automaticWithdrawal ? withdrawalFrequency : period),
659
- }, this.programId, {
660
- sender: sender.publicKey,
661
- senderTokens,
662
- recipient: new PublicKey(recipient.recipient),
663
- metadata: metadataPubKey,
664
- escrowTokens,
665
- recipientTokens,
666
- streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
667
- streamflowTreasuryTokens: streamflowTreasuryTokens,
668
- partner: partnerPublicKey,
669
- partnerTokens: partnerTokens,
670
- mint: new PublicKey(mint),
671
- feeOracle: FEE_ORACLE_PUBLIC_KEY,
672
- rent: SYSVAR_RENT_PUBKEY,
673
- timelockProgram: this.programId,
674
- tokenProgram: tokenProgramId,
675
- associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
676
- withdrawor: WITHDRAWOR_PUBLIC_KEY,
677
- systemProgram: SystemProgram.programId,
678
- }));
679
- return { ixs, metadata, metadataPubKey };
680
- }
681
820
  /**
682
821
  * Utility function to generate metadata for a Contract or return existing Pubkey
683
822
  */
@@ -693,6 +832,13 @@ export class SolanaStreamClient extends BaseStreamClient {
693
832
  }
694
833
  return { metadata, metadataPubKey };
695
834
  }
835
+ /**
836
+ * Utility function that checks whether the associated stream address is an aligned unlock contract, indicated by whether the sender/creator is a PDA
837
+ */
838
+ isAlignedUnlock(streamPublicKey, senderPublicKey) {
839
+ const pda = deriveContractPDA(this.alignedProxyProgram.programId, streamPublicKey);
840
+ return senderPublicKey.equals(pda);
841
+ }
696
842
  /**
697
843
  * Utility function that checks whether associated token accounts still exist and adds instructions to add them if not
698
844
  */
@@ -3,9 +3,11 @@ import { PublicKey } from "@solana/web3.js";
3
3
  import { Buffer } from "buffer";
4
4
  import { ISearchStreams } from "./types.js";
5
5
  export declare const TX_FINALITY_CONFIRMED = "confirmed";
6
+ export declare const ORIGINAL_CONTRACT_SENDER_OFFSET = 16;
6
7
  export declare const STREAM_STRUCT_OFFSET_SENDER = 49;
7
8
  export declare const STREAM_STRUCT_OFFSET_RECIPIENT = 113;
8
9
  export declare const STREAM_STRUCT_OFFSET_MINT = 177;
10
+ export declare const ALIGNED_PRECISION_FACTOR_POW = 9;
9
11
  export declare const STREAM_STRUCT_OFFSETS: Record<keyof ISearchStreams, number>;
10
12
  export declare const CREATE_PARAMS_PADDING = 126;
11
13
  export declare const PROGRAM_ID: {
@@ -14,6 +16,18 @@ export declare const PROGRAM_ID: {
14
16
  testnet: string;
15
17
  local: string;
16
18
  };
19
+ export declare const ALIGNED_UNLOCKS_PROGRAM_ID: {
20
+ devnet: string;
21
+ mainnet: string;
22
+ testnet: string;
23
+ local: string;
24
+ };
25
+ export declare const ALIGNED_COMPUTE_LIMIT = 300000;
26
+ export declare const CONTRACT_DISCRIMINATOR: number[];
27
+ export declare const TEST_ORACLE_DISCRIMINATOR: number[];
28
+ export declare const CONTRACT_SEED: Buffer;
29
+ export declare const ESCROW_SEED: Buffer;
30
+ export declare const TEST_ORACLE_SEED: Buffer;
17
31
  export declare const PARTNER_ORACLE_PROGRAM_ID = "pardpVtPjC8nLj1Dwncew62mUzfChdCX1EaoZe8oCAa";
18
32
  export declare const STREAMFLOW_TREASURY_PUBLIC_KEY: PublicKey;
19
33
  export declare const WITHDRAWOR_PUBLIC_KEY: PublicKey;
@@ -1,10 +1,12 @@
1
1
  import { PublicKey } from "@solana/web3.js";
2
2
  import { Buffer } from "buffer";
3
- import { ICluster, SolanaContractErrorCode } from "../common/types.js";
3
+ import { ICluster, SolanaContractErrorCode, SolanaAlignedProxyErrorCode } from "../common/types.js";
4
4
  export const TX_FINALITY_CONFIRMED = "confirmed";
5
+ export const ORIGINAL_CONTRACT_SENDER_OFFSET = 16;
5
6
  export const STREAM_STRUCT_OFFSET_SENDER = 49;
6
7
  export const STREAM_STRUCT_OFFSET_RECIPIENT = 113;
7
8
  export const STREAM_STRUCT_OFFSET_MINT = 177;
9
+ export const ALIGNED_PRECISION_FACTOR_POW = 9;
8
10
  export const STREAM_STRUCT_OFFSETS = {
9
11
  mint: STREAM_STRUCT_OFFSET_MINT,
10
12
  recipient: STREAM_STRUCT_OFFSET_RECIPIENT,
@@ -18,6 +20,19 @@ export const PROGRAM_ID = {
18
20
  [ICluster.Testnet]: "HqDGZjaVRXJ9MGRQEw7qDc2rAr6iH1n1kAQdCZaCMfMZ",
19
21
  [ICluster.Local]: "HqDGZjaVRXJ9MGRQEw7qDc2rAr6iH1n1kAQdCZaCMfMZ",
20
22
  };
23
+ export const ALIGNED_UNLOCKS_PROGRAM_ID = {
24
+ [ICluster.Devnet]: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH",
25
+ [ICluster.Mainnet]: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH",
26
+ [ICluster.Testnet]: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH",
27
+ [ICluster.Local]: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH",
28
+ };
29
+ // Aligned Unlocks Program transactions require a higher comput limit
30
+ export const ALIGNED_COMPUTE_LIMIT = 300000;
31
+ export const CONTRACT_DISCRIMINATOR = [172, 138, 115, 242, 121, 67, 183, 26];
32
+ export const TEST_ORACLE_DISCRIMINATOR = [198, 49, 63, 134, 232, 251, 168, 28];
33
+ export const CONTRACT_SEED = Buffer.from("contract", "utf-8");
34
+ export const ESCROW_SEED = Buffer.from("strm", "utf-8");
35
+ export const TEST_ORACLE_SEED = Buffer.from("test-oracle", "utf-8");
21
36
  export const PARTNER_ORACLE_PROGRAM_ID = "pardpVtPjC8nLj1Dwncew62mUzfChdCX1EaoZe8oCAa";
22
37
  export const STREAMFLOW_TREASURY_PUBLIC_KEY = new PublicKey("5SEpbdjFK5FxwTvfsGMXVQTD2v4M2c5tyRTxhdsPkgDw");
23
38
  export const WITHDRAWOR_PUBLIC_KEY = new PublicKey("wdrwhnCv4pzW8beKsbPa4S2UDZrXenjg16KJdKSpb5u");
@@ -59,4 +74,17 @@ export const SOLANA_ERROR_MAP = {
59
74
  0x85: SolanaContractErrorCode.AlreadyPaused,
60
75
  0x86: SolanaContractErrorCode.NotPaused,
61
76
  0x87: SolanaContractErrorCode.MetadataNotRentExempt,
77
+ 0x1770: SolanaAlignedProxyErrorCode.Unauthorized,
78
+ 0x1771: SolanaAlignedProxyErrorCode.ArithmeticError,
79
+ 0x1772: SolanaAlignedProxyErrorCode.UnsupportedTokenExtensions,
80
+ 0x1773: SolanaAlignedProxyErrorCode.PeriodTooShort,
81
+ 0x1774: SolanaAlignedProxyErrorCode.InvalidTickSize,
82
+ 0x1775: SolanaAlignedProxyErrorCode.InvalidPercentageBoundaries,
83
+ 0x1776: SolanaAlignedProxyErrorCode.InvalidPriceBoundaries,
84
+ 0x1777: SolanaAlignedProxyErrorCode.UnsupportedOracle,
85
+ 0x1778: SolanaAlignedProxyErrorCode.InvalidOracleAccount,
86
+ 0x1779: SolanaAlignedProxyErrorCode.InvalidOraclePrice,
87
+ 0x177a: SolanaAlignedProxyErrorCode.InvalidStreamMetadata,
88
+ 0x177b: SolanaAlignedProxyErrorCode.AmountAlreadyUpdated,
89
+ 0x177c: SolanaAlignedProxyErrorCode.AllFundsUnlocked,
62
90
  };