@streamflow/stream 7.5.3 → 8.0.0-alpha.p287.39c8818

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 (154) hide show
  1. package/dist/cjs/BaseStreamClient-CQOC8m8V.d.cts +542 -0
  2. package/dist/cjs/aptos/index.cjs +456 -0
  3. package/dist/cjs/aptos/index.cjs.map +1 -0
  4. package/dist/cjs/aptos/index.d.cts +14 -0
  5. package/dist/cjs/evm/index.cjs +1915 -0
  6. package/dist/cjs/evm/index.cjs.map +1 -0
  7. package/dist/cjs/evm/index.d.cts +13 -0
  8. package/dist/cjs/index-CYu6i--S.d.cts +136 -0
  9. package/dist/cjs/index-DUVcpIhD.d.cts +203 -0
  10. package/dist/cjs/index-b7Qo5mCj.d.cts +664 -0
  11. package/dist/cjs/index-fNLnPKzv.d.cts +213 -0
  12. package/dist/cjs/index.cjs +7189 -0
  13. package/dist/cjs/index.cjs.map +1 -0
  14. package/dist/cjs/index.d.cts +192 -0
  15. package/dist/cjs/solana/descriptor/streamflow_aligned_unlocks.cjs +4 -0
  16. package/dist/cjs/solana/descriptor/streamflow_aligned_unlocks.cjs.map +1 -0
  17. package/dist/cjs/solana/descriptor/streamflow_aligned_unlocks.d.cts +1234 -0
  18. package/dist/cjs/solana/index.cjs +3749 -0
  19. package/dist/cjs/solana/index.cjs.map +1 -0
  20. package/dist/cjs/solana/index.d.cts +17 -0
  21. package/dist/cjs/sui/index.cjs +1021 -0
  22. package/dist/cjs/sui/index.cjs.map +1 -0
  23. package/dist/cjs/sui/index.d.cts +13 -0
  24. package/dist/esm/BaseStreamClient-CQOC8m8V.d.ts +542 -0
  25. package/dist/esm/aptos/index.d.ts +14 -4
  26. package/dist/esm/aptos/index.js +443 -4
  27. package/dist/esm/aptos/index.js.map +1 -0
  28. package/dist/esm/evm/index.d.ts +13 -5
  29. package/dist/esm/evm/index.js +1902 -5
  30. package/dist/esm/evm/index.js.map +1 -0
  31. package/dist/esm/index-BEo0O2IG.d.ts +664 -0
  32. package/dist/esm/index-CWmb3-x9.d.ts +136 -0
  33. package/dist/esm/index-Cgv37xlG.d.ts +213 -0
  34. package/dist/esm/index-D6QYg8hn.d.ts +203 -0
  35. package/dist/esm/index.d.ts +192 -10
  36. package/dist/esm/index.js +7096 -10
  37. package/dist/esm/index.js.map +1 -0
  38. package/dist/esm/solana/descriptor/idl/streamflow_aligned_unlocks.json +917 -1368
  39. package/dist/esm/solana/descriptor/streamflow_aligned_unlocks.d.ts +3 -1
  40. package/dist/esm/solana/descriptor/streamflow_aligned_unlocks.js +3 -1
  41. package/dist/esm/solana/descriptor/streamflow_aligned_unlocks.js.map +1 -0
  42. package/dist/esm/solana/index.d.ts +17 -7
  43. package/dist/esm/solana/index.js +3693 -7
  44. package/dist/esm/solana/index.js.map +1 -0
  45. package/dist/esm/sui/index.d.ts +13 -4
  46. package/dist/esm/sui/index.js +1011 -4
  47. package/dist/esm/sui/index.js.map +1 -0
  48. package/package.json +57 -27
  49. package/dist/cjs/__tests__/aptos/streamClient.spec.js +0 -111
  50. package/dist/cjs/__tests__/common/GenericStreamClient.spec.js +0 -45
  51. package/dist/cjs/aptos/StreamClient.js +0 -226
  52. package/dist/cjs/aptos/constants.js +0 -27
  53. package/dist/cjs/aptos/index.js +0 -38
  54. package/dist/cjs/aptos/types.js +0 -69
  55. package/dist/cjs/aptos/utils.js +0 -34
  56. package/dist/cjs/aptos/wallet.js +0 -34
  57. package/dist/cjs/common/BaseStreamClient.js +0 -23
  58. package/dist/cjs/common/GenericStreamClient.js +0 -102
  59. package/dist/cjs/common/constants.js +0 -10
  60. package/dist/cjs/common/contractUtils.js +0 -77
  61. package/dist/cjs/common/types.js +0 -141
  62. package/dist/cjs/common/utils.js +0 -69
  63. package/dist/cjs/evm/StreamClient.js +0 -238
  64. package/dist/cjs/evm/abi.js +0 -1257
  65. package/dist/cjs/evm/constants.js +0 -38
  66. package/dist/cjs/evm/ercAbi.js +0 -224
  67. package/dist/cjs/evm/index.js +0 -40
  68. package/dist/cjs/evm/types.js +0 -66
  69. package/dist/cjs/evm/utils.js +0 -11
  70. package/dist/cjs/index.js +0 -43
  71. package/dist/cjs/solana/StreamClient.js +0 -1042
  72. package/dist/cjs/solana/constants.js +0 -95
  73. package/dist/cjs/solana/descriptor/idl/streamflow_aligned_unlocks.json +0 -1437
  74. package/dist/cjs/solana/descriptor/streamflow_aligned_unlocks.js +0 -2
  75. package/dist/cjs/solana/index.js +0 -40
  76. package/dist/cjs/solana/instructionTypes.js +0 -2
  77. package/dist/cjs/solana/instructions.js +0 -298
  78. package/dist/cjs/solana/layout.js +0 -182
  79. package/dist/cjs/solana/lib/derive-accounts.js +0 -17
  80. package/dist/cjs/solana/lib/utils.js +0 -127
  81. package/dist/cjs/solana/timelockIDL.js +0 -422
  82. package/dist/cjs/solana/types.js +0 -93
  83. package/dist/cjs/sui/StreamClient.js +0 -416
  84. package/dist/cjs/sui/constants.js +0 -42
  85. package/dist/cjs/sui/index.js +0 -37
  86. package/dist/cjs/sui/types.js +0 -68
  87. package/dist/cjs/sui/utils.js +0 -46
  88. package/dist/cjs/sui/wallet.js +0 -40
  89. package/dist/esm/__tests__/aptos/streamClient.spec.d.ts +0 -1
  90. package/dist/esm/__tests__/aptos/streamClient.spec.js +0 -106
  91. package/dist/esm/__tests__/common/GenericStreamClient.spec.d.ts +0 -1
  92. package/dist/esm/__tests__/common/GenericStreamClient.spec.js +0 -40
  93. package/dist/esm/aptos/StreamClient.d.ts +0 -53
  94. package/dist/esm/aptos/StreamClient.js +0 -226
  95. package/dist/esm/aptos/constants.d.ts +0 -8
  96. package/dist/esm/aptos/constants.js +0 -24
  97. package/dist/esm/aptos/types.d.ts +0 -109
  98. package/dist/esm/aptos/types.js +0 -105
  99. package/dist/esm/aptos/utils.d.ts +0 -7
  100. package/dist/esm/aptos/utils.js +0 -30
  101. package/dist/esm/aptos/wallet.d.ts +0 -9
  102. package/dist/esm/aptos/wallet.js +0 -33
  103. package/dist/esm/common/BaseStreamClient.d.ts +0 -22
  104. package/dist/esm/common/BaseStreamClient.js +0 -19
  105. package/dist/esm/common/GenericStreamClient.d.ts +0 -72
  106. package/dist/esm/common/GenericStreamClient.js +0 -101
  107. package/dist/esm/common/constants.d.ts +0 -4
  108. package/dist/esm/common/constants.js +0 -4
  109. package/dist/esm/common/contractUtils.d.ts +0 -63
  110. package/dist/esm/common/contractUtils.js +0 -61
  111. package/dist/esm/common/types.d.ts +0 -353
  112. package/dist/esm/common/types.js +0 -135
  113. package/dist/esm/common/utils.d.ts +0 -32
  114. package/dist/esm/common/utils.js +0 -59
  115. package/dist/esm/evm/StreamClient.d.ts +0 -32
  116. package/dist/esm/evm/StreamClient.js +0 -237
  117. package/dist/esm/evm/abi.d.ts +0 -111
  118. package/dist/esm/evm/abi.js +0 -1255
  119. package/dist/esm/evm/constants.d.ts +0 -20
  120. package/dist/esm/evm/constants.js +0 -35
  121. package/dist/esm/evm/ercAbi.d.ts +0 -39
  122. package/dist/esm/evm/ercAbi.js +0 -222
  123. package/dist/esm/evm/types.d.ts +0 -98
  124. package/dist/esm/evm/types.js +0 -102
  125. package/dist/esm/evm/utils.d.ts +0 -1
  126. package/dist/esm/evm/utils.js +0 -8
  127. package/dist/esm/solana/StreamClient.d.ts +0 -150
  128. package/dist/esm/solana/StreamClient.js +0 -1017
  129. package/dist/esm/solana/constants.d.ts +0 -70
  130. package/dist/esm/solana/constants.js +0 -92
  131. package/dist/esm/solana/instructionTypes.d.ts +0 -101
  132. package/dist/esm/solana/instructionTypes.js +0 -1
  133. package/dist/esm/solana/instructions.d.ts +0 -142
  134. package/dist/esm/solana/instructions.js +0 -265
  135. package/dist/esm/solana/layout.d.ts +0 -27
  136. package/dist/esm/solana/layout.js +0 -155
  137. package/dist/esm/solana/lib/derive-accounts.d.ts +0 -4
  138. package/dist/esm/solana/lib/derive-accounts.js +0 -11
  139. package/dist/esm/solana/lib/utils.d.ts +0 -22
  140. package/dist/esm/solana/lib/utils.js +0 -117
  141. package/dist/esm/solana/timelockIDL.d.ts +0 -22
  142. package/dist/esm/solana/timelockIDL.js +0 -420
  143. package/dist/esm/solana/types.d.ts +0 -180
  144. package/dist/esm/solana/types.js +0 -142
  145. package/dist/esm/sui/StreamClient.d.ts +0 -82
  146. package/dist/esm/sui/StreamClient.js +0 -417
  147. package/dist/esm/sui/constants.d.ts +0 -10
  148. package/dist/esm/sui/constants.js +0 -39
  149. package/dist/esm/sui/types.d.ts +0 -167
  150. package/dist/esm/sui/types.js +0 -104
  151. package/dist/esm/sui/utils.d.ts +0 -11
  152. package/dist/esm/sui/utils.js +0 -39
  153. package/dist/esm/sui/wallet.d.ts +0 -17
  154. package/dist/esm/sui/wallet.js +0 -38
@@ -1,1017 +0,0 @@
1
- // Latest version of the SDK that does not use Anchor. It supports raw instructions.
2
- import BN from "bn.js";
3
- import bs58 from "bs58";
4
- import { Buffer } from "buffer";
5
- import { ASSOCIATED_TOKEN_PROGRAM_ID, NATIVE_MINT } from "@solana/spl-token";
6
- import { Connection, Keypair, PublicKey, SystemProgram, SYSVAR_RENT_PUBKEY, TransactionMessage, VersionedTransaction, } from "@solana/web3.js";
7
- import { ata, checkOrCreateAtaBatch, signAndExecuteTransaction, getProgramAccounts, prepareWrappedAccount, prepareTransaction, prepareBaseInstructions, getMintAndProgram, executeTransaction, executeMultipleTransactions, buildSendThrottler, getMultipleAccountsInfoBatched, } from "@streamflow/common/solana";
8
- import * as borsh from "borsh";
9
- import { Program } from "@coral-xyz/anchor";
10
- import { getBN } from "@streamflow/common";
11
- import { Contract, AlignedContract, } from "./types.js";
12
- import { decodeStream, extractSolanaErrorCode, sendAndConfirmStreamRawTransaction, signAllTransactionWithRecipients, } from "./lib/utils.js";
13
- 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";
14
- import { withdrawStreamInstruction, cancelStreamInstruction, transferStreamInstruction, topupStreamInstruction, createStreamInstruction, createUncheckedStreamInstruction, updateStreamInstruction, } from "./instructions.js";
15
- import { ICluster, StreamDirection, StreamType, } from "../common/types.js";
16
- import { BaseStreamClient } from "../common/BaseStreamClient.js";
17
- import { calculateTotalAmountToDeposit } from "../common/utils.js";
18
- import { WITHDRAW_AVAILABLE_AMOUNT } from "../common/constants.js";
19
- import StreamflowAlignedUnlocksIDL from "./descriptor/idl/streamflow_aligned_unlocks.json";
20
- import { deriveContractPDA, deriveEscrowPDA, deriveTestOraclePDA } from "./lib/derive-accounts.js";
21
- import { isCreateAlignedStreamData } from "../common/contractUtils.js";
22
- const METADATA_ACC_SIZE = 1104;
23
- const ALIGNED_METADATA_ACC_SIZE = 320;
24
- export class SolanaStreamClient extends BaseStreamClient {
25
- connection;
26
- programId;
27
- commitment;
28
- alignedProxyProgram;
29
- schedulingParams;
30
- /**
31
- * Create Stream instance
32
- */
33
- constructor(optionsOrClusterUrl, cluster = ICluster.Mainnet, commitment = "confirmed", programId = "", sendRate = 1, sendThrottler) {
34
- super();
35
- if (typeof optionsOrClusterUrl === "string") {
36
- this.commitment = commitment;
37
- this.connection = new Connection(optionsOrClusterUrl, this.commitment);
38
- this.programId = programId !== "" ? new PublicKey(programId) : new PublicKey(PROGRAM_ID[cluster]);
39
- this.schedulingParams = {
40
- sendThrottler: sendThrottler ?? buildSendThrottler(sendRate),
41
- };
42
- }
43
- else {
44
- const { clusterUrl, cluster = ICluster.Mainnet, commitment = "confirmed", programId = "", sendScheduler, } = optionsOrClusterUrl;
45
- this.commitment = commitment;
46
- this.connection = new Connection(clusterUrl, this.commitment);
47
- this.programId = programId !== "" ? new PublicKey(programId) : new PublicKey(PROGRAM_ID[cluster]);
48
- const schedulingOptions = sendScheduler && "sendRate" in sendScheduler ? sendScheduler : undefined;
49
- const sendThrottler = !sendScheduler
50
- ? buildSendThrottler(1)
51
- : "sendRate" in sendScheduler
52
- ? buildSendThrottler(sendScheduler.sendRate ?? 1, sendScheduler.sendInterval)
53
- : sendScheduler;
54
- this.schedulingParams = {
55
- ...schedulingOptions,
56
- sendThrottler,
57
- };
58
- }
59
- const alignedUnlocksProgram = {
60
- ...StreamflowAlignedUnlocksIDL,
61
- address: StreamflowAlignedUnlocksIDL.address,
62
- };
63
- this.alignedProxyProgram = new Program(alignedUnlocksProgram, { connection: this.connection });
64
- }
65
- getConnection() {
66
- return this.connection;
67
- }
68
- getCommitment() {
69
- return typeof this.commitment == "string" ? this.commitment : this.commitment.commitment;
70
- }
71
- getProgramId() {
72
- return this.programId.toBase58();
73
- }
74
- /**
75
- * Creates a new stream/vesting contract.
76
- * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
77
- */
78
- async create(data, extParams) {
79
- const { partner, amount, tokenProgramId } = data;
80
- const { isNative, sender, customInstructions } = extParams;
81
- const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
82
- const mintPublicKey = new PublicKey(data.tokenId);
83
- if (!sender.publicKey) {
84
- throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
85
- }
86
- const ixs = await this.getCreateATAInstructions([STREAMFLOW_TREASURY_PUBLIC_KEY, partnerPublicKey], mintPublicKey, sender, true, tokenProgramId ? new PublicKey(tokenProgramId) : undefined);
87
- const { ixs: createIxs, metadata, metadataPubKey } = await this.prepareCreateInstructions(data, extParams);
88
- ixs.push(...createIxs);
89
- if (isNative) {
90
- const totalFee = await this.getTotalFee({
91
- address: partnerPublicKey.toString(),
92
- });
93
- const totalAmount = calculateTotalAmountToDeposit(amount, totalFee);
94
- ixs.push(...(await prepareWrappedAccount(this.connection, sender.publicKey, totalAmount)));
95
- }
96
- await this.applyCustomAfterInstructions(ixs, customInstructions, metadataPubKey);
97
- const { tx, hash, context } = await prepareTransaction(this.connection, ixs, sender.publicKey, undefined, metadata);
98
- const signature = await signAndExecuteTransaction(this.connection, extParams.sender, tx, {
99
- hash,
100
- context,
101
- commitment: this.getCommitment(),
102
- }, this.schedulingParams);
103
- return { ixs, txId: signature, metadataId: metadataPubKey.toBase58() };
104
- }
105
- async prepareCreateInstructions(streamParams, extParams) {
106
- const { ixs, metadata, metadataPubKey } = isCreateAlignedStreamData(streamParams)
107
- ? await this.prepareCreateAlignedUnlockInstructions(streamParams, extParams)
108
- : await this.prepareCreateStreamInstructions(streamParams, extParams);
109
- return { ixs, metadata, metadataPubKey };
110
- }
111
- async prepareCreateAlignedUnlockInstructions(streamParams, extParams) {
112
- 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, tokenProgramId: streamTokenProgramId, } = streamParams;
113
- const { isNative, sender, computeLimit, computePrice, metadataPubKeys } = extParams;
114
- if (!sender.publicKey) {
115
- throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
116
- }
117
- if (!priceOracle && oracleType && oracleType !== "none") {
118
- throw new Error("Price oracle is required for the specified oracle type");
119
- }
120
- const recipientPublicKey = new PublicKey(recipient);
121
- const mintPublicKey = isNative ? NATIVE_MINT : new PublicKey(mint);
122
- const metadata = !metadataPubKeys ? Keypair.generate() : undefined;
123
- const metadataPubKey = metadata ? metadata.publicKey : metadataPubKeys[0];
124
- let tokenProgramId = streamTokenProgramId ? new PublicKey(streamTokenProgramId) : undefined;
125
- if (!tokenProgramId) {
126
- tokenProgramId = (await getMintAndProgram(this.connection, mintPublicKey)).tokenProgramId;
127
- }
128
- const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
129
- const streamflowProgramPublicKey = new PublicKey(this.programId);
130
- const escrowPDA = deriveEscrowPDA(streamflowProgramPublicKey, metadataPubKey);
131
- const oracle = priceOracle ?? deriveTestOraclePDA(this.alignedProxyProgram.programId, mintPublicKey, sender.publicKey);
132
- const ixs = prepareBaseInstructions(this.connection, {
133
- computePrice,
134
- computeLimit: computeLimit ?? ALIGNED_COMPUTE_LIMIT,
135
- });
136
- ixs.push(...(await this.getCreateATAInstructions([recipientPublicKey], mintPublicKey, sender, true, tokenProgramId)));
137
- const encodedUIntArray = new TextEncoder().encode(streamName);
138
- const streamNameArray = Array.from(encodedUIntArray);
139
- const createIx = await this.alignedProxyProgram.methods
140
- .create({
141
- startTime: new BN(start),
142
- netAmountDeposited: depositedAmount,
143
- period: new BN(period),
144
- amountPerPeriod: amountPerPeriod,
145
- cliff: new BN(cliff),
146
- cliffAmount: cliffAmount,
147
- transferableBySender,
148
- transferableByRecipient,
149
- cancelableByRecipient,
150
- cancelableBySender,
151
- canTopup,
152
- oracleType: (!!oracleType ? { [oracleType]: {} } : { none: {} }),
153
- streamName: streamNameArray,
154
- minPrice: minPrice instanceof BN ? minPrice : getBN(minPrice, ALIGNED_PRECISION_FACTOR_POW),
155
- maxPrice: maxPrice instanceof BN ? maxPrice : getBN(maxPrice, ALIGNED_PRECISION_FACTOR_POW),
156
- minPercentage: minPercentage instanceof BN ? minPercentage : getBN(minPercentage, ALIGNED_PRECISION_FACTOR_POW),
157
- maxPercentage: maxPercentage instanceof BN ? maxPercentage : getBN(maxPercentage, ALIGNED_PRECISION_FACTOR_POW),
158
- tickSize: new BN(tickSize || 1),
159
- skipInitial: skipInitial ?? false,
160
- })
161
- .accountsPartial({
162
- payer: sender.publicKey,
163
- sender: sender.publicKey,
164
- streamMetadata: metadataPubKey,
165
- escrowTokens: escrowPDA,
166
- mint: mintPublicKey,
167
- partner: partnerPublicKey,
168
- recipient: recipientPublicKey,
169
- withdrawor: WITHDRAWOR_PUBLIC_KEY,
170
- feeOracle: FEE_ORACLE_PUBLIC_KEY,
171
- priceOracle: oracle,
172
- tokenProgram: tokenProgramId,
173
- streamflowProgram: this.programId,
174
- })
175
- .instruction();
176
- ixs.push(createIx);
177
- return { ixs, metadata, metadataPubKey };
178
- }
179
- /**
180
- * Creates a new stream/vesting contract.
181
- * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
182
- */
183
- 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, tokenProgramId: streamTokenProgramId, }, { sender, metadataPubKeys, isNative = false, computePrice, computeLimit }) {
184
- if (!sender.publicKey) {
185
- throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
186
- }
187
- const ixs = prepareBaseInstructions(this.connection, {
188
- computePrice,
189
- computeLimit,
190
- });
191
- const mintPublicKey = isNative ? NATIVE_MINT : new PublicKey(mint);
192
- const recipientPublicKey = new PublicKey(recipient);
193
- const { metadata, metadataPubKey } = this.getOrCreateStreamMetadata(metadataPubKeys);
194
- const [escrowTokens] = PublicKey.findProgramAddressSync([Buffer.from("strm"), metadataPubKey.toBuffer()], this.programId);
195
- let tokenProgramId = streamTokenProgramId ? new PublicKey(streamTokenProgramId) : undefined;
196
- if (!tokenProgramId) {
197
- tokenProgramId = (await getMintAndProgram(this.connection, mintPublicKey)).tokenProgramId;
198
- }
199
- const senderTokens = await ata(mintPublicKey, sender.publicKey, tokenProgramId);
200
- const recipientTokens = await ata(mintPublicKey, recipientPublicKey, tokenProgramId);
201
- const streamflowTreasuryTokens = await ata(mintPublicKey, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
202
- const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
203
- const partnerTokens = await ata(mintPublicKey, partnerPublicKey, tokenProgramId);
204
- ixs.push(await createStreamInstruction({
205
- start: new BN(start),
206
- depositedAmount,
207
- period: new BN(period),
208
- amountPerPeriod,
209
- cliff: new BN(cliff),
210
- cliffAmount: new BN(cliffAmount),
211
- cancelableBySender,
212
- cancelableByRecipient,
213
- automaticWithdrawal,
214
- transferableBySender,
215
- transferableByRecipient,
216
- canTopup,
217
- canUpdateRate: !!canUpdateRate,
218
- canPause: !!canPause,
219
- name,
220
- withdrawFrequency: new BN(automaticWithdrawal ? withdrawalFrequency : period),
221
- }, this.programId, {
222
- sender: sender.publicKey,
223
- senderTokens,
224
- recipient: new PublicKey(recipient),
225
- metadata: metadataPubKey,
226
- escrowTokens,
227
- recipientTokens,
228
- streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
229
- streamflowTreasuryTokens: streamflowTreasuryTokens,
230
- partner: partnerPublicKey,
231
- partnerTokens: partnerTokens,
232
- mint: new PublicKey(mint),
233
- feeOracle: FEE_ORACLE_PUBLIC_KEY,
234
- rent: SYSVAR_RENT_PUBKEY,
235
- timelockProgram: this.programId,
236
- tokenProgram: tokenProgramId,
237
- associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
238
- withdrawor: WITHDRAWOR_PUBLIC_KEY,
239
- systemProgram: SystemProgram.programId,
240
- }));
241
- return { ixs, metadata, metadataPubKey };
242
- }
243
- /**
244
- * Creates a new stream/vesting contract using unchecked instruction.
245
- *
246
- * Unchecked instruction differs from the regular in:
247
- * - does not check for initialized associated token account (wallets with no control over their ATA should not be used
248
- * as sender/recipient/partner or there are risks of funds being locked in the contract)
249
- * - initialized contract PDA off chain
250
- *
251
- * If you are not sure if you should use create or create_unchecked, go for create to be safer.
252
- */
253
- async createUnchecked(data, extParams) {
254
- const { ixs, metadata, metadataPubKey } = await this.prepareCreateUncheckedInstructions(data, extParams);
255
- const { tx, hash, context } = await prepareTransaction(this.connection, ixs, extParams.sender.publicKey, undefined, metadata);
256
- const signature = await signAndExecuteTransaction(this.connection, extParams.sender, tx, {
257
- hash,
258
- context,
259
- commitment: this.getCommitment(),
260
- }, this.schedulingParams);
261
- return { ixs, txId: signature, metadataId: metadataPubKey.toBase58() };
262
- }
263
- /**
264
- * Create Transaction instructions for `createUnchecked`
265
- */
266
- async prepareCreateUncheckedInstructions({ recipient, tokenId: mint, start, amount: depositedAmount, period, cliff, cliffAmount, amountPerPeriod, name, canTopup, canUpdateRate, canPause, cancelableBySender, cancelableByRecipient, transferableBySender, transferableByRecipient, automaticWithdrawal = false, withdrawalFrequency = 0, partner, }, { sender, metadataPubKeys, isNative = false, computePrice, computeLimit }) {
267
- if (!sender.publicKey) {
268
- throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
269
- }
270
- const mintPublicKey = new PublicKey(mint);
271
- const recipientPublicKey = new PublicKey(recipient);
272
- const { metadata, metadataPubKey } = this.getOrCreateStreamMetadata(metadataPubKeys);
273
- const rentToExempt = await this.connection.getMinimumBalanceForRentExemption(METADATA_ACC_SIZE);
274
- const createMetadataInstruction = SystemProgram.createAccount({
275
- programId: this.programId,
276
- space: METADATA_ACC_SIZE,
277
- lamports: rentToExempt,
278
- fromPubkey: sender?.publicKey,
279
- newAccountPubkey: metadataPubKey,
280
- });
281
- const [escrowTokens] = PublicKey.findProgramAddressSync([Buffer.from("strm"), metadataPubKey.toBuffer()], this.programId);
282
- const { tokenProgramId } = await getMintAndProgram(this.connection, mintPublicKey);
283
- const senderTokens = await ata(mintPublicKey, sender.publicKey, tokenProgramId);
284
- const partnerPublicKey = partner ? new PublicKey(partner) : WITHDRAWOR_PUBLIC_KEY;
285
- const ixs = prepareBaseInstructions(this.connection, {
286
- computePrice,
287
- computeLimit,
288
- });
289
- if (isNative) {
290
- const totalFee = await this.getTotalFee({ address: partnerPublicKey.toString() });
291
- const totalAmount = calculateTotalAmountToDeposit(depositedAmount, totalFee);
292
- ixs.push(...(await prepareWrappedAccount(this.connection, sender.publicKey, totalAmount)));
293
- }
294
- const createInstruction = await createUncheckedStreamInstruction({
295
- start: new BN(start),
296
- depositedAmount,
297
- period: new BN(period),
298
- amountPerPeriod,
299
- cliff: new BN(cliff),
300
- cliffAmount: new BN(cliffAmount),
301
- cancelableBySender,
302
- cancelableByRecipient,
303
- automaticWithdrawal,
304
- transferableBySender,
305
- transferableByRecipient,
306
- canTopup,
307
- canUpdateRate: !!canUpdateRate,
308
- canPause: !!canPause,
309
- name,
310
- withdrawFrequency: new BN(automaticWithdrawal ? withdrawalFrequency : period),
311
- recipient: recipientPublicKey,
312
- partner: partnerPublicKey,
313
- }, this.programId, {
314
- sender: sender.publicKey,
315
- senderTokens,
316
- metadata: metadataPubKey,
317
- escrowTokens,
318
- mint: new PublicKey(mint),
319
- feeOracle: FEE_ORACLE_PUBLIC_KEY,
320
- rent: SYSVAR_RENT_PUBKEY,
321
- timelockProgram: this.programId,
322
- tokenProgram: tokenProgramId,
323
- withdrawor: WITHDRAWOR_PUBLIC_KEY,
324
- systemProgram: SystemProgram.programId,
325
- });
326
- ixs.push(createMetadataInstruction, createInstruction);
327
- return { ixs, metadata, metadataPubKey };
328
- }
329
- /**
330
- * Creates multiple stream/vesting contracts.
331
- * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
332
- */
333
- async createMultiple(data, extParams) {
334
- const { recipients, ...streamParams } = data;
335
- const { sender, metadataPubKeys: metadataPubKeysExt, isNative, computePrice, computeLimit, customInstructions, } = extParams;
336
- const metadatas = [];
337
- const metadataToRecipient = {};
338
- const errors = [];
339
- const signatures = [];
340
- const batch = [];
341
- const instructionsBatch = [];
342
- const metadataPubKeys = metadataPubKeysExt || [];
343
- const partnerPublicKey = data.partner ? new PublicKey(data.partner) : WITHDRAWOR_PUBLIC_KEY;
344
- const mintPublicKey = new PublicKey(data.tokenId);
345
- if (recipients.length === 0) {
346
- throw new Error("Recipients array is empty!");
347
- }
348
- if (!sender.publicKey) {
349
- throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
350
- }
351
- for (let i = 0; i < recipients.length; i++) {
352
- const recipientData = recipients[i];
353
- const createStreamData = { ...streamParams, ...recipientData };
354
- const createStreamExtParams = {
355
- sender,
356
- metadataPubKeys: metadataPubKeys[i] ? [metadataPubKeys[i]] : undefined,
357
- computePrice,
358
- computeLimit,
359
- customInstructions,
360
- };
361
- const { ixs, metadata, metadataPubKey } = await this.prepareCreateInstructions(createStreamData, createStreamExtParams);
362
- await this.applyCustomAfterInstructions(ixs, customInstructions, metadataPubKey);
363
- metadataToRecipient[metadataPubKey.toBase58()] = recipientData;
364
- metadatas.push(metadataPubKey.toBase58());
365
- instructionsBatch.push({
366
- ixs,
367
- metadata,
368
- recipient: recipientData.recipient,
369
- });
370
- }
371
- const { value: hash, context } = await this.connection.getLatestBlockhashAndContext();
372
- for (const { ixs, metadata, recipient } of instructionsBatch) {
373
- const messageV0 = new TransactionMessage({
374
- payerKey: sender.publicKey,
375
- recentBlockhash: hash.blockhash,
376
- instructions: ixs,
377
- }).compileToV0Message();
378
- const tx = new VersionedTransaction(messageV0);
379
- if (metadata) {
380
- tx.sign([metadata]);
381
- }
382
- batch.push({ tx, recipient });
383
- }
384
- const prepareInstructions = await this.getCreateATAInstructions([STREAMFLOW_TREASURY_PUBLIC_KEY, partnerPublicKey], mintPublicKey, sender, true);
385
- if (isNative) {
386
- const totalDepositedAmount = recipients.reduce((acc, recipient) => recipient.amount.add(acc), new BN(0));
387
- const nativeInstructions = await prepareWrappedAccount(this.connection, sender.publicKey, totalDepositedAmount);
388
- prepareInstructions.push(...nativeInstructions);
389
- }
390
- if (prepareInstructions.length > 0) {
391
- const messageV0 = new TransactionMessage({
392
- payerKey: sender.publicKey,
393
- recentBlockhash: hash.blockhash,
394
- instructions: prepareInstructions,
395
- }).compileToV0Message();
396
- const tx = new VersionedTransaction(messageV0);
397
- batch.push({
398
- tx,
399
- recipient: sender.publicKey.toBase58(),
400
- });
401
- }
402
- const signedBatch = await signAllTransactionWithRecipients(sender, batch);
403
- if (prepareInstructions.length > 0) {
404
- const prepareTx = signedBatch.pop();
405
- await sendAndConfirmStreamRawTransaction(this.connection, prepareTx, { hash, context }, this.schedulingParams);
406
- }
407
- const responses = [];
408
- if (metadataPubKeys.length > 0) {
409
- //if metadata pub keys were passed we should execute transaction sequentially
410
- //ephemeral signer need to be used first before proceeding with the next
411
- for (const batchTx of signedBatch) {
412
- responses.push(...(await Promise.allSettled([
413
- executeTransaction(this.connection, batchTx.tx, { hash, context }, this.schedulingParams),
414
- ])));
415
- }
416
- }
417
- else {
418
- //send all transactions in parallel and wait for them to settle.
419
- //it allows to speed up the process of sending transactions
420
- //we then filter all promise responses and handle failed transactions
421
- responses.push(...(await executeMultipleTransactions(this.connection, signedBatch.map((item) => item.tx), { hash, context }, this.schedulingParams)));
422
- }
423
- responses.forEach((item, index) => {
424
- if (item.status === "fulfilled") {
425
- signatures.push(item.value);
426
- }
427
- else {
428
- errors.push({
429
- recipient: signedBatch[index].recipient,
430
- error: item.reason,
431
- contractErrorCode: this.extractErrorCode(item.reason) || undefined,
432
- });
433
- }
434
- });
435
- return { txs: signatures, metadatas, metadataToRecipient, errors };
436
- }
437
- /**
438
- * Creates multiple stream/vesting contracts, and send all transactions sequentially.
439
- * All fees are paid by sender (escrow metadata account rent, escrow token account rent, recipient's associated token account rent, Streamflow's service fee).
440
- * In most cases, createMultiple should be used instead.
441
- */
442
- async createMultipleSequential(data, extParams) {
443
- const { recipients, ...streamParams } = data;
444
- const { sender, metadataPubKeys: metadataPubKeysExt, isNative, computePrice, computeLimit, customInstructions, } = extParams;
445
- const metadatas = [];
446
- const metadataToRecipient = {};
447
- const errors = [];
448
- const signatures = [];
449
- const batch = [];
450
- const instructionsBatch = [];
451
- const metadataPubKeys = metadataPubKeysExt || [];
452
- const partnerPublicKey = data.partner ? new PublicKey(data.partner) : WITHDRAWOR_PUBLIC_KEY;
453
- const mintPublicKey = new PublicKey(data.tokenId);
454
- if (recipients.length === 0) {
455
- throw new Error("Recipients array is empty!");
456
- }
457
- if (!sender.publicKey) {
458
- throw new Error("Sender's PublicKey is not available, check passed wallet adapter!");
459
- }
460
- for (let i = 0; i < recipients.length; i++) {
461
- const recipientData = recipients[i];
462
- const createStreamData = { ...streamParams, ...recipientData };
463
- const createStreamExtParams = {
464
- sender,
465
- metadataPubKeys: metadataPubKeys[i] ? [metadataPubKeys[i]] : undefined,
466
- computePrice,
467
- computeLimit,
468
- customInstructions,
469
- };
470
- const { ixs, metadata, metadataPubKey } = await this.prepareCreateInstructions(createStreamData, createStreamExtParams);
471
- await this.applyCustomAfterInstructions(ixs, customInstructions, metadataPubKey);
472
- metadataToRecipient[metadataPubKey.toBase58()] = recipientData;
473
- metadatas.push(metadataPubKey.toBase58());
474
- instructionsBatch.push({
475
- ixs,
476
- metadata,
477
- recipient: recipientData.recipient,
478
- });
479
- }
480
- const { value: hash, context } = await this.connection.getLatestBlockhashAndContext();
481
- for (const { ixs, metadata, recipient } of instructionsBatch) {
482
- const messageV0 = new TransactionMessage({
483
- payerKey: sender.publicKey,
484
- recentBlockhash: hash.blockhash,
485
- instructions: ixs,
486
- }).compileToV0Message();
487
- const tx = new VersionedTransaction(messageV0);
488
- if (metadata) {
489
- tx.sign([metadata]);
490
- }
491
- batch.push({ tx, recipient });
492
- }
493
- const prepareInstructions = await this.getCreateATAInstructions([STREAMFLOW_TREASURY_PUBLIC_KEY, partnerPublicKey], mintPublicKey, sender, true);
494
- if (isNative) {
495
- const totalDepositedAmount = recipients.reduce((acc, recipient) => recipient.amount.add(acc), new BN(0));
496
- const nativeInstructions = await prepareWrappedAccount(this.connection, sender.publicKey, totalDepositedAmount);
497
- prepareInstructions.push(...nativeInstructions);
498
- }
499
- if (prepareInstructions.length > 0) {
500
- const messageV0 = new TransactionMessage({
501
- payerKey: sender.publicKey,
502
- recentBlockhash: hash.blockhash,
503
- instructions: prepareInstructions,
504
- }).compileToV0Message();
505
- const tx = new VersionedTransaction(messageV0);
506
- batch.push({
507
- tx,
508
- recipient: sender.publicKey.toBase58(),
509
- });
510
- }
511
- const signedBatch = await signAllTransactionWithRecipients(sender, batch);
512
- if (prepareInstructions.length > 0) {
513
- const prepareTx = signedBatch.shift();
514
- await sendAndConfirmStreamRawTransaction(this.connection, prepareTx, { hash, context }, this.schedulingParams);
515
- }
516
- const responses = [];
517
- for (const batchTx of signedBatch) {
518
- responses.push(...(await Promise.allSettled([
519
- executeTransaction(this.connection, batchTx.tx, { hash, context }, this.schedulingParams),
520
- ])));
521
- }
522
- responses.forEach((item, index) => {
523
- if (item.status === "fulfilled") {
524
- signatures.push(item.value);
525
- }
526
- else {
527
- errors.push({
528
- recipient: signedBatch[index].recipient,
529
- error: item.reason,
530
- contractErrorCode: this.extractErrorCode(item.reason) || undefined,
531
- });
532
- }
533
- });
534
- return { txs: signatures, metadatas, metadataToRecipient, errors };
535
- }
536
- /**
537
- * Attempts withdrawing from the specified stream.
538
- */
539
- async withdraw({ id, amount = WITHDRAW_AVAILABLE_AMOUNT }, extParams) {
540
- const { invoker, customInstructions } = extParams;
541
- if (!invoker.publicKey) {
542
- throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
543
- }
544
- const ixs = await this.prepareWithdrawInstructions({ id, amount }, extParams);
545
- const metadata = new PublicKey(id);
546
- await this.applyCustomAfterInstructions(ixs, customInstructions, metadata);
547
- const { tx, hash, context } = await prepareTransaction(this.connection, ixs, invoker.publicKey);
548
- const signature = await signAndExecuteTransaction(this.connection, extParams.invoker, tx, {
549
- hash,
550
- context,
551
- commitment: this.getCommitment(),
552
- }, this.schedulingParams);
553
- return { ixs, txId: signature };
554
- }
555
- /**
556
- * Creates Transaction Instructions for withdrawal
557
- */
558
- async prepareWithdrawInstructions({ id, amount = WITHDRAW_AVAILABLE_AMOUNT }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
559
- if (!invoker.publicKey) {
560
- throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
561
- }
562
- const ixs = prepareBaseInstructions(this.connection, {
563
- computePrice,
564
- computeLimit,
565
- });
566
- const streamPublicKey = new PublicKey(id);
567
- const escrow = await this.connection.getAccountInfo(streamPublicKey);
568
- if (!escrow?.data) {
569
- throw new Error("Couldn't get account info");
570
- }
571
- const data = decodeStream(escrow.data);
572
- const { sender, recipient, mint, streamflowTreasury, partner, recipientTokens, escrowTokens } = data;
573
- const { tokenProgramId } = await getMintAndProgram(this.connection, mint);
574
- const streamflowTreasuryTokens = await ata(mint, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
575
- const partnerTokens = await ata(mint, partner, tokenProgramId);
576
- const ataIx = await this.getCreateATAInstructions([sender, recipient, streamflowTreasury, partner], mint, invoker, checkTokenAccounts, tokenProgramId);
577
- ixs.push(...ataIx, await withdrawStreamInstruction(amount, this.programId, {
578
- partner,
579
- partnerTokens,
580
- mint,
581
- streamflowTreasuryTokens,
582
- recipientTokens,
583
- escrowTokens,
584
- authority: invoker.publicKey,
585
- recipient: invoker.publicKey,
586
- metadata: streamPublicKey,
587
- streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
588
- tokenProgram: tokenProgramId,
589
- }));
590
- return ixs;
591
- }
592
- /**
593
- * Attempts canceling the specified stream.
594
- */
595
- async cancel(cancelData, extParams) {
596
- const ixs = await this.prepareCancelInstructions(cancelData, extParams);
597
- const { tx, hash, context } = await prepareTransaction(this.connection, ixs, extParams.invoker.publicKey);
598
- const signature = await signAndExecuteTransaction(this.connection, extParams.invoker, tx, {
599
- hash,
600
- context,
601
- commitment: this.getCommitment(),
602
- }, this.schedulingParams);
603
- return { ixs, txId: signature };
604
- }
605
- async prepareCancelInstructions(cancelData, extParams) {
606
- const streamPublicKey = new PublicKey(cancelData.id);
607
- const account = await this.connection.getAccountInfo(streamPublicKey);
608
- if (!account) {
609
- throw new Error("Impossible to cancel a stream contract that does not exist");
610
- }
611
- const { sender: senderPublicKey } = decodeStream(account.data);
612
- const isAlignedUnlock = this.isAlignedUnlock(streamPublicKey, senderPublicKey);
613
- const ixs = isAlignedUnlock
614
- ? await this.prepareCancelAlignedUnlockInstructions(cancelData, extParams)
615
- : await this.prepareCancelStreamInstructions(cancelData, extParams);
616
- return ixs;
617
- }
618
- async prepareCancelAlignedUnlockInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
619
- if (!invoker.publicKey) {
620
- throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
621
- }
622
- const streamPublicKey = new PublicKey(id);
623
- const escrowAcc = await this.connection.getAccountInfo(streamPublicKey);
624
- if (!escrowAcc?.data) {
625
- throw new Error("Couldn't get account info");
626
- }
627
- const streamData = decodeStream(escrowAcc.data);
628
- const { sender, recipient, mint, streamflowTreasury, partner, escrowTokens } = streamData;
629
- const { tokenProgramId } = await getMintAndProgram(this.connection, mint);
630
- const ixs = prepareBaseInstructions(this.connection, {
631
- computePrice,
632
- computeLimit: computeLimit ?? ALIGNED_COMPUTE_LIMIT,
633
- });
634
- const ataIx = await this.getCreateATAInstructions([sender, recipient, partner, streamflowTreasury], mint, invoker, checkTokenAccounts, tokenProgramId);
635
- const cancelIx = await this.alignedProxyProgram.methods
636
- .cancel()
637
- .accountsPartial({
638
- mint,
639
- partner,
640
- recipient,
641
- escrowTokens,
642
- sender: invoker.publicKey,
643
- streamMetadata: streamPublicKey,
644
- streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
645
- tokenProgram: tokenProgramId,
646
- streamflowProgram: this.programId,
647
- })
648
- .instruction();
649
- ixs.push(...ataIx, cancelIx);
650
- return ixs;
651
- }
652
- /**
653
- * Creates Transaction Instructions for cancel
654
- */
655
- async prepareCancelStreamInstructions({ id }, { invoker, checkTokenAccounts, computePrice, computeLimit }) {
656
- if (!invoker.publicKey) {
657
- throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
658
- }
659
- const streamPublicKey = new PublicKey(id);
660
- const escrowAcc = await this.connection.getAccountInfo(streamPublicKey);
661
- if (!escrowAcc?.data) {
662
- throw new Error("Couldn't get account info");
663
- }
664
- const data = decodeStream(escrowAcc.data);
665
- const { sender, recipient, partner, streamflowTreasury, mint, senderTokens, recipientTokens, escrowTokens } = data;
666
- const { tokenProgramId } = await getMintAndProgram(this.connection, mint);
667
- const streamflowTreasuryTokens = await ata(mint, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
668
- const partnerTokens = await ata(mint, partner, tokenProgramId);
669
- const ixs = prepareBaseInstructions(this.connection, {
670
- computePrice,
671
- computeLimit,
672
- });
673
- const ixsAta = await this.getCreateATAInstructions([sender, recipient, partner, streamflowTreasury], mint, invoker, checkTokenAccounts, tokenProgramId);
674
- ixs.push(...ixsAta, await cancelStreamInstruction(this.programId, {
675
- sender,
676
- senderTokens,
677
- recipient,
678
- recipientTokens,
679
- streamflowTreasuryTokens,
680
- partner,
681
- partnerTokens,
682
- mint,
683
- escrowTokens,
684
- authority: invoker.publicKey,
685
- metadata: streamPublicKey,
686
- streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
687
- tokenProgram: tokenProgramId,
688
- }));
689
- return ixs;
690
- }
691
- /**
692
- * Attempts changing the stream/vesting contract's recipient (effectively transferring the stream/vesting contract).
693
- * Potential associated token account rent fee (to make it rent-exempt) is paid by the transaction initiator.
694
- */
695
- async transfer({ id, newRecipient }, extParams) {
696
- const ixs = await this.prepareTransferInstructions({ id, newRecipient }, extParams);
697
- const { tx, hash, context } = await prepareTransaction(this.connection, ixs, extParams.invoker.publicKey);
698
- const signature = await signAndExecuteTransaction(this.connection, extParams.invoker, tx, {
699
- hash,
700
- context,
701
- commitment: this.getCommitment(),
702
- }, this.schedulingParams);
703
- return { ixs, txId: signature };
704
- }
705
- /**
706
- * Attempts changing the stream/vesting contract's recipient (effectively transferring the stream/vesting contract).
707
- * Potential associated token account rent fee (to make it rent-exempt) is paid by the transaction initiator.
708
- */
709
- async prepareTransferInstructions({ id, newRecipient }, { invoker, computePrice, computeLimit = 100001 }) {
710
- if (!invoker.publicKey) {
711
- throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
712
- }
713
- const ixs = prepareBaseInstructions(this.connection, {
714
- computePrice,
715
- computeLimit,
716
- });
717
- const stream = new PublicKey(id);
718
- const newRecipientPublicKey = new PublicKey(newRecipient);
719
- const escrow = await this.connection.getAccountInfo(stream);
720
- if (!escrow?.data) {
721
- throw new Error("Couldn't get account info");
722
- }
723
- const { mint } = decodeStream(escrow?.data);
724
- const { tokenProgramId } = await getMintAndProgram(this.connection, mint);
725
- const newRecipientTokens = await ata(mint, newRecipientPublicKey, tokenProgramId);
726
- ixs.push(await transferStreamInstruction(this.programId, {
727
- authority: invoker.publicKey,
728
- newRecipient: newRecipientPublicKey,
729
- newRecipientTokens,
730
- metadata: stream,
731
- mint,
732
- rent: SYSVAR_RENT_PUBKEY,
733
- tokenProgram: tokenProgramId,
734
- associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
735
- systemProgram: SystemProgram.programId,
736
- }));
737
- return ixs;
738
- }
739
- /**
740
- * Tops up stream account with specified amount.
741
- */
742
- async topup({ id, amount }, extParams) {
743
- const ixs = await this.prepareTopupInstructions({ id, amount }, extParams);
744
- const { tx, hash, context } = await prepareTransaction(this.connection, ixs, extParams.invoker.publicKey);
745
- const signature = await signAndExecuteTransaction(this.connection, extParams.invoker, tx, {
746
- hash,
747
- context,
748
- commitment: this.getCommitment(),
749
- }, this.schedulingParams);
750
- return { ixs, txId: signature };
751
- }
752
- /**
753
- * Create Transaction instructions for topup
754
- */
755
- async prepareTopupInstructions({ id, amount }, { invoker, isNative, computePrice, computeLimit }) {
756
- if (!invoker.publicKey) {
757
- throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
758
- }
759
- const ixs = prepareBaseInstructions(this.connection, {
760
- computePrice,
761
- computeLimit,
762
- });
763
- const streamPublicKey = new PublicKey(id);
764
- const escrow = await this.connection.getAccountInfo(streamPublicKey);
765
- if (!escrow?.data) {
766
- throw new Error("Couldn't get account info");
767
- }
768
- const { mint, partner, senderTokens, escrowTokens } = decodeStream(escrow?.data);
769
- const { tokenProgramId } = await getMintAndProgram(this.connection, mint);
770
- const streamflowTreasuryTokens = await ata(mint, STREAMFLOW_TREASURY_PUBLIC_KEY, tokenProgramId);
771
- const partnerTokens = await ata(mint, partner, tokenProgramId);
772
- if (isNative) {
773
- ixs.push(...(await prepareWrappedAccount(this.connection, invoker.publicKey, amount)));
774
- }
775
- ixs.push(await topupStreamInstruction(amount, this.programId, {
776
- sender: invoker.publicKey,
777
- senderTokens,
778
- metadata: streamPublicKey,
779
- escrowTokens,
780
- streamflowTreasury: STREAMFLOW_TREASURY_PUBLIC_KEY,
781
- streamflowTreasuryTokens: streamflowTreasuryTokens,
782
- partner: partner,
783
- partnerTokens: partnerTokens,
784
- mint,
785
- tokenProgram: tokenProgramId,
786
- withdrawor: WITHDRAWOR_PUBLIC_KEY,
787
- systemProgram: SystemProgram.programId,
788
- }));
789
- return ixs;
790
- }
791
- /**
792
- * Fetch stream data by its id (address).
793
- */
794
- async getOne({ id }) {
795
- const streamPublicKey = new PublicKey(id);
796
- const escrow = await this.connection.getAccountInfo(streamPublicKey, TX_FINALITY_CONFIRMED);
797
- if (!escrow?.data) {
798
- throw new Error("Couldn't get account info.");
799
- }
800
- const stream = decodeStream(escrow.data);
801
- if (this.isAlignedUnlock(streamPublicKey, stream.sender)) {
802
- const alignedProxy = await this.alignedProxyProgram.account.contract.fetch(deriveContractPDA(this.alignedProxyProgram.programId, streamPublicKey));
803
- if (!alignedProxy) {
804
- throw new Error("Couldn't get proxy account info.");
805
- }
806
- return new AlignedContract(stream, alignedProxy);
807
- }
808
- return new Contract(stream);
809
- }
810
- /**
811
- * Fetch all aligned outgoing streams/contracts by the provided public key.
812
- */
813
- async getOutgoingAlignedStreams(sender) {
814
- const streams = {};
815
- const alignedOutgoingProgramAccounts = await this.alignedProxyProgram.account.contract.all([
816
- {
817
- memcmp: {
818
- offset: ORIGINAL_CONTRACT_SENDER_OFFSET,
819
- bytes: sender,
820
- },
821
- },
822
- {
823
- dataSize: ALIGNED_METADATA_ACC_SIZE,
824
- },
825
- ]);
826
- const streamPubKeys = alignedOutgoingProgramAccounts.map((account) => account.account.stream);
827
- const streamAccounts = await getMultipleAccountsInfoBatched(this.connection, streamPubKeys, TX_FINALITY_CONFIRMED);
828
- streamAccounts.forEach((account, index) => {
829
- if (account) {
830
- const alignedData = alignedOutgoingProgramAccounts[index].account;
831
- streams[streamPubKeys[index].toBase58()] = new AlignedContract(decodeStream(account.data), alignedData);
832
- }
833
- });
834
- return streams;
835
- }
836
- async getIncomingAlignedStreams(streamRecord) {
837
- const streams = {};
838
- const alignedStreamsPubKeys = Object.keys(streamRecord);
839
- const alignedProxyPDAs = alignedStreamsPubKeys.map((streamPubKey) => deriveContractPDA(this.alignedProxyProgram.programId, new PublicKey(streamPubKey)));
840
- const alignedProxyAccounts = await getMultipleAccountsInfoBatched(this.connection, alignedProxyPDAs);
841
- alignedProxyAccounts.forEach((account, index) => {
842
- if (account && account.data.length === ALIGNED_METADATA_ACC_SIZE) {
843
- const alignedData = streamRecord[alignedStreamsPubKeys[index]];
844
- streams[alignedStreamsPubKeys[index]] = new AlignedContract(alignedData, this.alignedProxyProgram.account.contract.coder.accounts.decode("contract", account.data));
845
- }
846
- });
847
- return streams;
848
- }
849
- /**
850
- * Fetch streams/contracts by providing direction.
851
- * Streams are sorted by start time in ascending order.
852
- */
853
- async get({ address, type = StreamType.All, direction = StreamDirection.All, }) {
854
- const publicKey = new PublicKey(address);
855
- let streams = {};
856
- // don't do unnecessary rpc calls if we are not querying for vesting streams
857
- const shouldFetchAligned = type === StreamType.All || type === StreamType.Vesting;
858
- if (direction !== StreamDirection.Incoming) {
859
- const outgoingStreamAccounts = await getProgramAccounts(this.connection, publicKey, STREAM_STRUCT_OFFSET_SENDER, this.programId);
860
- outgoingStreamAccounts.forEach((account) => {
861
- streams[account.pubkey.toBase58()] = new Contract(decodeStream(account.account.data));
862
- });
863
- if (shouldFetchAligned) {
864
- const alignedStreams = await this.getOutgoingAlignedStreams(address);
865
- streams = { ...streams, ...alignedStreams };
866
- }
867
- }
868
- if (direction !== StreamDirection.Outgoing) {
869
- const allIncomingAccounts = await getProgramAccounts(this.connection, publicKey, STREAM_STRUCT_OFFSET_RECIPIENT, this.programId);
870
- const allIncomingStreams = allIncomingAccounts.map((account) => decodeStream(account.account.data));
871
- const alignedDecoded = {};
872
- // filter out aligned unlocks and store them in a separate object
873
- allIncomingAccounts.forEach((account, index) => {
874
- if (this.isAlignedUnlock(account.pubkey, allIncomingStreams[index].sender)) {
875
- alignedDecoded[account.pubkey.toBase58()] = allIncomingStreams[index];
876
- }
877
- else {
878
- streams[account.pubkey.toBase58()] = new Contract(allIncomingStreams[index]);
879
- }
880
- });
881
- if (shouldFetchAligned) {
882
- const incomingAlignedStreams = await this.getIncomingAlignedStreams(alignedDecoded);
883
- streams = { ...streams, ...incomingAlignedStreams };
884
- }
885
- }
886
- const sortedStreams = Object.entries(streams).sort(([, stream1], [, stream2]) => stream2.start - stream1.start);
887
- if (type === StreamType.All)
888
- return sortedStreams;
889
- return sortedStreams.filter((stream) => stream[1].type === type);
890
- }
891
- async searchStreams(data) {
892
- const filters = Object.entries(data)
893
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
894
- .filter(([_, value]) => value !== undefined) // Only keep entries where the value is truthy
895
- .map(([key, value]) => ({
896
- memcmp: {
897
- offset: STREAM_STRUCT_OFFSETS[key],
898
- bytes: typeof value === "boolean" ? bs58.encode([Number(value)]) : value.toString(),
899
- },
900
- }));
901
- filters.push({ dataSize: METADATA_ACC_SIZE });
902
- const accounts = await this.connection.getProgramAccounts(this.programId, {
903
- filters,
904
- });
905
- return accounts.map(({ pubkey, account }) => ({
906
- publicKey: pubkey,
907
- account: new Contract(decodeStream(account.data)),
908
- }));
909
- }
910
- /**
911
- * Attempts updating the stream auto withdrawal params and amount per period
912
- */
913
- async update(data, extParams) {
914
- const ixs = await this.prepareUpdateInstructions(data, extParams);
915
- const { tx, hash, context } = await prepareTransaction(this.connection, ixs, extParams.invoker.publicKey);
916
- const signature = await signAndExecuteTransaction(this.connection, extParams.invoker, tx, {
917
- hash,
918
- context,
919
- commitment: this.getCommitment(),
920
- }, this.schedulingParams);
921
- return {
922
- ixs,
923
- txId: signature,
924
- };
925
- }
926
- /**
927
- * Create Transaction instructions for update
928
- */
929
- async prepareUpdateInstructions(data, { invoker, computePrice, computeLimit }) {
930
- if (!invoker.publicKey) {
931
- throw new Error("Invoker's PublicKey is not available, check passed wallet adapter!");
932
- }
933
- const streamPublicKey = new PublicKey(data.id);
934
- const escrow = await this.connection.getAccountInfo(streamPublicKey);
935
- if (!escrow) {
936
- throw new Error("Couldn't get account info");
937
- }
938
- const ixs = prepareBaseInstructions(this.connection, {
939
- computePrice,
940
- computeLimit,
941
- });
942
- ixs.push(await updateStreamInstruction(data, this.programId, {
943
- authority: invoker.publicKey,
944
- metadata: streamPublicKey,
945
- withdrawor: WITHDRAWOR_PUBLIC_KEY,
946
- systemProgram: SystemProgram.programId,
947
- }));
948
- return ixs;
949
- }
950
- async getFees({ address }) {
951
- const [metadataPubKey] = PublicKey.findProgramAddressSync([Buffer.from(FEES_METADATA_SEED)], new PublicKey(PARTNER_ORACLE_PROGRAM_ID));
952
- const data = await this.connection.getAccountInfo(metadataPubKey);
953
- if (!data) {
954
- return null;
955
- }
956
- const partners = borsh.deserialize(PARTNERS_SCHEMA, data.data);
957
- const filteredPartners = partners.filter((item) => new PublicKey(item.pubkey).toString() === address);
958
- if (filteredPartners.length === 0) {
959
- return null;
960
- }
961
- return {
962
- streamflowFee: Number(filteredPartners[0].strm_fee.toFixed(4)),
963
- partnerFee: Number(filteredPartners[0].partner_fee.toFixed(4)),
964
- };
965
- }
966
- async getDefaultStreamflowFee() {
967
- return DEFAULT_STREAMFLOW_FEE;
968
- }
969
- extractErrorCode(err) {
970
- const logs = "logs" in err && Array.isArray(err.logs) ? err.logs : undefined;
971
- return extractSolanaErrorCode(err.toString() ?? "Unknown error!", logs);
972
- }
973
- /**
974
- * Utility function to generate metadata for a Contract or return existing Pubkey
975
- */
976
- getOrCreateStreamMetadata(metadataPubKeys) {
977
- let metadata;
978
- let metadataPubKey;
979
- if (!metadataPubKeys) {
980
- metadata = Keypair.generate();
981
- metadataPubKey = metadata.publicKey;
982
- }
983
- else {
984
- metadataPubKey = metadataPubKeys[0];
985
- }
986
- return { metadata, metadataPubKey };
987
- }
988
- /**
989
- * Utility function that checks whether the associated stream address is an aligned unlock contract, indicated by whether the sender/creator is a PDA
990
- */
991
- isAlignedUnlock(streamPublicKey, senderPublicKey) {
992
- const pda = deriveContractPDA(this.alignedProxyProgram.programId, streamPublicKey);
993
- return senderPublicKey.equals(pda);
994
- }
995
- /**
996
- * Returns insrtuctions for creating associated token accounts for the provided owners
997
- */
998
- async getCreateATAInstructions(owners, mint, invoker, checkTokenAccounts, programId) {
999
- if (!checkTokenAccounts) {
1000
- return [];
1001
- }
1002
- // filter out duplicate PublicKeys, otherwise transaction will fail
1003
- const uniqueOwners = Array.from(new Set(owners.map((owner) => owner.toBase58()))).map((pkString) => new PublicKey(pkString));
1004
- return checkOrCreateAtaBatch(this.connection, uniqueOwners, mint, invoker, programId);
1005
- }
1006
- async applyCustomAfterInstructions(ixs, customInstructions, metadata) {
1007
- if (customInstructions?.after) {
1008
- const afterInstructions = typeof customInstructions.after === "function"
1009
- ? await customInstructions.after({
1010
- instructions: ixs,
1011
- metadata,
1012
- })
1013
- : customInstructions.after;
1014
- ixs.push(...afterInstructions);
1015
- }
1016
- }
1017
- }