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

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 +290 -139
  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 +22 -16
  22. package/dist/esm/solana/StreamClient.js +293 -141
  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,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
  }
@@ -74,13 +171,6 @@ export class SolanaStreamClient extends BaseStreamClient {
74
171
  const streamflowTreasuryTokens = await ata(mintPublicKey, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
75
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: partnerPublicKey.toString(),
80
- });
81
- const totalAmount = calculateTotalAmountToDeposit(depositedAmount, totalFee);
82
- ixs.push(...(await prepareWrappedAccount(this.connection, sender.publicKey, totalAmount)));
83
- }
84
174
  ixs.push(createStreamInstruction({
85
175
  start: new BN(start),
86
176
  depositedAmount,
@@ -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
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,24 +712,39 @@ 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
  }
@@ -616,68 +827,6 @@ export class SolanaStreamClient extends BaseStreamClient {
616
827
  const logs = "logs" in err && Array.isArray(err.logs) ? err.logs : undefined;
617
828
  return extractSolanaErrorCode(err.toString() ?? "Unknown error!", logs);
618
829
  }
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
830
  /**
682
831
  * Utility function to generate metadata for a Contract or return existing Pubkey
683
832
  */
@@ -694,18 +843,21 @@ export class SolanaStreamClient extends BaseStreamClient {
694
843
  return { metadata, metadataPubKey };
695
844
  }
696
845
  /**
697
- * 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
698
847
  */
699
- 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) {
700
856
  if (!checkTokenAccounts) {
701
- return;
702
- }
703
- const owners = Array.from(new Set([
704
- data.sender.toBase58(),
705
- data.recipient.toBase58(),
706
- data.partner.toBase58(),
707
- data.streamflowTreasury.toBase58(),
708
- ]), (address) => new PublicKey(address));
709
- 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);
710
862
  }
711
863
  }
@@ -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 = 9;
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;