@streamflow/stream 7.5.2 → 7.5.3-alpha.cffa362.20250508190445

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