@streamflow/stream 7.0.0-alpha.2 → 7.0.0-alpha.20

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 (78) hide show
  1. package/README.md +70 -67
  2. package/dist/cjs/__tests__/aptos/streamClient.spec.js +83 -134
  3. package/dist/cjs/__tests__/common/GenericStreamClient.spec.js +9 -9
  4. package/dist/cjs/aptos/StreamClient.js +162 -367
  5. package/dist/cjs/aptos/constants.js +7 -8
  6. package/dist/cjs/aptos/index.js +3 -3
  7. package/dist/cjs/aptos/types.js +28 -37
  8. package/dist/cjs/aptos/utils.js +4 -4
  9. package/dist/cjs/aptos/wallet.js +20 -75
  10. package/dist/cjs/common/BaseStreamClient.js +11 -59
  11. package/dist/cjs/common/GenericStreamClient.js +46 -72
  12. package/dist/cjs/common/constants.js +4 -3
  13. package/dist/cjs/common/contractUtils.js +33 -18
  14. package/dist/cjs/common/types.js +30 -1
  15. package/dist/cjs/common/utils.js +38 -80
  16. package/dist/cjs/evm/StreamClient.js +198 -456
  17. package/dist/cjs/evm/constants.js +19 -20
  18. package/dist/cjs/evm/types.js +25 -34
  19. package/dist/cjs/evm/utils.js +2 -2
  20. package/dist/cjs/index.js +10 -10
  21. package/dist/cjs/solana/StreamClient.js +759 -1090
  22. package/dist/cjs/solana/constants.js +44 -11
  23. package/dist/cjs/solana/descriptor/idl/streamflow_aligned_unlocks.json +1471 -0
  24. package/dist/cjs/solana/descriptor/streamflow_aligned_unlocks.js +2 -0
  25. package/dist/cjs/solana/index.js +2 -1
  26. package/dist/cjs/solana/instructions.js +75 -81
  27. package/dist/cjs/solana/layout.js +7 -8
  28. package/dist/cjs/solana/lib/derive-accounts.js +17 -0
  29. package/dist/cjs/solana/lib/utils.js +127 -0
  30. package/dist/cjs/solana/types.js +40 -27
  31. package/dist/cjs/sui/StreamClient.js +325 -571
  32. package/dist/cjs/sui/constants.js +19 -20
  33. package/dist/cjs/sui/types.js +28 -62
  34. package/dist/cjs/sui/utils.js +7 -7
  35. package/dist/cjs/sui/wallet.js +13 -63
  36. package/dist/esm/__tests__/aptos/streamClient.spec.js +4 -4
  37. package/dist/esm/aptos/index.d.ts +3 -3
  38. package/dist/esm/aptos/index.js +3 -3
  39. package/dist/esm/aptos/types.d.ts +14 -14
  40. package/dist/esm/aptos/types.js +13 -13
  41. package/dist/esm/common/GenericStreamClient.d.ts +4 -4
  42. package/dist/esm/common/GenericStreamClient.js +4 -4
  43. package/dist/esm/common/constants.d.ts +3 -2
  44. package/dist/esm/common/constants.js +3 -2
  45. package/dist/esm/common/contractUtils.d.ts +18 -15
  46. package/dist/esm/common/contractUtils.js +19 -6
  47. package/dist/esm/common/types.d.ts +112 -57
  48. package/dist/esm/common/types.js +29 -0
  49. package/dist/esm/common/utils.d.ts +11 -11
  50. package/dist/esm/common/utils.js +19 -16
  51. package/dist/esm/evm/StreamClient.d.ts +2 -2
  52. package/dist/esm/evm/StreamClient.js +7 -7
  53. package/dist/esm/evm/types.d.ts +14 -14
  54. package/dist/esm/evm/types.js +13 -13
  55. package/dist/esm/index.d.ts +9 -9
  56. package/dist/esm/index.js +9 -9
  57. package/dist/esm/solana/StreamClient.d.ts +24 -16
  58. package/dist/esm/solana/StreamClient.js +324 -156
  59. package/dist/esm/solana/constants.d.ts +17 -0
  60. package/dist/esm/solana/constants.js +35 -1
  61. package/dist/esm/solana/descriptor/idl/streamflow_aligned_unlocks.json +1471 -0
  62. package/dist/esm/solana/descriptor/streamflow_aligned_unlocks.d.ts +1272 -0
  63. package/dist/esm/solana/descriptor/streamflow_aligned_unlocks.js +1 -0
  64. package/dist/esm/solana/index.d.ts +2 -1
  65. package/dist/esm/solana/index.js +2 -1
  66. package/dist/esm/solana/instructions.d.ts +17 -17
  67. package/dist/esm/solana/instructions.js +18 -19
  68. package/dist/esm/solana/lib/derive-accounts.d.ts +4 -0
  69. package/dist/esm/solana/lib/derive-accounts.js +11 -0
  70. package/dist/esm/solana/{utils.d.ts → lib/utils.d.ts} +1 -3
  71. package/dist/esm/solana/{utils.js → lib/utils.js} +28 -34
  72. package/dist/esm/solana/types.d.ts +72 -39
  73. package/dist/esm/solana/types.js +32 -4
  74. package/dist/esm/sui/StreamClient.js +1 -1
  75. package/dist/esm/sui/types.d.ts +14 -14
  76. package/dist/esm/sui/types.js +13 -13
  77. package/package.json +12 -10
  78. package/dist/cjs/solana/utils.js +0 -222
@@ -1,24 +1,30 @@
1
1
  // Latest version of the SDK that does not use Anchor. It supports raw instructions.
2
- import BigNumber from "bignumber.js";
2
+ import BN from "bn.js";
3
3
  import { Buffer } from "buffer";
4
4
  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, } 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,23 @@ 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) {
46
- const { ixs, metadata, metadataPubKey } = await this.prepareCreateInstructions(data, extParams);
57
+ const { partner, amount } = data;
58
+ const { isNative, sender } = extParams;
59
+ const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
60
+ const mintPublicKey = new PublicKey(data.tokenId);
61
+ if (!sender.publicKey) {
62
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
63
+ }
64
+ const ixs = await this.getCreateATAInstructions([STREAMFLOW_TREASURY_PUBLIC_KEY, partnerPublicKey], mintPublicKey, sender, true);
65
+ const { ixs: createIxs, metadata, metadataPubKey } = await this.prepareCreateInstructions(data, extParams);
66
+ ixs.push(...createIxs);
67
+ if (isNative) {
68
+ const totalFee = await this.getTotalFee({
69
+ address: partnerPublicKey.toString(),
70
+ });
71
+ const totalAmount = calculateTotalAmountToDeposit(amount, totalFee);
72
+ ixs.push(...(await prepareWrappedAccount(this.connection, sender.publicKey, totalAmount)));
73
+ }
47
74
  const { tx, hash, context } = await prepareTransaction(this.connection, ixs, extParams.sender.publicKey, undefined, metadata);
48
75
  const signature = await signAndExecuteTransaction(this.connection, extParams.sender, tx, {
49
76
  hash,
@@ -52,11 +79,81 @@ export class SolanaStreamClient extends BaseStreamClient {
52
79
  }, { sendThrottler: this.sendThrottler });
53
80
  return { ixs, txId: signature, metadataId: metadataPubKey.toBase58() };
54
81
  }
82
+ async prepareCreateInstructions(streamParams, extParams) {
83
+ const { ixs, metadata, metadataPubKey } = isCreateAlignedStreamData(streamParams)
84
+ ? await this.prepareCreateAlignedUnlockInstructions(streamParams, extParams)
85
+ : await this.prepareCreateStreamInstructions(streamParams, extParams);
86
+ return { ixs, metadata, metadataPubKey };
87
+ }
88
+ async prepareCreateAlignedUnlockInstructions(streamParams, extParams) {
89
+ 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;
90
+ const { isNative, sender, computeLimit, computePrice, metadataPubKeys } = extParams;
91
+ if (!sender.publicKey) {
92
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
93
+ }
94
+ if (!priceOracle && oracleType && oracleType !== "none") {
95
+ throw new Error("Price oracle is required for the specified oracle type");
96
+ }
97
+ const recipientPublicKey = new PublicKey(recipient);
98
+ const mintPublicKey = isNative ? NATIVE_MINT : new PublicKey(mint);
99
+ const metadata = !metadataPubKeys ? Keypair.generate() : undefined;
100
+ const metadataPubKey = metadata ? metadata.publicKey : metadataPubKeys[0];
101
+ const { tokenProgramId } = await getMintAndProgram(this.connection, mintPublicKey);
102
+ const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
103
+ const streamflowProgramPublicKey = new PublicKey(this.programId);
104
+ const escrowPDA = deriveEscrowPDA(streamflowProgramPublicKey, metadataPubKey);
105
+ const oracle = priceOracle ?? deriveTestOraclePDA(this.alignedProxyProgram.programId, mintPublicKey, sender.publicKey);
106
+ const ixs = prepareBaseInstructions(this.connection, {
107
+ computePrice,
108
+ computeLimit: computeLimit ?? ALIGNED_COMPUTE_LIMIT,
109
+ });
110
+ ixs.push(...(await this.getCreateATAInstructions([recipientPublicKey], mintPublicKey, sender, true, tokenProgramId)));
111
+ const encodedUIntArray = new TextEncoder().encode(streamName);
112
+ const streamNameArray = Array.from(encodedUIntArray);
113
+ const createIx = await this.alignedProxyProgram.methods
114
+ .create({
115
+ startTime: new BN(start),
116
+ netAmountDeposited: depositedAmount,
117
+ period: new BN(period),
118
+ amountPerPeriod: amountPerPeriod,
119
+ cliff: new BN(cliff),
120
+ cliffAmount: cliffAmount,
121
+ transferableBySender,
122
+ transferableByRecipient,
123
+ cancelableByRecipient,
124
+ cancelableBySender,
125
+ canTopup,
126
+ oracleType: (!!oracleType ? { [oracleType]: {} } : { none: {} }),
127
+ streamName: streamNameArray,
128
+ minPrice: getBN(minPrice, ALIGNED_PRECISION_FACTOR_POW),
129
+ maxPrice: getBN(maxPrice, ALIGNED_PRECISION_FACTOR_POW),
130
+ minPercentage: getBN(minPercentage, ALIGNED_PRECISION_FACTOR_POW),
131
+ maxPercentage: getBN(maxPercentage, ALIGNED_PRECISION_FACTOR_POW),
132
+ tickSize: new BN(tickSize || 1),
133
+ skipInitial: skipInitial ?? false,
134
+ })
135
+ .accountsPartial({
136
+ sender: sender.publicKey,
137
+ streamMetadata: metadataPubKey,
138
+ escrowTokens: escrowPDA,
139
+ mint: mintPublicKey,
140
+ partner: partnerPublicKey,
141
+ recipient: recipientPublicKey,
142
+ withdrawor: WITHDRAWOR_PUBLIC_KEY,
143
+ feeOracle: FEE_ORACLE_PUBLIC_KEY,
144
+ priceOracle: oracle,
145
+ tokenProgram: tokenProgramId,
146
+ streamflowProgram: this.programId,
147
+ })
148
+ .instruction();
149
+ ixs.push(createIx);
150
+ return { ixs, metadata, metadataPubKey };
151
+ }
55
152
  /**
56
153
  * Creates a new stream/vesting contract.
57
154
  * 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
155
  */
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 }) {
156
+ 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
157
  if (!sender.publicKey) {
61
158
  throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
62
159
  }
@@ -72,22 +169,15 @@ export class SolanaStreamClient extends BaseStreamClient {
72
169
  const senderTokens = await ata(mintPublicKey, sender.publicKey, tokenProgramId);
73
170
  const recipientTokens = await ata(mintPublicKey, recipientPublicKey, tokenProgramId);
74
171
  const streamflowTreasuryTokens = await ata(mintPublicKey, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
75
- const partnerPublicKey = partner ? new PublicKey(partner) : STREAMFLOW_TREASURY_PUBLIC_KEY;
172
+ const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
76
173
  const partnerTokens = await ata(mintPublicKey, partnerPublicKey, tokenProgramId);
77
- if (isNative) {
78
- const totalFee = await this.getTotalFee({
79
- address: partner ?? sender.publicKey.toBase58(),
80
- });
81
- const totalAmount = calculateTotalAmountToDeposit(depositedAmount, totalFee);
82
- ixs.push(...(await prepareWrappedAccount(this.connection, sender.publicKey, totalAmount)));
83
- }
84
174
  ixs.push(createStreamInstruction({
85
- start: BigNumber(start),
175
+ start: new BN(start),
86
176
  depositedAmount,
87
- period: BigNumber(period),
177
+ period: new BN(period),
88
178
  amountPerPeriod,
89
- cliff: BigNumber(cliff),
90
- cliffAmount: BigNumber(cliffAmount),
179
+ cliff: new BN(cliff),
180
+ cliffAmount: new BN(cliffAmount),
91
181
  cancelableBySender,
92
182
  cancelableByRecipient,
93
183
  automaticWithdrawal,
@@ -97,7 +187,7 @@ export class SolanaStreamClient extends BaseStreamClient {
97
187
  canUpdateRate: !!canUpdateRate,
98
188
  canPause: !!canPause,
99
189
  name,
100
- withdrawFrequency: BigNumber(automaticWithdrawal ? withdrawalFrequency : period),
190
+ withdrawFrequency: new BN(automaticWithdrawal ? withdrawalFrequency : period),
101
191
  }, this.programId, {
102
192
  sender: sender.publicKey,
103
193
  senderTokens,
@@ -161,23 +251,23 @@ export class SolanaStreamClient extends BaseStreamClient {
161
251
  const [escrowTokens] = PublicKey.findProgramAddressSync([Buffer.from("strm"), metadataPubKey.toBuffer()], this.programId);
162
252
  const { tokenProgramId } = await getMintAndProgram(this.connection, mintPublicKey);
163
253
  const senderTokens = await ata(mintPublicKey, sender.publicKey, tokenProgramId);
164
- const partnerPublicKey = partner ? new PublicKey(partner) : STREAMFLOW_TREASURY_PUBLIC_KEY;
254
+ const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
165
255
  const ixs = prepareBaseInstructions(this.connection, {
166
256
  computePrice,
167
257
  computeLimit,
168
258
  });
169
259
  if (isNative) {
170
- const totalFee = await this.getTotalFee({ address: partner ?? sender.publicKey.toBase58() });
260
+ const totalFee = await this.getTotalFee({ address: partnerPublicKey.toString() });
171
261
  const totalAmount = calculateTotalAmountToDeposit(depositedAmount, totalFee);
172
262
  ixs.push(...(await prepareWrappedAccount(this.connection, sender.publicKey, totalAmount)));
173
263
  }
174
264
  const createInstruction = createUncheckedStreamInstruction({
175
- start: BigNumber(start),
265
+ start: new BN(start),
176
266
  depositedAmount,
177
- period: BigNumber(period),
267
+ period: new BN(period),
178
268
  amountPerPeriod,
179
- cliff: BigNumber(cliff),
180
- cliffAmount: BigNumber(cliffAmount),
269
+ cliff: new BN(cliff),
270
+ cliffAmount: new BN(cliffAmount),
181
271
  cancelableBySender,
182
272
  cancelableByRecipient,
183
273
  automaticWithdrawal,
@@ -187,7 +277,7 @@ export class SolanaStreamClient extends BaseStreamClient {
187
277
  canUpdateRate: !!canUpdateRate,
188
278
  canPause: !!canPause,
189
279
  name,
190
- withdrawFrequency: BigNumber(automaticWithdrawal ? withdrawalFrequency : period),
280
+ withdrawFrequency: new BN(automaticWithdrawal ? withdrawalFrequency : period),
191
281
  recipient: recipientPublicKey,
192
282
  partner: partnerPublicKey,
193
283
  }, this.programId, {
@@ -210,26 +300,34 @@ export class SolanaStreamClient extends BaseStreamClient {
210
300
  * Creates multiple stream/vesting contracts.
211
301
  * 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
302
  */
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
- }
303
+ async createMultiple(data, extParams) {
304
+ const { recipients, ...streamParams } = data;
305
+ const { sender, metadataPubKeys: metadataPubKeysExt, isNative, computePrice, computeLimit } = extParams;
218
306
  const metadatas = [];
219
307
  const metadataToRecipient = {};
220
308
  const errors = [];
221
309
  const signatures = [];
222
310
  const batch = [];
223
311
  const instructionsBatch = [];
224
- metadataPubKeys = metadataPubKeys || [];
312
+ const metadataPubKeys = metadataPubKeysExt || [];
313
+ const partnerPublicKey = data.partner ? new PublicKey(data.partner) : WITHDRAWOR_PUBLIC_KEY;
314
+ const mintPublicKey = new PublicKey(data.tokenId);
315
+ if (recipients.length === 0) {
316
+ throw new Error("Recipients array is empty!");
317
+ }
318
+ if (!sender.publicKey) {
319
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
320
+ }
225
321
  for (let i = 0; i < recipients.length; i++) {
226
322
  const recipientData = recipients[i];
227
- const { ixs, metadata, metadataPubKey } = await this.prepareStreamInstructions(recipientData, data, {
323
+ const createStreamData = { ...streamParams, ...recipientData };
324
+ const createStreamExtParams = {
228
325
  sender,
229
326
  metadataPubKeys: metadataPubKeys[i] ? [metadataPubKeys[i]] : undefined,
230
327
  computePrice,
231
328
  computeLimit,
232
- });
329
+ };
330
+ const { ixs, metadata, metadataPubKey } = await this.prepareCreateInstructions(createStreamData, createStreamExtParams);
233
331
  metadataToRecipient[metadataPubKey.toBase58()] = recipientData;
234
332
  metadatas.push(metadataPubKey.toBase58());
235
333
  instructionsBatch.push({
@@ -251,13 +349,17 @@ export class SolanaStreamClient extends BaseStreamClient {
251
349
  }
252
350
  batch.push({ tx, recipient });
253
351
  }
352
+ const prepareInstructions = await this.getCreateATAInstructions([STREAMFLOW_TREASURY_PUBLIC_KEY, partnerPublicKey], mintPublicKey, sender, true);
254
353
  if (isNative) {
255
- const totalDepositedAmount = recipients.reduce((acc, recipient) => recipient.amount.plus(acc), BigNumber(0));
354
+ const totalDepositedAmount = recipients.reduce((acc, recipient) => recipient.amount.add(acc), new BN(0));
256
355
  const nativeInstructions = await prepareWrappedAccount(this.connection, sender.publicKey, totalDepositedAmount);
356
+ prepareInstructions.push(...nativeInstructions);
357
+ }
358
+ if (prepareInstructions.length > 0) {
257
359
  const messageV0 = new TransactionMessage({
258
360
  payerKey: sender.publicKey,
259
361
  recentBlockhash: hash.blockhash,
260
- instructions: nativeInstructions,
362
+ instructions: prepareInstructions,
261
363
  }).compileToV0Message();
262
364
  const tx = new VersionedTransaction(messageV0);
263
365
  batch.push({
@@ -266,7 +368,7 @@ export class SolanaStreamClient extends BaseStreamClient {
266
368
  });
267
369
  }
268
370
  const signedBatch = await signAllTransactionWithRecipients(sender, batch);
269
- if (isNative) {
371
+ if (prepareInstructions.length > 0) {
270
372
  const prepareTx = signedBatch.pop();
271
373
  await sendAndConfirmStreamRawTransaction(this.connection, prepareTx, { hash, context }, { sendThrottler: this.sendThrottler });
272
374
  }
@@ -330,21 +432,22 @@ export class SolanaStreamClient extends BaseStreamClient {
330
432
  throw new Error("Couldn't get account info");
331
433
  }
332
434
  const data = decodeStream(escrow.data);
333
- const { tokenProgramId } = await getMintAndProgram(this.connection, data.mint);
334
- const streamflowTreasuryTokens = await ata(data.mint, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
335
- const partnerTokens = await ata(data.mint, data.partner, tokenProgramId);
336
- await this.checkAssociatedTokenAccounts(data, { invoker, checkTokenAccounts }, ixs, tokenProgramId);
337
- ixs.push(withdrawStreamInstruction(amount, this.programId, {
435
+ const { sender, recipient, mint, streamflowTreasury, partner, recipientTokens, escrowTokens } = data;
436
+ const { tokenProgramId } = await getMintAndProgram(this.connection, mint);
437
+ const streamflowTreasuryTokens = await ata(mint, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
438
+ const partnerTokens = await ata(mint, partner, tokenProgramId);
439
+ const ataIx = await this.getCreateATAInstructions([sender, recipient, streamflowTreasury, partner], mint, invoker, checkTokenAccounts, tokenProgramId);
440
+ ixs.push(...ataIx, withdrawStreamInstruction(amount, this.programId, {
441
+ partner,
442
+ partnerTokens,
443
+ mint,
444
+ streamflowTreasuryTokens,
445
+ recipientTokens,
446
+ escrowTokens,
338
447
  authority: invoker.publicKey,
339
448
  recipient: invoker.publicKey,
340
- recipientTokens: data.recipientTokens,
341
449
  metadata: streamPublicKey,
342
- escrowTokens: data.escrowTokens,
343
450
  streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
344
- streamflowTreasuryTokens,
345
- partner: data.partner,
346
- partnerTokens,
347
- mint: data.mint,
348
451
  tokenProgram: tokenProgramId,
349
452
  }));
350
453
  return ixs;
@@ -352,8 +455,8 @@ export class SolanaStreamClient extends BaseStreamClient {
352
455
  /**
353
456
  * Attempts canceling the specified stream.
354
457
  */
355
- async cancel({ id }, extParams) {
356
- const ixs = await this.prepareCancelInstructions({ id }, extParams);
458
+ async cancel(cancelData, extParams) {
459
+ const ixs = await this.prepareCancelInstructions(cancelData, extParams);
357
460
  const { tx, hash, context } = await prepareTransaction(this.connection, ixs, extParams.invoker.publicKey);
358
461
  const signature = await signAndExecuteTransaction(this.connection, extParams.invoker, tx, {
359
462
  hash,
@@ -362,10 +465,57 @@ export class SolanaStreamClient extends BaseStreamClient {
362
465
  }, { sendThrottler: this.sendThrottler });
363
466
  return { ixs, txId: signature };
364
467
  }
468
+ async prepareCancelInstructions(cancelData, extParams) {
469
+ const streamPublicKey = new PublicKey(cancelData.id);
470
+ const account = await this.connection.getAccountInfo(streamPublicKey);
471
+ if (!account) {
472
+ throw new Error("Impossible to cancel a stream contract that does not exist");
473
+ }
474
+ const { sender: senderPublicKey } = decodeStream(account.data);
475
+ const isAlignedUnlock = this.isAlignedUnlock(streamPublicKey, senderPublicKey);
476
+ const ixs = isAlignedUnlock
477
+ ? await this.prepareCancelAlignedUnlockInstructions(cancelData, extParams)
478
+ : await this.prepareCancelStreamInstructions(cancelData, extParams);
479
+ return ixs;
480
+ }
481
+ async prepareCancelAlignedUnlockInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
482
+ if (!invoker.publicKey) {
483
+ throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
484
+ }
485
+ const streamPublicKey = new PublicKey(id);
486
+ const escrowAcc = await this.connection.getAccountInfo(streamPublicKey);
487
+ if (!escrowAcc?.data) {
488
+ throw new Error("Couldn't get account info");
489
+ }
490
+ const streamData = decodeStream(escrowAcc.data);
491
+ const { sender, recipient, mint, streamflowTreasury, partner, escrowTokens } = streamData;
492
+ const { tokenProgramId } = await getMintAndProgram(this.connection, mint);
493
+ const ixs = prepareBaseInstructions(this.connection, {
494
+ computePrice,
495
+ computeLimit: computeLimit ?? ALIGNED_COMPUTE_LIMIT,
496
+ });
497
+ const ataIx = await this.getCreateATAInstructions([sender, recipient, partner, streamflowTreasury], mint, invoker, checkTokenAccounts, tokenProgramId);
498
+ const cancelIx = await this.alignedProxyProgram.methods
499
+ .cancel()
500
+ .accountsPartial({
501
+ mint,
502
+ partner,
503
+ recipient,
504
+ escrowTokens,
505
+ sender: invoker.publicKey,
506
+ streamMetadata: streamPublicKey,
507
+ streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
508
+ tokenProgram: tokenProgramId,
509
+ streamflowProgram: this.programId,
510
+ })
511
+ .instruction();
512
+ ixs.push(...ataIx, cancelIx);
513
+ return ixs;
514
+ }
365
515
  /**
366
516
  * Creates Transaction Instructions for cancel
367
517
  */
368
- async prepareCancelInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
518
+ async prepareCancelStreamInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
369
519
  if (!invoker.publicKey) {
370
520
  throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
371
521
  }
@@ -374,28 +524,29 @@ export class SolanaStreamClient extends BaseStreamClient {
374
524
  if (!escrowAcc?.data) {
375
525
  throw new Error("Couldn't get account info");
376
526
  }
377
- const data = decodeStream(escrowAcc?.data);
378
- const { tokenProgramId } = await getMintAndProgram(this.connection, data.mint);
379
- const streamflowTreasuryTokens = await ata(data.mint, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
380
- const partnerTokens = await ata(data.mint, data.partner, tokenProgramId);
527
+ const data = decodeStream(escrowAcc.data);
528
+ const { sender, recipient, partner, streamflowTreasury, mint, senderTokens, recipientTokens, escrowTokens } = data;
529
+ const { tokenProgramId } = await getMintAndProgram(this.connection, mint);
530
+ const streamflowTreasuryTokens = await ata(mint, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
531
+ const partnerTokens = await ata(mint, partner, tokenProgramId);
381
532
  const ixs = prepareBaseInstructions(this.connection, {
382
533
  computePrice,
383
534
  computeLimit,
384
535
  });
385
- await this.checkAssociatedTokenAccounts(data, { invoker, checkTokenAccounts }, ixs, tokenProgramId);
386
- ixs.push(cancelStreamInstruction(this.programId, {
536
+ const ixsAta = await this.getCreateATAInstructions([sender, recipient, partner, streamflowTreasury], mint, invoker, checkTokenAccounts, tokenProgramId);
537
+ ixs.push(...ixsAta, cancelStreamInstruction(this.programId, {
538
+ sender,
539
+ senderTokens,
540
+ recipient,
541
+ recipientTokens,
542
+ streamflowTreasuryTokens,
543
+ partner,
544
+ partnerTokens,
545
+ mint,
546
+ escrowTokens,
387
547
  authority: invoker.publicKey,
388
- sender: data.sender,
389
- senderTokens: data.senderTokens,
390
- recipient: data.recipient,
391
- recipientTokens: data.recipientTokens,
392
548
  metadata: streamPublicKey,
393
- escrowTokens: data.escrowTokens,
394
549
  streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
395
- streamflowTreasuryTokens: streamflowTreasuryTokens,
396
- partner: data.partner,
397
- partnerTokens,
398
- mint: data.mint,
399
550
  tokenProgram: tokenProgramId,
400
551
  }));
401
552
  return ixs;
@@ -504,11 +655,56 @@ export class SolanaStreamClient extends BaseStreamClient {
504
655
  * Fetch stream data by its id (address).
505
656
  */
506
657
  async getOne({ id }) {
507
- const escrow = await this.connection.getAccountInfo(new PublicKey(id), TX_FINALITY_CONFIRMED);
658
+ const streamPublicKey = new PublicKey(id);
659
+ const escrow = await this.connection.getAccountInfo(streamPublicKey, TX_FINALITY_CONFIRMED);
508
660
  if (!escrow?.data) {
509
661
  throw new Error("Couldn't get account info.");
510
662
  }
511
- return new Contract(decodeStream(escrow?.data));
663
+ const stream = decodeStream(escrow.data);
664
+ if (this.isAlignedUnlock(streamPublicKey, stream.sender)) {
665
+ const alignedProxy = await this.alignedProxyProgram.account.contract.fetch(deriveContractPDA(this.alignedProxyProgram.programId, streamPublicKey));
666
+ if (!alignedProxy) {
667
+ throw new Error("Couldn't get proxy account info.");
668
+ }
669
+ return new AlignedContract(stream, alignedProxy);
670
+ }
671
+ return new Contract(stream);
672
+ }
673
+ /**
674
+ * Fetch all aligned outgoing streams/contracts by the provided public key.
675
+ */
676
+ async getOutgoingAlignedStreams(sender) {
677
+ const streams = {};
678
+ const alignedOutgoingProgramAccounts = await this.alignedProxyProgram.account.contract.all([
679
+ {
680
+ memcmp: {
681
+ offset: ORIGINAL_CONTRACT_SENDER_OFFSET,
682
+ bytes: sender,
683
+ },
684
+ },
685
+ ]);
686
+ const streamPubKeys = alignedOutgoingProgramAccounts.map((account) => account.account.stream);
687
+ const streamAccounts = await this.connection.getMultipleAccountsInfo(streamPubKeys, TX_FINALITY_CONFIRMED);
688
+ streamAccounts.forEach((account, index) => {
689
+ if (account) {
690
+ const alignedData = alignedOutgoingProgramAccounts[index].account;
691
+ streams[streamPubKeys[index].toBase58()] = new AlignedContract(decodeStream(account.data), alignedData);
692
+ }
693
+ });
694
+ return streams;
695
+ }
696
+ async getIncomingAlignedStreams(streamRecord) {
697
+ const streams = {};
698
+ const alignedStreamsPubKeys = Object.keys(streamRecord);
699
+ const alignedProxyPDAs = alignedStreamsPubKeys.map((streamPubKey) => deriveContractPDA(this.alignedProxyProgram.programId, new PublicKey(streamPubKey)));
700
+ const alignedProxyAccounts = await this.alignedProxyProgram.account.contract.fetchMultiple(alignedProxyPDAs);
701
+ alignedProxyAccounts.forEach((account, index) => {
702
+ if (account) {
703
+ const alignedData = streamRecord[alignedStreamsPubKeys[index]];
704
+ streams[alignedStreamsPubKeys[index]] = new AlignedContract(alignedData, account);
705
+ }
706
+ });
707
+ return streams;
512
708
  }
513
709
  /**
514
710
  * Fetch streams/contracts by providing direction.
@@ -516,27 +712,58 @@ export class SolanaStreamClient extends BaseStreamClient {
516
712
  */
517
713
  async get({ address, type = StreamType.All, direction = StreamDirection.All, }) {
518
714
  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];
715
+ let streams = {};
716
+ // don't do unnecessary rpc calls if we are not querying for vesting streams
717
+ const shouldFetchAligned = type === StreamType.All || type === StreamType.Vesting;
718
+ if (direction !== StreamDirection.Incoming) {
719
+ const outgoingStreamAccounts = await getProgramAccounts(this.connection, publicKey, STREAM_STRUCT_OFFSET_SENDER, this.programId);
720
+ outgoingStreamAccounts.forEach((account) => {
721
+ streams[account.pubkey.toBase58()] = new Contract(decodeStream(account.account.data));
722
+ });
723
+ if (shouldFetchAligned) {
724
+ const alignedStreams = await this.getOutgoingAlignedStreams(address);
725
+ streams = { ...streams, ...alignedStreams };
726
+ }
525
727
  }
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);
728
+ if (direction !== StreamDirection.Outgoing) {
729
+ const allIncomingAccounts = await getProgramAccounts(this.connection, publicKey, STREAM_STRUCT_OFFSET_RECIPIENT, this.programId);
730
+ const allIncomingStreams = allIncomingAccounts.map((account) => decodeStream(account.account.data));
731
+ const alignedDecoded = {};
732
+ // filter out aligned unlocks and store them in a separate object
733
+ allIncomingAccounts.forEach((account, index) => {
734
+ if (this.isAlignedUnlock(account.pubkey, allIncomingStreams[index].sender)) {
735
+ alignedDecoded[account.pubkey.toBase58()] = allIncomingStreams[index];
736
+ }
737
+ else {
738
+ streams[account.pubkey.toBase58()] = new Contract(allIncomingStreams[index]);
739
+ }
740
+ });
741
+ if (shouldFetchAligned) {
742
+ const incomingAlignedStreams = await this.getIncomingAlignedStreams(alignedDecoded);
743
+ streams = { ...streams, ...incomingAlignedStreams };
744
+ }
529
745
  }
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
746
  const sortedStreams = Object.entries(streams).sort(([, stream1], [, stream2]) => stream2.start - stream1.start);
536
- if (type === "all")
747
+ if (type === StreamType.All)
537
748
  return sortedStreams;
538
749
  return sortedStreams.filter((stream) => stream[1].type === type);
539
750
  }
751
+ async searchStreams(data) {
752
+ const filters = Object.entries(data)
753
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
754
+ .filter(([_, value]) => value) // Only keep entries where the value is truthy
755
+ .map(([key, value]) => ({
756
+ memcmp: {
757
+ offset: STREAM_STRUCT_OFFSETS[key],
758
+ bytes: value,
759
+ },
760
+ }));
761
+ const accounts = await this.connection.getProgramAccounts(this.programId, { filters });
762
+ return accounts.map(({ pubkey, account }) => ({
763
+ publicKey: pubkey,
764
+ account: new Contract(decodeStream(account.data)),
765
+ }));
766
+ }
540
767
  /**
541
768
  * Attempts updating the stream auto withdrawal params and amount per period
542
769
  */
@@ -600,68 +827,6 @@ export class SolanaStreamClient extends BaseStreamClient {
600
827
  const logs = "logs" in err && Array.isArray(err.logs) ? err.logs : undefined;
601
828
  return extractSolanaErrorCode(err.toString() ?? "Unknown error!", logs);
602
829
  }
603
- /**
604
- * Forms instructions from params, creates a raw transaction and fetch recent blockhash.
605
- */
606
- async prepareStreamInstructions(recipient, streamParams, extParams) {
607
- const { tokenId: mint, start, period, cliff, canTopup, canUpdateRate, canPause, cancelableBySender, cancelableByRecipient, transferableBySender, transferableByRecipient, automaticWithdrawal = false, withdrawalFrequency = 0, partner, } = streamParams;
608
- const { sender, metadataPubKeys, computeLimit, computePrice } = extParams;
609
- if (!sender.publicKey) {
610
- throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
611
- }
612
- const ixs = prepareBaseInstructions(this.connection, {
613
- computePrice,
614
- computeLimit,
615
- });
616
- const recipientPublicKey = new PublicKey(recipient.recipient);
617
- const mintPublicKey = new PublicKey(mint);
618
- const { metadata, metadataPubKey } = this.getOrCreateStreamMetadata(metadataPubKeys);
619
- const [escrowTokens] = PublicKey.findProgramAddressSync([Buffer.from("strm"), metadataPubKey.toBuffer()], this.programId);
620
- const { tokenProgramId } = await getMintAndProgram(this.connection, mintPublicKey);
621
- const senderTokens = await ata(mintPublicKey, sender.publicKey, tokenProgramId);
622
- const recipientTokens = await ata(mintPublicKey, recipientPublicKey, tokenProgramId);
623
- const streamflowTreasuryTokens = await ata(mintPublicKey, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
624
- const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
625
- const partnerTokens = await ata(mintPublicKey, partnerPublicKey, tokenProgramId);
626
- ixs.push(createStreamInstruction({
627
- start: BigNumber(start),
628
- depositedAmount: recipient.amount,
629
- period: BigNumber(period),
630
- amountPerPeriod: recipient.amountPerPeriod,
631
- cliff: BigNumber(cliff),
632
- cliffAmount: BigNumber(recipient.cliffAmount),
633
- cancelableBySender,
634
- cancelableByRecipient,
635
- automaticWithdrawal,
636
- transferableBySender,
637
- transferableByRecipient,
638
- canTopup,
639
- canUpdateRate: !!canUpdateRate,
640
- canPause: !!canPause,
641
- name: recipient.name,
642
- withdrawFrequency: BigNumber(automaticWithdrawal ? withdrawalFrequency : period),
643
- }, this.programId, {
644
- sender: sender.publicKey,
645
- senderTokens,
646
- recipient: new PublicKey(recipient.recipient),
647
- metadata: metadataPubKey,
648
- escrowTokens,
649
- recipientTokens,
650
- streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
651
- streamflowTreasuryTokens: streamflowTreasuryTokens,
652
- partner: partnerPublicKey,
653
- partnerTokens: partnerTokens,
654
- mint: new PublicKey(mint),
655
- feeOracle: FEE_ORACLE_PUBLIC_KEY,
656
- rent: SYSVAR_RENT_PUBKEY,
657
- timelockProgram: this.programId,
658
- tokenProgram: tokenProgramId,
659
- associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
660
- withdrawor: WITHDRAWOR_PUBLIC_KEY,
661
- systemProgram: SystemProgram.programId,
662
- }));
663
- return { ixs, metadata, metadataPubKey };
664
- }
665
830
  /**
666
831
  * Utility function to generate metadata for a Contract or return existing Pubkey
667
832
  */
@@ -678,18 +843,21 @@ export class SolanaStreamClient extends BaseStreamClient {
678
843
  return { metadata, metadataPubKey };
679
844
  }
680
845
  /**
681
- * Utility function that checks whether associated token accounts still exist and adds instructions to add them if not
846
+ * Utility function that checks whether the associated stream address is an aligned unlock contract, indicated by whether the sender/creator is a PDA
682
847
  */
683
- async checkAssociatedTokenAccounts(data, { invoker, checkTokenAccounts }, ixs, programId) {
848
+ isAlignedUnlock(streamPublicKey, senderPublicKey) {
849
+ const pda = deriveContractPDA(this.alignedProxyProgram.programId, streamPublicKey);
850
+ return senderPublicKey.equals(pda);
851
+ }
852
+ /**
853
+ * Returns insrtuctions for creating associated token accounts for the provided owners
854
+ */
855
+ async getCreateATAInstructions(owners, mint, invoker, checkTokenAccounts, programId) {
684
856
  if (!checkTokenAccounts) {
685
- return;
686
- }
687
- const owners = Array.from(new Set([
688
- data.sender.toBase58(),
689
- data.recipient.toBase58(),
690
- data.partner.toBase58(),
691
- data.streamflowTreasury.toBase58(),
692
- ]), (address) => new PublicKey(address));
693
- ixs.push(...(await checkOrCreateAtaBatch(this.connection, owners, data.mint, invoker, programId)));
857
+ return [];
858
+ }
859
+ // filter out duplicate PublicKeys, otherwise transaction will fail
860
+ const uniqueOwners = Array.from(new Set(owners.map((owner) => owner.toBase58()))).map((pkString) => new PublicKey(pkString));
861
+ return checkOrCreateAtaBatch(this.connection, uniqueOwners, mint, invoker, programId);
694
862
  }
695
863
  }