@streamflow/stream 7.5.3 → 8.0.0-alpha.p284.726ba98

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 +7202 -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 +3762 -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 +7109 -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 +3706 -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,4 +1,1011 @@
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";
1
+ import { SuiClient } from '@mysten/sui/client';
2
+ import { Transaction } from '@mysten/sui/transactions';
3
+ import { SUI_CLOCK_OBJECT_ID, SUI_TYPE_ARG } from '@mysten/sui/utils';
4
+ import { bcs } from '@mysten/sui/bcs';
5
+ import { ICluster } from '@streamflow/common';
6
+ import BN4 from 'bn.js';
7
+ import { Keypair } from '@mysten/sui/cryptography';
8
+
9
+ var __create = Object.create;
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __getProtoOf = Object.getPrototypeOf;
14
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
15
+ var __commonJS = (cb, mod) => function __require() {
16
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ };
18
+ var __export = (target, all) => {
19
+ for (var name in all)
20
+ __defProp(target, name, { get: all[name], enumerable: true });
21
+ };
22
+ var __copyProps = (to, from, except, desc) => {
23
+ if (from && typeof from === "object" || typeof from === "function") {
24
+ for (let key of __getOwnPropNames(from))
25
+ if (!__hasOwnProp.call(to, key) && key !== except)
26
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
27
+ }
28
+ return to;
29
+ };
30
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
31
+ // If the importer is in node compatibility mode or this is not an ESM
32
+ // file that has been converted to a CommonJS file using a Babel-
33
+ // compatible transform (i.e. "__esModule" has not been set), then set
34
+ // "default" to the CommonJS "module.exports" for node compatibility.
35
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
36
+ mod
37
+ ));
38
+
39
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js
40
+ var require_retry_operation = __commonJS({
41
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports, module) {
42
+ function RetryOperation(timeouts, options) {
43
+ if (typeof options === "boolean") {
44
+ options = { forever: options };
45
+ }
46
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
47
+ this._timeouts = timeouts;
48
+ this._options = options || {};
49
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
50
+ this._fn = null;
51
+ this._errors = [];
52
+ this._attempts = 1;
53
+ this._operationTimeout = null;
54
+ this._operationTimeoutCb = null;
55
+ this._timeout = null;
56
+ this._operationStart = null;
57
+ this._timer = null;
58
+ if (this._options.forever) {
59
+ this._cachedTimeouts = this._timeouts.slice(0);
60
+ }
61
+ }
62
+ module.exports = RetryOperation;
63
+ RetryOperation.prototype.reset = function() {
64
+ this._attempts = 1;
65
+ this._timeouts = this._originalTimeouts.slice(0);
66
+ };
67
+ RetryOperation.prototype.stop = function() {
68
+ if (this._timeout) {
69
+ clearTimeout(this._timeout);
70
+ }
71
+ if (this._timer) {
72
+ clearTimeout(this._timer);
73
+ }
74
+ this._timeouts = [];
75
+ this._cachedTimeouts = null;
76
+ };
77
+ RetryOperation.prototype.retry = function(err) {
78
+ if (this._timeout) {
79
+ clearTimeout(this._timeout);
80
+ }
81
+ if (!err) {
82
+ return false;
83
+ }
84
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
85
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
86
+ this._errors.push(err);
87
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
88
+ return false;
89
+ }
90
+ this._errors.push(err);
91
+ var timeout = this._timeouts.shift();
92
+ if (timeout === void 0) {
93
+ if (this._cachedTimeouts) {
94
+ this._errors.splice(0, this._errors.length - 1);
95
+ timeout = this._cachedTimeouts.slice(-1);
96
+ } else {
97
+ return false;
98
+ }
99
+ }
100
+ var self = this;
101
+ this._timer = setTimeout(function() {
102
+ self._attempts++;
103
+ if (self._operationTimeoutCb) {
104
+ self._timeout = setTimeout(function() {
105
+ self._operationTimeoutCb(self._attempts);
106
+ }, self._operationTimeout);
107
+ if (self._options.unref) {
108
+ self._timeout.unref();
109
+ }
110
+ }
111
+ self._fn(self._attempts);
112
+ }, timeout);
113
+ if (this._options.unref) {
114
+ this._timer.unref();
115
+ }
116
+ return true;
117
+ };
118
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
119
+ this._fn = fn;
120
+ if (timeoutOps) {
121
+ if (timeoutOps.timeout) {
122
+ this._operationTimeout = timeoutOps.timeout;
123
+ }
124
+ if (timeoutOps.cb) {
125
+ this._operationTimeoutCb = timeoutOps.cb;
126
+ }
127
+ }
128
+ var self = this;
129
+ if (this._operationTimeoutCb) {
130
+ this._timeout = setTimeout(function() {
131
+ self._operationTimeoutCb();
132
+ }, self._operationTimeout);
133
+ }
134
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
135
+ this._fn(this._attempts);
136
+ };
137
+ RetryOperation.prototype.try = function(fn) {
138
+ console.log("Using RetryOperation.try() is deprecated");
139
+ this.attempt(fn);
140
+ };
141
+ RetryOperation.prototype.start = function(fn) {
142
+ console.log("Using RetryOperation.start() is deprecated");
143
+ this.attempt(fn);
144
+ };
145
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
146
+ RetryOperation.prototype.errors = function() {
147
+ return this._errors;
148
+ };
149
+ RetryOperation.prototype.attempts = function() {
150
+ return this._attempts;
151
+ };
152
+ RetryOperation.prototype.mainError = function() {
153
+ if (this._errors.length === 0) {
154
+ return null;
155
+ }
156
+ var counts = {};
157
+ var mainError = null;
158
+ var mainErrorCount = 0;
159
+ for (var i = 0; i < this._errors.length; i++) {
160
+ var error = this._errors[i];
161
+ var message = error.message;
162
+ var count = (counts[message] || 0) + 1;
163
+ counts[message] = count;
164
+ if (count >= mainErrorCount) {
165
+ mainError = error;
166
+ mainErrorCount = count;
167
+ }
168
+ }
169
+ return mainError;
170
+ };
171
+ }
172
+ });
173
+
174
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js
175
+ var require_retry = __commonJS({
176
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports) {
177
+ var RetryOperation = require_retry_operation();
178
+ exports.operation = function(options) {
179
+ var timeouts = exports.timeouts(options);
180
+ return new RetryOperation(timeouts, {
181
+ forever: options && (options.forever || options.retries === Infinity),
182
+ unref: options && options.unref,
183
+ maxRetryTime: options && options.maxRetryTime
184
+ });
185
+ };
186
+ exports.timeouts = function(options) {
187
+ if (options instanceof Array) {
188
+ return [].concat(options);
189
+ }
190
+ var opts = {
191
+ retries: 10,
192
+ factor: 2,
193
+ minTimeout: 1 * 1e3,
194
+ maxTimeout: Infinity,
195
+ randomize: false
196
+ };
197
+ for (var key in options) {
198
+ opts[key] = options[key];
199
+ }
200
+ if (opts.minTimeout > opts.maxTimeout) {
201
+ throw new Error("minTimeout is greater than maxTimeout");
202
+ }
203
+ var timeouts = [];
204
+ for (var i = 0; i < opts.retries; i++) {
205
+ timeouts.push(this.createTimeout(i, opts));
206
+ }
207
+ if (options && options.forever && !timeouts.length) {
208
+ timeouts.push(this.createTimeout(i, opts));
209
+ }
210
+ timeouts.sort(function(a, b) {
211
+ return a - b;
212
+ });
213
+ return timeouts;
214
+ };
215
+ exports.createTimeout = function(attempt, opts) {
216
+ var random = opts.randomize ? Math.random() + 1 : 1;
217
+ var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
218
+ timeout = Math.min(timeout, opts.maxTimeout);
219
+ return timeout;
220
+ };
221
+ exports.wrap = function(obj, options, methods) {
222
+ if (options instanceof Array) {
223
+ methods = options;
224
+ options = null;
225
+ }
226
+ if (!methods) {
227
+ methods = [];
228
+ for (var key in obj) {
229
+ if (typeof obj[key] === "function") {
230
+ methods.push(key);
231
+ }
232
+ }
233
+ }
234
+ for (var i = 0; i < methods.length; i++) {
235
+ var method = methods[i];
236
+ var original = obj[method];
237
+ obj[method] = function retryWrapper(original2) {
238
+ var op = exports.operation(options);
239
+ var args = Array.prototype.slice.call(arguments, 1);
240
+ var callback = args.pop();
241
+ args.push(function(err) {
242
+ if (op.retry(err)) {
243
+ return;
244
+ }
245
+ if (err) {
246
+ arguments[0] = op.mainError();
247
+ }
248
+ callback.apply(this, arguments);
249
+ });
250
+ op.attempt(function() {
251
+ original2.apply(obj, args);
252
+ });
253
+ }.bind(obj, original);
254
+ obj[method].options = options;
255
+ }
256
+ };
257
+ }
258
+ });
259
+
260
+ // ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js
261
+ var require_retry2 = __commonJS({
262
+ "../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports, module) {
263
+ module.exports = require_retry();
264
+ }
265
+ });
266
+
267
+ // common/BaseStreamClient.ts
268
+ var BaseStreamClient = class {
269
+ /**
270
+ * Returns total fee percent, streamflow fees + partner fees
271
+ * @param getFeesData structure with address for which we need to derive fee, either sender or partner usually
272
+ * @param chainSpecificParams additional parameters required by chain client
273
+ * @returns fee as floating number, so if fee is 0.99%, it will return 0.99
274
+ */
275
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
276
+ async getTotalFee(getFeesData, chainSpecificParams) {
277
+ const fees = await this.getFees(getFeesData, chainSpecificParams);
278
+ if (fees) {
279
+ return fees.partnerFee + fees.streamflowFee;
280
+ }
281
+ return this.getDefaultStreamflowFee(chainSpecificParams);
282
+ }
283
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
284
+ extractErrorCode(err) {
285
+ return null;
286
+ }
287
+ };
288
+
289
+ // sui/constants.ts
290
+ var constants_exports = {};
291
+ __export(constants_exports, {
292
+ SUI_CONFIG_IDS: () => SUI_CONFIG_IDS,
293
+ SUI_ERROR_MATCH_REGEX: () => SUI_ERROR_MATCH_REGEX,
294
+ SUI_FEE_TABLE_IDS: () => SUI_FEE_TABLE_IDS,
295
+ SUI_MODULE_ERROR_MAP: () => SUI_MODULE_ERROR_MAP,
296
+ SUI_PROGRAM_IDS: () => SUI_PROGRAM_IDS
297
+ });
298
+ var SUI_PROGRAM_IDS = {
299
+ [ICluster.Mainnet]: "0xe456a3a1d4e58e85b4b7175fabe6dae895b983f1379bb8948d6ec2f137b08a7b",
300
+ [ICluster.Devnet]: "0x34dacd839e1758ebb70bdcd4e08f18fbfef5e2b96d9aa7ce2b4a71d96ca0df5a",
301
+ [ICluster.Testnet]: "0x34dacd839e1758ebb70bdcd4e08f18fbfef5e2b96d9aa7ce2b4a71d96ca0df5a",
302
+ [ICluster.Local]: "0x34dacd839e1758ebb70bdcd4e08f18fbfef5e2b96d9aa7ce2b4a71d96ca0df5a"
303
+ };
304
+ var SUI_CONFIG_IDS = {
305
+ [ICluster.Mainnet]: "0x6cf6760b64245b8d23ef57c28ddceb6adbd540a23a509fef29b82237da4ab87b",
306
+ [ICluster.Devnet]: "0xd6c9f5074584f58074ce56e3c5cc436d82258ec3285f186a0d6438a60bacdbf8",
307
+ [ICluster.Testnet]: "0xd6c9f5074584f58074ce56e3c5cc436d82258ec3285f186a0d6438a60bacdbf8",
308
+ [ICluster.Local]: "0xd6c9f5074584f58074ce56e3c5cc436d82258ec3285f186a0d6438a60bacdbf8"
309
+ };
310
+ var SUI_FEE_TABLE_IDS = {
311
+ [ICluster.Mainnet]: "0xad9b75399632583fb9fcae6b5bcca34e6542ab3bedb630ecbd3f15cb1cc48dbe",
312
+ [ICluster.Devnet]: "0x6057b093904c5bdfec1067d2b8a4dc35f65bcab03b3029ad716c4882b0f36078",
313
+ [ICluster.Testnet]: "0x6057b093904c5bdfec1067d2b8a4dc35f65bcab03b3029ad716c4882b0f36078",
314
+ [ICluster.Local]: "0x6057b093904c5bdfec1067d2b8a4dc35f65bcab03b3029ad716c4882b0f36078"
315
+ };
316
+ var 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+)/;
317
+ var SUI_MODULE_ERROR_MAP = {
318
+ protocol: {
319
+ 1: "ECONTRACT_NOT_INIT" /* ECONTRACT_NOT_INIT */,
320
+ 2: "EBAD_AMOUNT" /* EBAD_AMOUNT */,
321
+ 3: "ENO_PERMISSIONS" /* ENO_PERMISSIONS */,
322
+ 4: "EBADINPUT" /* EBADINPUT */,
323
+ 5: "ECLOSED" /* ECLOSED */,
324
+ 6: "EBAD_INPUT_AMOUNT_PER_PERIOD" /* EBAD_INPUT_AMOUNT_PER_PERIOD */,
325
+ 8: "EBAD_INPUT_UPDATE_RATE" /* EBAD_INPUT_UPDATE_RATE */,
326
+ 9: "EBAD_INPUT_CLIFF_AMOUNT" /* EBAD_INPUT_CLIFF_AMOUNT */,
327
+ 10: "EBAD_INPUT_PERIOD" /* EBAD_INPUT_PERIOD */,
328
+ 11: "EBAD_INPUT_START" /* EBAD_INPUT_START */,
329
+ 13: "EBAD_INSUFFICIENT_WITHDRAWAL_FEES" /* EBAD_INSUFFICIENT_WITHDRAWAL_FEES */,
330
+ 14: "EBAD_INSUFFICIENT_AMOUNT" /* EBAD_INSUFFICIENT_AMOUNT */,
331
+ 15: "EPAUSED" /* EPAUSED */,
332
+ 16: "ENOTPAUSED" /* ENOTPAUSED */
333
+ }
334
+ };
335
+ var WITHDRAW_AVAILABLE_AMOUNT = new BN4("18446744073709551615");
336
+
337
+ // common/contractUtils.ts
338
+ var calculateUnlockedAmount = ({
339
+ depositedAmount,
340
+ cliff,
341
+ cliffAmount,
342
+ end,
343
+ currentTimestamp,
344
+ lastRateChangeTime,
345
+ period,
346
+ amountPerPeriod,
347
+ fundsUnlockedAtLastRateChange
348
+ }) => {
349
+ const deposited = depositedAmount;
350
+ if (currentTimestamp < cliff) return new BN4(0);
351
+ if (currentTimestamp > end) return deposited;
352
+ const savedUnlockedFunds = lastRateChangeTime === 0 ? cliffAmount : fundsUnlockedAtLastRateChange;
353
+ const savedUnlockedFundsTime = lastRateChangeTime === 0 ? cliff : lastRateChangeTime;
354
+ const streamed = new BN4(Math.floor((currentTimestamp - savedUnlockedFundsTime) / period)).mul(amountPerPeriod).add(savedUnlockedFunds);
355
+ return streamed.lt(deposited) ? streamed : deposited;
356
+ };
357
+ var isCliffCloseToDepositedAmount = (streamData) => {
358
+ return streamData.cliffAmount.gte(streamData.depositedAmount.sub(new BN4(1)));
359
+ };
360
+ var isVesting = (streamData) => {
361
+ return !streamData.canTopup && !isCliffCloseToDepositedAmount(streamData) && !isDynamicLock(streamData.minPrice, streamData.maxPrice, streamData.minPercentage, streamData.maxPercentage);
362
+ };
363
+ var isDynamicLock = (minPrice, maxPrice, minPercentage, maxPercentage) => {
364
+ return !!minPrice && !!maxPrice && minPrice > 0 && maxPrice - minPrice <= 1 && minPercentage === 0 && maxPercentage === 100;
365
+ };
366
+ var isTokenLock = (streamData) => {
367
+ return !streamData.canTopup && !streamData.automaticWithdrawal && !streamData.cancelableBySender && !streamData.cancelableByRecipient && !streamData.transferableBySender && !streamData.transferableByRecipient && (isCliffCloseToDepositedAmount(streamData) || isDynamicLock(streamData.minPrice, streamData.maxPrice, streamData.minPercentage, streamData.maxPercentage));
368
+ };
369
+ var buildStreamType = (streamData) => {
370
+ if (isVesting(streamData)) {
371
+ return "vesting" /* Vesting */;
372
+ }
373
+ if (isTokenLock(streamData)) {
374
+ return "lock" /* Lock */;
375
+ }
376
+ return "payment" /* Payment */;
377
+ };
378
+ var FEE_PRECISION = 4;
379
+ var FEE_NORMALIZER = 10 ** FEE_PRECISION;
380
+ var FEE_MULTIPLIER = new BN4(10 ** 6);
381
+ var getNumberFromBN = (value, decimals) => value.gt(new BN4(2 ** 53 - 1)) ? value.div(new BN4(10 ** decimals)).toNumber() : value.toNumber() / 10 ** decimals;
382
+ var calculateTotalAmountToDeposit = (depositedAmount, totalFee) => {
383
+ const totalFeeNormalized = new BN4(totalFee * FEE_NORMALIZER);
384
+ return depositedAmount.mul(totalFeeNormalized.add(FEE_MULTIPLIER)).div(FEE_MULTIPLIER);
385
+ };
386
+
387
+ // sui/types.ts
388
+ var Contract = class {
389
+ constructor(stream, tokenId) {
390
+ const meta = stream.meta.fields;
391
+ const fees = stream.fees.fields;
392
+ this.magic = 0;
393
+ this.version = parseInt(stream.version);
394
+ this.createdAt = parseInt(stream.created);
395
+ this.withdrawnAmount = new BN4(stream.withdrawn);
396
+ this.canceledAt = parseInt(stream.canceled_at);
397
+ this.end = parseInt(stream.end);
398
+ this.lastWithdrawnAt = parseInt(stream.last_withdrawn_at);
399
+ this.sender = stream.sender;
400
+ this.senderTokens = stream.sender;
401
+ this.recipient = stream.recipient;
402
+ this.recipientTokens = stream.recipient;
403
+ this.mint = tokenId;
404
+ this.escrowTokens = "";
405
+ this.streamflowTreasury = "";
406
+ this.streamflowTreasuryTokens = "";
407
+ this.streamflowFeeTotal = new BN4(0);
408
+ this.streamflowFeeWithdrawn = new BN4(0);
409
+ this.streamflowFeePercent = parseInt(fees.streamflow_fee_percentage) / 1e4;
410
+ this.partnerFeeTotal = new BN4(0);
411
+ this.partnerFeeWithdrawn = new BN4(0);
412
+ this.partnerFeePercent = parseInt(fees.partner_fee_percentage) / 1e4;
413
+ this.partner = stream.partner;
414
+ this.partnerTokens = "";
415
+ this.start = parseInt(stream.start);
416
+ this.depositedAmount = new BN4(stream.amount);
417
+ this.period = parseInt(stream.period);
418
+ this.amountPerPeriod = new BN4(stream.amount_per_period);
419
+ this.cliff = parseInt(stream.start);
420
+ this.cliffAmount = new BN4(stream.cliff_amount);
421
+ this.cancelableBySender = meta.cancelable_by_sender;
422
+ this.cancelableByRecipient = meta.cancelable_by_recipient;
423
+ this.automaticWithdrawal = meta.automatic_withdrawal;
424
+ this.transferableBySender = meta.transferable_by_sender;
425
+ this.transferableByRecipient = meta.transferable_by_recipient;
426
+ this.canTopup = meta.can_topup;
427
+ this.name = String.fromCharCode(...meta.contract_name);
428
+ this.withdrawalFrequency = parseInt(meta.withdrawal_frequency);
429
+ this.closed = stream.closed;
430
+ this.currentPauseStart = parseInt(stream.current_pause_start);
431
+ this.pauseCumulative = new BN4(stream.pause_cumulative);
432
+ this.lastRateChangeTime = parseInt(stream.last_rate_change_time);
433
+ this.fundsUnlockedAtLastRateChange = new BN4(stream.funds_unlocked_at_last_rate_change);
434
+ this.type = buildStreamType(this);
435
+ }
436
+ unlocked(currentTimestamp) {
437
+ return calculateUnlockedAmount({
438
+ ...this,
439
+ currentTimestamp
440
+ });
441
+ }
442
+ remaining(decimals) {
443
+ return getNumberFromBN(this.depositedAmount.sub(this.withdrawnAmount), decimals);
444
+ }
445
+ };
446
+
447
+ // ../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
448
+ var import_retry = __toESM(require_retry2());
449
+
450
+ // ../../node_modules/.pnpm/is-network-error@1.1.0/node_modules/is-network-error/index.js
451
+ var objectToString = Object.prototype.toString;
452
+ var isError = (value) => objectToString.call(value) === "[object Error]";
453
+ var errorMessages = /* @__PURE__ */ new Set([
454
+ "network error",
455
+ // Chrome
456
+ "Failed to fetch",
457
+ // Chrome
458
+ "NetworkError when attempting to fetch resource.",
459
+ // Firefox
460
+ "The Internet connection appears to be offline.",
461
+ // Safari 16
462
+ "Load failed",
463
+ // Safari 17+
464
+ "Network request failed",
465
+ // `cross-fetch`
466
+ "fetch failed",
467
+ // Undici (Node.js)
468
+ "terminated"
469
+ // Undici (Node.js)
470
+ ]);
471
+ function isNetworkError(error) {
472
+ const isValid = error && isError(error) && error.name === "TypeError" && typeof error.message === "string";
473
+ if (!isValid) {
474
+ return false;
475
+ }
476
+ if (error.message === "Load failed") {
477
+ return error.stack === void 0;
478
+ }
479
+ return errorMessages.has(error.message);
480
+ }
481
+
482
+ // ../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
483
+ var AbortError = class extends Error {
484
+ constructor(message) {
485
+ super();
486
+ if (message instanceof Error) {
487
+ this.originalError = message;
488
+ ({ message } = message);
489
+ } else {
490
+ this.originalError = new Error(message);
491
+ this.originalError.stack = this.stack;
492
+ }
493
+ this.name = "AbortError";
494
+ this.message = message;
495
+ }
496
+ };
497
+ var decorateErrorWithCounts = (error, attemptNumber, options) => {
498
+ const retriesLeft = options.retries - (attemptNumber - 1);
499
+ error.attemptNumber = attemptNumber;
500
+ error.retriesLeft = retriesLeft;
501
+ return error;
502
+ };
503
+ async function pRetry(input, options) {
504
+ return new Promise((resolve, reject) => {
505
+ options = { ...options };
506
+ options.onFailedAttempt ?? (options.onFailedAttempt = () => {
507
+ });
508
+ options.shouldRetry ?? (options.shouldRetry = () => true);
509
+ options.retries ?? (options.retries = 10);
510
+ const operation = import_retry.default.operation(options);
511
+ const abortHandler = () => {
512
+ operation.stop();
513
+ reject(options.signal?.reason);
514
+ };
515
+ if (options.signal && !options.signal.aborted) {
516
+ options.signal.addEventListener("abort", abortHandler, { once: true });
517
+ }
518
+ const cleanUp = () => {
519
+ options.signal?.removeEventListener("abort", abortHandler);
520
+ operation.stop();
521
+ };
522
+ operation.attempt(async (attemptNumber) => {
523
+ try {
524
+ const result = await input(attemptNumber);
525
+ cleanUp();
526
+ resolve(result);
527
+ } catch (error) {
528
+ try {
529
+ if (!(error instanceof Error)) {
530
+ throw new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
531
+ }
532
+ if (error instanceof AbortError) {
533
+ throw error.originalError;
534
+ }
535
+ if (error instanceof TypeError && !isNetworkError(error)) {
536
+ throw error;
537
+ }
538
+ decorateErrorWithCounts(error, attemptNumber, options);
539
+ if (!await options.shouldRetry(error)) {
540
+ operation.stop();
541
+ reject(error);
542
+ }
543
+ await options.onFailedAttempt(error);
544
+ if (!operation.retry(error)) {
545
+ throw operation.mainError();
546
+ }
547
+ } catch (finalError) {
548
+ decorateErrorWithCounts(finalError, attemptNumber, options);
549
+ cleanUp();
550
+ reject(finalError);
551
+ }
552
+ }
553
+ });
554
+ });
555
+ }
556
+
557
+ // sui/utils.ts
558
+ function extractSuiErrorInfo(errorText) {
559
+ const error = { text: errorText };
560
+ const match = SUI_ERROR_MATCH_REGEX.exec(errorText);
561
+ if (!match) {
562
+ return error;
563
+ }
564
+ const moduleName = match[2];
565
+ const errorCode = Number(match[4]);
566
+ const errorName = SUI_MODULE_ERROR_MAP[moduleName] ? SUI_MODULE_ERROR_MAP[moduleName][errorCode] : void 0;
567
+ const index = Number(match[5]);
568
+ if (index) {
569
+ error.index = index;
570
+ }
571
+ if (errorName) {
572
+ error.parsed = {
573
+ module: moduleName,
574
+ code: errorCode,
575
+ name: errorName
576
+ };
577
+ }
578
+ return error;
579
+ }
580
+ function getTransactionBlock(client, input) {
581
+ return pRetry(() => client.getTransactionBlock(input), {
582
+ retries: 5,
583
+ shouldRetry: (error) => error.message.includes("Could not find the referenced transaction"),
584
+ minTimeout: 500,
585
+ maxTimeout: 1e3
586
+ });
587
+ }
588
+ function isSignerKeypair(walletOrKeypair) {
589
+ return walletOrKeypair instanceof Keypair || walletOrKeypair.constructor === Keypair || walletOrKeypair.constructor.name === Keypair.prototype.constructor.name || "getSecretKey" in walletOrKeypair;
590
+ }
591
+ var SuiWalletWrapper = class {
592
+ constructor(wallet, client) {
593
+ this.client = client;
594
+ this.wallet = wallet;
595
+ if (isSignerKeypair(wallet)) {
596
+ this.address = wallet.toSuiAddress();
597
+ } else {
598
+ this.address = wallet.address;
599
+ }
600
+ }
601
+ async signAndExecuteTransaction(input) {
602
+ if (isSignerKeypair(this.wallet)) {
603
+ return this.client.signAndExecuteTransaction({
604
+ ...input,
605
+ // @ts-ignore
606
+ signer: this.wallet
607
+ });
608
+ }
609
+ return this.wallet.signAndExecuteTransaction(input);
610
+ }
611
+ };
612
+
613
+ // sui/StreamClient.ts
614
+ var SuiStreamClient = class extends BaseStreamClient {
615
+ constructor(clusterUrl, cluster = ICluster.Mainnet, ids) {
616
+ super();
617
+ this.programId = ids?.program ? ids.program : SUI_PROGRAM_IDS[cluster];
618
+ this.configId = ids?.config ? ids.config : SUI_CONFIG_IDS[cluster];
619
+ this.feeTableId = ids?.feeTable ? ids.feeTable : SUI_FEE_TABLE_IDS[cluster];
620
+ this.client = new SuiClient({ url: clusterUrl });
621
+ }
622
+ /**
623
+ * Creates a new stream/vesting contract.
624
+ */
625
+ async create(streamData, { senderWallet }) {
626
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
627
+ const totalFee = await this.getTotalFee({
628
+ address: streamData.partner ?? wallet.address
629
+ });
630
+ const [tx] = await this.generateCreateBlock(
631
+ wallet.address,
632
+ {
633
+ ...streamData,
634
+ recipients: [{ ...streamData }]
635
+ },
636
+ totalFee
637
+ );
638
+ const { digest, events } = await wallet.signAndExecuteTransaction({
639
+ transaction: tx,
640
+ options: { showEvents: true }
641
+ });
642
+ return {
643
+ ixs: [],
644
+ txId: digest,
645
+ metadataId: events[0].parsedJson.address
646
+ };
647
+ }
648
+ /**
649
+ * Creates multiple stream/vesting contracts.
650
+ * We don't chain transactions in one Block so that one failed transaction does not revert all others.
651
+ */
652
+ async createMultiple(multipleStreamData, { senderWallet }) {
653
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
654
+ const totalFee = await this.getTotalFee({
655
+ address: multipleStreamData.partner ?? wallet.address
656
+ });
657
+ const [tx, firstIndex] = await this.generateCreateBlock(wallet.address, multipleStreamData, totalFee);
658
+ const txs = [];
659
+ const metadatas = [];
660
+ const metadataToRecipient = {};
661
+ const errors = [];
662
+ try {
663
+ const executedTx = await wallet.signAndExecuteTransaction({
664
+ transaction: tx,
665
+ options: { showEffects: true, showEvents: true }
666
+ });
667
+ const digest = executedTx.digest;
668
+ const { events, effects } = !executedTx.effects || typeof executedTx.effects === "string" ? await getTransactionBlock(this.client, { digest, options: { showEvents: true, showEffects: true } }) : executedTx;
669
+ txs.push(digest);
670
+ if (effects.status.status === "failure") {
671
+ multipleStreamData.recipients.forEach((recipient) => {
672
+ errors.push({
673
+ error: effects.status.error ?? "Unknown error!",
674
+ recipient: recipient.recipient
675
+ });
676
+ });
677
+ } else {
678
+ multipleStreamData.recipients.forEach((recipient, index) => {
679
+ const metadataId = events[index].parsedJson.address;
680
+ metadatas.push(metadataId);
681
+ metadataToRecipient[metadataId] = recipient;
682
+ });
683
+ }
684
+ } catch (e) {
685
+ const errorInfo = extractSuiErrorInfo(e.toString() ?? "Unknown error!");
686
+ multipleStreamData.recipients.forEach((recipient, index) => {
687
+ if (errorInfo.index === void 0 || errorInfo.index < index + firstIndex || errorInfo.index >= multipleStreamData.recipients.length + firstIndex || errorInfo.index === index + firstIndex) {
688
+ errors.push({
689
+ error: errorInfo.text,
690
+ recipient: recipient.recipient,
691
+ contractErrorCode: errorInfo.parsed?.name
692
+ });
693
+ }
694
+ });
695
+ }
696
+ return {
697
+ txs,
698
+ metadatas,
699
+ metadataToRecipient,
700
+ errors
701
+ };
702
+ }
703
+ /**
704
+ * Attempts withdrawing from the specified stream.
705
+ */
706
+ async withdraw({ id, amount = WITHDRAW_AVAILABLE_AMOUNT }, { senderWallet, tokenId }) {
707
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
708
+ const tx = new Transaction();
709
+ tx.moveCall({
710
+ target: `${this.programId}::protocol::withdraw`,
711
+ typeArguments: [tokenId],
712
+ arguments: [
713
+ tx.object(id),
714
+ tx.object(this.configId),
715
+ tx.object(SUI_CLOCK_OBJECT_ID),
716
+ tx.pure.u64(amount.toString())
717
+ ]
718
+ });
719
+ const { digest } = await wallet.signAndExecuteTransaction({
720
+ transaction: tx
721
+ });
722
+ return {
723
+ ixs: [],
724
+ txId: digest
725
+ };
726
+ }
727
+ /**
728
+ * Attempts canceling the specified stream.
729
+ */
730
+ async cancel(cancelData, { senderWallet, tokenId }) {
731
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
732
+ const tx = new Transaction();
733
+ tx.moveCall({
734
+ target: `${this.programId}::protocol::cancel`,
735
+ typeArguments: [tokenId],
736
+ arguments: [tx.object(cancelData.id), tx.object(this.configId), tx.object(SUI_CLOCK_OBJECT_ID)]
737
+ });
738
+ const { digest } = await wallet.signAndExecuteTransaction({
739
+ transaction: tx
740
+ });
741
+ return {
742
+ ixs: [],
743
+ txId: digest
744
+ };
745
+ }
746
+ /**
747
+ * Attempts changing the stream/vesting contract's recipient (effectively transferring the stream/vesting contract).
748
+ */
749
+ async transfer(transferData, { senderWallet, tokenId }) {
750
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
751
+ const tx = new Transaction();
752
+ tx.moveCall({
753
+ target: `${this.programId}::protocol::transfer`,
754
+ typeArguments: [tokenId],
755
+ arguments: [tx.object(transferData.id), tx.pure.address(transferData.newRecipient)]
756
+ });
757
+ const { digest } = await wallet.signAndExecuteTransaction({
758
+ transaction: tx
759
+ });
760
+ return {
761
+ ixs: [],
762
+ txId: digest
763
+ };
764
+ }
765
+ /**
766
+ * Tops up stream account with specified amount.
767
+ */
768
+ async topup(topupData, { senderWallet, tokenId }) {
769
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
770
+ const tx = new Transaction();
771
+ const coins = await this.getAllCoins(wallet.address, tokenId);
772
+ const stream = await this.getOne({ id: topupData.id });
773
+ const totalFee = (stream.partnerFeePercent + stream.streamflowFeePercent) / 100;
774
+ const coinObject = this.splitCoinObjectForAmount(tx, topupData.amount, tokenId, coins, totalFee);
775
+ tx.moveCall({
776
+ target: `${this.programId}::protocol::topup`,
777
+ typeArguments: [tokenId],
778
+ arguments: [
779
+ tx.object(topupData.id),
780
+ tx.object(this.configId),
781
+ coinObject,
782
+ tx.gas,
783
+ tx.pure.u64(topupData.amount.toString())
784
+ ]
785
+ });
786
+ this.returnSplittedCoinObject(tx, tokenId, coins, coinObject);
787
+ const { digest } = await wallet.signAndExecuteTransaction({
788
+ transaction: tx
789
+ });
790
+ return {
791
+ ixs: [],
792
+ txId: digest
793
+ };
794
+ }
795
+ /**
796
+ * Fetch stream data by its id (address).
797
+ */
798
+ async getOne({ id }) {
799
+ const response = await this.client.getObject({
800
+ id,
801
+ options: {
802
+ showContent: true
803
+ }
804
+ });
805
+ if (!response.data) {
806
+ throw new Error(`Contract with id ${id} could not be found!`);
807
+ }
808
+ const content = response.data.content;
809
+ if (content.dataType !== "moveObject") {
810
+ throw new Error(`Not a Move Object!`);
811
+ }
812
+ return new Contract(
813
+ content.fields,
814
+ "0x97e9a9fb1392e9785319f5512d0bfde6ecf7757b09c6de41cec89e798dd361f2::strmt::STRMT"
815
+ );
816
+ }
817
+ async get() {
818
+ throw new Error("Get all method is not supported for Sui chain!");
819
+ }
820
+ /**
821
+ * Attempts updating the stream auto withdrawal params and amount per period
822
+ */
823
+ async update(updateData, { senderWallet, tokenId }) {
824
+ const wallet = new SuiWalletWrapper(senderWallet, this.client);
825
+ const tx = new Transaction();
826
+ tx.moveCall({
827
+ target: `${this.programId}::protocol::update`,
828
+ typeArguments: [tokenId],
829
+ arguments: [
830
+ tx.object(updateData.id),
831
+ tx.object(this.configId),
832
+ tx.object(SUI_CLOCK_OBJECT_ID),
833
+ tx.gas,
834
+ bcs.vector(bcs.bool()).serialize(updateData.enableAutomaticWithdrawal !== void 0 ? [updateData.enableAutomaticWithdrawal] : []),
835
+ bcs.vector(bcs.u64()).serialize(updateData.withdrawFrequency !== void 0 ? [updateData.withdrawFrequency.toString()] : []),
836
+ bcs.vector(bcs.u64()).serialize(updateData.amountPerPeriod !== void 0 ? [updateData.amountPerPeriod.toString()] : [])
837
+ ]
838
+ });
839
+ const { digest } = await wallet.signAndExecuteTransaction({
840
+ transaction: tx
841
+ });
842
+ return {
843
+ ixs: [],
844
+ txId: digest
845
+ };
846
+ }
847
+ extractErrorCode(err) {
848
+ const errorInfo = extractSuiErrorInfo(err.toString() ?? "Unknown error!");
849
+ return errorInfo?.parsed?.name || null;
850
+ }
851
+ async getFees({ address }) {
852
+ const response = await this.client.getObject({
853
+ id: this.feeTableId,
854
+ options: {
855
+ showContent: true
856
+ }
857
+ });
858
+ const content = response.data.content;
859
+ if (content.dataType !== "moveObject") {
860
+ throw new Error(`Not a Move Object!`);
861
+ }
862
+ const fields = content.fields;
863
+ const fieldsResponse = await this.client.getDynamicFields({
864
+ parentId: fields.values.fields.id.id
865
+ });
866
+ const partnerDynamicField = fieldsResponse.data.filter((item) => item.name.value === address)[0];
867
+ if (!partnerDynamicField) {
868
+ return null;
869
+ }
870
+ const valueResponse = await this.client.getObject({
871
+ id: partnerDynamicField.objectId,
872
+ options: {
873
+ showContent: true
874
+ }
875
+ });
876
+ const valueContent = valueResponse.data.content;
877
+ if (valueContent.dataType !== "moveObject") {
878
+ throw new Error(`Not a Move Object!`);
879
+ }
880
+ const valueFields = valueContent.fields.value.fields;
881
+ return {
882
+ streamflowFee: Number(valueFields.streamflow_fee) / 100,
883
+ partnerFee: Number(valueFields.partner_fee) / 100
884
+ };
885
+ }
886
+ async getDefaultStreamflowFee() {
887
+ const response = await this.client.getObject({
888
+ id: this.configId,
889
+ options: {
890
+ showContent: true
891
+ }
892
+ });
893
+ const content = response.data.content;
894
+ if (content.dataType !== "moveObject") {
895
+ throw new Error(`Not a Move Object!`);
896
+ }
897
+ const fields = content.fields;
898
+ return Number(fields.streamflow_fee) / 100;
899
+ }
900
+ /**
901
+ * Returns StreamClient protocol program ID.
902
+ */
903
+ getProgramId() {
904
+ return this.programId;
905
+ }
906
+ /**
907
+ * Utility function to generate Transaction Block to create streams
908
+ */
909
+ async generateCreateBlock(walletAddress, multipleStreamData, totalFee) {
910
+ let coins = await this.getAllCoins(walletAddress, multipleStreamData.tokenId);
911
+ const totalAmount = multipleStreamData.recipients.map((recipiient) => recipiient.amount).reduce((prev, current) => current.add(prev));
912
+ const tx = new Transaction();
913
+ const coinObject = this.splitCoinObjectForAmount(tx, totalAmount, multipleStreamData.tokenId, coins, totalFee);
914
+ coins = [coins[0]];
915
+ let firstIndex = null;
916
+ multipleStreamData.recipients.forEach((recipient) => {
917
+ const result = tx.moveCall({
918
+ target: `${this.programId}::protocol::create`,
919
+ typeArguments: [multipleStreamData.tokenId],
920
+ arguments: [
921
+ tx.object(this.configId),
922
+ tx.object(this.feeTableId),
923
+ tx.object(SUI_CLOCK_OBJECT_ID),
924
+ coinObject,
925
+ tx.gas,
926
+ tx.pure.u64(recipient.amount.toString()),
927
+ tx.pure.u64(multipleStreamData.period),
928
+ tx.pure.u64(recipient.amountPerPeriod.toString()),
929
+ tx.pure.u64(multipleStreamData.start),
930
+ tx.pure.u64(recipient.cliffAmount.toString()),
931
+ tx.pure.bool(multipleStreamData.cancelableBySender),
932
+ tx.pure.bool(multipleStreamData.cancelableByRecipient),
933
+ tx.pure.bool(multipleStreamData.transferableBySender),
934
+ tx.pure.bool(multipleStreamData.transferableByRecipient),
935
+ tx.pure.bool(multipleStreamData.canTopup),
936
+ tx.pure.bool(!!multipleStreamData.canPause),
937
+ tx.pure.bool(!!multipleStreamData.canUpdateRate),
938
+ tx.pure.bool(!!multipleStreamData.automaticWithdrawal),
939
+ tx.pure.u64(multipleStreamData.withdrawalFrequency || 0),
940
+ tx.pure.string(recipient.name),
941
+ tx.pure.address(recipient.recipient),
942
+ tx.pure.address(multipleStreamData.partner || walletAddress)
943
+ ]
944
+ });
945
+ if (result.$kind === "Result" && firstIndex === null) {
946
+ firstIndex = result.Result;
947
+ }
948
+ });
949
+ this.returnSplittedCoinObject(tx, multipleStreamData.tokenId, coins, coinObject);
950
+ return [tx, firstIndex];
951
+ }
952
+ /**
953
+ * Returns all coins owned by a Wallet
954
+ * @param walletAddress wallet address
955
+ * @param coinType coin type
956
+ * @returns Array of Coin Structs
957
+ */
958
+ async getAllCoins(walletAddress, coinType) {
959
+ let coinsResponse = await this.client.getCoins({
960
+ owner: walletAddress,
961
+ coinType
962
+ });
963
+ const coins = coinsResponse.data;
964
+ while (coinsResponse.hasNextPage) {
965
+ coinsResponse = await this.client.getCoins({
966
+ owner: walletAddress,
967
+ coinType,
968
+ cursor: coinsResponse.nextCursor
969
+ });
970
+ coins.push(...coinsResponse.data);
971
+ }
972
+ return coins;
973
+ }
974
+ /**
975
+ * Utility function to split Coin object and use splitted object for stream operations.
976
+ * We do it like thid to mitigate risk of Transaction reverting in case Stream is created for Sui Coin object.
977
+ * This way we can safely pass splitted Sui Coin object in Stream payload and use another object for gas/withdrawal fees.
978
+ * @param tx current transanction block
979
+ * @param amount minimal amount of coins requried
980
+ * @param coinType coin type
981
+ * @param coins array of owned coins of the same type
982
+ * @param totalFee partner and treasury fees
983
+ * @returns Coin Object to use in a Move Call
984
+ */
985
+ splitCoinObjectForAmount(tx, amount, coinType, coins, totalFee) {
986
+ const coinObject = coinType === SUI_TYPE_ARG ? tx.gas : tx.object(coins[0].coinObjectId);
987
+ if (coins.length > 1) {
988
+ tx.mergeCoins(
989
+ coinObject,
990
+ coins.slice(1).map((item) => tx.object(item.coinObjectId))
991
+ );
992
+ }
993
+ const totalAmount = calculateTotalAmountToDeposit(amount, totalFee);
994
+ return tx.splitCoins(coinObject, [tx.pure.u64(totalAmount.toString())])[0];
995
+ }
996
+ /**
997
+ * Return previously splitted Coin Object to owner and merge it to to rebate storage fees
998
+ * @param tx current transaction
999
+ * @param coinType coin type
1000
+ * @param coinObject splitted object
1001
+ * @param coins array of objects used in
1002
+ */
1003
+ returnSplittedCoinObject(tx, coinType, coins, coinObject) {
1004
+ const firstCoinObject = coinType === SUI_TYPE_ARG ? tx.gas : tx.object(coins[0].coinObjectId);
1005
+ tx.mergeCoins(firstCoinObject, [coinObject]);
1006
+ }
1007
+ };
1008
+
1009
+ export { Contract, SuiStreamClient, constants_exports as constants, extractSuiErrorInfo, getTransactionBlock };
1010
+ //# sourceMappingURL=index.js.map
1011
+ //# sourceMappingURL=index.js.map