@streamflow/stream 10.0.0-alpha.p311.10f340e → 10.0.0-alpha.p313.3ce4d29

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 (42) hide show
  1. package/README.md +8 -64
  2. package/dist/cjs/index.cjs +440 -3794
  3. package/dist/cjs/index.cjs.map +1 -1
  4. package/dist/cjs/index.d.cts +3 -182
  5. package/dist/cjs/solana/index.cjs +393 -309
  6. package/dist/cjs/solana/index.cjs.map +1 -1
  7. package/dist/cjs/solana/index.d.cts +1134 -17
  8. package/dist/esm/index.d.ts +3 -182
  9. package/dist/esm/index.js +258 -3626
  10. package/dist/esm/index.js.map +1 -1
  11. package/dist/esm/solana/index.d.ts +1134 -17
  12. package/dist/esm/solana/index.js +274 -240
  13. package/dist/esm/solana/index.js.map +1 -1
  14. package/package.json +4 -43
  15. package/dist/cjs/BaseStreamClient-Dvs8yWEE.d.cts +0 -550
  16. package/dist/cjs/aptos/index.cjs +0 -450
  17. package/dist/cjs/aptos/index.cjs.map +0 -1
  18. package/dist/cjs/aptos/index.d.cts +0 -14
  19. package/dist/cjs/evm/index.cjs +0 -1909
  20. package/dist/cjs/evm/index.cjs.map +0 -1
  21. package/dist/cjs/evm/index.d.cts +0 -13
  22. package/dist/cjs/index-BHKWsVnx.d.cts +0 -849
  23. package/dist/cjs/index-CGNg22mO.d.cts +0 -203
  24. package/dist/cjs/index-Dk1hKzM3.d.cts +0 -213
  25. package/dist/cjs/index-dSxy_PVV.d.cts +0 -136
  26. package/dist/cjs/sui/index.cjs +0 -1015
  27. package/dist/cjs/sui/index.cjs.map +0 -1
  28. package/dist/cjs/sui/index.d.cts +0 -13
  29. package/dist/esm/BaseStreamClient-Dvs8yWEE.d.ts +0 -550
  30. package/dist/esm/aptos/index.d.ts +0 -14
  31. package/dist/esm/aptos/index.js +0 -437
  32. package/dist/esm/aptos/index.js.map +0 -1
  33. package/dist/esm/evm/index.d.ts +0 -13
  34. package/dist/esm/evm/index.js +0 -1896
  35. package/dist/esm/evm/index.js.map +0 -1
  36. package/dist/esm/index-CRXW7eZy.d.ts +0 -203
  37. package/dist/esm/index-CgDmuCzv.d.ts +0 -849
  38. package/dist/esm/index-DED7TgAo.d.ts +0 -136
  39. package/dist/esm/index-li6QZ_tF.d.ts +0 -213
  40. package/dist/esm/sui/index.d.ts +0 -13
  41. package/dist/esm/sui/index.js +0 -1005
  42. package/dist/esm/sui/index.js.map +0 -1
@@ -1,1005 +0,0 @@
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 isDynamicLock = (minPrice, maxPrice, minPercentage, maxPercentage) => {
361
- return !!minPrice && !!maxPrice && minPrice > 0 && maxPrice - minPrice <= 1 && minPercentage === 0 && maxPercentage === 100;
362
- };
363
- var isTokenLock = (streamData) => {
364
- return !streamData.canTopup && !streamData.automaticWithdrawal && !streamData.cancelableBySender && !streamData.cancelableByRecipient && !streamData.transferableBySender && (isCliffCloseToDepositedAmount(streamData) || isDynamicLock(streamData.minPrice, streamData.maxPrice, streamData.minPercentage, streamData.maxPercentage));
365
- };
366
- var buildStreamType = (streamData) => {
367
- if (isTokenLock(streamData)) {
368
- return "lock" /* Lock */;
369
- }
370
- return "vesting" /* Vesting */;
371
- };
372
- var FEE_PRECISION = 4;
373
- var FEE_NORMALIZER = 10 ** FEE_PRECISION;
374
- var FEE_MULTIPLIER = new BN4(10 ** 6);
375
- var getNumberFromBN = (value, decimals) => value.gt(new BN4(2 ** 53 - 1)) ? value.div(new BN4(10 ** decimals)).toNumber() : value.toNumber() / 10 ** decimals;
376
- var calculateTotalAmountToDeposit = (depositedAmount, totalFee) => {
377
- const totalFeeNormalized = new BN4(totalFee * FEE_NORMALIZER);
378
- return depositedAmount.mul(totalFeeNormalized.add(FEE_MULTIPLIER)).div(FEE_MULTIPLIER);
379
- };
380
-
381
- // sui/types.ts
382
- var Contract = class {
383
- constructor(stream, tokenId) {
384
- const meta = stream.meta.fields;
385
- const fees = stream.fees.fields;
386
- this.magic = 0;
387
- this.version = parseInt(stream.version);
388
- this.createdAt = parseInt(stream.created);
389
- this.withdrawnAmount = new BN4(stream.withdrawn);
390
- this.canceledAt = parseInt(stream.canceled_at);
391
- this.end = parseInt(stream.end);
392
- this.lastWithdrawnAt = parseInt(stream.last_withdrawn_at);
393
- this.sender = stream.sender;
394
- this.senderTokens = stream.sender;
395
- this.recipient = stream.recipient;
396
- this.recipientTokens = stream.recipient;
397
- this.mint = tokenId;
398
- this.escrowTokens = "";
399
- this.streamflowTreasury = "";
400
- this.streamflowTreasuryTokens = "";
401
- this.streamflowFeeTotal = new BN4(0);
402
- this.streamflowFeeWithdrawn = new BN4(0);
403
- this.streamflowFeePercent = parseInt(fees.streamflow_fee_percentage) / 1e4;
404
- this.partnerFeeTotal = new BN4(0);
405
- this.partnerFeeWithdrawn = new BN4(0);
406
- this.partnerFeePercent = parseInt(fees.partner_fee_percentage) / 1e4;
407
- this.partner = stream.partner;
408
- this.partnerTokens = "";
409
- this.start = parseInt(stream.start);
410
- this.depositedAmount = new BN4(stream.amount);
411
- this.period = parseInt(stream.period);
412
- this.amountPerPeriod = new BN4(stream.amount_per_period);
413
- this.cliff = parseInt(stream.start);
414
- this.cliffAmount = new BN4(stream.cliff_amount);
415
- this.cancelableBySender = meta.cancelable_by_sender;
416
- this.cancelableByRecipient = meta.cancelable_by_recipient;
417
- this.automaticWithdrawal = meta.automatic_withdrawal;
418
- this.transferableBySender = meta.transferable_by_sender;
419
- this.transferableByRecipient = meta.transferable_by_recipient;
420
- this.canTopup = meta.can_topup;
421
- this.name = String.fromCharCode(...meta.contract_name);
422
- this.withdrawalFrequency = parseInt(meta.withdrawal_frequency);
423
- this.closed = stream.closed;
424
- this.currentPauseStart = parseInt(stream.current_pause_start);
425
- this.pauseCumulative = new BN4(stream.pause_cumulative);
426
- this.lastRateChangeTime = parseInt(stream.last_rate_change_time);
427
- this.fundsUnlockedAtLastRateChange = new BN4(stream.funds_unlocked_at_last_rate_change);
428
- this.type = buildStreamType(this);
429
- }
430
- unlocked(currentTimestamp) {
431
- return calculateUnlockedAmount({
432
- ...this,
433
- currentTimestamp
434
- });
435
- }
436
- remaining(decimals) {
437
- return getNumberFromBN(this.depositedAmount.sub(this.withdrawnAmount), decimals);
438
- }
439
- };
440
-
441
- // ../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
442
- var import_retry = __toESM(require_retry2());
443
-
444
- // ../../node_modules/.pnpm/is-network-error@1.1.0/node_modules/is-network-error/index.js
445
- var objectToString = Object.prototype.toString;
446
- var isError = (value) => objectToString.call(value) === "[object Error]";
447
- var errorMessages = /* @__PURE__ */ new Set([
448
- "network error",
449
- // Chrome
450
- "Failed to fetch",
451
- // Chrome
452
- "NetworkError when attempting to fetch resource.",
453
- // Firefox
454
- "The Internet connection appears to be offline.",
455
- // Safari 16
456
- "Load failed",
457
- // Safari 17+
458
- "Network request failed",
459
- // `cross-fetch`
460
- "fetch failed",
461
- // Undici (Node.js)
462
- "terminated"
463
- // Undici (Node.js)
464
- ]);
465
- function isNetworkError(error) {
466
- const isValid = error && isError(error) && error.name === "TypeError" && typeof error.message === "string";
467
- if (!isValid) {
468
- return false;
469
- }
470
- if (error.message === "Load failed") {
471
- return error.stack === void 0;
472
- }
473
- return errorMessages.has(error.message);
474
- }
475
-
476
- // ../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
477
- var AbortError = class extends Error {
478
- constructor(message) {
479
- super();
480
- if (message instanceof Error) {
481
- this.originalError = message;
482
- ({ message } = message);
483
- } else {
484
- this.originalError = new Error(message);
485
- this.originalError.stack = this.stack;
486
- }
487
- this.name = "AbortError";
488
- this.message = message;
489
- }
490
- };
491
- var decorateErrorWithCounts = (error, attemptNumber, options) => {
492
- const retriesLeft = options.retries - (attemptNumber - 1);
493
- error.attemptNumber = attemptNumber;
494
- error.retriesLeft = retriesLeft;
495
- return error;
496
- };
497
- async function pRetry(input, options) {
498
- return new Promise((resolve, reject) => {
499
- options = { ...options };
500
- options.onFailedAttempt ?? (options.onFailedAttempt = () => {
501
- });
502
- options.shouldRetry ?? (options.shouldRetry = () => true);
503
- options.retries ?? (options.retries = 10);
504
- const operation = import_retry.default.operation(options);
505
- const abortHandler = () => {
506
- operation.stop();
507
- reject(options.signal?.reason);
508
- };
509
- if (options.signal && !options.signal.aborted) {
510
- options.signal.addEventListener("abort", abortHandler, { once: true });
511
- }
512
- const cleanUp = () => {
513
- options.signal?.removeEventListener("abort", abortHandler);
514
- operation.stop();
515
- };
516
- operation.attempt(async (attemptNumber) => {
517
- try {
518
- const result = await input(attemptNumber);
519
- cleanUp();
520
- resolve(result);
521
- } catch (error) {
522
- try {
523
- if (!(error instanceof Error)) {
524
- throw new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
525
- }
526
- if (error instanceof AbortError) {
527
- throw error.originalError;
528
- }
529
- if (error instanceof TypeError && !isNetworkError(error)) {
530
- throw error;
531
- }
532
- decorateErrorWithCounts(error, attemptNumber, options);
533
- if (!await options.shouldRetry(error)) {
534
- operation.stop();
535
- reject(error);
536
- }
537
- await options.onFailedAttempt(error);
538
- if (!operation.retry(error)) {
539
- throw operation.mainError();
540
- }
541
- } catch (finalError) {
542
- decorateErrorWithCounts(finalError, attemptNumber, options);
543
- cleanUp();
544
- reject(finalError);
545
- }
546
- }
547
- });
548
- });
549
- }
550
-
551
- // sui/utils.ts
552
- function extractSuiErrorInfo(errorText) {
553
- const error = { text: errorText };
554
- const match = SUI_ERROR_MATCH_REGEX.exec(errorText);
555
- if (!match) {
556
- return error;
557
- }
558
- const moduleName = match[2];
559
- const errorCode = Number(match[4]);
560
- const errorName = SUI_MODULE_ERROR_MAP[moduleName] ? SUI_MODULE_ERROR_MAP[moduleName][errorCode] : void 0;
561
- const index = Number(match[5]);
562
- if (index) {
563
- error.index = index;
564
- }
565
- if (errorName) {
566
- error.parsed = {
567
- module: moduleName,
568
- code: errorCode,
569
- name: errorName
570
- };
571
- }
572
- return error;
573
- }
574
- function getTransactionBlock(client, input) {
575
- return pRetry(() => client.getTransactionBlock(input), {
576
- retries: 5,
577
- shouldRetry: (error) => error.message.includes("Could not find the referenced transaction"),
578
- minTimeout: 500,
579
- maxTimeout: 1e3
580
- });
581
- }
582
- function isSignerKeypair(walletOrKeypair) {
583
- return walletOrKeypair instanceof Keypair || walletOrKeypair.constructor === Keypair || walletOrKeypair.constructor.name === Keypair.prototype.constructor.name || "getSecretKey" in walletOrKeypair;
584
- }
585
- var SuiWalletWrapper = class {
586
- constructor(wallet, client) {
587
- this.client = client;
588
- this.wallet = wallet;
589
- if (isSignerKeypair(wallet)) {
590
- this.address = wallet.toSuiAddress();
591
- } else {
592
- this.address = wallet.address;
593
- }
594
- }
595
- async signAndExecuteTransaction(input) {
596
- if (isSignerKeypair(this.wallet)) {
597
- return this.client.signAndExecuteTransaction({
598
- ...input,
599
- // @ts-ignore
600
- signer: this.wallet
601
- });
602
- }
603
- return this.wallet.signAndExecuteTransaction(input);
604
- }
605
- };
606
-
607
- // sui/StreamClient.ts
608
- var SuiStreamClient = class extends BaseStreamClient {
609
- constructor(clusterUrl, cluster = ICluster.Mainnet, ids) {
610
- super();
611
- this.programId = ids?.program ? ids.program : SUI_PROGRAM_IDS[cluster];
612
- this.configId = ids?.config ? ids.config : SUI_CONFIG_IDS[cluster];
613
- this.feeTableId = ids?.feeTable ? ids.feeTable : SUI_FEE_TABLE_IDS[cluster];
614
- this.client = new SuiClient({ url: clusterUrl });
615
- }
616
- /**
617
- * Creates a new stream/vesting contract.
618
- */
619
- async create(streamData, { senderWallet }) {
620
- const wallet = new SuiWalletWrapper(senderWallet, this.client);
621
- const totalFee = await this.getTotalFee({
622
- address: streamData.partner ?? wallet.address
623
- });
624
- const [tx] = await this.generateCreateBlock(
625
- wallet.address,
626
- {
627
- ...streamData,
628
- recipients: [{ ...streamData }]
629
- },
630
- totalFee
631
- );
632
- const { digest, events } = await wallet.signAndExecuteTransaction({
633
- transaction: tx,
634
- options: { showEvents: true }
635
- });
636
- return {
637
- ixs: [],
638
- txId: digest,
639
- metadataId: events[0].parsedJson.address
640
- };
641
- }
642
- /**
643
- * Creates multiple stream/vesting contracts.
644
- * We don't chain transactions in one Block so that one failed transaction does not revert all others.
645
- */
646
- async createMultiple(multipleStreamData, { senderWallet }) {
647
- const wallet = new SuiWalletWrapper(senderWallet, this.client);
648
- const totalFee = await this.getTotalFee({
649
- address: multipleStreamData.partner ?? wallet.address
650
- });
651
- const [tx, firstIndex] = await this.generateCreateBlock(wallet.address, multipleStreamData, totalFee);
652
- const txs = [];
653
- const metadatas = [];
654
- const metadataToRecipient = {};
655
- const errors = [];
656
- try {
657
- const executedTx = await wallet.signAndExecuteTransaction({
658
- transaction: tx,
659
- options: { showEffects: true, showEvents: true }
660
- });
661
- const digest = executedTx.digest;
662
- const { events, effects } = !executedTx.effects || typeof executedTx.effects === "string" ? await getTransactionBlock(this.client, { digest, options: { showEvents: true, showEffects: true } }) : executedTx;
663
- txs.push(digest);
664
- if (effects.status.status === "failure") {
665
- multipleStreamData.recipients.forEach((recipient) => {
666
- errors.push({
667
- error: effects.status.error ?? "Unknown error!",
668
- recipient: recipient.recipient
669
- });
670
- });
671
- } else {
672
- multipleStreamData.recipients.forEach((recipient, index) => {
673
- const metadataId = events[index].parsedJson.address;
674
- metadatas.push(metadataId);
675
- metadataToRecipient[metadataId] = recipient;
676
- });
677
- }
678
- } catch (e) {
679
- const errorInfo = extractSuiErrorInfo(e.toString() ?? "Unknown error!");
680
- multipleStreamData.recipients.forEach((recipient, index) => {
681
- if (errorInfo.index === void 0 || errorInfo.index < index + firstIndex || errorInfo.index >= multipleStreamData.recipients.length + firstIndex || errorInfo.index === index + firstIndex) {
682
- errors.push({
683
- error: errorInfo.text,
684
- recipient: recipient.recipient,
685
- contractErrorCode: errorInfo.parsed?.name
686
- });
687
- }
688
- });
689
- }
690
- return {
691
- txs,
692
- metadatas,
693
- metadataToRecipient,
694
- errors
695
- };
696
- }
697
- /**
698
- * Attempts withdrawing from the specified stream.
699
- */
700
- async withdraw({ id, amount = WITHDRAW_AVAILABLE_AMOUNT }, { senderWallet, tokenId }) {
701
- const wallet = new SuiWalletWrapper(senderWallet, this.client);
702
- const tx = new Transaction();
703
- tx.moveCall({
704
- target: `${this.programId}::protocol::withdraw`,
705
- typeArguments: [tokenId],
706
- arguments: [
707
- tx.object(id),
708
- tx.object(this.configId),
709
- tx.object(SUI_CLOCK_OBJECT_ID),
710
- tx.pure.u64(amount.toString())
711
- ]
712
- });
713
- const { digest } = await wallet.signAndExecuteTransaction({
714
- transaction: tx
715
- });
716
- return {
717
- ixs: [],
718
- txId: digest
719
- };
720
- }
721
- /**
722
- * Attempts canceling the specified stream.
723
- */
724
- async cancel(cancelData, { senderWallet, tokenId }) {
725
- const wallet = new SuiWalletWrapper(senderWallet, this.client);
726
- const tx = new Transaction();
727
- tx.moveCall({
728
- target: `${this.programId}::protocol::cancel`,
729
- typeArguments: [tokenId],
730
- arguments: [tx.object(cancelData.id), tx.object(this.configId), tx.object(SUI_CLOCK_OBJECT_ID)]
731
- });
732
- const { digest } = await wallet.signAndExecuteTransaction({
733
- transaction: tx
734
- });
735
- return {
736
- ixs: [],
737
- txId: digest
738
- };
739
- }
740
- /**
741
- * Attempts changing the stream/vesting contract's recipient (effectively transferring the stream/vesting contract).
742
- */
743
- async transfer(transferData, { senderWallet, tokenId }) {
744
- const wallet = new SuiWalletWrapper(senderWallet, this.client);
745
- const tx = new Transaction();
746
- tx.moveCall({
747
- target: `${this.programId}::protocol::transfer`,
748
- typeArguments: [tokenId],
749
- arguments: [tx.object(transferData.id), tx.pure.address(transferData.newRecipient)]
750
- });
751
- const { digest } = await wallet.signAndExecuteTransaction({
752
- transaction: tx
753
- });
754
- return {
755
- ixs: [],
756
- txId: digest
757
- };
758
- }
759
- /**
760
- * Tops up stream account with specified amount.
761
- */
762
- async topup(topupData, { senderWallet, tokenId }) {
763
- const wallet = new SuiWalletWrapper(senderWallet, this.client);
764
- const tx = new Transaction();
765
- const coins = await this.getAllCoins(wallet.address, tokenId);
766
- const stream = await this.getOne({ id: topupData.id });
767
- const totalFee = (stream.partnerFeePercent + stream.streamflowFeePercent) / 100;
768
- const coinObject = this.splitCoinObjectForAmount(tx, topupData.amount, tokenId, coins, totalFee);
769
- tx.moveCall({
770
- target: `${this.programId}::protocol::topup`,
771
- typeArguments: [tokenId],
772
- arguments: [
773
- tx.object(topupData.id),
774
- tx.object(this.configId),
775
- coinObject,
776
- tx.gas,
777
- tx.pure.u64(topupData.amount.toString())
778
- ]
779
- });
780
- this.returnSplittedCoinObject(tx, tokenId, coins, coinObject);
781
- const { digest } = await wallet.signAndExecuteTransaction({
782
- transaction: tx
783
- });
784
- return {
785
- ixs: [],
786
- txId: digest
787
- };
788
- }
789
- /**
790
- * Fetch stream data by its id (address).
791
- */
792
- async getOne({ id }) {
793
- const response = await this.client.getObject({
794
- id,
795
- options: {
796
- showContent: true
797
- }
798
- });
799
- if (!response.data) {
800
- throw new Error(`Contract with id ${id} could not be found!`);
801
- }
802
- const content = response.data.content;
803
- if (content.dataType !== "moveObject") {
804
- throw new Error(`Not a Move Object!`);
805
- }
806
- return new Contract(
807
- content.fields,
808
- "0x97e9a9fb1392e9785319f5512d0bfde6ecf7757b09c6de41cec89e798dd361f2::strmt::STRMT"
809
- );
810
- }
811
- async get() {
812
- throw new Error("Get all method is not supported for Sui chain!");
813
- }
814
- /**
815
- * Attempts updating the stream auto withdrawal params and amount per period
816
- */
817
- async update(updateData, { senderWallet, tokenId }) {
818
- const wallet = new SuiWalletWrapper(senderWallet, this.client);
819
- const tx = new Transaction();
820
- tx.moveCall({
821
- target: `${this.programId}::protocol::update`,
822
- typeArguments: [tokenId],
823
- arguments: [
824
- tx.object(updateData.id),
825
- tx.object(this.configId),
826
- tx.object(SUI_CLOCK_OBJECT_ID),
827
- tx.gas,
828
- bcs.vector(bcs.bool()).serialize(updateData.enableAutomaticWithdrawal !== void 0 ? [updateData.enableAutomaticWithdrawal] : []),
829
- bcs.vector(bcs.u64()).serialize(updateData.withdrawFrequency !== void 0 ? [updateData.withdrawFrequency.toString()] : []),
830
- bcs.vector(bcs.u64()).serialize(updateData.amountPerPeriod !== void 0 ? [updateData.amountPerPeriod.toString()] : [])
831
- ]
832
- });
833
- const { digest } = await wallet.signAndExecuteTransaction({
834
- transaction: tx
835
- });
836
- return {
837
- ixs: [],
838
- txId: digest
839
- };
840
- }
841
- extractErrorCode(err) {
842
- const errorInfo = extractSuiErrorInfo(err.toString() ?? "Unknown error!");
843
- return errorInfo?.parsed?.name || null;
844
- }
845
- async getFees({ address }) {
846
- const response = await this.client.getObject({
847
- id: this.feeTableId,
848
- options: {
849
- showContent: true
850
- }
851
- });
852
- const content = response.data.content;
853
- if (content.dataType !== "moveObject") {
854
- throw new Error(`Not a Move Object!`);
855
- }
856
- const fields = content.fields;
857
- const fieldsResponse = await this.client.getDynamicFields({
858
- parentId: fields.values.fields.id.id
859
- });
860
- const partnerDynamicField = fieldsResponse.data.filter((item) => item.name.value === address)[0];
861
- if (!partnerDynamicField) {
862
- return null;
863
- }
864
- const valueResponse = await this.client.getObject({
865
- id: partnerDynamicField.objectId,
866
- options: {
867
- showContent: true
868
- }
869
- });
870
- const valueContent = valueResponse.data.content;
871
- if (valueContent.dataType !== "moveObject") {
872
- throw new Error(`Not a Move Object!`);
873
- }
874
- const valueFields = valueContent.fields.value.fields;
875
- return {
876
- streamflowFee: Number(valueFields.streamflow_fee) / 100,
877
- partnerFee: Number(valueFields.partner_fee) / 100
878
- };
879
- }
880
- async getDefaultStreamflowFee() {
881
- const response = await this.client.getObject({
882
- id: this.configId,
883
- options: {
884
- showContent: true
885
- }
886
- });
887
- const content = response.data.content;
888
- if (content.dataType !== "moveObject") {
889
- throw new Error(`Not a Move Object!`);
890
- }
891
- const fields = content.fields;
892
- return Number(fields.streamflow_fee) / 100;
893
- }
894
- /**
895
- * Returns StreamClient protocol program ID.
896
- */
897
- getProgramId() {
898
- return this.programId;
899
- }
900
- /**
901
- * Utility function to generate Transaction Block to create streams
902
- */
903
- async generateCreateBlock(walletAddress, multipleStreamData, totalFee) {
904
- let coins = await this.getAllCoins(walletAddress, multipleStreamData.tokenId);
905
- const totalAmount = multipleStreamData.recipients.map((recipiient) => recipiient.amount).reduce((prev, current) => current.add(prev));
906
- const tx = new Transaction();
907
- const coinObject = this.splitCoinObjectForAmount(tx, totalAmount, multipleStreamData.tokenId, coins, totalFee);
908
- coins = [coins[0]];
909
- let firstIndex = null;
910
- multipleStreamData.recipients.forEach((recipient) => {
911
- const result = tx.moveCall({
912
- target: `${this.programId}::protocol::create`,
913
- typeArguments: [multipleStreamData.tokenId],
914
- arguments: [
915
- tx.object(this.configId),
916
- tx.object(this.feeTableId),
917
- tx.object(SUI_CLOCK_OBJECT_ID),
918
- coinObject,
919
- tx.gas,
920
- tx.pure.u64(recipient.amount.toString()),
921
- tx.pure.u64(multipleStreamData.period),
922
- tx.pure.u64(recipient.amountPerPeriod.toString()),
923
- tx.pure.u64(multipleStreamData.start),
924
- tx.pure.u64(recipient.cliffAmount.toString()),
925
- tx.pure.bool(multipleStreamData.cancelableBySender),
926
- tx.pure.bool(multipleStreamData.cancelableByRecipient),
927
- tx.pure.bool(multipleStreamData.transferableBySender),
928
- tx.pure.bool(multipleStreamData.transferableByRecipient),
929
- tx.pure.bool(multipleStreamData.canTopup),
930
- tx.pure.bool(!!multipleStreamData.canPause),
931
- tx.pure.bool(!!multipleStreamData.canUpdateRate),
932
- tx.pure.bool(!!multipleStreamData.automaticWithdrawal),
933
- tx.pure.u64(multipleStreamData.withdrawalFrequency || 0),
934
- tx.pure.string(recipient.name),
935
- tx.pure.address(recipient.recipient),
936
- tx.pure.address(multipleStreamData.partner || walletAddress)
937
- ]
938
- });
939
- if (result.$kind === "Result" && firstIndex === null) {
940
- firstIndex = result.Result;
941
- }
942
- });
943
- this.returnSplittedCoinObject(tx, multipleStreamData.tokenId, coins, coinObject);
944
- return [tx, firstIndex];
945
- }
946
- /**
947
- * Returns all coins owned by a Wallet
948
- * @param walletAddress wallet address
949
- * @param coinType coin type
950
- * @returns Array of Coin Structs
951
- */
952
- async getAllCoins(walletAddress, coinType) {
953
- let coinsResponse = await this.client.getCoins({
954
- owner: walletAddress,
955
- coinType
956
- });
957
- const coins = coinsResponse.data;
958
- while (coinsResponse.hasNextPage) {
959
- coinsResponse = await this.client.getCoins({
960
- owner: walletAddress,
961
- coinType,
962
- cursor: coinsResponse.nextCursor
963
- });
964
- coins.push(...coinsResponse.data);
965
- }
966
- return coins;
967
- }
968
- /**
969
- * Utility function to split Coin object and use splitted object for stream operations.
970
- * We do it like thid to mitigate risk of Transaction reverting in case Stream is created for Sui Coin object.
971
- * This way we can safely pass splitted Sui Coin object in Stream payload and use another object for gas/withdrawal fees.
972
- * @param tx current transanction block
973
- * @param amount minimal amount of coins requried
974
- * @param coinType coin type
975
- * @param coins array of owned coins of the same type
976
- * @param totalFee partner and treasury fees
977
- * @returns Coin Object to use in a Move Call
978
- */
979
- splitCoinObjectForAmount(tx, amount, coinType, coins, totalFee) {
980
- const coinObject = coinType === SUI_TYPE_ARG ? tx.gas : tx.object(coins[0].coinObjectId);
981
- if (coins.length > 1) {
982
- tx.mergeCoins(
983
- coinObject,
984
- coins.slice(1).map((item) => tx.object(item.coinObjectId))
985
- );
986
- }
987
- const totalAmount = calculateTotalAmountToDeposit(amount, totalFee);
988
- return tx.splitCoins(coinObject, [tx.pure.u64(totalAmount.toString())])[0];
989
- }
990
- /**
991
- * Return previously splitted Coin Object to owner and merge it to to rebate storage fees
992
- * @param tx current transaction
993
- * @param coinType coin type
994
- * @param coinObject splitted object
995
- * @param coins array of objects used in
996
- */
997
- returnSplittedCoinObject(tx, coinType, coins, coinObject) {
998
- const firstCoinObject = coinType === SUI_TYPE_ARG ? tx.gas : tx.object(coins[0].coinObjectId);
999
- tx.mergeCoins(firstCoinObject, [coinObject]);
1000
- }
1001
- };
1002
-
1003
- export { Contract, SuiStreamClient, constants_exports as constants, extractSuiErrorInfo, getTransactionBlock };
1004
- //# sourceMappingURL=index.js.map
1005
- //# sourceMappingURL=index.js.map