@streamflow/stream 7.0.0-alpha.11 → 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 (56) hide show
  1. package/README.md +22 -17
  2. package/dist/cjs/__tests__/aptos/streamClient.spec.js +4 -4
  3. package/dist/cjs/aptos/types.js +12 -12
  4. package/dist/cjs/common/constants.js +4 -3
  5. package/dist/cjs/common/contractUtils.js +23 -7
  6. package/dist/cjs/common/types.js +30 -1
  7. package/dist/cjs/common/utils.js +22 -19
  8. package/dist/cjs/evm/StreamClient.js +7 -7
  9. package/dist/cjs/evm/types.js +12 -12
  10. package/dist/cjs/solana/StreamClient.js +256 -111
  11. package/dist/cjs/solana/constants.js +29 -1
  12. package/dist/cjs/solana/descriptor/idl/streamflow_aligned_unlocks.json +1471 -0
  13. package/dist/cjs/solana/descriptor/streamflow_aligned_unlocks.js +2 -0
  14. package/dist/cjs/solana/index.js +2 -1
  15. package/dist/cjs/solana/instructions.js +18 -19
  16. package/dist/cjs/solana/lib/derive-accounts.js +17 -0
  17. package/dist/cjs/solana/{utils.js → lib/utils.js} +29 -36
  18. package/dist/cjs/solana/types.js +26 -3
  19. package/dist/cjs/sui/StreamClient.js +1 -1
  20. package/dist/cjs/sui/types.js +12 -12
  21. package/dist/esm/__tests__/aptos/streamClient.spec.js +4 -4
  22. package/dist/esm/aptos/types.d.ts +14 -14
  23. package/dist/esm/aptos/types.js +13 -13
  24. package/dist/esm/common/constants.d.ts +3 -2
  25. package/dist/esm/common/constants.js +3 -2
  26. package/dist/esm/common/contractUtils.d.ts +18 -15
  27. package/dist/esm/common/contractUtils.js +19 -6
  28. package/dist/esm/common/types.d.ts +112 -57
  29. package/dist/esm/common/types.js +29 -0
  30. package/dist/esm/common/utils.d.ts +11 -11
  31. package/dist/esm/common/utils.js +19 -16
  32. package/dist/esm/evm/StreamClient.d.ts +2 -2
  33. package/dist/esm/evm/StreamClient.js +7 -7
  34. package/dist/esm/evm/types.d.ts +14 -14
  35. package/dist/esm/evm/types.js +13 -13
  36. package/dist/esm/solana/StreamClient.d.ts +20 -14
  37. package/dist/esm/solana/StreamClient.js +259 -113
  38. package/dist/esm/solana/constants.d.ts +14 -0
  39. package/dist/esm/solana/constants.js +29 -1
  40. package/dist/esm/solana/descriptor/idl/streamflow_aligned_unlocks.json +1471 -0
  41. package/dist/esm/solana/descriptor/streamflow_aligned_unlocks.d.ts +1272 -0
  42. package/dist/esm/solana/descriptor/streamflow_aligned_unlocks.js +1 -0
  43. package/dist/esm/solana/index.d.ts +2 -1
  44. package/dist/esm/solana/index.js +2 -1
  45. package/dist/esm/solana/instructions.d.ts +17 -17
  46. package/dist/esm/solana/instructions.js +18 -19
  47. package/dist/esm/solana/lib/derive-accounts.d.ts +4 -0
  48. package/dist/esm/solana/lib/derive-accounts.js +11 -0
  49. package/dist/esm/solana/{utils.d.ts → lib/utils.d.ts} +1 -3
  50. package/dist/esm/solana/{utils.js → lib/utils.js} +28 -34
  51. package/dist/esm/solana/types.d.ts +67 -39
  52. package/dist/esm/solana/types.js +32 -4
  53. package/dist/esm/sui/StreamClient.js +1 -1
  54. package/dist/esm/sui/types.d.ts +14 -14
  55. package/dist/esm/sui/types.js +13 -13
  56. package/package.json +7 -5
@@ -28,20 +28,25 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
28
28
  };
29
29
  Object.defineProperty(exports, "__esModule", { value: true });
30
30
  exports.SolanaStreamClient = void 0;
31
- const bignumber_js_1 = __importDefault(require("bignumber.js"));
31
+ const bn_js_1 = __importDefault(require("bn.js"));
32
32
  const buffer_1 = require("buffer");
33
33
  const spl_token_1 = require("@solana/spl-token");
34
34
  const web3_js_1 = require("@solana/web3.js");
35
35
  const solana_1 = require("@streamflow/common/solana");
36
36
  const borsh = __importStar(require("borsh"));
37
+ const anchor_1 = require("@coral-xyz/anchor");
38
+ const common_1 = require("@streamflow/common");
37
39
  const types_js_1 = require("./types.js");
38
- const utils_js_1 = require("./utils.js");
40
+ const utils_js_1 = require("./lib/utils.js");
39
41
  const constants_js_1 = require("./constants.js");
40
42
  const instructions_js_1 = require("./instructions.js");
41
43
  const types_js_2 = require("../common/types.js");
42
44
  const BaseStreamClient_js_1 = require("../common/BaseStreamClient.js");
43
45
  const utils_js_2 = require("../common/utils.js");
44
46
  const constants_js_2 = require("../common/constants.js");
47
+ const streamflow_aligned_unlocks_json_1 = __importDefault(require("./descriptor/idl/streamflow_aligned_unlocks.json"));
48
+ const derive_accounts_js_1 = require("./lib/derive-accounts.js");
49
+ const contractUtils_js_1 = require("../common/contractUtils.js");
45
50
  const METADATA_ACC_SIZE = 1104;
46
51
  class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
47
52
  /**
@@ -53,6 +58,11 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
53
58
  this.connection = new web3_js_1.Connection(clusterUrl, this.commitment);
54
59
  this.programId = programId !== "" ? new web3_js_1.PublicKey(programId) : new web3_js_1.PublicKey(constants_js_1.PROGRAM_ID[cluster]);
55
60
  this.sendThrottler = sendThrottler ?? (0, solana_1.buildSendThrottler)(sendRate);
61
+ const alignedUnlocksProgram = {
62
+ ...streamflow_aligned_unlocks_json_1.default,
63
+ address: streamflow_aligned_unlocks_json_1.default.address,
64
+ };
65
+ this.alignedProxyProgram = new anchor_1.Program(alignedUnlocksProgram, { connection: this.connection });
56
66
  }
57
67
  getConnection() {
58
68
  return this.connection;
@@ -68,7 +78,20 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
68
78
  * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
69
79
  */
70
80
  async create(data, extParams) {
81
+ const { partner, amount } = data;
82
+ const { isNative, sender } = extParams;
83
+ const partnerPublicKey = partner ? new web3_js_1.PublicKey(partner) : constants_js_1.WITHDRAWOR_PUBLIC_KEY;
84
+ if (!sender.publicKey) {
85
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
86
+ }
71
87
  const { ixs, metadata, metadataPubKey } = await this.prepareCreateInstructions(data, extParams);
88
+ if (isNative) {
89
+ const totalFee = await this.getTotalFee({
90
+ address: partnerPublicKey.toString(),
91
+ });
92
+ const totalAmount = (0, utils_js_2.calculateTotalAmountToDeposit)(amount, totalFee);
93
+ ixs.push(...(await (0, solana_1.prepareWrappedAccount)(this.connection, sender.publicKey, totalAmount)));
94
+ }
72
95
  const { tx, hash, context } = await (0, solana_1.prepareTransaction)(this.connection, ixs, extParams.sender.publicKey, undefined, metadata);
73
96
  const signature = await (0, solana_1.signAndExecuteTransaction)(this.connection, extParams.sender, tx, {
74
97
  hash,
@@ -77,11 +100,80 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
77
100
  }, { sendThrottler: this.sendThrottler });
78
101
  return { ixs, txId: signature, metadataId: metadataPubKey.toBase58() };
79
102
  }
103
+ async prepareCreateInstructions(streamParams, extParams) {
104
+ const { ixs, metadata, metadataPubKey } = (0, contractUtils_js_1.isCreateAlignedStreamData)(streamParams)
105
+ ? await this.prepareCreateAlignedUnlockInstructions(streamParams, extParams)
106
+ : await this.prepareCreateStreamInstructions(streamParams, extParams);
107
+ return { ixs, metadata, metadataPubKey };
108
+ }
109
+ async prepareCreateAlignedUnlockInstructions(streamParams, extParams) {
110
+ 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;
111
+ const { isNative, sender, computeLimit, computePrice, metadataPubKeys } = extParams;
112
+ if (!sender.publicKey) {
113
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
114
+ }
115
+ if (!priceOracle && oracleType && oracleType !== "none") {
116
+ throw new Error("Price oracle is required for the specified oracle type");
117
+ }
118
+ const recipientPublicKey = new web3_js_1.PublicKey(recipient);
119
+ const mintPublicKey = isNative ? spl_token_1.NATIVE_MINT : new web3_js_1.PublicKey(mint);
120
+ const metadata = !metadataPubKeys ? web3_js_1.Keypair.generate() : undefined;
121
+ const metadataPubKey = metadata ? metadata.publicKey : metadataPubKeys[0];
122
+ const { tokenProgramId } = await (0, solana_1.getMintAndProgram)(this.connection, mintPublicKey);
123
+ const partnerPublicKey = partner ? new web3_js_1.PublicKey(partner) : constants_js_1.WITHDRAWOR_PUBLIC_KEY;
124
+ const streamflowProgramPublicKey = new web3_js_1.PublicKey(this.programId);
125
+ const escrowPDA = (0, derive_accounts_js_1.deriveEscrowPDA)(streamflowProgramPublicKey, metadataPubKey);
126
+ const oracle = priceOracle ?? (0, derive_accounts_js_1.deriveTestOraclePDA)(this.alignedProxyProgram.programId, mintPublicKey, sender.publicKey);
127
+ const ixs = (0, solana_1.prepareBaseInstructions)(this.connection, {
128
+ computePrice,
129
+ computeLimit: computeLimit ?? constants_js_1.ALIGNED_COMPUTE_LIMIT,
130
+ });
131
+ const encodedUIntArray = new TextEncoder().encode(streamName);
132
+ const streamNameArray = Array.from(encodedUIntArray);
133
+ const createIx = await this.alignedProxyProgram.methods
134
+ .create({
135
+ startTime: new bn_js_1.default(start),
136
+ netAmountDeposited: depositedAmount,
137
+ period: new bn_js_1.default(period),
138
+ amountPerPeriod: amountPerPeriod,
139
+ cliff: new bn_js_1.default(cliff),
140
+ cliffAmount: cliffAmount,
141
+ transferableBySender,
142
+ transferableByRecipient,
143
+ cancelableByRecipient,
144
+ cancelableBySender,
145
+ canTopup,
146
+ oracleType: (!!oracleType ? { [oracleType]: {} } : { none: {} }),
147
+ streamName: streamNameArray,
148
+ minPrice: (0, common_1.getBN)(minPrice, constants_js_1.ALIGNED_PRECISION_FACTOR_POW),
149
+ maxPrice: (0, common_1.getBN)(maxPrice, constants_js_1.ALIGNED_PRECISION_FACTOR_POW),
150
+ minPercentage: (0, common_1.getBN)(minPercentage, constants_js_1.ALIGNED_PRECISION_FACTOR_POW),
151
+ maxPercentage: (0, common_1.getBN)(maxPercentage, constants_js_1.ALIGNED_PRECISION_FACTOR_POW),
152
+ tickSize: new bn_js_1.default(tickSize || 1),
153
+ skipInitial: skipInitial ?? false,
154
+ })
155
+ .accountsPartial({
156
+ sender: sender.publicKey,
157
+ streamMetadata: metadataPubKey,
158
+ escrowTokens: escrowPDA,
159
+ mint: mintPublicKey,
160
+ partner: partnerPublicKey,
161
+ recipient: recipientPublicKey,
162
+ withdrawor: constants_js_1.WITHDRAWOR_PUBLIC_KEY,
163
+ feeOracle: constants_js_1.FEE_ORACLE_PUBLIC_KEY,
164
+ priceOracle: oracle,
165
+ tokenProgram: tokenProgramId,
166
+ streamflowProgram: this.programId,
167
+ })
168
+ .instruction();
169
+ ixs.push(createIx);
170
+ return { ixs, metadata, metadataPubKey };
171
+ }
80
172
  /**
81
173
  * Creates a new stream/vesting contract.
82
174
  * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
83
175
  */
84
- 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 }) {
176
+ 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 }) {
85
177
  if (!sender.publicKey) {
86
178
  throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
87
179
  }
@@ -99,20 +191,13 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
99
191
  const streamflowTreasuryTokens = await (0, solana_1.ata)(mintPublicKey, constants_js_1.STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
100
192
  const partnerPublicKey = partner ? new web3_js_1.PublicKey(partner) : constants_js_1.WITHDRAWOR_PUBLIC_KEY;
101
193
  const partnerTokens = await (0, solana_1.ata)(mintPublicKey, partnerPublicKey, tokenProgramId);
102
- if (isNative) {
103
- const totalFee = await this.getTotalFee({
104
- address: partnerPublicKey.toString(),
105
- });
106
- const totalAmount = (0, utils_js_2.calculateTotalAmountToDeposit)(depositedAmount, totalFee);
107
- ixs.push(...(await (0, solana_1.prepareWrappedAccount)(this.connection, sender.publicKey, totalAmount)));
108
- }
109
194
  ixs.push((0, instructions_js_1.createStreamInstruction)({
110
- start: (0, bignumber_js_1.default)(start),
195
+ start: new bn_js_1.default(start),
111
196
  depositedAmount,
112
- period: (0, bignumber_js_1.default)(period),
197
+ period: new bn_js_1.default(period),
113
198
  amountPerPeriod,
114
- cliff: (0, bignumber_js_1.default)(cliff),
115
- cliffAmount: (0, bignumber_js_1.default)(cliffAmount),
199
+ cliff: new bn_js_1.default(cliff),
200
+ cliffAmount: new bn_js_1.default(cliffAmount),
116
201
  cancelableBySender,
117
202
  cancelableByRecipient,
118
203
  automaticWithdrawal,
@@ -122,7 +207,7 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
122
207
  canUpdateRate: !!canUpdateRate,
123
208
  canPause: !!canPause,
124
209
  name,
125
- withdrawFrequency: (0, bignumber_js_1.default)(automaticWithdrawal ? withdrawalFrequency : period),
210
+ withdrawFrequency: new bn_js_1.default(automaticWithdrawal ? withdrawalFrequency : period),
126
211
  }, this.programId, {
127
212
  sender: sender.publicKey,
128
213
  senderTokens,
@@ -197,12 +282,12 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
197
282
  ixs.push(...(await (0, solana_1.prepareWrappedAccount)(this.connection, sender.publicKey, totalAmount)));
198
283
  }
199
284
  const createInstruction = (0, instructions_js_1.createUncheckedStreamInstruction)({
200
- start: (0, bignumber_js_1.default)(start),
285
+ start: new bn_js_1.default(start),
201
286
  depositedAmount,
202
- period: (0, bignumber_js_1.default)(period),
287
+ period: new bn_js_1.default(period),
203
288
  amountPerPeriod,
204
- cliff: (0, bignumber_js_1.default)(cliff),
205
- cliffAmount: (0, bignumber_js_1.default)(cliffAmount),
289
+ cliff: new bn_js_1.default(cliff),
290
+ cliffAmount: new bn_js_1.default(cliffAmount),
206
291
  cancelableBySender,
207
292
  cancelableByRecipient,
208
293
  automaticWithdrawal,
@@ -212,7 +297,7 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
212
297
  canUpdateRate: !!canUpdateRate,
213
298
  canPause: !!canPause,
214
299
  name,
215
- withdrawFrequency: (0, bignumber_js_1.default)(automaticWithdrawal ? withdrawalFrequency : period),
300
+ withdrawFrequency: new bn_js_1.default(automaticWithdrawal ? withdrawalFrequency : period),
216
301
  recipient: recipientPublicKey,
217
302
  partner: partnerPublicKey,
218
303
  }, this.programId, {
@@ -235,26 +320,32 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
235
320
  * Creates multiple stream/vesting contracts.
236
321
  * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
237
322
  */
238
- async createMultiple(data, { sender, metadataPubKeys, isNative = false, computePrice, computeLimit }) {
239
- const { recipients } = data;
240
- if (!sender.publicKey) {
241
- throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
242
- }
323
+ async createMultiple(data, extParams) {
324
+ const { recipients, ...streamParams } = data;
325
+ const { sender, metadataPubKeys: metadataPubKeysExt, isNative, computePrice, computeLimit } = extParams;
243
326
  const metadatas = [];
244
327
  const metadataToRecipient = {};
245
328
  const errors = [];
246
329
  const signatures = [];
247
330
  const batch = [];
248
331
  const instructionsBatch = [];
249
- metadataPubKeys = metadataPubKeys || [];
332
+ const metadataPubKeys = metadataPubKeysExt || [];
333
+ if (recipients.length === 0) {
334
+ throw new Error("Recipients array is empty!");
335
+ }
336
+ if (!sender.publicKey) {
337
+ throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
338
+ }
250
339
  for (let i = 0; i < recipients.length; i++) {
251
340
  const recipientData = recipients[i];
252
- const { ixs, metadata, metadataPubKey } = await this.prepareStreamInstructions(recipientData, data, {
341
+ const createStreamData = { ...streamParams, ...recipientData };
342
+ const createStreamExtParams = {
253
343
  sender,
254
344
  metadataPubKeys: metadataPubKeys[i] ? [metadataPubKeys[i]] : undefined,
255
345
  computePrice,
256
346
  computeLimit,
257
- });
347
+ };
348
+ const { ixs, metadata, metadataPubKey } = await this.prepareCreateInstructions(createStreamData, createStreamExtParams);
258
349
  metadataToRecipient[metadataPubKey.toBase58()] = recipientData;
259
350
  metadatas.push(metadataPubKey.toBase58());
260
351
  instructionsBatch.push({
@@ -277,7 +368,7 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
277
368
  batch.push({ tx, recipient });
278
369
  }
279
370
  if (isNative) {
280
- const totalDepositedAmount = recipients.reduce((acc, recipient) => recipient.amount.plus(acc), (0, bignumber_js_1.default)(0));
371
+ const totalDepositedAmount = recipients.reduce((acc, recipient) => recipient.amount.add(acc), new bn_js_1.default(0));
281
372
  const nativeInstructions = await (0, solana_1.prepareWrappedAccount)(this.connection, sender.publicKey, totalDepositedAmount);
282
373
  const messageV0 = new web3_js_1.TransactionMessage({
283
374
  payerKey: sender.publicKey,
@@ -377,8 +468,8 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
377
468
  /**
378
469
  * Attempts canceling the specified stream.
379
470
  */
380
- async cancel({ id }, extParams) {
381
- const ixs = await this.prepareCancelInstructions({ id }, extParams);
471
+ async cancel(cancelData, extParams) {
472
+ const ixs = await this.prepareCancelInstructions(cancelData, extParams);
382
473
  const { tx, hash, context } = await (0, solana_1.prepareTransaction)(this.connection, ixs, extParams.invoker.publicKey);
383
474
  const signature = await (0, solana_1.signAndExecuteTransaction)(this.connection, extParams.invoker, tx, {
384
475
  hash,
@@ -387,10 +478,59 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
387
478
  }, { sendThrottler: this.sendThrottler });
388
479
  return { ixs, txId: signature };
389
480
  }
481
+ async prepareCancelInstructions(cancelData, extParams) {
482
+ const streamPublicKey = new web3_js_1.PublicKey(cancelData.id);
483
+ const account = await this.connection.getAccountInfo(streamPublicKey);
484
+ if (!account) {
485
+ throw new Error("Impossible to cancel a stream contract that does not exist");
486
+ }
487
+ const { sender: senderPublicKey } = (0, utils_js_1.decodeStream)(account.data);
488
+ const isAlignedUnlock = this.isAlignedUnlock(streamPublicKey, senderPublicKey);
489
+ const ixs = isAlignedUnlock
490
+ ? await this.prepareCancelAlignedUnlockInstructions(cancelData, extParams)
491
+ : await this.prepareCancelStreamInstructions(cancelData, extParams);
492
+ return ixs;
493
+ }
494
+ async prepareCancelAlignedUnlockInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
495
+ if (!invoker.publicKey) {
496
+ throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
497
+ }
498
+ const streamPublicKey = new web3_js_1.PublicKey(id);
499
+ const escrowAcc = await this.connection.getAccountInfo(streamPublicKey);
500
+ if (!escrowAcc?.data) {
501
+ throw new Error("Couldn't get account info");
502
+ }
503
+ const streamflowProgramPublicKey = new web3_js_1.PublicKey(this.programId);
504
+ const streamData = (0, utils_js_1.decodeStream)(escrowAcc?.data);
505
+ const escrowPDA = (0, derive_accounts_js_1.deriveEscrowPDA)(streamflowProgramPublicKey, streamPublicKey);
506
+ const { tokenProgramId } = await (0, solana_1.getMintAndProgram)(this.connection, streamData.mint);
507
+ const partnerPublicKey = streamData.partner;
508
+ const ixs = (0, solana_1.prepareBaseInstructions)(this.connection, {
509
+ computePrice,
510
+ computeLimit: computeLimit ?? constants_js_1.ALIGNED_COMPUTE_LIMIT,
511
+ });
512
+ await this.checkAssociatedTokenAccounts(streamData, { invoker, checkTokenAccounts }, ixs, tokenProgramId);
513
+ const cancelIx = await this.alignedProxyProgram.methods
514
+ .cancel()
515
+ .accountsPartial({
516
+ sender: invoker.publicKey,
517
+ streamMetadata: streamPublicKey,
518
+ escrowTokens: escrowPDA,
519
+ recipient: streamData.recipient,
520
+ partner: partnerPublicKey,
521
+ streamflowTreasury: constants_js_1.STREAMFLOW_TREASURY_PUBLIC_KEY,
522
+ mint: streamData.mint,
523
+ tokenProgram: tokenProgramId,
524
+ streamflowProgram: this.programId,
525
+ })
526
+ .instruction();
527
+ ixs.push(cancelIx);
528
+ return ixs;
529
+ }
390
530
  /**
391
531
  * Creates Transaction Instructions for cancel
392
532
  */
393
- async prepareCancelInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
533
+ async prepareCancelStreamInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
394
534
  if (!invoker.publicKey) {
395
535
  throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
396
536
  }
@@ -529,11 +669,56 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
529
669
  * Fetch stream data by its id (address).
530
670
  */
531
671
  async getOne({ id }) {
532
- const escrow = await this.connection.getAccountInfo(new web3_js_1.PublicKey(id), constants_js_1.TX_FINALITY_CONFIRMED);
672
+ const streamPublicKey = new web3_js_1.PublicKey(id);
673
+ const escrow = await this.connection.getAccountInfo(streamPublicKey, constants_js_1.TX_FINALITY_CONFIRMED);
533
674
  if (!escrow?.data) {
534
675
  throw new Error("Couldn't get account info.");
535
676
  }
536
- return new types_js_1.Contract((0, utils_js_1.decodeStream)(escrow?.data));
677
+ const stream = (0, utils_js_1.decodeStream)(escrow.data);
678
+ if (this.isAlignedUnlock(streamPublicKey, stream.sender)) {
679
+ const alignedProxy = await this.alignedProxyProgram.account.contract.fetch((0, derive_accounts_js_1.deriveContractPDA)(this.alignedProxyProgram.programId, streamPublicKey));
680
+ if (!alignedProxy) {
681
+ throw new Error("Couldn't get proxy account info.");
682
+ }
683
+ return new types_js_1.AlignedContract(stream, alignedProxy);
684
+ }
685
+ return new types_js_1.Contract(stream);
686
+ }
687
+ /**
688
+ * Fetch all aligned outgoing streams/contracts by the provided public key.
689
+ */
690
+ async getOutgoingAlignedStreams(sender) {
691
+ const streams = {};
692
+ const alignedOutgoingProgramAccounts = await this.alignedProxyProgram.account.contract.all([
693
+ {
694
+ memcmp: {
695
+ offset: constants_js_1.ORIGINAL_CONTRACT_SENDER_OFFSET,
696
+ bytes: sender,
697
+ },
698
+ },
699
+ ]);
700
+ const streamPubKeys = alignedOutgoingProgramAccounts.map((account) => account.account.stream);
701
+ const streamAccounts = await this.connection.getMultipleAccountsInfo(streamPubKeys, constants_js_1.TX_FINALITY_CONFIRMED);
702
+ streamAccounts.forEach((account, index) => {
703
+ if (account) {
704
+ const alignedData = alignedOutgoingProgramAccounts[index].account;
705
+ streams[alignedData.sender.toBase58()] = new types_js_1.AlignedContract((0, utils_js_1.decodeStream)(account.data), alignedData);
706
+ }
707
+ });
708
+ return streams;
709
+ }
710
+ async getIncomingAlignedStreams(streamRecord) {
711
+ const streams = {};
712
+ const alignedStreamsPubKeys = Object.keys(streamRecord);
713
+ const alignedProxyPDAs = alignedStreamsPubKeys.map((streamPubKey) => (0, derive_accounts_js_1.deriveContractPDA)(this.alignedProxyProgram.programId, new web3_js_1.PublicKey(streamPubKey)));
714
+ const alignedProxyAccounts = await this.alignedProxyProgram.account.contract.fetchMultiple(alignedProxyPDAs);
715
+ alignedProxyAccounts.forEach((account, index) => {
716
+ if (account) {
717
+ const alignedData = streamRecord[alignedStreamsPubKeys[index]];
718
+ streams[alignedStreamsPubKeys[index]] = new types_js_1.AlignedContract(alignedData, account);
719
+ }
720
+ });
721
+ return streams;
537
722
  }
538
723
  /**
539
724
  * Fetch streams/contracts by providing direction.
@@ -541,24 +726,39 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
541
726
  */
542
727
  async get({ address, type = types_js_2.StreamType.All, direction = types_js_2.StreamDirection.All, }) {
543
728
  const publicKey = new web3_js_1.PublicKey(address);
544
- let accounts = [];
545
- //todo: we need to be smart with our layout so we minimize rpc calls to the chain
546
- if (direction === "all") {
547
- const outgoingAccounts = await (0, solana_1.getProgramAccounts)(this.connection, publicKey, constants_js_1.STREAM_STRUCT_OFFSET_SENDER, this.programId);
548
- const incomingAccounts = await (0, solana_1.getProgramAccounts)(this.connection, publicKey, constants_js_1.STREAM_STRUCT_OFFSET_RECIPIENT, this.programId);
549
- accounts = [...outgoingAccounts, ...incomingAccounts];
729
+ let streams = {};
730
+ // don't do unnecessary rpc calls if we are not querying for vesting streams
731
+ const shouldFetchAligned = type === types_js_2.StreamType.All || type === types_js_2.StreamType.Vesting;
732
+ if (direction !== types_js_2.StreamDirection.Incoming) {
733
+ const outgoingStreamAccounts = await (0, solana_1.getProgramAccounts)(this.connection, publicKey, constants_js_1.STREAM_STRUCT_OFFSET_SENDER, this.programId);
734
+ outgoingStreamAccounts.forEach((account) => {
735
+ streams[account.pubkey.toBase58()] = new types_js_1.Contract((0, utils_js_1.decodeStream)(account.account.data));
736
+ });
737
+ if (shouldFetchAligned) {
738
+ const alignedStreams = await this.getOutgoingAlignedStreams(address);
739
+ streams = { ...streams, ...alignedStreams };
740
+ }
550
741
  }
551
- else {
552
- const offset = direction === "outgoing" ? constants_js_1.STREAM_STRUCT_OFFSET_SENDER : constants_js_1.STREAM_STRUCT_OFFSET_RECIPIENT;
553
- accounts = await (0, solana_1.getProgramAccounts)(this.connection, publicKey, offset, this.programId);
742
+ if (direction !== types_js_2.StreamDirection.Outgoing) {
743
+ const allIncomingAccounts = await (0, solana_1.getProgramAccounts)(this.connection, publicKey, constants_js_1.STREAM_STRUCT_OFFSET_RECIPIENT, this.programId);
744
+ const allIncomingStreams = allIncomingAccounts.map((account) => (0, utils_js_1.decodeStream)(account.account.data));
745
+ const alignedDecoded = {};
746
+ // filter out aligned unlocks and store them in a separate object
747
+ allIncomingAccounts.forEach((account, index) => {
748
+ if (this.isAlignedUnlock(account.pubkey, allIncomingStreams[index].sender)) {
749
+ alignedDecoded[account.pubkey.toBase58()] = allIncomingStreams[index];
750
+ }
751
+ else {
752
+ streams[account.pubkey.toBase58()] = new types_js_1.Contract(allIncomingStreams[index]);
753
+ }
754
+ });
755
+ if (shouldFetchAligned) {
756
+ const incomingAlignedStreams = await this.getIncomingAlignedStreams(alignedDecoded);
757
+ streams = { ...streams, ...incomingAlignedStreams };
758
+ }
554
759
  }
555
- let streams = {};
556
- accounts.forEach((account) => {
557
- const decoded = new types_js_1.Contract((0, utils_js_1.decodeStream)(account.account.data));
558
- streams = { ...streams, [account.pubkey.toBase58()]: decoded };
559
- });
560
760
  const sortedStreams = Object.entries(streams).sort(([, stream1], [, stream2]) => stream2.start - stream1.start);
561
- if (type === "all")
761
+ if (type === types_js_2.StreamType.All)
562
762
  return sortedStreams;
563
763
  return sortedStreams.filter((stream) => stream[1].type === type);
564
764
  }
@@ -641,68 +841,6 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
641
841
  const logs = "logs" in err && Array.isArray(err.logs) ? err.logs : undefined;
642
842
  return (0, utils_js_1.extractSolanaErrorCode)(err.toString() ?? "Unknown error!", logs);
643
843
  }
644
- /**
645
- * Forms instructions from params, creates a raw transaction and fetch recent blockhash.
646
- */
647
- async prepareStreamInstructions(recipient, streamParams, extParams) {
648
- const { tokenId: mint, start, period, cliff, canTopup, canUpdateRate, canPause, cancelableBySender, cancelableByRecipient, transferableBySender, transferableByRecipient, automaticWithdrawal = false, withdrawalFrequency = 0, partner, } = streamParams;
649
- const { sender, metadataPubKeys, computeLimit, computePrice } = extParams;
650
- if (!sender.publicKey) {
651
- throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
652
- }
653
- const ixs = (0, solana_1.prepareBaseInstructions)(this.connection, {
654
- computePrice,
655
- computeLimit,
656
- });
657
- const recipientPublicKey = new web3_js_1.PublicKey(recipient.recipient);
658
- const mintPublicKey = new web3_js_1.PublicKey(mint);
659
- const { metadata, metadataPubKey } = this.getOrCreateStreamMetadata(metadataPubKeys);
660
- const [escrowTokens] = web3_js_1.PublicKey.findProgramAddressSync([buffer_1.Buffer.from("strm"), metadataPubKey.toBuffer()], this.programId);
661
- const { tokenProgramId } = await (0, solana_1.getMintAndProgram)(this.connection, mintPublicKey);
662
- const senderTokens = await (0, solana_1.ata)(mintPublicKey, sender.publicKey, tokenProgramId);
663
- const recipientTokens = await (0, solana_1.ata)(mintPublicKey, recipientPublicKey, tokenProgramId);
664
- const streamflowTreasuryTokens = await (0, solana_1.ata)(mintPublicKey, constants_js_1.STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
665
- const partnerPublicKey = partner ? new web3_js_1.PublicKey(partner) : constants_js_1.WITHDRAWOR_PUBLIC_KEY;
666
- const partnerTokens = await (0, solana_1.ata)(mintPublicKey, partnerPublicKey, tokenProgramId);
667
- ixs.push((0, instructions_js_1.createStreamInstruction)({
668
- start: (0, bignumber_js_1.default)(start),
669
- depositedAmount: recipient.amount,
670
- period: (0, bignumber_js_1.default)(period),
671
- amountPerPeriod: recipient.amountPerPeriod,
672
- cliff: (0, bignumber_js_1.default)(cliff),
673
- cliffAmount: (0, bignumber_js_1.default)(recipient.cliffAmount),
674
- cancelableBySender,
675
- cancelableByRecipient,
676
- automaticWithdrawal,
677
- transferableBySender,
678
- transferableByRecipient,
679
- canTopup,
680
- canUpdateRate: !!canUpdateRate,
681
- canPause: !!canPause,
682
- name: recipient.name,
683
- withdrawFrequency: (0, bignumber_js_1.default)(automaticWithdrawal ? withdrawalFrequency : period),
684
- }, this.programId, {
685
- sender: sender.publicKey,
686
- senderTokens,
687
- recipient: new web3_js_1.PublicKey(recipient.recipient),
688
- metadata: metadataPubKey,
689
- escrowTokens,
690
- recipientTokens,
691
- streamflowTreasury: constants_js_1.STREAMFLOW_TREASURY_PUBLIC_KEY,
692
- streamflowTreasuryTokens: streamflowTreasuryTokens,
693
- partner: partnerPublicKey,
694
- partnerTokens: partnerTokens,
695
- mint: new web3_js_1.PublicKey(mint),
696
- feeOracle: constants_js_1.FEE_ORACLE_PUBLIC_KEY,
697
- rent: web3_js_1.SYSVAR_RENT_PUBKEY,
698
- timelockProgram: this.programId,
699
- tokenProgram: tokenProgramId,
700
- associatedTokenProgram: spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID,
701
- withdrawor: constants_js_1.WITHDRAWOR_PUBLIC_KEY,
702
- systemProgram: web3_js_1.SystemProgram.programId,
703
- }));
704
- return { ixs, metadata, metadataPubKey };
705
- }
706
844
  /**
707
845
  * Utility function to generate metadata for a Contract or return existing Pubkey
708
846
  */
@@ -718,6 +856,13 @@ class SolanaStreamClient extends BaseStreamClient_js_1.BaseStreamClient {
718
856
  }
719
857
  return { metadata, metadataPubKey };
720
858
  }
859
+ /**
860
+ * Utility function that checks whether the associated stream address is an aligned unlock contract, indicated by whether the sender/creator is a PDA
861
+ */
862
+ isAlignedUnlock(streamPublicKey, senderPublicKey) {
863
+ const pda = (0, derive_accounts_js_1.deriveContractPDA)(this.alignedProxyProgram.programId, streamPublicKey);
864
+ return senderPublicKey.equals(pda);
865
+ }
721
866
  /**
722
867
  * Utility function that checks whether associated token accounts still exist and adds instructions to add them if not
723
868
  */
@@ -1,13 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SOLANA_ERROR_MAP = exports.SOLANA_ERROR_MATCH_REGEX = exports.PARTNERS_SCHEMA = exports.PARTNER_SCHEMA = exports.AIRDROP_AMOUNT = exports.DEFAULT_STREAMFLOW_FEE = exports.FEES_METADATA_SEED = exports.AIRDROP_TEST_TOKEN = exports.FEE_ORACLE_PUBLIC_KEY = exports.WITHDRAWOR_PUBLIC_KEY = exports.STREAMFLOW_TREASURY_PUBLIC_KEY = exports.PARTNER_ORACLE_PROGRAM_ID = exports.PROGRAM_ID = exports.CREATE_PARAMS_PADDING = exports.STREAM_STRUCT_OFFSETS = exports.STREAM_STRUCT_OFFSET_MINT = exports.STREAM_STRUCT_OFFSET_RECIPIENT = exports.STREAM_STRUCT_OFFSET_SENDER = exports.TX_FINALITY_CONFIRMED = void 0;
3
+ exports.SOLANA_ERROR_MAP = exports.SOLANA_ERROR_MATCH_REGEX = exports.PARTNERS_SCHEMA = exports.PARTNER_SCHEMA = exports.AIRDROP_AMOUNT = exports.DEFAULT_STREAMFLOW_FEE = exports.FEES_METADATA_SEED = exports.AIRDROP_TEST_TOKEN = exports.FEE_ORACLE_PUBLIC_KEY = exports.WITHDRAWOR_PUBLIC_KEY = exports.STREAMFLOW_TREASURY_PUBLIC_KEY = exports.PARTNER_ORACLE_PROGRAM_ID = exports.TEST_ORACLE_SEED = exports.ESCROW_SEED = exports.CONTRACT_SEED = exports.TEST_ORACLE_DISCRIMINATOR = exports.CONTRACT_DISCRIMINATOR = exports.ALIGNED_COMPUTE_LIMIT = exports.ALIGNED_UNLOCKS_PROGRAM_ID = exports.PROGRAM_ID = exports.CREATE_PARAMS_PADDING = exports.STREAM_STRUCT_OFFSETS = exports.ALIGNED_PRECISION_FACTOR_POW = exports.STREAM_STRUCT_OFFSET_MINT = exports.STREAM_STRUCT_OFFSET_RECIPIENT = exports.STREAM_STRUCT_OFFSET_SENDER = exports.ORIGINAL_CONTRACT_SENDER_OFFSET = exports.TX_FINALITY_CONFIRMED = void 0;
4
4
  const web3_js_1 = require("@solana/web3.js");
5
5
  const buffer_1 = require("buffer");
6
6
  const types_js_1 = require("../common/types.js");
7
7
  exports.TX_FINALITY_CONFIRMED = "confirmed";
8
+ exports.ORIGINAL_CONTRACT_SENDER_OFFSET = 16;
8
9
  exports.STREAM_STRUCT_OFFSET_SENDER = 49;
9
10
  exports.STREAM_STRUCT_OFFSET_RECIPIENT = 113;
10
11
  exports.STREAM_STRUCT_OFFSET_MINT = 177;
12
+ exports.ALIGNED_PRECISION_FACTOR_POW = 9;
11
13
  exports.STREAM_STRUCT_OFFSETS = {
12
14
  mint: exports.STREAM_STRUCT_OFFSET_MINT,
13
15
  recipient: exports.STREAM_STRUCT_OFFSET_RECIPIENT,
@@ -21,6 +23,19 @@ exports.PROGRAM_ID = {
21
23
  [types_js_1.ICluster.Testnet]: "HqDGZjaVRXJ9MGRQEw7qDc2rAr6iH1n1kAQdCZaCMfMZ",
22
24
  [types_js_1.ICluster.Local]: "HqDGZjaVRXJ9MGRQEw7qDc2rAr6iH1n1kAQdCZaCMfMZ",
23
25
  };
26
+ exports.ALIGNED_UNLOCKS_PROGRAM_ID = {
27
+ [types_js_1.ICluster.Devnet]: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH",
28
+ [types_js_1.ICluster.Mainnet]: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH",
29
+ [types_js_1.ICluster.Testnet]: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH",
30
+ [types_js_1.ICluster.Local]: "aSTRM2NKoKxNnkmLWk9sz3k74gKBk9t7bpPrTGxMszH",
31
+ };
32
+ // Aligned Unlocks Program transactions require a higher comput limit
33
+ exports.ALIGNED_COMPUTE_LIMIT = 300000;
34
+ exports.CONTRACT_DISCRIMINATOR = [172, 138, 115, 242, 121, 67, 183, 26];
35
+ exports.TEST_ORACLE_DISCRIMINATOR = [198, 49, 63, 134, 232, 251, 168, 28];
36
+ exports.CONTRACT_SEED = buffer_1.Buffer.from("contract", "utf-8");
37
+ exports.ESCROW_SEED = buffer_1.Buffer.from("strm", "utf-8");
38
+ exports.TEST_ORACLE_SEED = buffer_1.Buffer.from("test-oracle", "utf-8");
24
39
  exports.PARTNER_ORACLE_PROGRAM_ID = "pardpVtPjC8nLj1Dwncew62mUzfChdCX1EaoZe8oCAa";
25
40
  exports.STREAMFLOW_TREASURY_PUBLIC_KEY = new web3_js_1.PublicKey("5SEpbdjFK5FxwTvfsGMXVQTD2v4M2c5tyRTxhdsPkgDw");
26
41
  exports.WITHDRAWOR_PUBLIC_KEY = new web3_js_1.PublicKey("wdrwhnCv4pzW8beKsbPa4S2UDZrXenjg16KJdKSpb5u");
@@ -62,4 +77,17 @@ exports.SOLANA_ERROR_MAP = {
62
77
  0x85: types_js_1.SolanaContractErrorCode.AlreadyPaused,
63
78
  0x86: types_js_1.SolanaContractErrorCode.NotPaused,
64
79
  0x87: types_js_1.SolanaContractErrorCode.MetadataNotRentExempt,
80
+ 0x1770: types_js_1.SolanaAlignedProxyErrorCode.Unauthorized,
81
+ 0x1771: types_js_1.SolanaAlignedProxyErrorCode.ArithmeticError,
82
+ 0x1772: types_js_1.SolanaAlignedProxyErrorCode.UnsupportedTokenExtensions,
83
+ 0x1773: types_js_1.SolanaAlignedProxyErrorCode.PeriodTooShort,
84
+ 0x1774: types_js_1.SolanaAlignedProxyErrorCode.InvalidTickSize,
85
+ 0x1775: types_js_1.SolanaAlignedProxyErrorCode.InvalidPercentageBoundaries,
86
+ 0x1776: types_js_1.SolanaAlignedProxyErrorCode.InvalidPriceBoundaries,
87
+ 0x1777: types_js_1.SolanaAlignedProxyErrorCode.UnsupportedOracle,
88
+ 0x1778: types_js_1.SolanaAlignedProxyErrorCode.InvalidOracleAccount,
89
+ 0x1779: types_js_1.SolanaAlignedProxyErrorCode.InvalidOraclePrice,
90
+ 0x177a: types_js_1.SolanaAlignedProxyErrorCode.InvalidStreamMetadata,
91
+ 0x177b: types_js_1.SolanaAlignedProxyErrorCode.AmountAlreadyUpdated,
92
+ 0x177c: types_js_1.SolanaAlignedProxyErrorCode.AllFundsUnlocked,
65
93
  };