@streamflow/stream 6.3.8 → 7.0.0-alpha.1

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 (121) hide show
  1. package/README.md +33 -1
  2. package/dist/{__tests__ → cjs/__tests__}/aptos/streamClient.spec.js +22 -21
  3. package/dist/cjs/__tests__/common/GenericStreamClient.spec.js +45 -0
  4. package/dist/{aptos → cjs/aptos}/StreamClient.js +20 -20
  5. package/dist/cjs/aptos/constants.js +28 -0
  6. package/dist/{aptos → cjs/aptos}/index.js +3 -3
  7. package/dist/{aptos → cjs/aptos}/types.js +12 -11
  8. package/dist/{aptos → cjs/aptos}/utils.js +2 -2
  9. package/dist/{common → cjs/common}/GenericStreamClient.js +19 -19
  10. package/dist/{common → cjs/common}/contractUtils.js +4 -4
  11. package/dist/{common → cjs/common}/utils.js +4 -6
  12. package/dist/{evm → cjs/evm}/StreamClient.js +29 -29
  13. package/dist/cjs/evm/constants.js +39 -0
  14. package/dist/{evm → cjs/evm}/index.js +8 -8
  15. package/dist/{evm → cjs/evm}/types.js +5 -5
  16. package/dist/{evm → cjs/evm}/utils.js +2 -2
  17. package/dist/{solana → cjs/solana}/StreamClient.js +73 -66
  18. package/dist/cjs/solana/constants.js +60 -0
  19. package/dist/cjs/solana/index.js +39 -0
  20. package/dist/{solana → cjs/solana}/instructions.js +20 -12
  21. package/dist/{solana → cjs/solana}/layout.js +8 -2
  22. package/dist/{solana → cjs/solana}/types.js +5 -5
  23. package/dist/{solana → cjs/solana}/utils.js +6 -6
  24. package/dist/{sui → cjs/sui}/StreamClient.js +25 -25
  25. package/dist/cjs/sui/constants.js +43 -0
  26. package/dist/{sui → cjs/sui}/index.js +5 -5
  27. package/dist/{sui → cjs/sui}/types.js +5 -5
  28. package/dist/{sui → cjs/sui}/utils.js +3 -3
  29. package/dist/esm/__tests__/aptos/streamClient.spec.js +106 -0
  30. package/dist/esm/__tests__/common/GenericStreamClient.spec.js +40 -0
  31. package/dist/{aptos → esm/aptos}/StreamClient.d.ts +3 -3
  32. package/dist/esm/aptos/StreamClient.js +226 -0
  33. package/dist/{aptos → esm/aptos}/constants.d.ts +1 -1
  34. package/dist/esm/aptos/constants.js +24 -0
  35. package/dist/{aptos → esm/aptos}/index.d.ts +1 -1
  36. package/dist/{sui/index.d.ts → esm/aptos/index.js} +1 -1
  37. package/dist/{aptos → esm/aptos}/types.d.ts +1 -1
  38. package/dist/esm/aptos/types.js +105 -0
  39. package/dist/esm/aptos/utils.js +30 -0
  40. package/dist/esm/aptos/wallet.js +33 -0
  41. package/dist/{common → esm/common}/BaseStreamClient.d.ts +1 -1
  42. package/dist/esm/common/BaseStreamClient.js +19 -0
  43. package/dist/{common → esm/common}/GenericStreamClient.d.ts +2 -2
  44. package/dist/esm/common/GenericStreamClient.js +101 -0
  45. package/dist/esm/common/constants.js +3 -0
  46. package/dist/{common → esm/common}/contractUtils.d.ts +1 -1
  47. package/dist/esm/common/contractUtils.js +42 -0
  48. package/dist/esm/common/types.js +106 -0
  49. package/dist/{common → esm/common}/utils.d.ts +0 -1
  50. package/dist/esm/common/utils.js +59 -0
  51. package/dist/{evm → esm/evm}/StreamClient.d.ts +2 -2
  52. package/dist/esm/evm/StreamClient.js +237 -0
  53. package/dist/esm/evm/abi.js +1255 -0
  54. package/dist/{evm → esm/evm}/constants.d.ts +1 -1
  55. package/dist/esm/evm/constants.js +35 -0
  56. package/dist/esm/evm/ercAbi.js +222 -0
  57. package/dist/esm/evm/index.d.ts +5 -0
  58. package/dist/esm/evm/index.js +5 -0
  59. package/dist/{evm → esm/evm}/types.d.ts +1 -1
  60. package/dist/esm/evm/types.js +102 -0
  61. package/dist/esm/evm/utils.js +8 -0
  62. package/dist/esm/index.js +9 -0
  63. package/dist/{solana → esm/solana}/StreamClient.d.ts +6 -6
  64. package/dist/esm/solana/StreamClient.js +695 -0
  65. package/dist/{solana → esm/solana}/constants.d.ts +2 -0
  66. package/dist/esm/solana/constants.js +56 -0
  67. package/dist/esm/solana/index.d.ts +6 -0
  68. package/dist/esm/solana/index.js +6 -0
  69. package/dist/esm/solana/instructionTypes.js +1 -0
  70. package/dist/{solana → esm/solana}/instructions.d.ts +5 -1
  71. package/dist/esm/solana/instructions.js +256 -0
  72. package/dist/{solana → esm/solana}/layout.d.ts +2 -1
  73. package/dist/esm/solana/layout.js +155 -0
  74. package/dist/esm/solana/timelockIDL.js +420 -0
  75. package/dist/{solana → esm/solana}/types.d.ts +2 -1
  76. package/dist/esm/solana/types.js +101 -0
  77. package/dist/{solana → esm/solana}/utils.d.ts +2 -1
  78. package/dist/esm/solana/utils.js +117 -0
  79. package/dist/{sui → esm/sui}/StreamClient.d.ts +3 -3
  80. package/dist/esm/sui/StreamClient.js +403 -0
  81. package/dist/{sui → esm/sui}/constants.d.ts +1 -1
  82. package/dist/esm/sui/constants.js +39 -0
  83. package/dist/esm/sui/index.d.ts +4 -0
  84. package/dist/esm/sui/index.js +4 -0
  85. package/dist/{sui → esm/sui}/types.d.ts +1 -1
  86. package/dist/esm/sui/types.js +104 -0
  87. package/dist/{sui → esm/sui}/utils.d.ts +1 -1
  88. package/dist/esm/sui/utils.js +23 -0
  89. package/dist/{sui → esm/sui}/wallet.d.ts +1 -1
  90. package/dist/esm/sui/wallet.js +38 -0
  91. package/package.json +36 -33
  92. package/dist/__tests__/common/GenericStreamClient.spec.js +0 -44
  93. package/dist/aptos/constants.js +0 -28
  94. package/dist/evm/constants.js +0 -39
  95. package/dist/evm/index.d.ts +0 -5
  96. package/dist/solana/constants.js +0 -59
  97. package/dist/solana/index.d.ts +0 -7
  98. package/dist/solana/index.js +0 -43
  99. package/dist/sui/constants.js +0 -43
  100. /package/dist/{aptos → cjs/aptos}/wallet.js +0 -0
  101. /package/dist/{common → cjs/common}/BaseStreamClient.js +0 -0
  102. /package/dist/{common → cjs/common}/constants.js +0 -0
  103. /package/dist/{common → cjs/common}/types.js +0 -0
  104. /package/dist/{evm → cjs/evm}/abi.js +0 -0
  105. /package/dist/{evm → cjs/evm}/ercAbi.js +0 -0
  106. /package/dist/{index.js → cjs/index.js} +0 -0
  107. /package/dist/{solana → cjs/solana}/instructionTypes.js +0 -0
  108. /package/dist/{solana → cjs/solana}/timelockIDL.js +0 -0
  109. /package/dist/{sui → cjs/sui}/wallet.js +0 -0
  110. /package/dist/{__tests__ → esm/__tests__}/aptos/streamClient.spec.d.ts +0 -0
  111. /package/dist/{__tests__ → esm/__tests__}/common/GenericStreamClient.spec.d.ts +0 -0
  112. /package/dist/{aptos → esm/aptos}/utils.d.ts +0 -0
  113. /package/dist/{aptos → esm/aptos}/wallet.d.ts +0 -0
  114. /package/dist/{common → esm/common}/constants.d.ts +0 -0
  115. /package/dist/{common → esm/common}/types.d.ts +0 -0
  116. /package/dist/{evm → esm/evm}/abi.d.ts +0 -0
  117. /package/dist/{evm → esm/evm}/ercAbi.d.ts +0 -0
  118. /package/dist/{evm → esm/evm}/utils.d.ts +0 -0
  119. /package/dist/{index.d.ts → esm/index.d.ts} +0 -0
  120. /package/dist/{solana → esm/solana}/instructionTypes.d.ts +0 -0
  121. /package/dist/{solana → esm/solana}/timelockIDL.d.ts +0 -0
@@ -0,0 +1,403 @@
1
+ import { SuiClient } from "@mysten/sui.js/client";
2
+ import { TransactionBlock } from "@mysten/sui.js/transactions";
3
+ import { SUI_CLOCK_OBJECT_ID, SUI_TYPE_ARG } from "@mysten/sui.js/utils";
4
+ import { BaseStreamClient } from "../common/BaseStreamClient.js";
5
+ import { ICluster, } from "../common/types.js";
6
+ import { SUI_PROGRAM_IDS, SUI_FEE_TABLE_IDS, SUI_CONFIG_IDS } from "./constants.js";
7
+ import { Contract, } from "./types.js";
8
+ import { extractSuiErrorInfo } from "./utils.js";
9
+ import { SuiWalletWrapper } from "./wallet.js";
10
+ import { calculateTotalAmountToDeposit } from "../common/utils.js";
11
+ import { WITHDRAW_AVAILABLE_AMOUNT } from "../common/constants.js";
12
+ export default class SuiStreamClient extends BaseStreamClient {
13
+ programId;
14
+ configId;
15
+ feeTableId;
16
+ client;
17
+ constructor(clusterUrl, cluster = ICluster.Mainnet, ids) {
18
+ super();
19
+ this.programId = ids?.program ? ids.program : SUI_PROGRAM_IDS[cluster];
20
+ this.configId = ids?.config ? ids.config : SUI_CONFIG_IDS[cluster];
21
+ this.feeTableId = ids?.feeTable ? ids.feeTable : SUI_FEE_TABLE_IDS[cluster];
22
+ this.client = new SuiClient({ url: clusterUrl });
23
+ }
24
+ /**
25
+ * Creates a new stream/vesting contract.
26
+ */
27
+ async create(streamData, { senderWallet }) {
28
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
29
+ const totalFee = await this.getTotalFee({
30
+ address: streamData.partner ?? wallet.address,
31
+ });
32
+ const [txb] = await this.generateCreateBlock(wallet.address, {
33
+ ...streamData,
34
+ recipients: [{ ...streamData }],
35
+ }, totalFee);
36
+ const { digest, events } = await wallet.signAndExecuteTransactionBlock({
37
+ transactionBlock: txb,
38
+ options: { showEvents: true },
39
+ });
40
+ return {
41
+ ixs: [],
42
+ txId: digest,
43
+ metadataId: events[0].parsedJson.address,
44
+ };
45
+ }
46
+ /**
47
+ * Creates multiple stream/vesting contracts.
48
+ * We don't chain transactions in one Block so that one failed transaction does not revert all others.
49
+ */
50
+ async createMultiple(multipleStreamData, { senderWallet }) {
51
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
52
+ const totalFee = await this.getTotalFee({
53
+ address: multipleStreamData.partner ?? wallet.address,
54
+ });
55
+ const [txb, firstIndex] = await this.generateCreateBlock(wallet.address, multipleStreamData, totalFee);
56
+ const txs = [];
57
+ const metadatas = [];
58
+ const metadataToRecipient = {};
59
+ const errors = [];
60
+ try {
61
+ const { digest, events, effects } = await wallet.signAndExecuteTransactionBlock({
62
+ transactionBlock: txb,
63
+ options: { showEffects: true, showEvents: true },
64
+ });
65
+ txs.push(digest);
66
+ if (effects.status.status === "failure") {
67
+ multipleStreamData.recipients.forEach((recipient) => {
68
+ errors.push({
69
+ error: effects.status.error ?? "Unknown error!",
70
+ recipient: recipient.recipient,
71
+ });
72
+ });
73
+ }
74
+ else {
75
+ multipleStreamData.recipients.forEach((recipient, index) => {
76
+ const metadataId = events[index].parsedJson.address;
77
+ metadatas.push(metadataId);
78
+ metadataToRecipient[metadataId] = recipient;
79
+ });
80
+ }
81
+ }
82
+ catch (e) {
83
+ const errorInfo = extractSuiErrorInfo(e.toString() ?? "Unknown error!");
84
+ multipleStreamData.recipients.forEach((recipient, index) => {
85
+ if (errorInfo.index === undefined ||
86
+ errorInfo.index < index + firstIndex ||
87
+ errorInfo.index >= multipleStreamData.recipients.length + firstIndex ||
88
+ errorInfo.index === index + firstIndex) {
89
+ errors.push({
90
+ error: errorInfo.text,
91
+ recipient: recipient.recipient,
92
+ contractErrorCode: errorInfo.parsed?.name,
93
+ });
94
+ }
95
+ });
96
+ }
97
+ return {
98
+ txs,
99
+ metadatas,
100
+ metadataToRecipient,
101
+ errors,
102
+ };
103
+ }
104
+ /**
105
+ * Attempts withdrawing from the specified stream.
106
+ */
107
+ async withdraw({ id, amount = WITHDRAW_AVAILABLE_AMOUNT }, { senderWallet, tokenId }) {
108
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
109
+ const txb = new TransactionBlock();
110
+ txb.moveCall({
111
+ target: `${this.programId}::protocol::withdraw`,
112
+ typeArguments: [tokenId],
113
+ arguments: [
114
+ txb.object(id),
115
+ txb.object(this.configId),
116
+ txb.object(SUI_CLOCK_OBJECT_ID),
117
+ txb.pure(amount.toString()),
118
+ ],
119
+ });
120
+ const { digest } = await wallet.signAndExecuteTransactionBlock({
121
+ transactionBlock: txb,
122
+ });
123
+ return {
124
+ ixs: [],
125
+ txId: digest,
126
+ };
127
+ }
128
+ /**
129
+ * Attempts canceling the specified stream.
130
+ */
131
+ async cancel(cancelData, { senderWallet, tokenId }) {
132
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
133
+ const txb = new TransactionBlock();
134
+ txb.moveCall({
135
+ target: `${this.programId}::protocol::cancel`,
136
+ typeArguments: [tokenId],
137
+ arguments: [txb.object(cancelData.id), txb.object(this.configId), txb.object(SUI_CLOCK_OBJECT_ID)],
138
+ });
139
+ const { digest } = await wallet.signAndExecuteTransactionBlock({
140
+ transactionBlock: txb,
141
+ });
142
+ return {
143
+ ixs: [],
144
+ txId: digest,
145
+ };
146
+ }
147
+ /**
148
+ * Attempts changing the stream/vesting contract's recipient (effectively transferring the stream/vesting contract).
149
+ */
150
+ async transfer(transferData, { senderWallet, tokenId }) {
151
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
152
+ const txb = new TransactionBlock();
153
+ txb.moveCall({
154
+ target: `${this.programId}::protocol::transfer`,
155
+ typeArguments: [tokenId],
156
+ arguments: [txb.object(transferData.id), txb.pure(transferData.newRecipient)],
157
+ });
158
+ const { digest } = await wallet.signAndExecuteTransactionBlock({
159
+ transactionBlock: txb,
160
+ });
161
+ return {
162
+ ixs: [],
163
+ txId: digest,
164
+ };
165
+ }
166
+ /**
167
+ * Tops up stream account with specified amount.
168
+ */
169
+ async topup(topupData, { senderWallet, tokenId }) {
170
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
171
+ const txb = new TransactionBlock();
172
+ const coins = await this.getAllCoins(wallet.address, tokenId);
173
+ const stream = await this.getOne({ id: topupData.id });
174
+ const totalFee = (stream.partnerFeePercent + stream.streamflowFeePercent) / 100;
175
+ const coinObject = this.splitCoinObjectForAmount(txb, topupData.amount, tokenId, coins, totalFee);
176
+ txb.moveCall({
177
+ target: `${this.programId}::protocol::topup`,
178
+ typeArguments: [tokenId],
179
+ arguments: [
180
+ txb.object(topupData.id),
181
+ txb.object(this.configId),
182
+ coinObject,
183
+ txb.gas,
184
+ txb.pure(topupData.amount.toString()),
185
+ ],
186
+ });
187
+ this.returnSplittedCoinObject(txb, tokenId, coins, coinObject);
188
+ const { digest } = await wallet.signAndExecuteTransactionBlock({
189
+ transactionBlock: txb,
190
+ });
191
+ return {
192
+ ixs: [],
193
+ txId: digest,
194
+ };
195
+ }
196
+ /**
197
+ * Fetch stream data by its id (address).
198
+ */
199
+ async getOne({ id }) {
200
+ const response = await this.client.getObject({
201
+ id,
202
+ options: {
203
+ showContent: true,
204
+ },
205
+ });
206
+ if (!response.data) {
207
+ throw new Error(`Contract with id ${id} could not be found!`);
208
+ }
209
+ const content = response.data.content;
210
+ if (content.dataType !== "moveObject") {
211
+ throw new Error(`Not a Move Object!`);
212
+ }
213
+ return new Contract(content.fields, "0x97e9a9fb1392e9785319f5512d0bfde6ecf7757b09c6de41cec89e798dd361f2::strmt::STRMT");
214
+ }
215
+ async get() {
216
+ throw new Error("Get all method is not supported for Sui chain!");
217
+ }
218
+ /**
219
+ * Attempts updating the stream auto withdrawal params and amount per period
220
+ */
221
+ async update(updateData, { senderWallet, tokenId }) {
222
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
223
+ const txb = new TransactionBlock();
224
+ txb.moveCall({
225
+ target: `${this.programId}::protocol::update`,
226
+ typeArguments: [tokenId],
227
+ arguments: [
228
+ txb.object(updateData.id),
229
+ txb.object(this.configId),
230
+ txb.object(SUI_CLOCK_OBJECT_ID),
231
+ txb.gas,
232
+ txb.pure(updateData.enableAutomaticWithdrawal !== undefined ? [updateData.enableAutomaticWithdrawal] : [], "vector<bool>"),
233
+ txb.pure(updateData.withdrawFrequency !== undefined ? [updateData.withdrawFrequency.toString()] : [], "vector<u64>"),
234
+ txb.pure(updateData.amountPerPeriod !== undefined ? [updateData.amountPerPeriod.toString()] : [], "vector<u64>"),
235
+ ],
236
+ });
237
+ const { digest } = await wallet.signAndExecuteTransactionBlock({
238
+ transactionBlock: txb,
239
+ });
240
+ return {
241
+ ixs: [],
242
+ txId: digest,
243
+ };
244
+ }
245
+ extractErrorCode(err) {
246
+ const errorInfo = extractSuiErrorInfo(err.toString() ?? "Unknown error!");
247
+ return errorInfo?.parsed?.name || null;
248
+ }
249
+ async getFees({ address }) {
250
+ const response = await this.client.getObject({
251
+ id: this.feeTableId,
252
+ options: {
253
+ showContent: true,
254
+ },
255
+ });
256
+ const content = response.data.content;
257
+ if (content.dataType !== "moveObject") {
258
+ throw new Error(`Not a Move Object!`);
259
+ }
260
+ const fields = content.fields;
261
+ const fieldsResponse = await this.client.getDynamicFields({
262
+ parentId: fields.values.fields.id.id,
263
+ });
264
+ const partnerDynamicField = fieldsResponse.data.filter((item) => item.name.value === address)[0];
265
+ if (!partnerDynamicField) {
266
+ return null;
267
+ }
268
+ const valueResponse = await this.client.getObject({
269
+ id: partnerDynamicField.objectId,
270
+ options: {
271
+ showContent: true,
272
+ },
273
+ });
274
+ const valueContent = valueResponse.data.content;
275
+ if (valueContent.dataType !== "moveObject") {
276
+ throw new Error(`Not a Move Object!`);
277
+ }
278
+ const valueFields = valueContent.fields.value.fields;
279
+ return {
280
+ streamflowFee: Number(valueFields.streamflow_fee) / 100,
281
+ partnerFee: Number(valueFields.partner_fee) / 100,
282
+ };
283
+ }
284
+ async getDefaultStreamflowFee() {
285
+ const response = await this.client.getObject({
286
+ id: this.configId,
287
+ options: {
288
+ showContent: true,
289
+ },
290
+ });
291
+ const content = response.data.content;
292
+ if (content.dataType !== "moveObject") {
293
+ throw new Error(`Not a Move Object!`);
294
+ }
295
+ const fields = content.fields;
296
+ return Number(fields.streamflow_fee) / 100;
297
+ }
298
+ /**
299
+ * Returns StreamClient protocol program ID.
300
+ */
301
+ getProgramId() {
302
+ return this.programId;
303
+ }
304
+ /**
305
+ * Utility function to generate Transaction Block to create streams
306
+ */
307
+ async generateCreateBlock(walletAddress, multipleStreamData, totalFee) {
308
+ let coins = await this.getAllCoins(walletAddress, multipleStreamData.tokenId);
309
+ const totalAmount = multipleStreamData.recipients
310
+ .map((recipiient) => recipiient.amount)
311
+ .reduce((prev, current) => current.add(prev));
312
+ const txb = new TransactionBlock();
313
+ const coinObject = this.splitCoinObjectForAmount(txb, totalAmount, multipleStreamData.tokenId, coins, totalFee);
314
+ coins = [coins[0]];
315
+ let firstIndex = null;
316
+ multipleStreamData.recipients.forEach((recipient) => {
317
+ const result = txb.moveCall({
318
+ target: `${this.programId}::protocol::create`,
319
+ typeArguments: [multipleStreamData.tokenId],
320
+ arguments: [
321
+ txb.object(this.configId),
322
+ txb.object(this.feeTableId),
323
+ txb.object(SUI_CLOCK_OBJECT_ID),
324
+ coinObject,
325
+ txb.gas,
326
+ txb.pure(recipient.amount.toString()),
327
+ txb.pure(multipleStreamData.period),
328
+ txb.pure(recipient.amountPerPeriod.toString()),
329
+ txb.pure(multipleStreamData.start),
330
+ txb.pure(recipient.cliffAmount.toString()),
331
+ txb.pure(multipleStreamData.cancelableBySender),
332
+ txb.pure(multipleStreamData.cancelableByRecipient),
333
+ txb.pure(multipleStreamData.transferableBySender),
334
+ txb.pure(multipleStreamData.transferableByRecipient),
335
+ txb.pure(multipleStreamData.canTopup),
336
+ txb.pure(!!multipleStreamData.canPause),
337
+ txb.pure(!!multipleStreamData.canUpdateRate),
338
+ txb.pure(!!multipleStreamData.automaticWithdrawal),
339
+ txb.pure(multipleStreamData.withdrawalFrequency || 0),
340
+ txb.pure(recipient.name),
341
+ txb.pure(recipient.recipient),
342
+ txb.pure(multipleStreamData.partner || walletAddress),
343
+ ],
344
+ });
345
+ if (result.kind === "Result" && firstIndex === null) {
346
+ firstIndex = result.index;
347
+ }
348
+ });
349
+ this.returnSplittedCoinObject(txb, multipleStreamData.tokenId, coins, coinObject);
350
+ return [txb, firstIndex];
351
+ }
352
+ /**
353
+ * Returns all coins owned by a Wallet
354
+ * @param walletAddress wallet address
355
+ * @param coinType coin type
356
+ * @returns Array of Coin Structs
357
+ */
358
+ async getAllCoins(walletAddress, coinType) {
359
+ let coinsResponse = await this.client.getCoins({
360
+ owner: walletAddress,
361
+ coinType: coinType,
362
+ });
363
+ const coins = coinsResponse.data;
364
+ while (coinsResponse.hasNextPage) {
365
+ coinsResponse = await this.client.getCoins({
366
+ owner: walletAddress,
367
+ coinType: coinType,
368
+ cursor: coinsResponse.nextCursor,
369
+ });
370
+ coins.push(...coinsResponse.data);
371
+ }
372
+ return coins;
373
+ }
374
+ /**
375
+ * Utility function to split Coin object and use splitted object for stream operations.
376
+ * We do it like thid to mitigate risk of Transaction reverting in case Stream is created for Sui Coin object.
377
+ * This way we can safely pass splitted Sui Coin object in Stream payload and use another object for gas/withdrawal fees.
378
+ * @param txb current transanction block
379
+ * @param amount minimal amount of coins requried
380
+ * @param coinType coin type
381
+ * @param coins array of owned coins of the same type
382
+ * @returns Coin Object to use in a Move Call
383
+ */
384
+ splitCoinObjectForAmount(txb, amount, coinType, coins, totalFee) {
385
+ const coinObject = coinType === SUI_TYPE_ARG ? txb.gas : txb.object(coins[0].coinObjectId);
386
+ if (coins.length > 1) {
387
+ txb.mergeCoins(coinObject, coins.slice(1).map((item) => txb.object(item.coinObjectId)));
388
+ }
389
+ const totalAmount = calculateTotalAmountToDeposit(amount, totalFee);
390
+ return txb.splitCoins(coinObject, [txb.pure(totalAmount.toString())])[0];
391
+ }
392
+ /**
393
+ * Return previously splitted Coin Object to owner and merge it to to rebate storage fees
394
+ * @param txb current transanction block
395
+ * @param coinType coin type
396
+ * @param coinObject splitted object
397
+ * @param coins array of objects used in
398
+ */
399
+ returnSplittedCoinObject(txb, coinType, coins, coinObject) {
400
+ const firstCoinObject = coinType === SUI_TYPE_ARG ? txb.gas : txb.object(coins[0].coinObjectId);
401
+ txb.mergeCoins(firstCoinObject, [coinObject]);
402
+ }
403
+ }
@@ -1,4 +1,4 @@
1
- import { ICluster } from "../common/types";
1
+ import { ICluster } from "../common/types.js";
2
2
  export declare const SUI_PROGRAM_IDS: Record<ICluster, string>;
3
3
  export declare const SUI_CONFIG_IDS: Record<ICluster, string>;
4
4
  export declare const SUI_FEE_TABLE_IDS: Record<ICluster, string>;
@@ -0,0 +1,39 @@
1
+ import { ContractErrorCode, ICluster } from "../common/types.js";
2
+ // TODO: remove Devnet and Local addresses as they are not deployed, they are just a copy Testnet values
3
+ export const SUI_PROGRAM_IDS = {
4
+ [ICluster.Mainnet]: "0xe456a3a1d4e58e85b4b7175fabe6dae895b983f1379bb8948d6ec2f137b08a7b",
5
+ [ICluster.Devnet]: "0x34dacd839e1758ebb70bdcd4e08f18fbfef5e2b96d9aa7ce2b4a71d96ca0df5a",
6
+ [ICluster.Testnet]: "0x34dacd839e1758ebb70bdcd4e08f18fbfef5e2b96d9aa7ce2b4a71d96ca0df5a",
7
+ [ICluster.Local]: "0x34dacd839e1758ebb70bdcd4e08f18fbfef5e2b96d9aa7ce2b4a71d96ca0df5a",
8
+ };
9
+ export const SUI_CONFIG_IDS = {
10
+ [ICluster.Mainnet]: "0x6cf6760b64245b8d23ef57c28ddceb6adbd540a23a509fef29b82237da4ab87b",
11
+ [ICluster.Devnet]: "0xd6c9f5074584f58074ce56e3c5cc436d82258ec3285f186a0d6438a60bacdbf8",
12
+ [ICluster.Testnet]: "0xd6c9f5074584f58074ce56e3c5cc436d82258ec3285f186a0d6438a60bacdbf8",
13
+ [ICluster.Local]: "0xd6c9f5074584f58074ce56e3c5cc436d82258ec3285f186a0d6438a60bacdbf8",
14
+ };
15
+ export const SUI_FEE_TABLE_IDS = {
16
+ [ICluster.Mainnet]: "0xad9b75399632583fb9fcae6b5bcca34e6542ab3bedb630ecbd3f15cb1cc48dbe",
17
+ [ICluster.Devnet]: "0x6057b093904c5bdfec1067d2b8a4dc35f65bcab03b3029ad716c4882b0f36078",
18
+ [ICluster.Testnet]: "0x6057b093904c5bdfec1067d2b8a4dc35f65bcab03b3029ad716c4882b0f36078",
19
+ [ICluster.Local]: "0x6057b093904c5bdfec1067d2b8a4dc35f65bcab03b3029ad716c4882b0f36078",
20
+ };
21
+ export const SUI_ERROR_MATCH_REGEX = /MoveAbort\(MoveLocation \{ module: ModuleId \{ address: (\w+), name: Identifier\("([\w_]+)"\) }, function: \d+, instruction: \d+, function_name: Some\("([\w_]+)"\) }, (\d+)\) in command (\d+)/;
22
+ export const SUI_MODULE_ERROR_MAP = {
23
+ protocol: {
24
+ 1: ContractErrorCode.ECONTRACT_NOT_INIT,
25
+ 2: ContractErrorCode.EBAD_AMOUNT,
26
+ 3: ContractErrorCode.ENO_PERMISSIONS,
27
+ 4: ContractErrorCode.EBADINPUT,
28
+ 5: ContractErrorCode.ECLOSED,
29
+ 6: ContractErrorCode.EBAD_INPUT_AMOUNT_PER_PERIOD,
30
+ 8: ContractErrorCode.EBAD_INPUT_UPDATE_RATE,
31
+ 9: ContractErrorCode.EBAD_INPUT_CLIFF_AMOUNT,
32
+ 10: ContractErrorCode.EBAD_INPUT_PERIOD,
33
+ 11: ContractErrorCode.EBAD_INPUT_START,
34
+ 13: ContractErrorCode.EBAD_INSUFFICIENT_WITHDRAWAL_FEES,
35
+ 14: ContractErrorCode.EBAD_INSUFFICIENT_AMOUNT,
36
+ 15: ContractErrorCode.EPAUSED,
37
+ 16: ContractErrorCode.ENOTPAUSED,
38
+ },
39
+ };
@@ -0,0 +1,4 @@
1
+ export { default as SuiStreamClient } from "./StreamClient.js";
2
+ export * from "./utils.js";
3
+ export * from "./types.js";
4
+ export * as constants from "./constants.js";
@@ -0,0 +1,4 @@
1
+ export { default as SuiStreamClient } from "./StreamClient.js";
2
+ export * from "./utils.js";
3
+ export * from "./types.js";
4
+ export * as constants from "./constants.js";
@@ -3,7 +3,7 @@ import { WalletContextState } from "@suiet/wallet-kit";
3
3
  import { TransactionBlock } from "@mysten/sui.js/transactions";
4
4
  import { ExecuteTransactionRequestType, SuiTransactionBlockResponseOptions } from "@mysten/sui.js/client";
5
5
  import BN from "bn.js";
6
- import { Stream, StreamType } from "../common/types";
6
+ import { Stream, StreamType } from "../common/types.js";
7
7
  export interface ICreateStreamSuiExt {
8
8
  senderWallet: WalletContextState | Keypair;
9
9
  }
@@ -0,0 +1,104 @@
1
+ import BN from "bn.js";
2
+ import { buildStreamType, calculateUnlockedAmount } from "../common/contractUtils.js";
3
+ import { getNumberFromBN } from "../common/utils.js";
4
+ export class Contract {
5
+ magic;
6
+ version;
7
+ createdAt;
8
+ withdrawnAmount;
9
+ canceledAt;
10
+ end;
11
+ lastWithdrawnAt;
12
+ sender;
13
+ senderTokens;
14
+ recipient;
15
+ recipientTokens;
16
+ mint;
17
+ escrowTokens;
18
+ streamflowTreasury;
19
+ streamflowTreasuryTokens;
20
+ streamflowFeeTotal;
21
+ streamflowFeeWithdrawn;
22
+ streamflowFeePercent;
23
+ partnerFeeTotal;
24
+ partnerFeeWithdrawn;
25
+ partnerFeePercent;
26
+ partner;
27
+ partnerTokens;
28
+ start;
29
+ depositedAmount;
30
+ period;
31
+ amountPerPeriod;
32
+ cliff;
33
+ cliffAmount;
34
+ cancelableBySender;
35
+ cancelableByRecipient;
36
+ automaticWithdrawal;
37
+ transferableBySender;
38
+ transferableByRecipient;
39
+ canTopup;
40
+ name;
41
+ withdrawalFrequency;
42
+ closed;
43
+ currentPauseStart;
44
+ pauseCumulative;
45
+ lastRateChangeTime;
46
+ fundsUnlockedAtLastRateChange;
47
+ type;
48
+ constructor(stream, tokenId) {
49
+ const meta = stream.meta.fields;
50
+ const fees = stream.fees.fields;
51
+ this.magic = 0;
52
+ this.version = parseInt(stream.version);
53
+ this.createdAt = parseInt(stream.created);
54
+ this.withdrawnAmount = new BN(stream.withdrawn);
55
+ this.canceledAt = parseInt(stream.canceled_at);
56
+ this.end = parseInt(stream.end);
57
+ this.lastWithdrawnAt = parseInt(stream.last_withdrawn_at);
58
+ this.sender = stream.sender;
59
+ this.senderTokens = stream.sender;
60
+ this.recipient = stream.recipient;
61
+ this.recipientTokens = stream.recipient;
62
+ this.mint = tokenId;
63
+ this.escrowTokens = "";
64
+ this.streamflowTreasury = "";
65
+ this.streamflowTreasuryTokens = "";
66
+ this.streamflowFeeTotal = new BN(0);
67
+ this.streamflowFeeWithdrawn = new BN(0);
68
+ this.streamflowFeePercent = parseInt(fees.streamflow_fee_percentage) / 10000;
69
+ this.partnerFeeTotal = new BN(0);
70
+ this.partnerFeeWithdrawn = new BN(0);
71
+ this.partnerFeePercent = parseInt(fees.partner_fee_percentage) / 10000;
72
+ this.partner = stream.partner;
73
+ this.partnerTokens = "";
74
+ this.start = parseInt(stream.start);
75
+ this.depositedAmount = new BN(stream.amount);
76
+ this.period = parseInt(stream.period);
77
+ this.amountPerPeriod = new BN(stream.amount_per_period);
78
+ this.cliff = parseInt(stream.start);
79
+ this.cliffAmount = new BN(stream.cliff_amount);
80
+ this.cancelableBySender = meta.cancelable_by_sender;
81
+ this.cancelableByRecipient = meta.cancelable_by_recipient;
82
+ this.automaticWithdrawal = meta.automatic_withdrawal;
83
+ this.transferableBySender = meta.transferable_by_sender;
84
+ this.transferableByRecipient = meta.transferable_by_recipient;
85
+ this.canTopup = meta.can_topup;
86
+ this.name = String.fromCharCode(...meta.contract_name);
87
+ this.withdrawalFrequency = parseInt(meta.withdrawal_frequency);
88
+ this.closed = stream.closed;
89
+ this.currentPauseStart = parseInt(stream.current_pause_start);
90
+ this.pauseCumulative = new BN(stream.pause_cumulative);
91
+ this.lastRateChangeTime = parseInt(stream.last_rate_change_time);
92
+ this.fundsUnlockedAtLastRateChange = new BN(stream.funds_unlocked_at_last_rate_change);
93
+ this.type = buildStreamType(this);
94
+ }
95
+ unlocked(currentTimestamp) {
96
+ return calculateUnlockedAmount({
97
+ ...this,
98
+ currentTimestamp,
99
+ });
100
+ }
101
+ remaining(decimals) {
102
+ return getNumberFromBN(this.depositedAmount.sub(this.withdrawnAmount), decimals);
103
+ }
104
+ }
@@ -1,2 +1,2 @@
1
- import { SuiErrorInfo } from "./types";
1
+ import { SuiErrorInfo } from "./types.js";
2
2
  export declare function extractSuiErrorInfo(errorText: string): SuiErrorInfo;
@@ -0,0 +1,23 @@
1
+ import { SUI_ERROR_MATCH_REGEX, SUI_MODULE_ERROR_MAP } from "./constants.js";
2
+ export function extractSuiErrorInfo(errorText) {
3
+ const error = { text: errorText };
4
+ const match = SUI_ERROR_MATCH_REGEX.exec(errorText);
5
+ if (!match) {
6
+ return error;
7
+ }
8
+ const moduleName = match[2];
9
+ const errorCode = Number(match[4]);
10
+ const errorName = SUI_MODULE_ERROR_MAP[moduleName] ? SUI_MODULE_ERROR_MAP[moduleName][errorCode] : undefined;
11
+ const index = Number(match[5]);
12
+ if (index) {
13
+ error.index = index;
14
+ }
15
+ if (errorName) {
16
+ error.parsed = {
17
+ module: moduleName,
18
+ code: errorCode,
19
+ name: errorName,
20
+ };
21
+ }
22
+ return error;
23
+ }
@@ -1,7 +1,7 @@
1
1
  import { Keypair } from "@mysten/sui.js/cryptography";
2
2
  import { WalletContextState } from "@suiet/wallet-kit";
3
3
  import { SuiClient, SuiTransactionBlockResponse } from "@mysten/sui.js/client";
4
- import { SuiSignAndExecuteTransactionBlockInput } from "./types";
4
+ import { SuiSignAndExecuteTransactionBlockInput } from "./types.js";
5
5
  /**
6
6
  * Utility function to check if the transaction initiator is a Wallet object
7
7
  * @param {Keypair | WalletContextState} walletOrKeypair - Wallet or Keypair in question
@@ -0,0 +1,38 @@
1
+ import { Keypair } from "@mysten/sui.js/cryptography";
2
+ /**
3
+ * Utility function to check if the transaction initiator is a Wallet object
4
+ * @param {Keypair | WalletContextState} walletOrKeypair - Wallet or Keypair in question
5
+ * @return {boolean} - Returns true if parameter is a Wallet.
6
+ */
7
+ export function isSignerKeypair(walletOrKeypair) {
8
+ return (walletOrKeypair instanceof Keypair ||
9
+ walletOrKeypair.constructor === Keypair ||
10
+ walletOrKeypair.constructor.name === Keypair.prototype.constructor.name ||
11
+ "export" in walletOrKeypair);
12
+ }
13
+ export class SuiWalletWrapper {
14
+ wallet;
15
+ address;
16
+ client;
17
+ constructor(wallet, client) {
18
+ this.client = client;
19
+ this.wallet = wallet;
20
+ if (isSignerKeypair(wallet)) {
21
+ this.address = wallet.toSuiAddress();
22
+ }
23
+ else {
24
+ this.address = wallet.address;
25
+ }
26
+ }
27
+ async signAndExecuteTransactionBlock(input) {
28
+ if (isSignerKeypair(this.wallet)) {
29
+ return this.client.signAndExecuteTransactionBlock({
30
+ ...input,
31
+ // @ts-ignore
32
+ signer: this.wallet,
33
+ });
34
+ }
35
+ // @ts-ignore
36
+ return this.wallet.signAndExecuteTransactionBlock(input);
37
+ }
38
+ }