@msafe/sui-app-store 0.0.24 → 0.0.26
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.
- package/dist/index.js +1 -2909
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -2880
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -4
- package/dist/index.global.js +0 -46
- package/dist/index.global.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,2910 +1,2 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name in all)
|
|
10
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
-
};
|
|
12
|
-
var __copyProps = (to, from, except, desc) => {
|
|
13
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
-
for (let key of __getOwnPropNames(from))
|
|
15
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
-
}
|
|
18
|
-
return to;
|
|
19
|
-
};
|
|
20
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
-
mod
|
|
27
|
-
));
|
|
28
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
-
|
|
30
|
-
// src/index.ts
|
|
31
|
-
var src_exports = {};
|
|
32
|
-
__export(src_exports, {
|
|
33
|
-
appHelpers: () => appHelpers
|
|
34
|
-
});
|
|
35
|
-
module.exports = __toCommonJS(src_exports);
|
|
36
|
-
|
|
37
|
-
// src/apps/mpay/helper.ts
|
|
38
|
-
var import_sui3_utils = require("@msafe/sui3-utils");
|
|
39
|
-
|
|
40
|
-
// src/apps/msafe-core/intention.ts
|
|
41
|
-
var import_sort_keys_recursive = __toESM(require("sort-keys-recursive"));
|
|
42
|
-
var CoreBaseIntention = class {
|
|
43
|
-
constructor(data) {
|
|
44
|
-
this.data = data;
|
|
45
|
-
}
|
|
46
|
-
get application() {
|
|
47
|
-
return "msafe-core";
|
|
48
|
-
}
|
|
49
|
-
serialize() {
|
|
50
|
-
return JSON.stringify((0, import_sort_keys_recursive.default)(this.data));
|
|
51
|
-
}
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
// src/apps/mpay/config/dev.json
|
|
55
|
-
var dev_exports = {};
|
|
56
|
-
__export(dev_exports, {
|
|
57
|
-
contractId: () => contractId,
|
|
58
|
-
default: () => dev_default,
|
|
59
|
-
feeObjId: () => feeObjId,
|
|
60
|
-
roleObjId: () => roleObjId,
|
|
61
|
-
status: () => status,
|
|
62
|
-
transaction: () => transaction,
|
|
63
|
-
upgradeCapObjId: () => upgradeCapObjId,
|
|
64
|
-
vaultObjId: () => vaultObjId
|
|
65
|
-
});
|
|
66
|
-
var transaction = "DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j";
|
|
67
|
-
var status = "success";
|
|
68
|
-
var contractId = "0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d";
|
|
69
|
-
var roleObjId = "0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a";
|
|
70
|
-
var vaultObjId = "0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d";
|
|
71
|
-
var feeObjId = "0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1";
|
|
72
|
-
var upgradeCapObjId = "0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115";
|
|
73
|
-
var dev_default = {
|
|
74
|
-
transaction,
|
|
75
|
-
status,
|
|
76
|
-
contractId,
|
|
77
|
-
roleObjId,
|
|
78
|
-
vaultObjId,
|
|
79
|
-
feeObjId,
|
|
80
|
-
upgradeCapObjId
|
|
81
|
-
};
|
|
82
|
-
|
|
83
|
-
// src/apps/mpay/config/prod.json
|
|
84
|
-
var prod_exports = {};
|
|
85
|
-
__export(prod_exports, {
|
|
86
|
-
contractId: () => contractId2,
|
|
87
|
-
default: () => prod_default,
|
|
88
|
-
feeObjId: () => feeObjId2,
|
|
89
|
-
roleObjId: () => roleObjId2,
|
|
90
|
-
status: () => status2,
|
|
91
|
-
transaction: () => transaction2,
|
|
92
|
-
upgradeCapObjId: () => upgradeCapObjId2,
|
|
93
|
-
vaultObjId: () => vaultObjId2
|
|
94
|
-
});
|
|
95
|
-
var transaction2 = "855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB";
|
|
96
|
-
var status2 = "success";
|
|
97
|
-
var contractId2 = "0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa";
|
|
98
|
-
var roleObjId2 = "0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1";
|
|
99
|
-
var vaultObjId2 = "0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378";
|
|
100
|
-
var feeObjId2 = "0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94";
|
|
101
|
-
var upgradeCapObjId2 = "0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a";
|
|
102
|
-
var prod_default = {
|
|
103
|
-
transaction: transaction2,
|
|
104
|
-
status: status2,
|
|
105
|
-
contractId: contractId2,
|
|
106
|
-
roleObjId: roleObjId2,
|
|
107
|
-
vaultObjId: vaultObjId2,
|
|
108
|
-
feeObjId: feeObjId2,
|
|
109
|
-
upgradeCapObjId: upgradeCapObjId2
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
// src/apps/mpay/common/env.ts
|
|
113
|
-
var DEV_RPC_ENDPOINT = "https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD";
|
|
114
|
-
var STG_RPC_ENDPOINT = "https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD";
|
|
115
|
-
var PREV_RPC_ENDPOINT = "https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7";
|
|
116
|
-
var PROD_RPC_ENDPOINT = "https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7";
|
|
117
|
-
var DEV_BE_API = "https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod";
|
|
118
|
-
var STG_BE_API = "https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod";
|
|
119
|
-
var PREV_BE_API = "https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod";
|
|
120
|
-
var PROD_BE_API = "https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod";
|
|
121
|
-
var CONTRACT_DEV = dev_exports;
|
|
122
|
-
var CONTRACT_PROD = prod_exports;
|
|
123
|
-
var ENV_CONFIG = /* @__PURE__ */ new Map([
|
|
124
|
-
[
|
|
125
|
-
"dev" /* dev */,
|
|
126
|
-
{
|
|
127
|
-
env: "dev" /* dev */,
|
|
128
|
-
rpc: {
|
|
129
|
-
url: DEV_RPC_ENDPOINT
|
|
130
|
-
},
|
|
131
|
-
backend: {
|
|
132
|
-
url: DEV_BE_API
|
|
133
|
-
},
|
|
134
|
-
contract: CONTRACT_DEV
|
|
135
|
-
}
|
|
136
|
-
],
|
|
137
|
-
[
|
|
138
|
-
"stg" /* stg */,
|
|
139
|
-
{
|
|
140
|
-
env: "stg" /* stg */,
|
|
141
|
-
rpc: {
|
|
142
|
-
url: STG_RPC_ENDPOINT
|
|
143
|
-
},
|
|
144
|
-
backend: {
|
|
145
|
-
url: STG_BE_API
|
|
146
|
-
},
|
|
147
|
-
contract: CONTRACT_DEV
|
|
148
|
-
}
|
|
149
|
-
],
|
|
150
|
-
[
|
|
151
|
-
"prev" /* prev */,
|
|
152
|
-
{
|
|
153
|
-
env: "prev" /* prev */,
|
|
154
|
-
rpc: {
|
|
155
|
-
url: PREV_RPC_ENDPOINT
|
|
156
|
-
},
|
|
157
|
-
backend: {
|
|
158
|
-
url: PREV_BE_API
|
|
159
|
-
},
|
|
160
|
-
contract: CONTRACT_PROD
|
|
161
|
-
}
|
|
162
|
-
],
|
|
163
|
-
[
|
|
164
|
-
"prod" /* prod */,
|
|
165
|
-
{
|
|
166
|
-
env: "prod" /* prod */,
|
|
167
|
-
rpc: {
|
|
168
|
-
url: PROD_RPC_ENDPOINT
|
|
169
|
-
},
|
|
170
|
-
backend: {
|
|
171
|
-
url: PROD_BE_API
|
|
172
|
-
},
|
|
173
|
-
contract: CONTRACT_PROD
|
|
174
|
-
}
|
|
175
|
-
]
|
|
176
|
-
]);
|
|
177
|
-
function getConfig(env, options) {
|
|
178
|
-
const ec = ENV_CONFIG.get(env);
|
|
179
|
-
if (!ec) {
|
|
180
|
-
throw new Error(`Env not supported: ${env}`);
|
|
181
|
-
}
|
|
182
|
-
if (options && options.rpc) {
|
|
183
|
-
ec.rpc = options.rpc;
|
|
184
|
-
}
|
|
185
|
-
if (options && options.backend) {
|
|
186
|
-
ec.backend = options.backend;
|
|
187
|
-
}
|
|
188
|
-
if (options && options.contract) {
|
|
189
|
-
ec.contract = options.contract;
|
|
190
|
-
}
|
|
191
|
-
return ec;
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
// src/apps/mpay/common/globals.ts
|
|
195
|
-
var import_client = require("@mysten/sui.js/client");
|
|
196
|
-
|
|
197
|
-
// src/apps/mpay/error/base.ts
|
|
198
|
-
var MPayError = class extends Error {
|
|
199
|
-
mpayErrorCode;
|
|
200
|
-
context;
|
|
201
|
-
constructor(mpayErrorCode, msg, options = {}) {
|
|
202
|
-
const { cause, context } = options;
|
|
203
|
-
if (cause) {
|
|
204
|
-
super(`[MPay] ${msg}: ${cause}`);
|
|
205
|
-
} else {
|
|
206
|
-
super(`[MPay] ${msg}`);
|
|
207
|
-
}
|
|
208
|
-
this.mpayErrorCode = mpayErrorCode;
|
|
209
|
-
this.context = context;
|
|
210
|
-
}
|
|
211
|
-
};
|
|
212
|
-
|
|
213
|
-
// src/apps/mpay/error/NoBackendError.ts
|
|
214
|
-
var NoBackendError = class extends MPayError {
|
|
215
|
-
constructor() {
|
|
216
|
-
super(11 /* NoBackend */, "Backend is not specified");
|
|
217
|
-
}
|
|
218
|
-
};
|
|
219
|
-
|
|
220
|
-
// src/apps/mpay/error/WalletNotConnectedError.ts
|
|
221
|
-
var WalletNotConnectedError = class extends MPayError {
|
|
222
|
-
constructor() {
|
|
223
|
-
super(1 /* walletNotConnected */, "Wallet not connected");
|
|
224
|
-
}
|
|
225
|
-
};
|
|
226
|
-
|
|
227
|
-
// src/apps/mpay/stream/backend.ts
|
|
228
|
-
var import_axios = __toESM(require("axios"));
|
|
229
|
-
|
|
230
|
-
// src/apps/mpay/error/BackendError.ts
|
|
231
|
-
var BackendError = class extends MPayError {
|
|
232
|
-
constructor(msg, context) {
|
|
233
|
-
super(10 /* BackendError */, msg, { context });
|
|
234
|
-
}
|
|
235
|
-
};
|
|
236
|
-
|
|
237
|
-
// src/apps/mpay/stream/backend.ts
|
|
238
|
-
var Backend = class _Backend {
|
|
239
|
-
constructor(apiURL) {
|
|
240
|
-
this.apiURL = apiURL;
|
|
241
|
-
}
|
|
242
|
-
static parseResponseData(response) {
|
|
243
|
-
if (response instanceof import_axios.AxiosError) {
|
|
244
|
-
throw new BackendError(response.response?.statusText);
|
|
245
|
-
}
|
|
246
|
-
if (response.status === 200) {
|
|
247
|
-
if (response.data.success) {
|
|
248
|
-
return response.data.data;
|
|
249
|
-
}
|
|
250
|
-
throw new BackendError(response.data.code);
|
|
251
|
-
}
|
|
252
|
-
throw new BackendError(response.status.toString());
|
|
253
|
-
}
|
|
254
|
-
async getIncomingStreams(recipient, options) {
|
|
255
|
-
const res = await import_axios.default.post(`${this.apiURL}/stream`, {
|
|
256
|
-
recipient,
|
|
257
|
-
...options
|
|
258
|
-
});
|
|
259
|
-
return _Backend.parseResponseData(res);
|
|
260
|
-
}
|
|
261
|
-
async getOutgoingStreams(sender, options) {
|
|
262
|
-
const res = await import_axios.default.post(`${this.apiURL}/stream`, {
|
|
263
|
-
sender,
|
|
264
|
-
...options
|
|
265
|
-
});
|
|
266
|
-
return _Backend.parseResponseData(res);
|
|
267
|
-
}
|
|
268
|
-
async getStreamHistory(query) {
|
|
269
|
-
const res = await import_axios.default.post(`${this.apiURL}/stream-events`, query);
|
|
270
|
-
const paginatedData = _Backend.parseResponseData(res);
|
|
271
|
-
paginatedData.data.forEach((event) => {
|
|
272
|
-
const formalizedEvent = event;
|
|
273
|
-
if (formalizedEvent.data.type === "create_stream") {
|
|
274
|
-
formalizedEvent.data.balance = BigInt(formalizedEvent.data.balance);
|
|
275
|
-
} else if (formalizedEvent.data.type === "cancel_stream") {
|
|
276
|
-
formalizedEvent.data.withdrawAmount = BigInt(formalizedEvent.data.withdrawAmount);
|
|
277
|
-
} else if (formalizedEvent.data.type === "claim" || formalizedEvent.data.type === "auto_claim") {
|
|
278
|
-
formalizedEvent.data.claimAmount = BigInt(formalizedEvent.data.claimAmount);
|
|
279
|
-
} else if (formalizedEvent.data.type === "set_auto_claim") {
|
|
280
|
-
formalizedEvent.data.enabled = !!formalizedEvent.data.enabled;
|
|
281
|
-
}
|
|
282
|
-
formalizedEvent.createdAt = new Date(formalizedEvent.createdAt);
|
|
283
|
-
return formalizedEvent;
|
|
284
|
-
});
|
|
285
|
-
return paginatedData;
|
|
286
|
-
}
|
|
287
|
-
async getAllCoinTypes(address) {
|
|
288
|
-
const res = await import_axios.default.post(`${this.apiURL}/stream-info`, { address });
|
|
289
|
-
return _Backend.parseResponseData(res);
|
|
290
|
-
}
|
|
291
|
-
async getAllRecipients(sender, options) {
|
|
292
|
-
const res = await import_axios.default.post(`${this.apiURL}/stream-info`, { sender, status: options });
|
|
293
|
-
return _Backend.parseResponseData(res);
|
|
294
|
-
}
|
|
295
|
-
async getAllSenders(recipient, options) {
|
|
296
|
-
const res = await import_axios.default.post(`${this.apiURL}/stream-info`, { recipient, status: options });
|
|
297
|
-
return _Backend.parseResponseData(res);
|
|
298
|
-
}
|
|
299
|
-
};
|
|
300
|
-
|
|
301
|
-
// src/apps/mpay/common/globals.ts
|
|
302
|
-
var Globals = class _Globals {
|
|
303
|
-
signer;
|
|
304
|
-
suiClient;
|
|
305
|
-
envConfig;
|
|
306
|
-
_backend;
|
|
307
|
-
constructor(envConfig) {
|
|
308
|
-
this.envConfig = envConfig;
|
|
309
|
-
this.suiClient = new import_client.SuiClient({ url: envConfig.rpc.url });
|
|
310
|
-
if (envConfig.backend) {
|
|
311
|
-
this._backend = new Backend(envConfig.backend.url);
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
static new(env, options) {
|
|
315
|
-
const ec = getConfig(env, options);
|
|
316
|
-
return new _Globals(ec);
|
|
317
|
-
}
|
|
318
|
-
get walletType() {
|
|
319
|
-
if (!this.wallet) {
|
|
320
|
-
return "disconnected";
|
|
321
|
-
}
|
|
322
|
-
return this.wallet.type;
|
|
323
|
-
}
|
|
324
|
-
get backend() {
|
|
325
|
-
if (!this._backend) {
|
|
326
|
-
throw new NoBackendError();
|
|
327
|
-
}
|
|
328
|
-
return this._backend;
|
|
329
|
-
}
|
|
330
|
-
// Used for test cases
|
|
331
|
-
set backend(b) {
|
|
332
|
-
this._backend = b;
|
|
333
|
-
}
|
|
334
|
-
connectWallet(wallet) {
|
|
335
|
-
this.signer = wallet;
|
|
336
|
-
}
|
|
337
|
-
disconnect() {
|
|
338
|
-
this.signer = void 0;
|
|
339
|
-
}
|
|
340
|
-
get wallet() {
|
|
341
|
-
if (!this.signer) {
|
|
342
|
-
throw new WalletNotConnectedError();
|
|
343
|
-
}
|
|
344
|
-
return this.signer;
|
|
345
|
-
}
|
|
346
|
-
async walletAddress() {
|
|
347
|
-
return this.wallet.address();
|
|
348
|
-
}
|
|
349
|
-
};
|
|
350
|
-
|
|
351
|
-
// src/apps/mpay/stream/client.ts
|
|
352
|
-
var import_utils9 = require("@mysten/sui.js/utils");
|
|
353
|
-
|
|
354
|
-
// src/apps/mpay/stream/helper.ts
|
|
355
|
-
var import_utils5 = require("@mysten/sui.js/utils");
|
|
356
|
-
var import_luxon = require("luxon");
|
|
357
|
-
|
|
358
|
-
// src/apps/mpay/builder/MPayBuilder.ts
|
|
359
|
-
var import_transactions3 = require("@mysten/sui.js/transactions");
|
|
360
|
-
|
|
361
|
-
// src/apps/mpay/builder/CreateStreamHelper.ts
|
|
362
|
-
var import_transactions = require("@mysten/sui.js/transactions");
|
|
363
|
-
var import_utils3 = require("@mysten/sui.js/utils");
|
|
364
|
-
|
|
365
|
-
// src/apps/mpay/builder/const.ts
|
|
366
|
-
var FEE_NUMERATOR = 50n;
|
|
367
|
-
var FEE_DENOMINATOR = 10000n;
|
|
368
|
-
var CLAIM_FEE_NUMERATOR = 25n;
|
|
369
|
-
var FLAT_FEE_SUI = 100000000n;
|
|
370
|
-
|
|
371
|
-
// src/apps/mpay/common/transaction.ts
|
|
372
|
-
var MoveObject = class {
|
|
373
|
-
constructor(object) {
|
|
374
|
-
this.object = object;
|
|
375
|
-
}
|
|
376
|
-
moveArg(txb) {
|
|
377
|
-
return txb.object(this.object);
|
|
378
|
-
}
|
|
379
|
-
};
|
|
380
|
-
var ObjectVector = class {
|
|
381
|
-
constructor(objects) {
|
|
382
|
-
this.objects = objects;
|
|
383
|
-
}
|
|
384
|
-
moveArgs(txb) {
|
|
385
|
-
return txb.makeMoveVec({ objects: this.objects.map((o) => txb.object(o)) });
|
|
386
|
-
}
|
|
387
|
-
};
|
|
388
|
-
var ResultRef = class _ResultRef {
|
|
389
|
-
constructor(result) {
|
|
390
|
-
this.result = result;
|
|
391
|
-
return new Proxy(this, {
|
|
392
|
-
set() {
|
|
393
|
-
throw new Error("The transaction result is a proxy, and does not support setting properties directly");
|
|
394
|
-
},
|
|
395
|
-
get(target, property) {
|
|
396
|
-
if (property in target) {
|
|
397
|
-
return Reflect.get(target, property);
|
|
398
|
-
}
|
|
399
|
-
const nestedResultFor = (resultIndex2) => new _ResultRef(target.result[resultIndex2]);
|
|
400
|
-
if (property === Symbol.iterator) {
|
|
401
|
-
return function* () {
|
|
402
|
-
let i = 0;
|
|
403
|
-
while (true) {
|
|
404
|
-
yield nestedResultFor(i);
|
|
405
|
-
i++;
|
|
406
|
-
}
|
|
407
|
-
};
|
|
408
|
-
}
|
|
409
|
-
if (typeof property === "symbol") {
|
|
410
|
-
return;
|
|
411
|
-
}
|
|
412
|
-
const resultIndex = parseInt(property, 10);
|
|
413
|
-
if (Number.isNaN(resultIndex) || resultIndex < 0) {
|
|
414
|
-
return;
|
|
415
|
-
}
|
|
416
|
-
return nestedResultFor(resultIndex);
|
|
417
|
-
}
|
|
418
|
-
});
|
|
419
|
-
}
|
|
420
|
-
moveArg() {
|
|
421
|
-
return this.result;
|
|
422
|
-
}
|
|
423
|
-
};
|
|
424
|
-
|
|
425
|
-
// src/apps/mpay/contract/InspectViewer.ts
|
|
426
|
-
var import_buffer = require("buffer");
|
|
427
|
-
var import_utils = require("@mysten/sui.js/utils");
|
|
428
|
-
|
|
429
|
-
// src/apps/mpay/error/InvalidRpcResultError.ts
|
|
430
|
-
var InvalidRpcResultError = class extends MPayError {
|
|
431
|
-
constructor(msg, ctx) {
|
|
432
|
-
super(3 /* InvalidRpcResult */, msg, { context: ctx });
|
|
433
|
-
}
|
|
434
|
-
};
|
|
435
|
-
|
|
436
|
-
// src/apps/mpay/contract/InspectViewer.ts
|
|
437
|
-
var InspectViewer = class {
|
|
438
|
-
constructor(results) {
|
|
439
|
-
this.results = results;
|
|
440
|
-
}
|
|
441
|
-
callResult(index) {
|
|
442
|
-
return this.results.results[index];
|
|
443
|
-
}
|
|
444
|
-
returnValue(returned, index) {
|
|
445
|
-
return returned.returnValues[index];
|
|
446
|
-
}
|
|
447
|
-
getValue(callIndex = 0, returnIndex = 0) {
|
|
448
|
-
const callResult = this.callResult(callIndex);
|
|
449
|
-
return this.returnValue(callResult, returnIndex);
|
|
450
|
-
}
|
|
451
|
-
getAddress(callIndex = 0, returnIndex = 0) {
|
|
452
|
-
const [value, type] = this.getValue(callIndex, returnIndex);
|
|
453
|
-
if (type !== "address") {
|
|
454
|
-
throw new InvalidRpcResultError("Invalid contract return type.", {
|
|
455
|
-
ctx: {
|
|
456
|
-
expectType: "address",
|
|
457
|
-
gotType: type
|
|
458
|
-
}
|
|
459
|
-
});
|
|
460
|
-
}
|
|
461
|
-
return (0, import_utils.normalizeSuiAddress)(import_buffer.Buffer.from(value).toString("hex"));
|
|
462
|
-
}
|
|
463
|
-
getU64(callIndex = 0, returnIndex = 0) {
|
|
464
|
-
const [value, type] = this.getValue(callIndex, returnIndex);
|
|
465
|
-
if (type !== "u64") {
|
|
466
|
-
throw new InvalidRpcResultError("Invalid contract return type.", {
|
|
467
|
-
ctx: {
|
|
468
|
-
expectType: "u64",
|
|
469
|
-
gotType: type
|
|
470
|
-
}
|
|
471
|
-
});
|
|
472
|
-
}
|
|
473
|
-
return import_buffer.Buffer.from(value).readBigInt64LE();
|
|
474
|
-
}
|
|
475
|
-
};
|
|
476
|
-
|
|
477
|
-
// src/apps/mpay/stream/metadata.ts
|
|
478
|
-
var import_bcs = require("@mysten/sui.js/bcs");
|
|
479
|
-
|
|
480
|
-
// src/apps/mpay/error/InvalidInputError.ts
|
|
481
|
-
var InvalidInputError = class extends MPayError {
|
|
482
|
-
constructor(msg, fieldKey, fieldValue) {
|
|
483
|
-
super(2 /* InvalidInput */, `Invalid input: ${msg}`, {
|
|
484
|
-
context: {
|
|
485
|
-
fieldKey,
|
|
486
|
-
fieldValue
|
|
487
|
-
}
|
|
488
|
-
});
|
|
489
|
-
}
|
|
490
|
-
};
|
|
491
|
-
|
|
492
|
-
// src/apps/mpay/stream/metadata.ts
|
|
493
|
-
var metadataBcsType = {
|
|
494
|
-
groupId: "string",
|
|
495
|
-
name: "string"
|
|
496
|
-
};
|
|
497
|
-
var MAX_NAME_SIZE = 64;
|
|
498
|
-
function encodeMetadata(metadata) {
|
|
499
|
-
validateMetadata(metadata);
|
|
500
|
-
return import_bcs.bcs.ser(metadataBcsType, metadata).toString("base64");
|
|
501
|
-
}
|
|
502
|
-
function decodeMetadata(metaStr) {
|
|
503
|
-
const metadata = import_bcs.bcs.de(metadataBcsType, metaStr, "base64");
|
|
504
|
-
validateMetadata(metadata);
|
|
505
|
-
return metadata;
|
|
506
|
-
}
|
|
507
|
-
function validateMetadata(metadata) {
|
|
508
|
-
if (!isAsciiString(metadata.name)) {
|
|
509
|
-
throw new InvalidInputError("Invalid metadata: Name contains unknown character");
|
|
510
|
-
}
|
|
511
|
-
if (!isAsciiString(metadata.groupId)) {
|
|
512
|
-
throw new InvalidInputError("Invalid metadata: Group ID contains unknown character");
|
|
513
|
-
}
|
|
514
|
-
if (metadata.name.length > MAX_NAME_SIZE) {
|
|
515
|
-
throw new InvalidInputError("Invalid metadata: Name exceed max length 64");
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
function isAsciiString(str) {
|
|
519
|
-
const asciiPattern = /^[\x00-\x7F]+$/;
|
|
520
|
-
return asciiPattern.test(str);
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
// src/apps/mpay/sui/utils.ts
|
|
524
|
-
var import_utils2 = require("@mysten/sui.js/utils");
|
|
525
|
-
function isSameCoinType(type1, type2) {
|
|
526
|
-
return (0, import_utils2.normalizeStructTag)(type1) === (0, import_utils2.normalizeStructTag)(type2);
|
|
527
|
-
}
|
|
528
|
-
function isSameTarget(target1, target2) {
|
|
529
|
-
return (0, import_utils2.normalizeStructTag)(target1) === (0, import_utils2.normalizeStructTag)(target2);
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
// src/apps/mpay/types/wallet.ts
|
|
533
|
-
var GAS_OBJECT_SPEC = "txn.gas";
|
|
534
|
-
|
|
535
|
-
// src/apps/mpay/utils/random.ts
|
|
536
|
-
var import_buffer2 = require("buffer");
|
|
537
|
-
var import_nanoid = require("nanoid");
|
|
538
|
-
if (typeof window !== "undefined") {
|
|
539
|
-
window.global = window.global ?? window;
|
|
540
|
-
window.Buffer = window.Buffer ?? import_buffer2.Buffer;
|
|
541
|
-
}
|
|
542
|
-
function generateGroupId() {
|
|
543
|
-
return (0, import_nanoid.nanoid)();
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
// src/apps/mpay/builder/CreateStreamHelper.ts
|
|
547
|
-
var CreateStreamHelper = class _CreateStreamHelper {
|
|
548
|
-
constructor(globals, feeContract, streamContract) {
|
|
549
|
-
this.globals = globals;
|
|
550
|
-
this.feeContract = feeContract;
|
|
551
|
-
this.streamContract = streamContract;
|
|
552
|
-
}
|
|
553
|
-
static convertCreateStreamInfoToInternal(info) {
|
|
554
|
-
return {
|
|
555
|
-
metadata: encodeMetadata({
|
|
556
|
-
name: info.name,
|
|
557
|
-
groupId: generateGroupId()
|
|
558
|
-
}),
|
|
559
|
-
coinType: (0, import_utils3.normalizeStructTag)(info.coinType),
|
|
560
|
-
recipients: info.recipients.map((recipient) => ({
|
|
561
|
-
address: recipient.address,
|
|
562
|
-
cliffAmount: recipient.cliffAmount,
|
|
563
|
-
amountPerEpoch: recipient.amountPerStep
|
|
564
|
-
})),
|
|
565
|
-
epochInterval: info.interval,
|
|
566
|
-
numberEpoch: info.steps,
|
|
567
|
-
startTime: info.startTimeMs,
|
|
568
|
-
cancelable: info.cancelable
|
|
569
|
-
};
|
|
570
|
-
}
|
|
571
|
-
async buildCreateStreamTransactionBlock(info) {
|
|
572
|
-
const txb = new import_transactions.TransactionBlock();
|
|
573
|
-
const paymentWithFee = this.calculateFeesInternal(info);
|
|
574
|
-
const coinReqs = this.getCreateStreamCoinRequests(info, paymentWithFee);
|
|
575
|
-
const coinResp = await this.wallet.requestCoins(coinReqs);
|
|
576
|
-
const paymentMergedObject = await this.addMergeCoins(txb, coinResp[0]);
|
|
577
|
-
let flatFeeMergedObject;
|
|
578
|
-
if (coinReqs.length > 1) {
|
|
579
|
-
flatFeeMergedObject = await this.addMergeCoins(txb, coinResp[1]);
|
|
580
|
-
} else {
|
|
581
|
-
flatFeeMergedObject = paymentMergedObject;
|
|
582
|
-
}
|
|
583
|
-
for (let i = 0; i < info.recipients.length; i++) {
|
|
584
|
-
const recipient = info.recipients[i];
|
|
585
|
-
const paymentAmount = this.amountForRecipient(recipient, info.numberEpoch);
|
|
586
|
-
const feeAmount = this.getStreamFeeLocal(paymentAmount);
|
|
587
|
-
const [paymentCoin] = txb.splitCoins(paymentMergedObject, [txb.pure(paymentAmount + feeAmount, "u64")]);
|
|
588
|
-
const [flatFeeCoin] = txb.splitCoins(flatFeeMergedObject, [txb.pure(this.flatSuiFee, "u64")]);
|
|
589
|
-
this.streamContract.createStream(txb, {
|
|
590
|
-
paymentCoin: new ResultRef(paymentCoin),
|
|
591
|
-
flatFeeCoin: new ResultRef(flatFeeCoin),
|
|
592
|
-
metadata: info.metadata,
|
|
593
|
-
recipient: recipient.address,
|
|
594
|
-
timeStart: info.startTime,
|
|
595
|
-
cliff: recipient.cliffAmount,
|
|
596
|
-
epochInterval: info.epochInterval,
|
|
597
|
-
numEpoch: info.numberEpoch,
|
|
598
|
-
amountPerEpoch: recipient.amountPerEpoch,
|
|
599
|
-
cancelable: info.cancelable,
|
|
600
|
-
coinType: info.coinType
|
|
601
|
-
});
|
|
602
|
-
}
|
|
603
|
-
return txb;
|
|
604
|
-
}
|
|
605
|
-
calculateCreateStreamFees(createInfo) {
|
|
606
|
-
const infoInternal = _CreateStreamHelper.convertCreateStreamInfoToInternal(createInfo);
|
|
607
|
-
return this.calculateFeesInternal(infoInternal);
|
|
608
|
-
}
|
|
609
|
-
feeParams() {
|
|
610
|
-
return {
|
|
611
|
-
createFeePercent: {
|
|
612
|
-
numerator: FEE_NUMERATOR,
|
|
613
|
-
denominator: FEE_DENOMINATOR
|
|
614
|
-
},
|
|
615
|
-
claimFeePercent: {
|
|
616
|
-
numerator: CLAIM_FEE_NUMERATOR,
|
|
617
|
-
denominator: FEE_DENOMINATOR
|
|
618
|
-
},
|
|
619
|
-
flatFeePerStream: FLAT_FEE_SUI
|
|
620
|
-
};
|
|
621
|
-
}
|
|
622
|
-
async addMergeCoins(txb, coins) {
|
|
623
|
-
let mergedCoin;
|
|
624
|
-
if (coins.mergedCoins && coins.mergedCoins.length) {
|
|
625
|
-
txb.mergeCoins(
|
|
626
|
-
txb.object(coins.primaryCoin),
|
|
627
|
-
coins.mergedCoins.map((coinId) => txb.object(coinId))
|
|
628
|
-
);
|
|
629
|
-
mergedCoin = txb.object(coins.primaryCoin);
|
|
630
|
-
} else if (coins.primaryCoin === GAS_OBJECT_SPEC) {
|
|
631
|
-
mergedCoin = txb.gas;
|
|
632
|
-
} else {
|
|
633
|
-
mergedCoin = txb.object(coins.primaryCoin);
|
|
634
|
-
}
|
|
635
|
-
return mergedCoin;
|
|
636
|
-
}
|
|
637
|
-
getCreateStreamCoinRequests(info, payment) {
|
|
638
|
-
const streamCoinType = info.coinType;
|
|
639
|
-
if (isSameCoinType(streamCoinType, import_utils3.SUI_TYPE_ARG)) {
|
|
640
|
-
return [
|
|
641
|
-
{
|
|
642
|
-
coinType: streamCoinType,
|
|
643
|
-
amount: payment.totalAmount + payment.streamFeeAmount + payment.flatFeeAmount
|
|
644
|
-
}
|
|
645
|
-
];
|
|
646
|
-
}
|
|
647
|
-
return [
|
|
648
|
-
{
|
|
649
|
-
coinType: streamCoinType,
|
|
650
|
-
amount: payment.totalAmount + payment.streamFeeAmount
|
|
651
|
-
},
|
|
652
|
-
{
|
|
653
|
-
coinType: import_utils3.SUI_TYPE_ARG,
|
|
654
|
-
amount: payment.flatFeeAmount
|
|
655
|
-
}
|
|
656
|
-
];
|
|
657
|
-
}
|
|
658
|
-
calculateFeesInternal(info) {
|
|
659
|
-
const streamPayment = info.recipients.reduce(
|
|
660
|
-
(sum, recipient) => {
|
|
661
|
-
const totalAmount = this.amountForRecipient(recipient, info.numberEpoch);
|
|
662
|
-
const fee = this.getStreamFeeLocal(totalAmount);
|
|
663
|
-
return {
|
|
664
|
-
totalAmount: sum.totalAmount + totalAmount,
|
|
665
|
-
streamFeeAmount: sum.streamFeeAmount + fee
|
|
666
|
-
};
|
|
667
|
-
},
|
|
668
|
-
{
|
|
669
|
-
totalAmount: 0n,
|
|
670
|
-
streamFeeAmount: 0n
|
|
671
|
-
}
|
|
672
|
-
);
|
|
673
|
-
const flatFeeAmount = BigInt(info.recipients.length) * this.flatSuiFee;
|
|
674
|
-
return {
|
|
675
|
-
flatFeeAmount,
|
|
676
|
-
...streamPayment
|
|
677
|
-
};
|
|
678
|
-
}
|
|
679
|
-
amountForRecipient(recipient, numEpoch) {
|
|
680
|
-
return BigInt(recipient.amountPerEpoch) * BigInt(numEpoch) + BigInt(recipient.cliffAmount);
|
|
681
|
-
}
|
|
682
|
-
get flatSuiFee() {
|
|
683
|
-
return FLAT_FEE_SUI;
|
|
684
|
-
}
|
|
685
|
-
getStreamFeeLocal(streamAmount) {
|
|
686
|
-
return streamAmount * FEE_NUMERATOR / FEE_DENOMINATOR;
|
|
687
|
-
}
|
|
688
|
-
async getStreamFeeRemote(streamAmount) {
|
|
689
|
-
const txb = this.feeContract.streamingFee(new import_transactions.TransactionBlock(), streamAmount);
|
|
690
|
-
const res = await this.globals.suiClient.devInspectTransactionBlock({
|
|
691
|
-
sender: await this.globals.walletAddress(),
|
|
692
|
-
transactionBlock: txb
|
|
693
|
-
});
|
|
694
|
-
const iv = new InspectViewer(res);
|
|
695
|
-
return iv.getU64();
|
|
696
|
-
}
|
|
697
|
-
get wallet() {
|
|
698
|
-
return this.globals.wallet;
|
|
699
|
-
}
|
|
700
|
-
};
|
|
701
|
-
|
|
702
|
-
// src/apps/mpay/contract/BaseContract.ts
|
|
703
|
-
var import_transactions2 = require("@mysten/sui.js/transactions");
|
|
704
|
-
|
|
705
|
-
// src/apps/mpay/const.ts
|
|
706
|
-
var CLOCK_ID = "0x0000000000000000000000000000000000000000000000000000000000000006";
|
|
707
|
-
|
|
708
|
-
// src/apps/mpay/contract/BaseContract.ts
|
|
709
|
-
var BaseContract = class {
|
|
710
|
-
constructor(moduleName, config, globals) {
|
|
711
|
-
this.moduleName = moduleName;
|
|
712
|
-
this.config = config;
|
|
713
|
-
this.globals = globals;
|
|
714
|
-
}
|
|
715
|
-
addContractCall(txb, input) {
|
|
716
|
-
const target = `${this.config.contractId}::${this.moduleName}::${input.method}`;
|
|
717
|
-
txb.add(
|
|
718
|
-
import_transactions2.Transactions.MoveCall({
|
|
719
|
-
target,
|
|
720
|
-
arguments: input.arguments.map((arg) => {
|
|
721
|
-
if (arg instanceof ObjectVector) {
|
|
722
|
-
return arg.moveArgs(txb);
|
|
723
|
-
}
|
|
724
|
-
if (arg instanceof MoveObject) {
|
|
725
|
-
return arg.moveArg(txb);
|
|
726
|
-
}
|
|
727
|
-
if (arg instanceof ResultRef) {
|
|
728
|
-
return arg.moveArg();
|
|
729
|
-
}
|
|
730
|
-
return txb.pure(arg);
|
|
731
|
-
}),
|
|
732
|
-
typeArguments: input.typeArgs
|
|
733
|
-
})
|
|
734
|
-
);
|
|
735
|
-
return txb;
|
|
736
|
-
}
|
|
737
|
-
addTransactionBlock(txb, target, callArgs = [], typeArgs = []) {
|
|
738
|
-
txb.add(
|
|
739
|
-
import_transactions2.Transactions.MoveCall({
|
|
740
|
-
target,
|
|
741
|
-
arguments: callArgs.map((arg) => {
|
|
742
|
-
if (arg instanceof ObjectVector) {
|
|
743
|
-
return arg.moveArgs(txb);
|
|
744
|
-
}
|
|
745
|
-
if (arg instanceof MoveObject) {
|
|
746
|
-
return arg.moveArg(txb);
|
|
747
|
-
}
|
|
748
|
-
if (arg instanceof ResultRef) {
|
|
749
|
-
return arg.moveArg();
|
|
750
|
-
}
|
|
751
|
-
return txb.pure(arg);
|
|
752
|
-
}),
|
|
753
|
-
typeArguments: typeArgs
|
|
754
|
-
})
|
|
755
|
-
);
|
|
756
|
-
}
|
|
757
|
-
makeObject(object) {
|
|
758
|
-
return typeof object === "string" ? new MoveObject(object) : object;
|
|
759
|
-
}
|
|
760
|
-
vaultObject() {
|
|
761
|
-
return new MoveObject(this.config.vaultObjId);
|
|
762
|
-
}
|
|
763
|
-
roleObject() {
|
|
764
|
-
return new MoveObject(this.config.roleObjId);
|
|
765
|
-
}
|
|
766
|
-
feeObject() {
|
|
767
|
-
return new MoveObject(this.config.feeObjId);
|
|
768
|
-
}
|
|
769
|
-
clockObject() {
|
|
770
|
-
return new MoveObject(CLOCK_ID);
|
|
771
|
-
}
|
|
772
|
-
};
|
|
773
|
-
|
|
774
|
-
// src/apps/mpay/contract/FeeContract.ts
|
|
775
|
-
var FeeContract = class _FeeContract extends BaseContract {
|
|
776
|
-
constructor(config, globals) {
|
|
777
|
-
super(_FeeContract.ModuleName, config, globals);
|
|
778
|
-
this.config = config;
|
|
779
|
-
this.globals = globals;
|
|
780
|
-
}
|
|
781
|
-
static ModuleName = "fee_module";
|
|
782
|
-
static MethodName = {
|
|
783
|
-
set_streaming_fee: "set_streaming_fee",
|
|
784
|
-
set_claim_fee: "set_claim_fee",
|
|
785
|
-
set_streaming_flat_fee: "set_streaming_flat_fee",
|
|
786
|
-
streaming_flat_fee: "streaming_flat_fee",
|
|
787
|
-
streaming_fee: "streaming_fee",
|
|
788
|
-
claim_fee: "claim_fee",
|
|
789
|
-
fee_denominator: "fee_denominator"
|
|
790
|
-
};
|
|
791
|
-
setStreamingFee(txb, createFeeNumerator) {
|
|
792
|
-
const roleObject = this.roleObject();
|
|
793
|
-
const feeObject = this.feeObject();
|
|
794
|
-
return this.addContractCall(txb, {
|
|
795
|
-
method: _FeeContract.MethodName.set_streaming_fee,
|
|
796
|
-
arguments: [roleObject, feeObject, createFeeNumerator],
|
|
797
|
-
typeArgs: []
|
|
798
|
-
});
|
|
799
|
-
}
|
|
800
|
-
setStreamingFlatFee(txb, flatFee) {
|
|
801
|
-
const roleObject = this.roleObject();
|
|
802
|
-
const feeObject = this.feeObject();
|
|
803
|
-
return this.addContractCall(txb, {
|
|
804
|
-
method: _FeeContract.MethodName.set_streaming_flat_fee,
|
|
805
|
-
arguments: [roleObject, feeObject, flatFee],
|
|
806
|
-
typeArgs: []
|
|
807
|
-
});
|
|
808
|
-
}
|
|
809
|
-
setClaimFee(txb, claimFee) {
|
|
810
|
-
const roleObject = this.roleObject();
|
|
811
|
-
const feeObject = this.feeObject();
|
|
812
|
-
return this.addContractCall(txb, {
|
|
813
|
-
method: _FeeContract.MethodName.set_claim_fee,
|
|
814
|
-
arguments: [roleObject, feeObject, claimFee],
|
|
815
|
-
typeArgs: []
|
|
816
|
-
});
|
|
817
|
-
}
|
|
818
|
-
streamingFee(txb, amount) {
|
|
819
|
-
const feeObject = this.feeObject();
|
|
820
|
-
return this.addContractCall(txb, {
|
|
821
|
-
method: _FeeContract.MethodName.streaming_fee,
|
|
822
|
-
arguments: [feeObject, amount],
|
|
823
|
-
typeArgs: []
|
|
824
|
-
});
|
|
825
|
-
}
|
|
826
|
-
claimFee(txb, amount) {
|
|
827
|
-
return this.addContractCall(txb, {
|
|
828
|
-
method: _FeeContract.MethodName.claim_fee,
|
|
829
|
-
arguments: [this.feeObject(), amount],
|
|
830
|
-
typeArgs: []
|
|
831
|
-
});
|
|
832
|
-
}
|
|
833
|
-
feeDenominator(txb) {
|
|
834
|
-
return this.addContractCall(txb, {
|
|
835
|
-
method: _FeeContract.MethodName.fee_denominator,
|
|
836
|
-
arguments: [this.feeObject()],
|
|
837
|
-
typeArgs: []
|
|
838
|
-
});
|
|
839
|
-
}
|
|
840
|
-
};
|
|
841
|
-
|
|
842
|
-
// src/apps/mpay/contract/StreamContract.ts
|
|
843
|
-
var StreamContract = class _StreamContract extends BaseContract {
|
|
844
|
-
constructor(config, globals) {
|
|
845
|
-
super(_StreamContract.ModuleName, config, globals);
|
|
846
|
-
this.config = config;
|
|
847
|
-
this.globals = globals;
|
|
848
|
-
}
|
|
849
|
-
static ModuleName = "stream";
|
|
850
|
-
static MethodName = {
|
|
851
|
-
create_stream: "create_stream",
|
|
852
|
-
set_auto_claim: "set_auto_claim",
|
|
853
|
-
cancel_stream: "cancel_stream",
|
|
854
|
-
claim_stream: "claim_stream",
|
|
855
|
-
claim_stream_by_proxy: "claim_stream_by_proxy",
|
|
856
|
-
stream_current_epoch: "stream_current_epoch",
|
|
857
|
-
now_milli_seconds: "now_milli_seconds"
|
|
858
|
-
};
|
|
859
|
-
createStream(txb, input) {
|
|
860
|
-
const feeObject = this.feeObject();
|
|
861
|
-
const vaultObject = this.vaultObject();
|
|
862
|
-
const paymentCoinObject = this.makeObject(input.paymentCoin);
|
|
863
|
-
const flatFeeObject = this.makeObject(input.flatFeeCoin);
|
|
864
|
-
const clockObject = this.clockObject();
|
|
865
|
-
return this.addContractCall(txb, {
|
|
866
|
-
method: _StreamContract.MethodName.create_stream,
|
|
867
|
-
arguments: [
|
|
868
|
-
feeObject,
|
|
869
|
-
vaultObject,
|
|
870
|
-
paymentCoinObject,
|
|
871
|
-
flatFeeObject,
|
|
872
|
-
input.metadata,
|
|
873
|
-
input.recipient,
|
|
874
|
-
input.timeStart,
|
|
875
|
-
input.cliff,
|
|
876
|
-
input.epochInterval,
|
|
877
|
-
input.numEpoch,
|
|
878
|
-
input.amountPerEpoch,
|
|
879
|
-
input.cancelable,
|
|
880
|
-
clockObject
|
|
881
|
-
],
|
|
882
|
-
typeArgs: [input.coinType]
|
|
883
|
-
});
|
|
884
|
-
}
|
|
885
|
-
setAutoClaim(txb, input) {
|
|
886
|
-
const streamObject = this.makeObject(input.streamId);
|
|
887
|
-
return this.addContractCall(txb, {
|
|
888
|
-
method: _StreamContract.MethodName.set_auto_claim,
|
|
889
|
-
arguments: [streamObject, input.enabled],
|
|
890
|
-
typeArgs: [input.coinType]
|
|
891
|
-
});
|
|
892
|
-
}
|
|
893
|
-
cancelStream(txb, input) {
|
|
894
|
-
const streamObject = this.makeObject(input.streamId);
|
|
895
|
-
const clockObject = this.clockObject();
|
|
896
|
-
return this.addContractCall(txb, {
|
|
897
|
-
method: _StreamContract.MethodName.cancel_stream,
|
|
898
|
-
arguments: [streamObject, clockObject],
|
|
899
|
-
typeArgs: [input.coinType]
|
|
900
|
-
});
|
|
901
|
-
}
|
|
902
|
-
claimStream(txb, input) {
|
|
903
|
-
const streamObject = this.makeObject(input.streamId);
|
|
904
|
-
const clockObject = this.clockObject();
|
|
905
|
-
return this.addContractCall(txb, {
|
|
906
|
-
method: _StreamContract.MethodName.claim_stream,
|
|
907
|
-
arguments: [streamObject, clockObject],
|
|
908
|
-
typeArgs: [input.coinType]
|
|
909
|
-
});
|
|
910
|
-
}
|
|
911
|
-
claimStreamByProxy(txb, input) {
|
|
912
|
-
const streamObject = this.makeObject(input.streamId);
|
|
913
|
-
const vaultObject = this.vaultObject();
|
|
914
|
-
const feeObject = this.feeObject();
|
|
915
|
-
const clockObject = this.clockObject();
|
|
916
|
-
return this.addContractCall(txb, {
|
|
917
|
-
method: _StreamContract.MethodName.claim_stream_by_proxy,
|
|
918
|
-
arguments: [streamObject, vaultObject, feeObject, clockObject],
|
|
919
|
-
typeArgs: [input.coinType]
|
|
920
|
-
});
|
|
921
|
-
}
|
|
922
|
-
get createStreamTarget() {
|
|
923
|
-
return `${this.config.contractId}::${_StreamContract.ModuleName}::${_StreamContract.MethodName.create_stream}`;
|
|
924
|
-
}
|
|
925
|
-
get setAutoClaimTarget() {
|
|
926
|
-
return `${this.config.contractId}::${_StreamContract.ModuleName}::${_StreamContract.MethodName.set_auto_claim}`;
|
|
927
|
-
}
|
|
928
|
-
get cancelStreamTarget() {
|
|
929
|
-
return `${this.config.contractId}::${_StreamContract.ModuleName}::${_StreamContract.MethodName.cancel_stream}`;
|
|
930
|
-
}
|
|
931
|
-
get claimStreamTarget() {
|
|
932
|
-
return `${this.config.contractId}::${_StreamContract.ModuleName}::${_StreamContract.MethodName.claim_stream}`;
|
|
933
|
-
}
|
|
934
|
-
get claimStreamByProxyTarget() {
|
|
935
|
-
return `${this.config.contractId}::${_StreamContract.ModuleName}::${_StreamContract.MethodName.claim_stream_by_proxy}`;
|
|
936
|
-
}
|
|
937
|
-
};
|
|
938
|
-
|
|
939
|
-
// src/apps/mpay/builder/MPayBuilder.ts
|
|
940
|
-
var MPayBuilder = class {
|
|
941
|
-
constructor(globals) {
|
|
942
|
-
this.globals = globals;
|
|
943
|
-
const config = globals.envConfig.contract;
|
|
944
|
-
this.feeContract = new FeeContract(config, globals);
|
|
945
|
-
this.streamContract = new StreamContract(config, globals);
|
|
946
|
-
}
|
|
947
|
-
feeContract;
|
|
948
|
-
streamContract;
|
|
949
|
-
async createStreams(info) {
|
|
950
|
-
const infoInternal = CreateStreamHelper.convertCreateStreamInfoToInternal(info);
|
|
951
|
-
return this.createStreamHelper().buildCreateStreamTransactionBlock(infoInternal);
|
|
952
|
-
}
|
|
953
|
-
createStreamHelper() {
|
|
954
|
-
return new CreateStreamHelper(this.globals, this.feeContract, this.streamContract);
|
|
955
|
-
}
|
|
956
|
-
setAutoClaim(streamId, enabled, coinType) {
|
|
957
|
-
const txb = new import_transactions3.TransactionBlock();
|
|
958
|
-
return this.streamContract.setAutoClaim(txb, {
|
|
959
|
-
streamId,
|
|
960
|
-
enabled,
|
|
961
|
-
coinType
|
|
962
|
-
});
|
|
963
|
-
}
|
|
964
|
-
claimStream(streamId, coinType) {
|
|
965
|
-
const txb = new import_transactions3.TransactionBlock();
|
|
966
|
-
return this.streamContract.claimStream(txb, {
|
|
967
|
-
streamId,
|
|
968
|
-
coinType
|
|
969
|
-
});
|
|
970
|
-
}
|
|
971
|
-
claimStreamByProxy(streamId, coinType) {
|
|
972
|
-
const txb = new import_transactions3.TransactionBlock();
|
|
973
|
-
return this.streamContract.claimStreamByProxy(txb, {
|
|
974
|
-
streamId,
|
|
975
|
-
coinType
|
|
976
|
-
});
|
|
977
|
-
}
|
|
978
|
-
cancelStream(streamId, coinType) {
|
|
979
|
-
const txb = new import_transactions3.TransactionBlock();
|
|
980
|
-
this.streamContract.cancelStream(txb, {
|
|
981
|
-
streamId,
|
|
982
|
-
coinType
|
|
983
|
-
});
|
|
984
|
-
return txb;
|
|
985
|
-
}
|
|
986
|
-
};
|
|
987
|
-
|
|
988
|
-
// src/apps/mpay/error/TransactionFailedError.ts
|
|
989
|
-
var TransactionFailedError = class extends MPayError {
|
|
990
|
-
constructor(status3, msg) {
|
|
991
|
-
super(12 /* TransactionFailed */, `Transaction failed: ${msg}`, {
|
|
992
|
-
context: {
|
|
993
|
-
status: status3,
|
|
994
|
-
msg
|
|
995
|
-
}
|
|
996
|
-
});
|
|
997
|
-
}
|
|
998
|
-
};
|
|
999
|
-
|
|
1000
|
-
// src/apps/mpay/stream/helper.ts
|
|
1001
|
-
var MIN_INTERVAL_MS = 1e3;
|
|
1002
|
-
var MPayHelper = class {
|
|
1003
|
-
constructor(globals) {
|
|
1004
|
-
this.globals = globals;
|
|
1005
|
-
this.coinMetaHelper = new CoinMetaHelper(globals.suiClient);
|
|
1006
|
-
this.createStreamHelper = new MPayBuilder(globals).createStreamHelper();
|
|
1007
|
-
}
|
|
1008
|
-
coinMetaHelper;
|
|
1009
|
-
createStreamHelper;
|
|
1010
|
-
getStreamIdsFromCreateStreamResponse(res) {
|
|
1011
|
-
if (res.effects?.status.status !== "success") {
|
|
1012
|
-
throw new TransactionFailedError(res.effects?.status.status, res.effects?.status.error);
|
|
1013
|
-
}
|
|
1014
|
-
return res.objectChanges.filter(
|
|
1015
|
-
(change) => change.type === "created" && change.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)
|
|
1016
|
-
).map((change) => change.objectId);
|
|
1017
|
-
}
|
|
1018
|
-
calculateCreateStreamFees(info) {
|
|
1019
|
-
return this.createStreamHelper.calculateCreateStreamFees(info);
|
|
1020
|
-
}
|
|
1021
|
-
feeParams() {
|
|
1022
|
-
return this.createStreamHelper.feeParams();
|
|
1023
|
-
}
|
|
1024
|
-
calculateStreamAmount(input) {
|
|
1025
|
-
if (input.steps === 0n) {
|
|
1026
|
-
throw new InvalidInputError("Invalid stream steps: 0");
|
|
1027
|
-
}
|
|
1028
|
-
const cliffFraction = input.cliff ? input.cliff : {
|
|
1029
|
-
numerator: 0n,
|
|
1030
|
-
denominator: 100n
|
|
1031
|
-
};
|
|
1032
|
-
const cliffAmount = input.totalAmount * cliffFraction.numerator / cliffFraction.denominator;
|
|
1033
|
-
const amountPerStep = (input.totalAmount - cliffAmount) / input.steps;
|
|
1034
|
-
const realTotalAmount = amountPerStep * input.steps + cliffAmount;
|
|
1035
|
-
const res = {
|
|
1036
|
-
realTotalAmount,
|
|
1037
|
-
cliffAmount,
|
|
1038
|
-
amountPerStep
|
|
1039
|
-
};
|
|
1040
|
-
this.validateStreamAmount(res, input.totalAmount);
|
|
1041
|
-
return res;
|
|
1042
|
-
}
|
|
1043
|
-
calculateTimelineByInterval(input) {
|
|
1044
|
-
if (input.steps === 0n) {
|
|
1045
|
-
throw new InvalidInputError("Invalid stream steps: 0");
|
|
1046
|
-
}
|
|
1047
|
-
const timeEnd = input.timeStart.plus(input.interval.toMillis() * Number(input.steps));
|
|
1048
|
-
const res = {
|
|
1049
|
-
timeStart: input.timeStart,
|
|
1050
|
-
timeEnd,
|
|
1051
|
-
interval: input.interval,
|
|
1052
|
-
steps: input.steps
|
|
1053
|
-
};
|
|
1054
|
-
this.validateTimeline(res);
|
|
1055
|
-
return res;
|
|
1056
|
-
}
|
|
1057
|
-
calculateTimelineByTotalDuration(input) {
|
|
1058
|
-
if (input.steps === 0n) {
|
|
1059
|
-
throw new InvalidInputError("Invalid stream steps: 0");
|
|
1060
|
-
}
|
|
1061
|
-
const intervalMilli = BigInt(input.total.toMillis()) / input.steps;
|
|
1062
|
-
const timeEnd = input.timeStart.plus(import_luxon.Duration.fromMillis(Number(intervalMilli * input.steps)));
|
|
1063
|
-
const res = {
|
|
1064
|
-
timeStart: input.timeStart,
|
|
1065
|
-
timeEnd,
|
|
1066
|
-
interval: import_luxon.Duration.fromMillis(Number(intervalMilli)),
|
|
1067
|
-
steps: input.steps
|
|
1068
|
-
};
|
|
1069
|
-
this.validateTimeline(res);
|
|
1070
|
-
return res;
|
|
1071
|
-
}
|
|
1072
|
-
async getBalance(address, coinType) {
|
|
1073
|
-
const balance = await this.globals.suiClient.getBalance({
|
|
1074
|
-
owner: address,
|
|
1075
|
-
coinType
|
|
1076
|
-
});
|
|
1077
|
-
const coinMeta = await this.getCoinMeta(coinType);
|
|
1078
|
-
return {
|
|
1079
|
-
...balance,
|
|
1080
|
-
coinType: (0, import_utils5.normalizeStructTag)(balance.coinType),
|
|
1081
|
-
coinMeta
|
|
1082
|
-
};
|
|
1083
|
-
}
|
|
1084
|
-
async getAllBalance(address) {
|
|
1085
|
-
const allBalance = await this.globals.suiClient.getAllBalances({
|
|
1086
|
-
owner: address
|
|
1087
|
-
});
|
|
1088
|
-
const coinMetas = await Promise.all(allBalance.map((bal) => this.getCoinMeta(bal.coinType)));
|
|
1089
|
-
return allBalance.map((bal, i) => ({
|
|
1090
|
-
...bal,
|
|
1091
|
-
coinType: (0, import_utils5.normalizeStructTag)(bal.coinType),
|
|
1092
|
-
coinMeta: coinMetas[i]
|
|
1093
|
-
}));
|
|
1094
|
-
}
|
|
1095
|
-
async getCoinMeta(coinType) {
|
|
1096
|
-
return this.coinMetaHelper.getCoinMeta(coinType);
|
|
1097
|
-
}
|
|
1098
|
-
async simulateTransactionBlock(txb) {
|
|
1099
|
-
return this.globals.suiClient.devInspectTransactionBlock({
|
|
1100
|
-
transactionBlock: txb,
|
|
1101
|
-
sender: await this.globals.wallet.address()
|
|
1102
|
-
});
|
|
1103
|
-
}
|
|
1104
|
-
validateStreamAmount(val, originTotalAmount) {
|
|
1105
|
-
if (val.amountPerStep === 0n) {
|
|
1106
|
-
throw new InvalidInputError("Stream amount too small", "totalAmount", originTotalAmount);
|
|
1107
|
-
}
|
|
1108
|
-
if (val.cliffAmount > val.realTotalAmount) {
|
|
1109
|
-
throw new InvalidInputError("Invalid cliff settings");
|
|
1110
|
-
}
|
|
1111
|
-
}
|
|
1112
|
-
validateTimeline(val) {
|
|
1113
|
-
if (val.interval.toMillis() < MIN_INTERVAL_MS) {
|
|
1114
|
-
throw new InvalidInputError("Interval shall be at least 1 second", "interval", val.interval);
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
};
|
|
1118
|
-
var CoinMetaHelper = class {
|
|
1119
|
-
constructor(suiClient) {
|
|
1120
|
-
this.suiClient = suiClient;
|
|
1121
|
-
this.coinMetaReg = /* @__PURE__ */ new Map();
|
|
1122
|
-
}
|
|
1123
|
-
coinMetaReg;
|
|
1124
|
-
async getCoinMeta(coinType) {
|
|
1125
|
-
const normalized = (0, import_utils5.normalizeStructTag)(coinType || import_utils5.SUI_TYPE_ARG);
|
|
1126
|
-
if (this.coinMetaReg.has(normalized)) {
|
|
1127
|
-
return this.coinMetaReg.get(normalized);
|
|
1128
|
-
}
|
|
1129
|
-
const meta = await this.queryCoinMeta(normalized);
|
|
1130
|
-
if (meta) {
|
|
1131
|
-
this.coinMetaReg.set(normalized, meta);
|
|
1132
|
-
}
|
|
1133
|
-
return meta;
|
|
1134
|
-
}
|
|
1135
|
-
async queryCoinMeta(coinType) {
|
|
1136
|
-
const res = await this.suiClient.getCoinMetadata({ coinType });
|
|
1137
|
-
return res || void 0;
|
|
1138
|
-
}
|
|
1139
|
-
};
|
|
1140
|
-
|
|
1141
|
-
// src/apps/mpay/stream/query.ts
|
|
1142
|
-
var import_utils8 = require("@mysten/sui.js/utils");
|
|
1143
|
-
var import_luxon4 = require("luxon");
|
|
1144
|
-
|
|
1145
|
-
// src/apps/mpay/stream/Stream.ts
|
|
1146
|
-
var import_transactions4 = require("@mysten/sui.js/transactions");
|
|
1147
|
-
var import_utils6 = require("@mysten/sui.js/utils");
|
|
1148
|
-
var import_luxon3 = require("luxon");
|
|
1149
|
-
|
|
1150
|
-
// src/apps/mpay/error/NotCreatorError.ts
|
|
1151
|
-
var NotCreatorError = class extends MPayError {
|
|
1152
|
-
constructor() {
|
|
1153
|
-
super(7 /* NotCreator */, "Connected wallet is not creator");
|
|
1154
|
-
}
|
|
1155
|
-
};
|
|
1156
|
-
|
|
1157
|
-
// src/apps/mpay/error/NotRecipientError.ts
|
|
1158
|
-
var NotRecipientError = class extends MPayError {
|
|
1159
|
-
constructor() {
|
|
1160
|
-
super(8 /* NotRecipient */, "Connected wallet is not recipient");
|
|
1161
|
-
}
|
|
1162
|
-
};
|
|
1163
|
-
|
|
1164
|
-
// src/apps/mpay/error/RpcError.ts
|
|
1165
|
-
var RpcError = class extends MPayError {
|
|
1166
|
-
constructor(msg, context) {
|
|
1167
|
-
super(6 /* RpcError */, msg, {
|
|
1168
|
-
context
|
|
1169
|
-
});
|
|
1170
|
-
}
|
|
1171
|
-
};
|
|
1172
|
-
|
|
1173
|
-
// src/apps/mpay/error/SanityError.ts
|
|
1174
|
-
var SanityError = class extends MPayError {
|
|
1175
|
-
constructor(msg, options = {}) {
|
|
1176
|
-
super(0 /* sanity */, msg, options);
|
|
1177
|
-
}
|
|
1178
|
-
};
|
|
1179
|
-
|
|
1180
|
-
// src/apps/mpay/error/StreamNotFoundError.ts
|
|
1181
|
-
var StreamNotFoundError = class extends MPayError {
|
|
1182
|
-
constructor(streamId) {
|
|
1183
|
-
super(5 /* StreamNotFound */, "Stream not found", {
|
|
1184
|
-
context: {
|
|
1185
|
-
streamId
|
|
1186
|
-
}
|
|
1187
|
-
});
|
|
1188
|
-
}
|
|
1189
|
-
};
|
|
1190
|
-
|
|
1191
|
-
// src/apps/mpay/utils/utils.ts
|
|
1192
|
-
var import_luxon2 = require("luxon");
|
|
1193
|
-
var MAX_U64 = (1n << 64n) - 1n;
|
|
1194
|
-
var TIME_ROUND_UNIT = 1e3;
|
|
1195
|
-
function roundDateTime(date) {
|
|
1196
|
-
let dateMs;
|
|
1197
|
-
if (typeof date === "number") {
|
|
1198
|
-
dateMs = date;
|
|
1199
|
-
} else if (typeof date === "bigint") {
|
|
1200
|
-
dateMs = Number(date);
|
|
1201
|
-
} else {
|
|
1202
|
-
dateMs = date.toMillis();
|
|
1203
|
-
}
|
|
1204
|
-
const roundMs = Math.round(dateMs / TIME_ROUND_UNIT);
|
|
1205
|
-
return import_luxon2.DateTime.fromMillis(roundMs * TIME_ROUND_UNIT);
|
|
1206
|
-
}
|
|
1207
|
-
function roundDuration(duration) {
|
|
1208
|
-
let durationMs;
|
|
1209
|
-
if (typeof duration === "number") {
|
|
1210
|
-
durationMs = duration;
|
|
1211
|
-
} else if (typeof duration === "bigint") {
|
|
1212
|
-
durationMs = Number(duration);
|
|
1213
|
-
} else {
|
|
1214
|
-
durationMs = duration.toMillis();
|
|
1215
|
-
}
|
|
1216
|
-
const roundMs = Math.round(durationMs / TIME_ROUND_UNIT);
|
|
1217
|
-
return import_luxon2.Duration.fromMillis(roundMs * TIME_ROUND_UNIT);
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
|
-
// src/apps/mpay/stream/Stream.ts
|
|
1221
|
-
var Stream = class _Stream {
|
|
1222
|
-
constructor(globals, streamId, rawData) {
|
|
1223
|
-
this.globals = globals;
|
|
1224
|
-
this.streamId = streamId;
|
|
1225
|
-
this.rawData = rawData;
|
|
1226
|
-
this.streamContract = new StreamContract(globals.envConfig.contract, globals);
|
|
1227
|
-
}
|
|
1228
|
-
streamContract;
|
|
1229
|
-
type = "Stream";
|
|
1230
|
-
static async new(globals, streamId) {
|
|
1231
|
-
const rawData = await _Stream.fetchStreamData(globals, streamId);
|
|
1232
|
-
return new _Stream(globals, streamId, rawData);
|
|
1233
|
-
}
|
|
1234
|
-
static fromObjectData(globals, streamId, data) {
|
|
1235
|
-
const rawData = _Stream.parseRawStreamData(streamId, data);
|
|
1236
|
-
return new _Stream(globals, streamId, rawData);
|
|
1237
|
-
}
|
|
1238
|
-
get info() {
|
|
1239
|
-
return {
|
|
1240
|
-
name: this.name,
|
|
1241
|
-
creator: this.creator,
|
|
1242
|
-
coinType: this.coinType,
|
|
1243
|
-
totalAmount: this.totalAmount,
|
|
1244
|
-
start: this.timeStart,
|
|
1245
|
-
end: this.timeEnd,
|
|
1246
|
-
cancelable: this.cancelable,
|
|
1247
|
-
cliffAmount: this.cliff,
|
|
1248
|
-
duration: this.duration,
|
|
1249
|
-
interval: this.interval,
|
|
1250
|
-
steps: this.totalSteps,
|
|
1251
|
-
nextReleaseDate: this.nextReleaseDate,
|
|
1252
|
-
nextReleaseAmount: this.nextReleaseAmount,
|
|
1253
|
-
groupId: this.groupId,
|
|
1254
|
-
streamId: this.streamId,
|
|
1255
|
-
recipient: this.recipient,
|
|
1256
|
-
progress: this.progress,
|
|
1257
|
-
autoClaim: this.autoClaim
|
|
1258
|
-
};
|
|
1259
|
-
}
|
|
1260
|
-
get groupCommonInfo() {
|
|
1261
|
-
return {
|
|
1262
|
-
name: this.name,
|
|
1263
|
-
groupId: this.groupId,
|
|
1264
|
-
creator: this.creator,
|
|
1265
|
-
start: this.timeStart,
|
|
1266
|
-
interval: this.interval,
|
|
1267
|
-
steps: this.totalSteps,
|
|
1268
|
-
cancelable: this.cancelable
|
|
1269
|
-
};
|
|
1270
|
-
}
|
|
1271
|
-
async refresh() {
|
|
1272
|
-
this.rawData = await _Stream.fetchStreamData(this.globals, this.streamId);
|
|
1273
|
-
}
|
|
1274
|
-
refreshWithData(data) {
|
|
1275
|
-
if (data.data?.objectId !== this.streamId) {
|
|
1276
|
-
throw new SanityError("Object Id does not align");
|
|
1277
|
-
}
|
|
1278
|
-
this.rawData = _Stream.parseRawStreamData(this.streamId, data);
|
|
1279
|
-
}
|
|
1280
|
-
async historyEvents(pagination) {
|
|
1281
|
-
return this.globals.backend.getStreamHistory({
|
|
1282
|
-
streamId: this.streamId,
|
|
1283
|
-
pagination
|
|
1284
|
-
});
|
|
1285
|
-
}
|
|
1286
|
-
async cancel() {
|
|
1287
|
-
if (await this.globals.walletAddress() !== this.creator) {
|
|
1288
|
-
throw new NotCreatorError();
|
|
1289
|
-
}
|
|
1290
|
-
const txb = new import_transactions4.TransactionBlock();
|
|
1291
|
-
this.streamContract.cancelStream(txb, {
|
|
1292
|
-
streamId: this.streamId,
|
|
1293
|
-
coinType: this.coinType
|
|
1294
|
-
});
|
|
1295
|
-
return txb;
|
|
1296
|
-
}
|
|
1297
|
-
async claim() {
|
|
1298
|
-
if (await this.globals.walletAddress() !== this.recipient) {
|
|
1299
|
-
throw new NotRecipientError();
|
|
1300
|
-
}
|
|
1301
|
-
const txb = new import_transactions4.TransactionBlock();
|
|
1302
|
-
this.streamContract.claimStream(txb, {
|
|
1303
|
-
streamId: this.streamId,
|
|
1304
|
-
coinType: this.coinType
|
|
1305
|
-
});
|
|
1306
|
-
return txb;
|
|
1307
|
-
}
|
|
1308
|
-
async setAutoClaim(enabled) {
|
|
1309
|
-
if (await this.globals.walletAddress() !== this.recipient) {
|
|
1310
|
-
throw new NotRecipientError();
|
|
1311
|
-
}
|
|
1312
|
-
const txb = new import_transactions4.TransactionBlock();
|
|
1313
|
-
this.streamContract.setAutoClaim(txb, {
|
|
1314
|
-
streamId: this.streamId,
|
|
1315
|
-
coinType: this.coinType,
|
|
1316
|
-
enabled
|
|
1317
|
-
});
|
|
1318
|
-
return txb;
|
|
1319
|
-
}
|
|
1320
|
-
async claimByProxy() {
|
|
1321
|
-
const txb = new import_transactions4.TransactionBlock();
|
|
1322
|
-
this.streamContract.claimStreamByProxy(txb, {
|
|
1323
|
-
streamId: this.streamId,
|
|
1324
|
-
coinType: this.coinType
|
|
1325
|
-
});
|
|
1326
|
-
return txb;
|
|
1327
|
-
}
|
|
1328
|
-
get wallet() {
|
|
1329
|
-
return this.globals.wallet;
|
|
1330
|
-
}
|
|
1331
|
-
get client() {
|
|
1332
|
-
return this.globals.suiClient;
|
|
1333
|
-
}
|
|
1334
|
-
get coinType() {
|
|
1335
|
-
return (0, import_utils6.normalizeStructTag)(this.rawData.coinType);
|
|
1336
|
-
}
|
|
1337
|
-
get progress() {
|
|
1338
|
-
return {
|
|
1339
|
-
status: this.streamStatus,
|
|
1340
|
-
total: this.totalAmount,
|
|
1341
|
-
streamed: this.streamedAmount,
|
|
1342
|
-
claimed: this.claimedAmount,
|
|
1343
|
-
claimable: this.claimable,
|
|
1344
|
-
canceled: this.canceledAmount
|
|
1345
|
-
};
|
|
1346
|
-
}
|
|
1347
|
-
get balance() {
|
|
1348
|
-
return this.rawData.balance;
|
|
1349
|
-
}
|
|
1350
|
-
get autoClaim() {
|
|
1351
|
-
return this.rawData.autoClaim;
|
|
1352
|
-
}
|
|
1353
|
-
get amountPerEpoch() {
|
|
1354
|
-
return this.rawData.config.amountPerEpoch;
|
|
1355
|
-
}
|
|
1356
|
-
get cancelable() {
|
|
1357
|
-
return this.rawData.config.cancelable;
|
|
1358
|
-
}
|
|
1359
|
-
get cliff() {
|
|
1360
|
-
return this.rawData.config.cliff;
|
|
1361
|
-
}
|
|
1362
|
-
get creator() {
|
|
1363
|
-
return this.rawData.config.creator;
|
|
1364
|
-
}
|
|
1365
|
-
get interval() {
|
|
1366
|
-
return roundDuration(this.rawData.config.epochInterval);
|
|
1367
|
-
}
|
|
1368
|
-
get groupId() {
|
|
1369
|
-
const { metadata } = this.rawData.config;
|
|
1370
|
-
const md = decodeMetadata(metadata);
|
|
1371
|
-
return md.groupId;
|
|
1372
|
-
}
|
|
1373
|
-
get name() {
|
|
1374
|
-
const { metadata } = this.rawData.config;
|
|
1375
|
-
const md = decodeMetadata(metadata);
|
|
1376
|
-
return md.name;
|
|
1377
|
-
}
|
|
1378
|
-
get recipient() {
|
|
1379
|
-
return this.rawData.config.recipient;
|
|
1380
|
-
}
|
|
1381
|
-
get timeStart() {
|
|
1382
|
-
return roundDateTime(this.rawData.config.timeStart);
|
|
1383
|
-
}
|
|
1384
|
-
get duration() {
|
|
1385
|
-
const rawConfig = this.rawData.config;
|
|
1386
|
-
const duration = rawConfig.epochInterval * rawConfig.totalEpoch;
|
|
1387
|
-
return roundDuration(duration);
|
|
1388
|
-
}
|
|
1389
|
-
get timeEnd() {
|
|
1390
|
-
return this.timeStart.plus(this.duration);
|
|
1391
|
-
}
|
|
1392
|
-
get totalSteps() {
|
|
1393
|
-
return this.rawData.config.totalEpoch;
|
|
1394
|
-
}
|
|
1395
|
-
get claimable() {
|
|
1396
|
-
return this.streamedAmount - this.claimedAmount;
|
|
1397
|
-
}
|
|
1398
|
-
get nextReleaseDate() {
|
|
1399
|
-
if (this.currentEpoch === -1n) {
|
|
1400
|
-
return this.timeStart;
|
|
1401
|
-
}
|
|
1402
|
-
if (this.currentEpoch >= this.totalSteps || this.isCanceled) {
|
|
1403
|
-
return null;
|
|
1404
|
-
}
|
|
1405
|
-
return roundDateTime((this.currentEpoch + 1n) * this.rawData.config.epochInterval + this.rawData.config.timeStart);
|
|
1406
|
-
}
|
|
1407
|
-
get nextReleaseAmount() {
|
|
1408
|
-
if (this.currentEpoch === -1n) {
|
|
1409
|
-
return this.cliff;
|
|
1410
|
-
}
|
|
1411
|
-
if (this.currentEpoch >= this.totalSteps || this.isCanceled) {
|
|
1412
|
-
return null;
|
|
1413
|
-
}
|
|
1414
|
-
return this.amountPerEpoch;
|
|
1415
|
-
}
|
|
1416
|
-
get streamStatus() {
|
|
1417
|
-
const rawStatus = this.rawData.status.status;
|
|
1418
|
-
if (rawStatus === 16 /* CANCELED */) {
|
|
1419
|
-
return "CANCELED" /* CANCELED */;
|
|
1420
|
-
}
|
|
1421
|
-
if (rawStatus === 17 /* CANCELED_COMPLETED */) {
|
|
1422
|
-
return "SETTLED" /* SETTLED */;
|
|
1423
|
-
}
|
|
1424
|
-
if (rawStatus === 1 /* COMPLETED */) {
|
|
1425
|
-
return "COMPLETED" /* COMPLETED */;
|
|
1426
|
-
}
|
|
1427
|
-
if (this.currentEpoch >= this.totalSteps) {
|
|
1428
|
-
return "STREAMED" /* STREAMED */;
|
|
1429
|
-
}
|
|
1430
|
-
return "STREAMING" /* STREAMING */;
|
|
1431
|
-
}
|
|
1432
|
-
get streamedAmount() {
|
|
1433
|
-
if (this.currentEpoch === -1n) {
|
|
1434
|
-
return 0n;
|
|
1435
|
-
}
|
|
1436
|
-
if (this.isCanceled) {
|
|
1437
|
-
return this.rawData.status.epochCanceled * this.amountPerEpoch + this.cliff;
|
|
1438
|
-
}
|
|
1439
|
-
return this.currentEpoch * this.amountPerEpoch + this.cliff;
|
|
1440
|
-
}
|
|
1441
|
-
get claimedAmount() {
|
|
1442
|
-
if (this.rawData.status.epochClaimed === MAX_U64) {
|
|
1443
|
-
return 0n;
|
|
1444
|
-
}
|
|
1445
|
-
return this.rawData.status.epochClaimed * this.amountPerEpoch + this.cliff;
|
|
1446
|
-
}
|
|
1447
|
-
get currentEpoch() {
|
|
1448
|
-
const timeNowMs = import_luxon3.DateTime.now().toMillis();
|
|
1449
|
-
const timeStartMs = this.timeStart.toMillis();
|
|
1450
|
-
if (timeNowMs < timeStartMs) {
|
|
1451
|
-
return -1n;
|
|
1452
|
-
}
|
|
1453
|
-
const epoch = Math.floor((timeNowMs - timeStartMs) / Number(this.rawData.config.epochInterval));
|
|
1454
|
-
return BigInt(epoch) > Number(this.rawData.config.totalEpoch) ? this.rawData.config.totalEpoch : BigInt(epoch);
|
|
1455
|
-
}
|
|
1456
|
-
get totalAmount() {
|
|
1457
|
-
const rawConfig = this.rawData.config;
|
|
1458
|
-
return rawConfig.amountPerEpoch * rawConfig.totalEpoch + rawConfig.cliff;
|
|
1459
|
-
}
|
|
1460
|
-
get isCanceled() {
|
|
1461
|
-
const rawStatus = this.rawData.status.status;
|
|
1462
|
-
return rawStatus === 16 /* CANCELED */ || rawStatus === 17 /* CANCELED_COMPLETED */;
|
|
1463
|
-
}
|
|
1464
|
-
get canceledAmount() {
|
|
1465
|
-
return this.isCanceled ? this.totalAmount - this.streamedAmount : 0n;
|
|
1466
|
-
}
|
|
1467
|
-
static async fetchStreamData(globals, streamId) {
|
|
1468
|
-
const res = await globals.suiClient.getObject({
|
|
1469
|
-
id: streamId,
|
|
1470
|
-
options: {
|
|
1471
|
-
showContent: true,
|
|
1472
|
-
showType: true
|
|
1473
|
-
}
|
|
1474
|
-
});
|
|
1475
|
-
return _Stream.parseRawStreamData(streamId, res);
|
|
1476
|
-
}
|
|
1477
|
-
static parseRawStreamData(streamId, res) {
|
|
1478
|
-
if (res.error) {
|
|
1479
|
-
if (res.error.code === "notExists") {
|
|
1480
|
-
throw new StreamNotFoundError(streamId);
|
|
1481
|
-
}
|
|
1482
|
-
throw new RpcError(`get stream data: ${res.error.code}`, {
|
|
1483
|
-
streamId,
|
|
1484
|
-
...res.error
|
|
1485
|
-
});
|
|
1486
|
-
}
|
|
1487
|
-
const content = res.data.content;
|
|
1488
|
-
if (content.dataType !== "moveObject") {
|
|
1489
|
-
throw new RpcError("Unexpected object type", {
|
|
1490
|
-
gotType: content.dataType
|
|
1491
|
-
});
|
|
1492
|
-
}
|
|
1493
|
-
const { typeParams } = (0, import_utils6.parseStructTag)(content.type);
|
|
1494
|
-
const coinType = (0, import_utils6.normalizeStructTag)(typeParams[0]);
|
|
1495
|
-
const dataFields = content.fields;
|
|
1496
|
-
const config = dataFields.config.fields;
|
|
1497
|
-
const status3 = dataFields.status.fields;
|
|
1498
|
-
return {
|
|
1499
|
-
coinType,
|
|
1500
|
-
autoClaim: dataFields.auto_claim,
|
|
1501
|
-
balance: BigInt(dataFields.balance.fields.balance),
|
|
1502
|
-
config: {
|
|
1503
|
-
amountPerEpoch: BigInt(config.amount_per_epoch),
|
|
1504
|
-
cancelable: config.cancelable,
|
|
1505
|
-
cliff: BigInt(config.cliff),
|
|
1506
|
-
creator: config.creator,
|
|
1507
|
-
epochInterval: BigInt(config.epoch_interval),
|
|
1508
|
-
metadata: config.metadata,
|
|
1509
|
-
recipient: config.recipient,
|
|
1510
|
-
timeStart: BigInt(config.time_start),
|
|
1511
|
-
totalEpoch: BigInt(config.total_epoch)
|
|
1512
|
-
},
|
|
1513
|
-
status: {
|
|
1514
|
-
status: status3.status,
|
|
1515
|
-
epochCanceled: BigInt(status3.epoch_canceled),
|
|
1516
|
-
epochClaimed: BigInt(status3.epoch_claimed)
|
|
1517
|
-
}
|
|
1518
|
-
};
|
|
1519
|
-
}
|
|
1520
|
-
};
|
|
1521
|
-
|
|
1522
|
-
// src/apps/mpay/error/InvalidStreamGroupError.ts
|
|
1523
|
-
var InvalidStreamGroupError = class extends MPayError {
|
|
1524
|
-
constructor(msg, context) {
|
|
1525
|
-
super(9 /* InvalidStreamGroup */, `Invalid stream group: ${msg}`, { context });
|
|
1526
|
-
}
|
|
1527
|
-
};
|
|
1528
|
-
|
|
1529
|
-
// src/apps/mpay/sui/iterator/iterator.ts
|
|
1530
|
-
async function getAllFromIterator(it) {
|
|
1531
|
-
const res = [];
|
|
1532
|
-
while (await it.hasNext()) {
|
|
1533
|
-
const val = await it.next();
|
|
1534
|
-
res.push(val);
|
|
1535
|
-
}
|
|
1536
|
-
if (res && Array.isArray(res[0])) {
|
|
1537
|
-
return res.flat(1);
|
|
1538
|
-
}
|
|
1539
|
-
return res;
|
|
1540
|
-
}
|
|
1541
|
-
var PagedIterator = class {
|
|
1542
|
-
constructor(requester) {
|
|
1543
|
-
this.requester = requester;
|
|
1544
|
-
this.curPage = void 0;
|
|
1545
|
-
this.init = true;
|
|
1546
|
-
}
|
|
1547
|
-
curPage;
|
|
1548
|
-
init;
|
|
1549
|
-
async hasNext() {
|
|
1550
|
-
if (this.init) {
|
|
1551
|
-
if (!this.curPage) {
|
|
1552
|
-
this.curPage = await this.requester.doNextRequest();
|
|
1553
|
-
}
|
|
1554
|
-
return !!this.curPage.data?.length || this.curPage.hasNext;
|
|
1555
|
-
}
|
|
1556
|
-
if (!this.curPage) {
|
|
1557
|
-
throw new Error("invalid implementation of iterator");
|
|
1558
|
-
}
|
|
1559
|
-
return this.curPage.hasNext;
|
|
1560
|
-
}
|
|
1561
|
-
async next() {
|
|
1562
|
-
if (this.init) {
|
|
1563
|
-
this.init = false;
|
|
1564
|
-
if (!this.curPage) {
|
|
1565
|
-
this.curPage = await this.requester.doNextRequest();
|
|
1566
|
-
}
|
|
1567
|
-
return this.curPage.data;
|
|
1568
|
-
}
|
|
1569
|
-
this.curPage = await this.requester.doNextRequest();
|
|
1570
|
-
return this.curPage.data;
|
|
1571
|
-
}
|
|
1572
|
-
};
|
|
1573
|
-
var EntryIterator = class {
|
|
1574
|
-
constructor(requester) {
|
|
1575
|
-
this.requester = requester;
|
|
1576
|
-
this.pager = new PagedIterator(requester);
|
|
1577
|
-
this.curData = [];
|
|
1578
|
-
this.cursor = 0;
|
|
1579
|
-
}
|
|
1580
|
-
cursor;
|
|
1581
|
-
pager;
|
|
1582
|
-
curData;
|
|
1583
|
-
async hasNext() {
|
|
1584
|
-
if (this.cursor < this.curData.length - 1) {
|
|
1585
|
-
return true;
|
|
1586
|
-
}
|
|
1587
|
-
return this.pager.hasNext();
|
|
1588
|
-
}
|
|
1589
|
-
async next() {
|
|
1590
|
-
this.cursor += 1;
|
|
1591
|
-
while (this.cursor >= this.curData.length) {
|
|
1592
|
-
if (!await this.pager.hasNext()) {
|
|
1593
|
-
throw new Error("not more data");
|
|
1594
|
-
} else {
|
|
1595
|
-
this.curData = await this.pager.next();
|
|
1596
|
-
this.cursor = 0;
|
|
1597
|
-
}
|
|
1598
|
-
}
|
|
1599
|
-
return this.curData[this.cursor];
|
|
1600
|
-
}
|
|
1601
|
-
};
|
|
1602
|
-
|
|
1603
|
-
// src/apps/mpay/sui/iterator/object.ts
|
|
1604
|
-
var REQUEST_PAGE_SIZE = 25;
|
|
1605
|
-
async function getObjectsById(suiClient, ids, options) {
|
|
1606
|
-
const oidIter = new ListOidIterator(ids);
|
|
1607
|
-
const iter = new ObjectBatchIterator(suiClient, oidIter, options);
|
|
1608
|
-
return await getAllFromIterator(iter);
|
|
1609
|
-
}
|
|
1610
|
-
var ListOidIterator = class {
|
|
1611
|
-
constructor(ids) {
|
|
1612
|
-
this.ids = ids;
|
|
1613
|
-
this.cursor = -1;
|
|
1614
|
-
}
|
|
1615
|
-
cursor;
|
|
1616
|
-
async hasNext() {
|
|
1617
|
-
return this.cursor < this.ids.length - 1;
|
|
1618
|
-
}
|
|
1619
|
-
async next() {
|
|
1620
|
-
this.cursor += 1;
|
|
1621
|
-
if (this.cursor >= this.ids.length) {
|
|
1622
|
-
throw new Error("invalid iterator implementation");
|
|
1623
|
-
}
|
|
1624
|
-
return this.ids[this.cursor];
|
|
1625
|
-
}
|
|
1626
|
-
};
|
|
1627
|
-
var ObjectBatchIterator = class extends EntryIterator {
|
|
1628
|
-
constructor(suiClient, idIter, options) {
|
|
1629
|
-
super(new ObjectBatchRequester(suiClient, idIter, options));
|
|
1630
|
-
this.suiClient = suiClient;
|
|
1631
|
-
this.idIter = idIter;
|
|
1632
|
-
this.options = options;
|
|
1633
|
-
}
|
|
1634
|
-
};
|
|
1635
|
-
var ObjectBatchRequester = class {
|
|
1636
|
-
constructor(suiClient, stringIter, options) {
|
|
1637
|
-
this.suiClient = suiClient;
|
|
1638
|
-
this.stringIter = stringIter;
|
|
1639
|
-
this.options = options;
|
|
1640
|
-
this.filter = options?.filter;
|
|
1641
|
-
this.pageSize = options?.pageSize || REQUEST_PAGE_SIZE;
|
|
1642
|
-
this.objectOptions = options?.objectOptions || {
|
|
1643
|
-
showType: true,
|
|
1644
|
-
showContent: true
|
|
1645
|
-
};
|
|
1646
|
-
}
|
|
1647
|
-
filter;
|
|
1648
|
-
pageSize;
|
|
1649
|
-
objectOptions;
|
|
1650
|
-
async doNextRequest() {
|
|
1651
|
-
const requestPage = [];
|
|
1652
|
-
while (requestPage.length < this.pageSize) {
|
|
1653
|
-
const hasNext = await this.stringIter.hasNext();
|
|
1654
|
-
if (!hasNext) {
|
|
1655
|
-
break;
|
|
1656
|
-
}
|
|
1657
|
-
const objId = await this.stringIter.next();
|
|
1658
|
-
if (objId) {
|
|
1659
|
-
requestPage.push(objId);
|
|
1660
|
-
}
|
|
1661
|
-
}
|
|
1662
|
-
const res = await this.suiClient.multiGetObjects({
|
|
1663
|
-
ids: requestPage,
|
|
1664
|
-
options: this.objectOptions
|
|
1665
|
-
});
|
|
1666
|
-
let filtered;
|
|
1667
|
-
if (this.filter) {
|
|
1668
|
-
const { filter } = this;
|
|
1669
|
-
filtered = res.filter((r) => filter?.(r));
|
|
1670
|
-
} else {
|
|
1671
|
-
filtered = res;
|
|
1672
|
-
}
|
|
1673
|
-
return {
|
|
1674
|
-
data: filtered,
|
|
1675
|
-
hasNext: await this.stringIter.hasNext()
|
|
1676
|
-
};
|
|
1677
|
-
}
|
|
1678
|
-
};
|
|
1679
|
-
|
|
1680
|
-
// src/apps/mpay/stream/StreamGroup.ts
|
|
1681
|
-
var StreamGroup = class _StreamGroup {
|
|
1682
|
-
constructor(globals, streams) {
|
|
1683
|
-
this.globals = globals;
|
|
1684
|
-
this.streams = streams;
|
|
1685
|
-
if (streams.length === 0) {
|
|
1686
|
-
throw new InvalidStreamGroupError("stream size 0");
|
|
1687
|
-
}
|
|
1688
|
-
const gids = streams.map((st) => st.groupId);
|
|
1689
|
-
const set = new Set(gids);
|
|
1690
|
-
if (set.size !== 1) {
|
|
1691
|
-
throw new InvalidInputError("Stream does not have same group ID");
|
|
1692
|
-
}
|
|
1693
|
-
}
|
|
1694
|
-
type = "StreamGroup";
|
|
1695
|
-
static async new(globals, ids) {
|
|
1696
|
-
const streamObjs = await getObjectsById(globals.suiClient, ids);
|
|
1697
|
-
streamObjs.forEach((obj) => {
|
|
1698
|
-
if (!obj) {
|
|
1699
|
-
throw new SanityError("stream group object data undefined");
|
|
1700
|
-
}
|
|
1701
|
-
});
|
|
1702
|
-
return _StreamGroup.newFromObjectResponse(globals, ids, streamObjs);
|
|
1703
|
-
}
|
|
1704
|
-
static async newFromObjectResponse(globals, ids, responses) {
|
|
1705
|
-
const streams = await _StreamGroup.parseGroupStreams(globals, ids, responses);
|
|
1706
|
-
return new _StreamGroup(globals, streams);
|
|
1707
|
-
}
|
|
1708
|
-
static checkStreamGroup(streams) {
|
|
1709
|
-
const commonInfos = streams.map((stream) => stream.groupCommonInfo);
|
|
1710
|
-
const expInfo = commonInfos[0];
|
|
1711
|
-
let isEqual = true;
|
|
1712
|
-
commonInfos.forEach((info) => {
|
|
1713
|
-
if (!isEqualStreamGroupCommonInfo(expInfo, info)) {
|
|
1714
|
-
isEqual = false;
|
|
1715
|
-
}
|
|
1716
|
-
});
|
|
1717
|
-
return isEqual;
|
|
1718
|
-
}
|
|
1719
|
-
async refresh() {
|
|
1720
|
-
const streamObjs = await getObjectsById(
|
|
1721
|
-
this.globals.suiClient,
|
|
1722
|
-
this.streams.map((stream) => stream.streamId)
|
|
1723
|
-
);
|
|
1724
|
-
this.streams.forEach((stream, i) => {
|
|
1725
|
-
stream.refreshWithData(streamObjs[i]);
|
|
1726
|
-
});
|
|
1727
|
-
}
|
|
1728
|
-
get groupId() {
|
|
1729
|
-
return this.streams[0].groupId;
|
|
1730
|
-
}
|
|
1731
|
-
get creator() {
|
|
1732
|
-
return this.streams[0].creator;
|
|
1733
|
-
}
|
|
1734
|
-
get info() {
|
|
1735
|
-
return {
|
|
1736
|
-
groupId: this.groupId,
|
|
1737
|
-
streamIds: this.streams.map((st) => st.streamId),
|
|
1738
|
-
progress: this.progress,
|
|
1739
|
-
name: this.streams[0].name,
|
|
1740
|
-
creator: this.creator,
|
|
1741
|
-
coinType: this.streams[0].coinType,
|
|
1742
|
-
totalAmount: this.streams.reduce((sum, st) => sum + st.totalAmount, 0n),
|
|
1743
|
-
start: this.streams[0].timeStart,
|
|
1744
|
-
end: this.streams[0].timeEnd,
|
|
1745
|
-
cancelable: this.streams[0].cancelable,
|
|
1746
|
-
cliffAmount: this.streams.reduce((sum, st) => sum + st.cliff, 0n),
|
|
1747
|
-
duration: this.streams[0].duration,
|
|
1748
|
-
interval: this.streams[0].interval,
|
|
1749
|
-
steps: this.streams[0].totalSteps,
|
|
1750
|
-
nextReleaseAmount: this.streams.reduce((sum, st) => {
|
|
1751
|
-
if (st.nextReleaseAmount === null) {
|
|
1752
|
-
return sum;
|
|
1753
|
-
}
|
|
1754
|
-
return sum + st.nextReleaseAmount;
|
|
1755
|
-
}, 0n),
|
|
1756
|
-
nextReleaseDate: this.streams[0].nextReleaseDate
|
|
1757
|
-
};
|
|
1758
|
-
}
|
|
1759
|
-
get progress() {
|
|
1760
|
-
return {
|
|
1761
|
-
total: this.streams.reduce((sum, st) => sum + st.totalAmount, 0n),
|
|
1762
|
-
streamed: this.streams.reduce((sum, st) => sum + st.streamedAmount, 0n),
|
|
1763
|
-
claimed: this.streams.reduce((sum, st) => sum + st.claimedAmount, 0n),
|
|
1764
|
-
claimable: this.streams.reduce((sum, st) => sum + st.claimable, 0n),
|
|
1765
|
-
canceled: this.streams.reduce((sum, st) => sum + st.canceledAmount, 0n)
|
|
1766
|
-
};
|
|
1767
|
-
}
|
|
1768
|
-
async historyEvents(pagination) {
|
|
1769
|
-
return this.globals.backend.getStreamHistory({
|
|
1770
|
-
groupId: this.groupId,
|
|
1771
|
-
pagination
|
|
1772
|
-
});
|
|
1773
|
-
}
|
|
1774
|
-
static async parseGroupStreams(globals, ids, responses) {
|
|
1775
|
-
const streams = responses.map((obj, i) => Stream.fromObjectData(globals, ids[i], obj)).filter((stream) => !!stream);
|
|
1776
|
-
if (new Set(streams.map((st) => st.groupId)).size !== 1) {
|
|
1777
|
-
throw new InvalidStreamGroupError("Not same group ID");
|
|
1778
|
-
}
|
|
1779
|
-
if (!this.checkStreamGroup(streams)) {
|
|
1780
|
-
throw new InvalidStreamGroupError("Not same stream settings");
|
|
1781
|
-
}
|
|
1782
|
-
return streams;
|
|
1783
|
-
}
|
|
1784
|
-
};
|
|
1785
|
-
function isEqualStreamGroupCommonInfo(info1, info2) {
|
|
1786
|
-
return info1.name === info2.name && info1.groupId === info2.groupId && info1.creator === info2.creator && info1.start.toMillis() === info2.start.toMillis() && info1.interval.toMillis() === info2.interval.toMillis() && info1.steps === info2.steps && info1.cancelable === info2.cancelable;
|
|
1787
|
-
}
|
|
1788
|
-
|
|
1789
|
-
// src/apps/mpay/stream/query.ts
|
|
1790
|
-
var PagedStreamListIterator = class _PagedStreamListIterator {
|
|
1791
|
-
constructor(it, pageSize) {
|
|
1792
|
-
this.it = it;
|
|
1793
|
-
this.pageSize = pageSize;
|
|
1794
|
-
}
|
|
1795
|
-
static async newIncoming(input) {
|
|
1796
|
-
const it = await StreamListIterator.newIncoming(input);
|
|
1797
|
-
return new _PagedStreamListIterator(it, input.pageSize);
|
|
1798
|
-
}
|
|
1799
|
-
static async newOutgoing(input) {
|
|
1800
|
-
const it = await StreamListIterator.newOutgoing(input);
|
|
1801
|
-
return new _PagedStreamListIterator(it, input.pageSize);
|
|
1802
|
-
}
|
|
1803
|
-
async hasNext() {
|
|
1804
|
-
return this.it.hasNext();
|
|
1805
|
-
}
|
|
1806
|
-
async next() {
|
|
1807
|
-
const res = [];
|
|
1808
|
-
while (res.length < this.pageSize && await this.it.hasNext()) {
|
|
1809
|
-
res.push(await this.it.next());
|
|
1810
|
-
}
|
|
1811
|
-
return res;
|
|
1812
|
-
}
|
|
1813
|
-
};
|
|
1814
|
-
var StreamListIterator = class _StreamListIterator {
|
|
1815
|
-
constructor(requester) {
|
|
1816
|
-
this.requester = requester;
|
|
1817
|
-
}
|
|
1818
|
-
cachedNext;
|
|
1819
|
-
static async newIncoming(input) {
|
|
1820
|
-
const requester = await StreamListRequester.newIncomingQuery(input);
|
|
1821
|
-
return new _StreamListIterator(requester);
|
|
1822
|
-
}
|
|
1823
|
-
static async newOutgoing(input) {
|
|
1824
|
-
const requester = await StreamListRequester.newOutgoingQuery(input);
|
|
1825
|
-
return new _StreamListIterator(requester);
|
|
1826
|
-
}
|
|
1827
|
-
async hasNext() {
|
|
1828
|
-
if (this.cachedNext === void 0) {
|
|
1829
|
-
this.cachedNext = await this.requester.doNextRequest();
|
|
1830
|
-
}
|
|
1831
|
-
return this.cachedNext !== null;
|
|
1832
|
-
}
|
|
1833
|
-
async next() {
|
|
1834
|
-
if (this.cachedNext === void 0) {
|
|
1835
|
-
const res2 = await this.requester.doNextRequest();
|
|
1836
|
-
if (res2 === null) {
|
|
1837
|
-
throw new SanityError("No more results");
|
|
1838
|
-
}
|
|
1839
|
-
return res2;
|
|
1840
|
-
}
|
|
1841
|
-
const res = this.cachedNext;
|
|
1842
|
-
this.cachedNext = void 0;
|
|
1843
|
-
if (res === null) {
|
|
1844
|
-
throw new SanityError("No more results");
|
|
1845
|
-
}
|
|
1846
|
-
return res;
|
|
1847
|
-
}
|
|
1848
|
-
};
|
|
1849
|
-
var StreamListRequester = class _StreamListRequester {
|
|
1850
|
-
constructor(globals, recipient, groupRefs, query) {
|
|
1851
|
-
this.globals = globals;
|
|
1852
|
-
this.recipient = recipient;
|
|
1853
|
-
this.groupRefs = groupRefs;
|
|
1854
|
-
this.query = query;
|
|
1855
|
-
this.current = 0;
|
|
1856
|
-
const oidIter = new ListOidIterator(groupRefs.flat().map((ref) => ref.streamId));
|
|
1857
|
-
this.objectIter = new ObjectBatchIterator(globals.suiClient, oidIter);
|
|
1858
|
-
}
|
|
1859
|
-
current = 0;
|
|
1860
|
-
objectIter;
|
|
1861
|
-
static async newIncomingQuery(input) {
|
|
1862
|
-
const backendQuery = convertToIncomingBackendQuery(input.query);
|
|
1863
|
-
const recipient = await input.globals.walletAddress();
|
|
1864
|
-
const refs = await input.globals.backend.getIncomingStreams(recipient, backendQuery);
|
|
1865
|
-
const filtered = refs.filter((ref) => (0, import_utils8.normalizeSuiAddress)(ref.recipient) === (0, import_utils8.normalizeSuiAddress)(recipient));
|
|
1866
|
-
const groupedRefs = groupAndSortRefs(filtered);
|
|
1867
|
-
return new _StreamListRequester(input.globals, recipient, groupedRefs, input.query);
|
|
1868
|
-
}
|
|
1869
|
-
static async newOutgoingQuery(input) {
|
|
1870
|
-
const backendQuery = convertToOutgoingBackendQuery(input.query);
|
|
1871
|
-
const sender = await input.globals.walletAddress();
|
|
1872
|
-
const refs = await input.globals.backend.getOutgoingStreams(sender, backendQuery);
|
|
1873
|
-
const groupedRefs = groupAndSortRefs(refs);
|
|
1874
|
-
return new _StreamListRequester(input.globals, sender, groupedRefs, input.query);
|
|
1875
|
-
}
|
|
1876
|
-
async doNextRequest() {
|
|
1877
|
-
if (this.current >= this.groupRefs.length) {
|
|
1878
|
-
return null;
|
|
1879
|
-
}
|
|
1880
|
-
const stRefs = this.groupRefs[this.current];
|
|
1881
|
-
if (stRefs.length === 1) {
|
|
1882
|
-
const stream = await getStreamFromIterator(this.globals, stRefs[0].streamId, this.objectIter);
|
|
1883
|
-
this.current++;
|
|
1884
|
-
return isStreamOfQuery(stream, this.query) ? stream : this.doNextRequest();
|
|
1885
|
-
}
|
|
1886
|
-
if (stRefs.length > 1) {
|
|
1887
|
-
const sg = await getStreamGroupFromIterator(
|
|
1888
|
-
this.globals,
|
|
1889
|
-
stRefs.map((ref) => ref.streamId),
|
|
1890
|
-
this.objectIter
|
|
1891
|
-
);
|
|
1892
|
-
this.current++;
|
|
1893
|
-
return isStreamGroupOfQuery(sg, this.query) ? sg : this.doNextRequest();
|
|
1894
|
-
}
|
|
1895
|
-
throw new SanityError("Stream group with no stream");
|
|
1896
|
-
}
|
|
1897
|
-
};
|
|
1898
|
-
function groupAndSortRefs(refs) {
|
|
1899
|
-
const m = /* @__PURE__ */ new Map();
|
|
1900
|
-
refs.forEach((ref) => {
|
|
1901
|
-
const groupList = m.get(ref.groupId);
|
|
1902
|
-
if (groupList) {
|
|
1903
|
-
groupList.push(ref);
|
|
1904
|
-
m.set(ref.groupId, groupList);
|
|
1905
|
-
} else {
|
|
1906
|
-
m.set(ref.groupId, [ref]);
|
|
1907
|
-
}
|
|
1908
|
-
});
|
|
1909
|
-
return Array.from(m.values()).sort(
|
|
1910
|
-
(gl1, gl2) => import_luxon4.DateTime.fromISO(gl2[0].createDate).toMillis() - import_luxon4.DateTime.fromISO(gl1[0].createDate).toMillis()
|
|
1911
|
-
);
|
|
1912
|
-
}
|
|
1913
|
-
function isStreamOfQuery(stream, query) {
|
|
1914
|
-
if (query === void 0) {
|
|
1915
|
-
return true;
|
|
1916
|
-
}
|
|
1917
|
-
const isStatus = isStreamOfStatus(stream, query.status);
|
|
1918
|
-
if (query && "claimable" in query && query.claimable !== void 0) {
|
|
1919
|
-
const isClaimable = query.claimable ? stream.progress.claimable !== 0n : stream.progress.claimable === 0n;
|
|
1920
|
-
return isStatus && isClaimable;
|
|
1921
|
-
}
|
|
1922
|
-
return isStatus;
|
|
1923
|
-
}
|
|
1924
|
-
function isStreamOfStatus(stream, filter) {
|
|
1925
|
-
if (filter === void 0) {
|
|
1926
|
-
return true;
|
|
1927
|
-
}
|
|
1928
|
-
if (!Array.isArray(filter)) {
|
|
1929
|
-
return stream.progress.status === filter;
|
|
1930
|
-
}
|
|
1931
|
-
return filter.includes(stream.progress.status);
|
|
1932
|
-
}
|
|
1933
|
-
function isStreamGroupOfQuery(sg, query) {
|
|
1934
|
-
if (!query) {
|
|
1935
|
-
return true;
|
|
1936
|
-
}
|
|
1937
|
-
let isStatus = false;
|
|
1938
|
-
sg.streams.forEach((stream) => {
|
|
1939
|
-
if (isStreamOfQuery(stream, query)) {
|
|
1940
|
-
isStatus = true;
|
|
1941
|
-
}
|
|
1942
|
-
});
|
|
1943
|
-
return isStatus;
|
|
1944
|
-
}
|
|
1945
|
-
async function getStreamFromIterator(globals, streamId, it) {
|
|
1946
|
-
const data = await getStreamObjectResponseFromIter(it, streamId);
|
|
1947
|
-
return Stream.fromObjectData(globals, streamId, data);
|
|
1948
|
-
}
|
|
1949
|
-
async function getStreamGroupFromIterator(globals, streamIds, it) {
|
|
1950
|
-
const objResponses = [];
|
|
1951
|
-
while (objResponses.length < streamIds.length) {
|
|
1952
|
-
const data = await getStreamObjectResponseFromIter(it, streamIds[objResponses.length]);
|
|
1953
|
-
objResponses.push(data);
|
|
1954
|
-
}
|
|
1955
|
-
return StreamGroup.newFromObjectResponse(globals, streamIds, objResponses);
|
|
1956
|
-
}
|
|
1957
|
-
async function getStreamObjectResponseFromIter(it, streamId) {
|
|
1958
|
-
if (!await it.hasNext()) {
|
|
1959
|
-
throw new SanityError("object iterator has been consumed");
|
|
1960
|
-
}
|
|
1961
|
-
const data = await it.next();
|
|
1962
|
-
if (!data || data.error || data.data === void 0 || data.data === null) {
|
|
1963
|
-
throw new SanityError(`object iterator undefined response`, {
|
|
1964
|
-
cause: data?.error
|
|
1965
|
-
});
|
|
1966
|
-
}
|
|
1967
|
-
if (data?.data?.objectId !== streamId) {
|
|
1968
|
-
throw new SanityError("stream id not aligned");
|
|
1969
|
-
}
|
|
1970
|
-
return data;
|
|
1971
|
-
}
|
|
1972
|
-
function convertToIncomingBackendQuery(query) {
|
|
1973
|
-
return {
|
|
1974
|
-
status: convertStreamStatus(query?.status),
|
|
1975
|
-
coinType: normalizeCoinTypeFilter(query?.coinType),
|
|
1976
|
-
sender: normalizeAddressFilter(query?.sender)
|
|
1977
|
-
};
|
|
1978
|
-
}
|
|
1979
|
-
function convertToOutgoingBackendQuery(query) {
|
|
1980
|
-
return {
|
|
1981
|
-
status: convertStreamStatus(query?.status),
|
|
1982
|
-
coinType: normalizeCoinTypeFilter(query?.coinType),
|
|
1983
|
-
recipient: normalizeAddressFilter(query?.recipient)
|
|
1984
|
-
};
|
|
1985
|
-
}
|
|
1986
|
-
function convertStreamStatus(status3) {
|
|
1987
|
-
if (status3 === void 0 || status3.length === 0) {
|
|
1988
|
-
return "all";
|
|
1989
|
-
}
|
|
1990
|
-
if (!Array.isArray(status3)) {
|
|
1991
|
-
return convertStreamStatusSingle(status3);
|
|
1992
|
-
}
|
|
1993
|
-
return status3.reduce((res, st) => {
|
|
1994
|
-
const sts = convertStreamStatus(st);
|
|
1995
|
-
if (!res) {
|
|
1996
|
-
return sts;
|
|
1997
|
-
}
|
|
1998
|
-
if (res === sts) {
|
|
1999
|
-
return sts;
|
|
2000
|
-
}
|
|
2001
|
-
return "all";
|
|
2002
|
-
}, void 0);
|
|
2003
|
-
}
|
|
2004
|
-
function convertStreamStatusSingle(status3) {
|
|
2005
|
-
switch (status3) {
|
|
2006
|
-
case "STREAMING":
|
|
2007
|
-
case "STREAMED":
|
|
2008
|
-
case "CANCELED":
|
|
2009
|
-
return "active";
|
|
2010
|
-
case "COMPLETED":
|
|
2011
|
-
case "SETTLED":
|
|
2012
|
-
return "inactive";
|
|
2013
|
-
default:
|
|
2014
|
-
throw new InvalidInputError("Unknown stream filtered status");
|
|
2015
|
-
}
|
|
2016
|
-
}
|
|
2017
|
-
function normalizeCoinTypeFilter(coinType) {
|
|
2018
|
-
if (!coinType) {
|
|
2019
|
-
return void 0;
|
|
2020
|
-
}
|
|
2021
|
-
if (!Array.isArray(coinType)) {
|
|
2022
|
-
return (0, import_utils8.normalizeStructTag)(coinType);
|
|
2023
|
-
}
|
|
2024
|
-
return coinType.length !== 0 ? coinType.map((ct) => (0, import_utils8.normalizeStructTag)(ct)) : void 0;
|
|
2025
|
-
}
|
|
2026
|
-
function normalizeAddressFilter(address) {
|
|
2027
|
-
if (!address) {
|
|
2028
|
-
return void 0;
|
|
2029
|
-
}
|
|
2030
|
-
if (!Array.isArray(address)) {
|
|
2031
|
-
return (0, import_utils8.normalizeSuiAddress)(address);
|
|
2032
|
-
}
|
|
2033
|
-
return address.length !== 0 ? address.map((addr) => (0, import_utils8.normalizeSuiAddress)(addr)) : void 0;
|
|
2034
|
-
}
|
|
2035
|
-
|
|
2036
|
-
// src/apps/mpay/error/NotEnoughBalanceError.ts
|
|
2037
|
-
var NotEnoughBalanceError = class extends MPayError {
|
|
2038
|
-
constructor(coinType, requestAmount, gotAmount) {
|
|
2039
|
-
super(4 /* NotEnoughBalance */, `Not enough balance: ${coinType}`, {
|
|
2040
|
-
context: {
|
|
2041
|
-
coinType,
|
|
2042
|
-
requestAmount,
|
|
2043
|
-
gotAmount
|
|
2044
|
-
}
|
|
2045
|
-
});
|
|
2046
|
-
this.coinType = coinType;
|
|
2047
|
-
this.requestAmount = requestAmount;
|
|
2048
|
-
this.gotAmount = gotAmount;
|
|
2049
|
-
}
|
|
2050
|
-
};
|
|
2051
|
-
|
|
2052
|
-
// src/apps/mpay/sui/iterator/coin.ts
|
|
2053
|
-
var DEF_REQ_PAGE_SIZE = 25;
|
|
2054
|
-
async function getCoinsWithAmount(suiClient, owner, requestAmount, coinType = "0x2::sui::SUI", pageSize = DEF_REQ_PAGE_SIZE) {
|
|
2055
|
-
const it = new OwnedCoinIterator(suiClient, owner, coinType, pageSize);
|
|
2056
|
-
let totalAmount = BigInt(0);
|
|
2057
|
-
const res = [];
|
|
2058
|
-
while (await it.hasNext() && totalAmount < requestAmount) {
|
|
2059
|
-
const val = await it.next();
|
|
2060
|
-
if (!val) {
|
|
2061
|
-
continue;
|
|
2062
|
-
}
|
|
2063
|
-
res.push(val);
|
|
2064
|
-
totalAmount += BigInt(val.balance);
|
|
2065
|
-
}
|
|
2066
|
-
if (totalAmount < requestAmount) {
|
|
2067
|
-
throw new NotEnoughBalanceError(coinType, requestAmount, totalAmount);
|
|
2068
|
-
}
|
|
2069
|
-
return res;
|
|
2070
|
-
}
|
|
2071
|
-
var OwnedCoinIterator = class extends EntryIterator {
|
|
2072
|
-
constructor(suiClient, owner, coinType, reqPageSize) {
|
|
2073
|
-
super(new OwnedCoinRequester(suiClient, owner, coinType, reqPageSize));
|
|
2074
|
-
this.suiClient = suiClient;
|
|
2075
|
-
this.owner = owner;
|
|
2076
|
-
this.coinType = coinType;
|
|
2077
|
-
this.reqPageSize = reqPageSize;
|
|
2078
|
-
}
|
|
2079
|
-
};
|
|
2080
|
-
var OwnedCoinRequester = class {
|
|
2081
|
-
constructor(suiClient, owner, coinType, reqPageSize) {
|
|
2082
|
-
this.suiClient = suiClient;
|
|
2083
|
-
this.owner = owner;
|
|
2084
|
-
this.coinType = coinType;
|
|
2085
|
-
this.reqPageSize = reqPageSize;
|
|
2086
|
-
if (reqPageSize <= 0) {
|
|
2087
|
-
throw new SanityError("Invalid reqPageSize");
|
|
2088
|
-
}
|
|
2089
|
-
}
|
|
2090
|
-
nextCursor;
|
|
2091
|
-
async doNextRequest() {
|
|
2092
|
-
const res = await this.suiClient.getCoins({
|
|
2093
|
-
owner: this.owner,
|
|
2094
|
-
coinType: this.coinType,
|
|
2095
|
-
cursor: this.nextCursor,
|
|
2096
|
-
limit: this.reqPageSize
|
|
2097
|
-
});
|
|
2098
|
-
this.nextCursor = res.nextCursor;
|
|
2099
|
-
return {
|
|
2100
|
-
data: res.data,
|
|
2101
|
-
hasNext: res.hasNextPage
|
|
2102
|
-
};
|
|
2103
|
-
}
|
|
2104
|
-
};
|
|
2105
|
-
|
|
2106
|
-
// src/apps/mpay/stream/client.ts
|
|
2107
|
-
var MSafeAccountAdapter = class {
|
|
2108
|
-
constructor(msafe) {
|
|
2109
|
-
this.msafe = msafe;
|
|
2110
|
-
}
|
|
2111
|
-
get type() {
|
|
2112
|
-
return "msafe" /* msafe */;
|
|
2113
|
-
}
|
|
2114
|
-
async address() {
|
|
2115
|
-
return this.msafe.address();
|
|
2116
|
-
}
|
|
2117
|
-
async requestCoins(reqs) {
|
|
2118
|
-
return this.msafe.requestCoins(reqs);
|
|
2119
|
-
}
|
|
2120
|
-
};
|
|
2121
|
-
var MSafeSingleWallet = class {
|
|
2122
|
-
constructor(account) {
|
|
2123
|
-
this.account = account;
|
|
2124
|
-
}
|
|
2125
|
-
async address() {
|
|
2126
|
-
return this.account.address;
|
|
2127
|
-
}
|
|
2128
|
-
};
|
|
2129
|
-
var SingleWalletAdapter = class {
|
|
2130
|
-
constructor(singleWallet, suiClient) {
|
|
2131
|
-
this.singleWallet = singleWallet;
|
|
2132
|
-
this.suiClient = suiClient;
|
|
2133
|
-
}
|
|
2134
|
-
get type() {
|
|
2135
|
-
return "single" /* single */;
|
|
2136
|
-
}
|
|
2137
|
-
async address() {
|
|
2138
|
-
return this.singleWallet.address();
|
|
2139
|
-
}
|
|
2140
|
-
async requestCoins(reqs) {
|
|
2141
|
-
return Promise.all(reqs.map((req) => this.requestCoin(req)));
|
|
2142
|
-
}
|
|
2143
|
-
async requestCoin(req) {
|
|
2144
|
-
if (isSameCoinType(req.coinType, import_utils9.SUI_TYPE_ARG)) {
|
|
2145
|
-
return {
|
|
2146
|
-
primaryCoin: GAS_OBJECT_SPEC
|
|
2147
|
-
};
|
|
2148
|
-
}
|
|
2149
|
-
if (req.amount <= 0) {
|
|
2150
|
-
throw new InvalidInputError("Invalid coin request", "coinAmount", req.amount);
|
|
2151
|
-
}
|
|
2152
|
-
const coins = await getCoinsWithAmount(this.suiClient, await this.address(), req.amount, req.coinType);
|
|
2153
|
-
if (coins.length === 0) {
|
|
2154
|
-
throw new SanityError("no coins available");
|
|
2155
|
-
}
|
|
2156
|
-
return {
|
|
2157
|
-
primaryCoin: coins[0].coinObjectId,
|
|
2158
|
-
mergedCoins: coins.slice(1).map((coin) => coin.coinObjectId)
|
|
2159
|
-
};
|
|
2160
|
-
}
|
|
2161
|
-
};
|
|
2162
|
-
var MPayClient = class {
|
|
2163
|
-
globals;
|
|
2164
|
-
helper;
|
|
2165
|
-
constructor(env, options) {
|
|
2166
|
-
this.globals = Globals.new(env, options);
|
|
2167
|
-
this.helper = new MPayHelper(this.globals);
|
|
2168
|
-
}
|
|
2169
|
-
connectSingleWallet(wallet) {
|
|
2170
|
-
const adapter = new SingleWalletAdapter(wallet, this.globals.suiClient);
|
|
2171
|
-
this.globals.connectWallet(adapter);
|
|
2172
|
-
}
|
|
2173
|
-
connectMSafeAccount(msafe) {
|
|
2174
|
-
const adapter = new MSafeAccountAdapter(msafe);
|
|
2175
|
-
this.globals.connectWallet(adapter);
|
|
2176
|
-
}
|
|
2177
|
-
async createStream(info) {
|
|
2178
|
-
return this.builder().createStreams(info);
|
|
2179
|
-
}
|
|
2180
|
-
async getStream(streamId) {
|
|
2181
|
-
return Stream.new(this.globals, streamId);
|
|
2182
|
-
}
|
|
2183
|
-
async getIncomingStreams(query, pageSize = 10) {
|
|
2184
|
-
return PagedStreamListIterator.newIncoming({
|
|
2185
|
-
globals: this.globals,
|
|
2186
|
-
query,
|
|
2187
|
-
pageSize
|
|
2188
|
-
});
|
|
2189
|
-
}
|
|
2190
|
-
async getOutgoingStreams(query, pageSize = 10) {
|
|
2191
|
-
return PagedStreamListIterator.newOutgoing({
|
|
2192
|
-
globals: this.globals,
|
|
2193
|
-
query,
|
|
2194
|
-
pageSize
|
|
2195
|
-
});
|
|
2196
|
-
}
|
|
2197
|
-
async getCoinTypesForStreamFilter() {
|
|
2198
|
-
const address = await this.wallet.address();
|
|
2199
|
-
const coinTypes = await this.globals.backend.getAllCoinTypes(address);
|
|
2200
|
-
return coinTypes.map((coinType) => (0, import_utils9.normalizeStructTag)(coinType));
|
|
2201
|
-
}
|
|
2202
|
-
async getRecipientsForStreamFilter(options) {
|
|
2203
|
-
const address = await this.wallet.address();
|
|
2204
|
-
const recipients = await this.globals.backend.getAllRecipients(address, options);
|
|
2205
|
-
return recipients.map((recipient) => (0, import_utils9.normalizeSuiAddress)(recipient));
|
|
2206
|
-
}
|
|
2207
|
-
async getCreatorsForStreamFilter(options) {
|
|
2208
|
-
const address = await this.wallet.address();
|
|
2209
|
-
const creators = await this.globals.backend.getAllSenders(address, options);
|
|
2210
|
-
return creators.map((creator) => (0, import_utils9.normalizeSuiAddress)(creator));
|
|
2211
|
-
}
|
|
2212
|
-
get wallet() {
|
|
2213
|
-
return this.globals.wallet;
|
|
2214
|
-
}
|
|
2215
|
-
builder() {
|
|
2216
|
-
return new MPayBuilder(this.globals);
|
|
2217
|
-
}
|
|
2218
|
-
};
|
|
2219
|
-
|
|
2220
|
-
// src/apps/mpay/cancel-stream.ts
|
|
2221
|
-
var CancelStreamIntention = class _CancelStreamIntention extends CoreBaseIntention {
|
|
2222
|
-
constructor(data) {
|
|
2223
|
-
super(data);
|
|
2224
|
-
this.data = data;
|
|
2225
|
-
}
|
|
2226
|
-
txType;
|
|
2227
|
-
txSubType;
|
|
2228
|
-
async build(input) {
|
|
2229
|
-
const { network, account } = input;
|
|
2230
|
-
const mpayClient = new MPayClient(network === "sui:mainnet" ? "prod" /* prod */ : "dev" /* dev */);
|
|
2231
|
-
mpayClient.connectSingleWallet(new MSafeSingleWallet(account));
|
|
2232
|
-
const stream = await mpayClient.getStream(this.data.streamId);
|
|
2233
|
-
const txb = await stream.cancel();
|
|
2234
|
-
return txb;
|
|
2235
|
-
}
|
|
2236
|
-
static fromData(data) {
|
|
2237
|
-
return new _CancelStreamIntention(data);
|
|
2238
|
-
}
|
|
2239
|
-
};
|
|
2240
|
-
|
|
2241
|
-
// src/apps/mpay/claim-by-proxy-stream.ts
|
|
2242
|
-
var ClaimByProxyStreamIntention = class _ClaimByProxyStreamIntention extends CoreBaseIntention {
|
|
2243
|
-
constructor(data) {
|
|
2244
|
-
super(data);
|
|
2245
|
-
this.data = data;
|
|
2246
|
-
}
|
|
2247
|
-
txType;
|
|
2248
|
-
txSubType;
|
|
2249
|
-
async build(input) {
|
|
2250
|
-
const { network, account } = input;
|
|
2251
|
-
const mpayClient = new MPayClient(network === "sui:mainnet" ? "prod" /* prod */ : "dev" /* dev */);
|
|
2252
|
-
mpayClient.connectSingleWallet(new MSafeSingleWallet(account));
|
|
2253
|
-
const stream = await mpayClient.getStream(this.data.streamId);
|
|
2254
|
-
const txb = await stream.claimByProxy();
|
|
2255
|
-
return txb;
|
|
2256
|
-
}
|
|
2257
|
-
static fromData(data) {
|
|
2258
|
-
return new _ClaimByProxyStreamIntention(data);
|
|
2259
|
-
}
|
|
2260
|
-
};
|
|
2261
|
-
|
|
2262
|
-
// src/apps/mpay/claim-stream.ts
|
|
2263
|
-
var ClaimStreamIntention = class _ClaimStreamIntention extends CoreBaseIntention {
|
|
2264
|
-
constructor(data) {
|
|
2265
|
-
super(data);
|
|
2266
|
-
this.data = data;
|
|
2267
|
-
}
|
|
2268
|
-
txType;
|
|
2269
|
-
txSubType;
|
|
2270
|
-
async build(input) {
|
|
2271
|
-
const { network, account } = input;
|
|
2272
|
-
const mpayClient = new MPayClient(network === "sui:mainnet" ? "prod" /* prod */ : "dev" /* dev */);
|
|
2273
|
-
mpayClient.connectSingleWallet(new MSafeSingleWallet(account));
|
|
2274
|
-
const stream = await mpayClient.getStream(this.data.streamId);
|
|
2275
|
-
const txb = await stream.claim();
|
|
2276
|
-
return txb;
|
|
2277
|
-
}
|
|
2278
|
-
static fromData(data) {
|
|
2279
|
-
return new _ClaimStreamIntention(data);
|
|
2280
|
-
}
|
|
2281
|
-
};
|
|
2282
|
-
|
|
2283
|
-
// src/apps/mpay/create-stream.ts
|
|
2284
|
-
var CreateStreamIntention = class _CreateStreamIntention extends CoreBaseIntention {
|
|
2285
|
-
constructor(data) {
|
|
2286
|
-
super(data);
|
|
2287
|
-
this.data = data;
|
|
2288
|
-
}
|
|
2289
|
-
txType;
|
|
2290
|
-
txSubType;
|
|
2291
|
-
async build(input) {
|
|
2292
|
-
const { network, account } = input;
|
|
2293
|
-
const mpayClient = new MPayClient(network === "sui:mainnet" ? "prod" /* prod */ : "dev" /* dev */);
|
|
2294
|
-
mpayClient.connectSingleWallet(new MSafeSingleWallet(account));
|
|
2295
|
-
const txb = await mpayClient.createStream(this.data);
|
|
2296
|
-
return txb;
|
|
2297
|
-
}
|
|
2298
|
-
static fromData(data) {
|
|
2299
|
-
return new _CreateStreamIntention(data);
|
|
2300
|
-
}
|
|
2301
|
-
};
|
|
2302
|
-
|
|
2303
|
-
// src/apps/mpay/decoder/create.ts
|
|
2304
|
-
var import_utils12 = require("@mysten/sui.js/utils");
|
|
2305
|
-
|
|
2306
|
-
// src/apps/mpay/decoder/moveCall.ts
|
|
2307
|
-
var import_bcs2 = require("@mysten/sui.js/bcs");
|
|
2308
|
-
var import_utils11 = require("@mysten/sui.js/utils");
|
|
2309
|
-
var MoveCallHelper = class _MoveCallHelper {
|
|
2310
|
-
constructor(moveCall, txb) {
|
|
2311
|
-
this.moveCall = moveCall;
|
|
2312
|
-
this.txb = txb;
|
|
2313
|
-
}
|
|
2314
|
-
decodeSharedObjectId(argIndex) {
|
|
2315
|
-
const input = this.getInputParam(argIndex);
|
|
2316
|
-
return _MoveCallHelper.getSharedObjectId(input);
|
|
2317
|
-
}
|
|
2318
|
-
decodeOwnedObjectId(argIndex) {
|
|
2319
|
-
const input = this.getInputParam(argIndex);
|
|
2320
|
-
return _MoveCallHelper.getOwnedObjectId(input);
|
|
2321
|
-
}
|
|
2322
|
-
decodeInputU64(argIndex) {
|
|
2323
|
-
const strVal = this.decodePureArg(argIndex, "u64");
|
|
2324
|
-
return BigInt(strVal);
|
|
2325
|
-
}
|
|
2326
|
-
decodeInputAddress(argIndex) {
|
|
2327
|
-
const input = this.decodePureArg(argIndex, "address");
|
|
2328
|
-
return (0, import_utils11.normalizeSuiAddress)(input);
|
|
2329
|
-
}
|
|
2330
|
-
decodeInputString(argIndex) {
|
|
2331
|
-
return this.decodePureArg(argIndex, "string");
|
|
2332
|
-
}
|
|
2333
|
-
decodeInputBool(argIndex) {
|
|
2334
|
-
return this.decodePureArg(argIndex, "bool");
|
|
2335
|
-
}
|
|
2336
|
-
decodePureArg(argIndex, bcsType) {
|
|
2337
|
-
const input = this.getInputParam(argIndex);
|
|
2338
|
-
return _MoveCallHelper.getPureInputValue(input, bcsType);
|
|
2339
|
-
}
|
|
2340
|
-
getInputParam(argIndex) {
|
|
2341
|
-
const arg = this.moveCall.arguments[argIndex];
|
|
2342
|
-
if (arg.kind !== "Input") {
|
|
2343
|
-
throw new Error("not input type");
|
|
2344
|
-
}
|
|
2345
|
-
return this.txb.blockData.inputs[arg.index];
|
|
2346
|
-
}
|
|
2347
|
-
static getPureInputValue(input, bcsType) {
|
|
2348
|
-
if (input.type !== "pure") {
|
|
2349
|
-
throw new Error("not pure argument");
|
|
2350
|
-
}
|
|
2351
|
-
if (typeof input.value === "object" && "Pure" in input.value) {
|
|
2352
|
-
const bcsNums = input.value.Pure;
|
|
2353
|
-
return import_bcs2.bcs.de(bcsType, new Uint8Array(bcsNums));
|
|
2354
|
-
}
|
|
2355
|
-
return input.value;
|
|
2356
|
-
}
|
|
2357
|
-
static getOwnedObjectId(input) {
|
|
2358
|
-
if (input.type !== "object") {
|
|
2359
|
-
throw new Error(`not object argument: ${JSON.stringify(input)}`);
|
|
2360
|
-
}
|
|
2361
|
-
if (typeof input.value === "object") {
|
|
2362
|
-
if (!("Object" in input.value) || !("ImmOrOwned" in input.value.Object)) {
|
|
2363
|
-
throw new Error("not ImmOrOwned");
|
|
2364
|
-
}
|
|
2365
|
-
return (0, import_utils11.normalizeSuiAddress)(input.value.Object.ImmOrOwned.objectId);
|
|
2366
|
-
}
|
|
2367
|
-
return (0, import_utils11.normalizeSuiAddress)(input.value);
|
|
2368
|
-
}
|
|
2369
|
-
static getSharedObjectId(input) {
|
|
2370
|
-
if (input.type !== "object") {
|
|
2371
|
-
throw new Error(`not object argument: ${JSON.stringify(input)}`);
|
|
2372
|
-
}
|
|
2373
|
-
if (typeof input.value !== "object") {
|
|
2374
|
-
return (0, import_utils11.normalizeSuiAddress)(input.value);
|
|
2375
|
-
}
|
|
2376
|
-
if (!("Object" in input.value) || !("Shared" in input.value.Object)) {
|
|
2377
|
-
throw new Error("not Shared");
|
|
2378
|
-
}
|
|
2379
|
-
return (0, import_utils11.normalizeSuiAddress)(input.value.Object.Shared.objectId);
|
|
2380
|
-
}
|
|
2381
|
-
static getPureInput(input, bcsType) {
|
|
2382
|
-
if (input.type !== "pure") {
|
|
2383
|
-
throw new Error("not pure argument");
|
|
2384
|
-
}
|
|
2385
|
-
if (typeof input.value !== "object") {
|
|
2386
|
-
return input.value;
|
|
2387
|
-
}
|
|
2388
|
-
if (!("Pure" in input.value)) {
|
|
2389
|
-
throw new Error("Pure not in value");
|
|
2390
|
-
}
|
|
2391
|
-
const bcsVal = input.value.Pure;
|
|
2392
|
-
return import_bcs2.bcs.de(bcsType, new Uint8Array(bcsVal));
|
|
2393
|
-
}
|
|
2394
|
-
typeArg(index) {
|
|
2395
|
-
return (0, import_utils11.normalizeStructTag)(this.moveCall.typeArguments[index]);
|
|
2396
|
-
}
|
|
2397
|
-
txArg(index) {
|
|
2398
|
-
return this.moveCall.arguments[index];
|
|
2399
|
-
}
|
|
2400
|
-
};
|
|
2401
|
-
|
|
2402
|
-
// src/apps/mpay/decoder/create.ts
|
|
2403
|
-
var CreateStreamDecodeHelper = class {
|
|
2404
|
-
constructor(globals, txb) {
|
|
2405
|
-
this.globals = globals;
|
|
2406
|
-
this.txb = txb;
|
|
2407
|
-
}
|
|
2408
|
-
decode() {
|
|
2409
|
-
const streamInfo = this.decodeCreateStreamInfo();
|
|
2410
|
-
const fees = this.createStreamHelper().calculateCreateStreamFees(streamInfo);
|
|
2411
|
-
const coinMerges = this.getCoinMerges();
|
|
2412
|
-
return {
|
|
2413
|
-
type: "CreateStream" /* CREATE_STREAM */,
|
|
2414
|
-
info: streamInfo,
|
|
2415
|
-
fees,
|
|
2416
|
-
coinMerges
|
|
2417
|
-
};
|
|
2418
|
-
}
|
|
2419
|
-
decodeCreateStreamInfo() {
|
|
2420
|
-
const moveCalls = this.createStreamTransactions();
|
|
2421
|
-
const infos = moveCalls.map((moveCall) => this.getCreationInfoFromMoveCall(moveCall));
|
|
2422
|
-
return this.aggregateGroupStreamInfo(infos);
|
|
2423
|
-
}
|
|
2424
|
-
createStreamTransactions() {
|
|
2425
|
-
const txs = this.transactions.filter(
|
|
2426
|
-
(tx) => tx.kind === "MoveCall" && isSameTarget(tx.target, this.contract.createStreamTarget)
|
|
2427
|
-
);
|
|
2428
|
-
if (txs.length === 0) {
|
|
2429
|
-
throw new SanityError("No create stream transactions");
|
|
2430
|
-
}
|
|
2431
|
-
return txs.map((tx) => new MoveCallHelper(tx, this.txb));
|
|
2432
|
-
}
|
|
2433
|
-
getCreationInfoFromMoveCall(moveCall) {
|
|
2434
|
-
const metadata = moveCall.decodeInputString(4);
|
|
2435
|
-
const { name, groupId } = decodeMetadata(metadata);
|
|
2436
|
-
const recipient = moveCall.decodeInputAddress(5);
|
|
2437
|
-
const timeStart = moveCall.decodeInputU64(6);
|
|
2438
|
-
const cliff = moveCall.decodeInputU64(7);
|
|
2439
|
-
const epochInterval = moveCall.decodeInputU64(8);
|
|
2440
|
-
const totalEpoch = moveCall.decodeInputU64(9);
|
|
2441
|
-
const amountPerEpoch = moveCall.decodeInputU64(10);
|
|
2442
|
-
const cancelable = moveCall.decodeInputBool(11);
|
|
2443
|
-
const coinType = moveCall.typeArg(0);
|
|
2444
|
-
return {
|
|
2445
|
-
name,
|
|
2446
|
-
groupId,
|
|
2447
|
-
recipient,
|
|
2448
|
-
timeStart,
|
|
2449
|
-
cliff,
|
|
2450
|
-
epochInterval,
|
|
2451
|
-
totalEpoch,
|
|
2452
|
-
amountPerEpoch,
|
|
2453
|
-
cancelable,
|
|
2454
|
-
coinType
|
|
2455
|
-
};
|
|
2456
|
-
}
|
|
2457
|
-
aggregateGroupStreamInfo(infos) {
|
|
2458
|
-
const commonInfoSet = new Set(
|
|
2459
|
-
infos.map(
|
|
2460
|
-
(info) => JSON.stringify({
|
|
2461
|
-
name: info.name,
|
|
2462
|
-
groupId: info.groupId,
|
|
2463
|
-
timeStart: String(info.timeStart),
|
|
2464
|
-
epochInterval: String(info.epochInterval),
|
|
2465
|
-
totalEpoch: String(info.totalEpoch),
|
|
2466
|
-
cancelable: info.cancelable,
|
|
2467
|
-
coinType: info.coinType
|
|
2468
|
-
})
|
|
2469
|
-
)
|
|
2470
|
-
);
|
|
2471
|
-
if (commonInfoSet.size !== 1) {
|
|
2472
|
-
throw new InvalidInputError("Stream group not have common info");
|
|
2473
|
-
}
|
|
2474
|
-
const recipients = infos.map((info) => ({
|
|
2475
|
-
address: info.recipient,
|
|
2476
|
-
amountPerStep: info.amountPerEpoch,
|
|
2477
|
-
cliffAmount: info.cliff
|
|
2478
|
-
}));
|
|
2479
|
-
return {
|
|
2480
|
-
name: infos[0].name,
|
|
2481
|
-
coinType: infos[0].coinType,
|
|
2482
|
-
recipients,
|
|
2483
|
-
interval: infos[0].epochInterval,
|
|
2484
|
-
steps: infos[0].totalEpoch,
|
|
2485
|
-
startTimeMs: infos[0].timeStart,
|
|
2486
|
-
cancelable: infos[0].cancelable
|
|
2487
|
-
};
|
|
2488
|
-
}
|
|
2489
|
-
getCoinMerges() {
|
|
2490
|
-
const createStreamTx = this.createStreamTransactions()[0];
|
|
2491
|
-
return this.getCoinMergeForCreateStream(createStreamTx);
|
|
2492
|
-
}
|
|
2493
|
-
getCoinMergeForCreateStream(moveCall) {
|
|
2494
|
-
const coinType = moveCall.typeArg(0);
|
|
2495
|
-
const paymentCoin = moveCall.txArg(2);
|
|
2496
|
-
const paymentCoinMerge = this.getCoinMergeFromNestedResult(paymentCoin, coinType, moveCall);
|
|
2497
|
-
if (coinType === (0, import_utils12.normalizeStructTag)(import_utils12.SUI_TYPE_ARG)) {
|
|
2498
|
-
return [paymentCoinMerge];
|
|
2499
|
-
}
|
|
2500
|
-
const flatFeeCoin = moveCall.txArg(3);
|
|
2501
|
-
const flatCoinMerge = this.getCoinMergeFromNestedResult(flatFeeCoin, (0, import_utils12.normalizeStructTag)(import_utils12.SUI_TYPE_ARG), moveCall);
|
|
2502
|
-
return [paymentCoinMerge, flatCoinMerge];
|
|
2503
|
-
}
|
|
2504
|
-
getCoinMergeFromNestedResult(coinArg, coinType, moveCall) {
|
|
2505
|
-
if (coinArg.kind === "GasCoin") {
|
|
2506
|
-
return {
|
|
2507
|
-
primary: "GAS",
|
|
2508
|
-
coinType
|
|
2509
|
-
};
|
|
2510
|
-
}
|
|
2511
|
-
if (coinArg.kind === "Input") {
|
|
2512
|
-
const arg = this.getInputArg(coinArg);
|
|
2513
|
-
const objectId = MoveCallHelper.getOwnedObjectId(arg);
|
|
2514
|
-
const mergeTx = this.transactions.find((tx) => {
|
|
2515
|
-
if (tx.kind !== "MergeCoins") {
|
|
2516
|
-
return false;
|
|
2517
|
-
}
|
|
2518
|
-
if (tx.destination.kind !== "Input") {
|
|
2519
|
-
throw new Error("merge coin destination not Input type");
|
|
2520
|
-
}
|
|
2521
|
-
const primaryCoinInput = this.getInputArg(tx.destination);
|
|
2522
|
-
return MoveCallHelper.getOwnedObjectId(primaryCoinInput) === objectId;
|
|
2523
|
-
});
|
|
2524
|
-
if (!mergeTx) {
|
|
2525
|
-
return {
|
|
2526
|
-
primary: objectId,
|
|
2527
|
-
coinType
|
|
2528
|
-
};
|
|
2529
|
-
}
|
|
2530
|
-
return {
|
|
2531
|
-
primary: objectId,
|
|
2532
|
-
merged: mergeTx.sources.map((sourceArg) => {
|
|
2533
|
-
const sourceInputArg = this.getInputArg(sourceArg);
|
|
2534
|
-
return MoveCallHelper.getOwnedObjectId(sourceInputArg);
|
|
2535
|
-
}),
|
|
2536
|
-
coinType
|
|
2537
|
-
};
|
|
2538
|
-
}
|
|
2539
|
-
if (coinArg.kind === "NestedResult") {
|
|
2540
|
-
const parentTx = this.transactions[coinArg.index];
|
|
2541
|
-
if (parentTx.kind !== "SplitCoins") {
|
|
2542
|
-
throw new InvalidInputError(`Transaction type not expected. Expect SplitCoins, got ${parentTx.kind}`);
|
|
2543
|
-
}
|
|
2544
|
-
return this.getCoinMergeFromNestedResult(parentTx.coin, coinType, moveCall);
|
|
2545
|
-
}
|
|
2546
|
-
if (coinArg.kind === "Result") {
|
|
2547
|
-
throw new Error("Result type not expected for coin inputs");
|
|
2548
|
-
}
|
|
2549
|
-
throw new Error(`Unknown argument kind`);
|
|
2550
|
-
}
|
|
2551
|
-
mergeCoinTransactions() {
|
|
2552
|
-
return this.transactions.filter((tx) => tx.kind === "MergeCoins");
|
|
2553
|
-
}
|
|
2554
|
-
get transactions() {
|
|
2555
|
-
return this.txb.blockData.transactions;
|
|
2556
|
-
}
|
|
2557
|
-
get contract() {
|
|
2558
|
-
return new StreamContract(this.globals.envConfig.contract, this.globals);
|
|
2559
|
-
}
|
|
2560
|
-
get feeContract() {
|
|
2561
|
-
return new FeeContract(this.globals.envConfig.contract, this.globals);
|
|
2562
|
-
}
|
|
2563
|
-
createStreamHelper() {
|
|
2564
|
-
return new CreateStreamHelper(this.globals, this.feeContract, this.contract);
|
|
2565
|
-
}
|
|
2566
|
-
getInputArg(arg) {
|
|
2567
|
-
if (arg.kind !== "Input") {
|
|
2568
|
-
throw new Error("not input type");
|
|
2569
|
-
}
|
|
2570
|
-
return "value" in arg ? arg : this.txb.blockData.inputs[arg.index];
|
|
2571
|
-
}
|
|
2572
|
-
};
|
|
2573
|
-
|
|
2574
|
-
// src/apps/mpay/decoder/decoder.ts
|
|
2575
|
-
var DecodeHelper = class {
|
|
2576
|
-
constructor(globals, txb) {
|
|
2577
|
-
this.globals = globals;
|
|
2578
|
-
this.txb = txb;
|
|
2579
|
-
this.contract = new StreamContract(globals.envConfig.contract, globals);
|
|
2580
|
-
}
|
|
2581
|
-
contract;
|
|
2582
|
-
decode() {
|
|
2583
|
-
if (this.isCreateStreamTransaction()) {
|
|
2584
|
-
return this.decodeCreateStreamTransaction();
|
|
2585
|
-
}
|
|
2586
|
-
if (this.isClaimByProxyTransaction()) {
|
|
2587
|
-
return this.decodeClaimByProxyTransaction();
|
|
2588
|
-
}
|
|
2589
|
-
if (this.isSetAutoClaimTransaction()) {
|
|
2590
|
-
return this.decodeSetAutoClaimTransaction();
|
|
2591
|
-
}
|
|
2592
|
-
if (this.isCancelStreamTransaction()) {
|
|
2593
|
-
return this.decodeCancelStreamTransaction();
|
|
2594
|
-
}
|
|
2595
|
-
if (this.isClaimStreamTransaction()) {
|
|
2596
|
-
return this.decodeClaimTransaction();
|
|
2597
|
-
}
|
|
2598
|
-
return void 0;
|
|
2599
|
-
}
|
|
2600
|
-
get transactions() {
|
|
2601
|
-
return this.txb.blockData.transactions;
|
|
2602
|
-
}
|
|
2603
|
-
isCreateStreamTransaction() {
|
|
2604
|
-
const createStreamIndex = this.transactions.findIndex(
|
|
2605
|
-
(tx) => tx.kind === "MoveCall" && isSameTarget(tx.target, this.contract.createStreamTarget)
|
|
2606
|
-
);
|
|
2607
|
-
return createStreamIndex !== -1;
|
|
2608
|
-
}
|
|
2609
|
-
isSetAutoClaimTransaction() {
|
|
2610
|
-
return this.transactions.length === 1 && this.transactions[0].kind === "MoveCall" && isSameTarget(this.transactions[0].target, this.contract.setAutoClaimTarget);
|
|
2611
|
-
}
|
|
2612
|
-
isCancelStreamTransaction() {
|
|
2613
|
-
return this.transactions.length === 1 && this.transactions[0].kind === "MoveCall" && isSameTarget(this.transactions[0].target, this.contract.cancelStreamTarget);
|
|
2614
|
-
}
|
|
2615
|
-
isClaimStreamTransaction() {
|
|
2616
|
-
return this.transactions.length === 1 && this.transactions[0].kind === "MoveCall" && isSameTarget(this.transactions[0].target, this.contract.claimStreamTarget);
|
|
2617
|
-
}
|
|
2618
|
-
isClaimByProxyTransaction() {
|
|
2619
|
-
return this.transactions.length === 1 && this.transactions[0].kind === "MoveCall" && isSameTarget(this.transactions[0].target, this.contract.claimStreamByProxyTarget);
|
|
2620
|
-
}
|
|
2621
|
-
decodeCreateStreamTransaction() {
|
|
2622
|
-
const helper = new CreateStreamDecodeHelper(this.globals, this.txb);
|
|
2623
|
-
return helper.decode();
|
|
2624
|
-
}
|
|
2625
|
-
decodeSetAutoClaimTransaction() {
|
|
2626
|
-
const streamId = this.helper.decodeSharedObjectId(0);
|
|
2627
|
-
const enabled = this.helper.decodeInputBool(1);
|
|
2628
|
-
return {
|
|
2629
|
-
type: "SetAutoClaim" /* SET_AUTO_CLAIM */,
|
|
2630
|
-
streamId,
|
|
2631
|
-
enabled
|
|
2632
|
-
};
|
|
2633
|
-
}
|
|
2634
|
-
decodeClaimTransaction() {
|
|
2635
|
-
const streamId = this.helper.decodeSharedObjectId(0);
|
|
2636
|
-
return {
|
|
2637
|
-
type: "Claim" /* CLAIM */,
|
|
2638
|
-
streamId
|
|
2639
|
-
};
|
|
2640
|
-
}
|
|
2641
|
-
decodeClaimByProxyTransaction() {
|
|
2642
|
-
const streamId = this.helper.decodeSharedObjectId(0);
|
|
2643
|
-
return {
|
|
2644
|
-
type: "ClaimByProxy" /* CLAIM_BY_PROXY */,
|
|
2645
|
-
streamId
|
|
2646
|
-
};
|
|
2647
|
-
}
|
|
2648
|
-
decodeCancelStreamTransaction() {
|
|
2649
|
-
const streamId = this.helper.decodeSharedObjectId(0);
|
|
2650
|
-
return {
|
|
2651
|
-
type: "Cancel" /* CANCEL */,
|
|
2652
|
-
streamId
|
|
2653
|
-
};
|
|
2654
|
-
}
|
|
2655
|
-
get helper() {
|
|
2656
|
-
const moveCall = this.transactions[0];
|
|
2657
|
-
return new MoveCallHelper(moveCall, this.txb);
|
|
2658
|
-
}
|
|
2659
|
-
};
|
|
2660
|
-
|
|
2661
|
-
// src/apps/mpay/set-auto-claim-stream.ts
|
|
2662
|
-
var SetAutoClaimStreamIntention = class _SetAutoClaimStreamIntention extends CoreBaseIntention {
|
|
2663
|
-
constructor(data) {
|
|
2664
|
-
super(data);
|
|
2665
|
-
this.data = data;
|
|
2666
|
-
}
|
|
2667
|
-
txType;
|
|
2668
|
-
txSubType;
|
|
2669
|
-
async build(input) {
|
|
2670
|
-
const { network, account } = input;
|
|
2671
|
-
const mpayClient = new MPayClient(network === "sui:mainnet" ? "prod" /* prod */ : "dev" /* dev */);
|
|
2672
|
-
mpayClient.connectSingleWallet(new MSafeSingleWallet(account));
|
|
2673
|
-
const stream = await mpayClient.getStream(this.data.streamId);
|
|
2674
|
-
const txb = await stream.setAutoClaim(true);
|
|
2675
|
-
return txb;
|
|
2676
|
-
}
|
|
2677
|
-
static fromData(data) {
|
|
2678
|
-
return new _SetAutoClaimStreamIntention(data);
|
|
2679
|
-
}
|
|
2680
|
-
};
|
|
2681
|
-
|
|
2682
|
-
// src/apps/mpay/helper.ts
|
|
2683
|
-
var MPayAppHelper = class {
|
|
2684
|
-
application = "mpay";
|
|
2685
|
-
async deserialize(input) {
|
|
2686
|
-
const { chain, transactionBlock } = input;
|
|
2687
|
-
const globals = Globals.new(chain === "sui:mainnet" ? "prod" /* prod */ : "dev" /* dev */);
|
|
2688
|
-
const decoder = new DecodeHelper(globals, transactionBlock);
|
|
2689
|
-
const result = decoder.decode();
|
|
2690
|
-
if (result.type === "CreateStream" /* CREATE_STREAM */) {
|
|
2691
|
-
return {
|
|
2692
|
-
txType: import_sui3_utils.TransactionType.Stream,
|
|
2693
|
-
txSubType: result.type,
|
|
2694
|
-
intentionData: result.info
|
|
2695
|
-
};
|
|
2696
|
-
}
|
|
2697
|
-
if (result.type === "Claim" /* CLAIM */) {
|
|
2698
|
-
return {
|
|
2699
|
-
txType: import_sui3_utils.TransactionType.Stream,
|
|
2700
|
-
txSubType: result.type,
|
|
2701
|
-
intentionData: {
|
|
2702
|
-
streamId: result.streamId
|
|
2703
|
-
}
|
|
2704
|
-
};
|
|
2705
|
-
}
|
|
2706
|
-
if (result.type === "ClaimByProxy" /* CLAIM_BY_PROXY */) {
|
|
2707
|
-
return {
|
|
2708
|
-
txType: import_sui3_utils.TransactionType.Stream,
|
|
2709
|
-
txSubType: result.type,
|
|
2710
|
-
intentionData: {
|
|
2711
|
-
streamId: result.streamId
|
|
2712
|
-
}
|
|
2713
|
-
};
|
|
2714
|
-
}
|
|
2715
|
-
if (result.type === "SetAutoClaim" /* SET_AUTO_CLAIM */) {
|
|
2716
|
-
return {
|
|
2717
|
-
txType: import_sui3_utils.TransactionType.Stream,
|
|
2718
|
-
txSubType: result.type,
|
|
2719
|
-
intentionData: {
|
|
2720
|
-
streamId: result.streamId,
|
|
2721
|
-
enabled: result.enabled
|
|
2722
|
-
}
|
|
2723
|
-
};
|
|
2724
|
-
}
|
|
2725
|
-
if (result.type === "Cancel" /* CANCEL */) {
|
|
2726
|
-
return {
|
|
2727
|
-
txType: import_sui3_utils.TransactionType.Stream,
|
|
2728
|
-
txSubType: result.type,
|
|
2729
|
-
intentionData: {
|
|
2730
|
-
streamId: result.streamId
|
|
2731
|
-
}
|
|
2732
|
-
};
|
|
2733
|
-
}
|
|
2734
|
-
throw new Error(`Unknown transaction type: ${result}`);
|
|
2735
|
-
}
|
|
2736
|
-
async build(input) {
|
|
2737
|
-
const { network, intentionData, suiClient, account } = input;
|
|
2738
|
-
let intention;
|
|
2739
|
-
switch (input.txSubType) {
|
|
2740
|
-
case "CreateStream" /* CREATE_STREAM */:
|
|
2741
|
-
intention = CreateStreamIntention.fromData(intentionData);
|
|
2742
|
-
break;
|
|
2743
|
-
case "Claim" /* CLAIM */:
|
|
2744
|
-
intention = ClaimStreamIntention.fromData(intentionData);
|
|
2745
|
-
break;
|
|
2746
|
-
case "ClaimByProxy" /* CLAIM_BY_PROXY */:
|
|
2747
|
-
intention = ClaimByProxyStreamIntention.fromData(intentionData);
|
|
2748
|
-
break;
|
|
2749
|
-
case "SetAutoClaim" /* SET_AUTO_CLAIM */:
|
|
2750
|
-
intention = SetAutoClaimStreamIntention.fromData(intentionData);
|
|
2751
|
-
break;
|
|
2752
|
-
case "Cancel" /* CANCEL */:
|
|
2753
|
-
intention = CancelStreamIntention.fromData(intentionData);
|
|
2754
|
-
break;
|
|
2755
|
-
default:
|
|
2756
|
-
throw new Error("not implemented");
|
|
2757
|
-
}
|
|
2758
|
-
return intention.build({ network, suiClient, account });
|
|
2759
|
-
}
|
|
2760
|
-
};
|
|
2761
|
-
|
|
2762
|
-
// src/apps/msafe-core/helper.ts
|
|
2763
|
-
var import_sui3_utils5 = require("@msafe/sui3-utils");
|
|
2764
|
-
|
|
2765
|
-
// src/apps/msafe-core/coin-transfer.ts
|
|
2766
|
-
var import_sui3_utils2 = require("@msafe/sui3-utils");
|
|
2767
|
-
var CoinTransferIntention = class _CoinTransferIntention extends CoreBaseIntention {
|
|
2768
|
-
constructor(data) {
|
|
2769
|
-
super(data);
|
|
2770
|
-
this.data = data;
|
|
2771
|
-
}
|
|
2772
|
-
txType;
|
|
2773
|
-
txSubType;
|
|
2774
|
-
async build(input) {
|
|
2775
|
-
const { suiClient, account } = input;
|
|
2776
|
-
return (0, import_sui3_utils2.buildCoinTransferTxb)(suiClient, this.data, account.address);
|
|
2777
|
-
}
|
|
2778
|
-
static fromData(data) {
|
|
2779
|
-
return new _CoinTransferIntention(data);
|
|
2780
|
-
}
|
|
2781
|
-
};
|
|
2782
|
-
|
|
2783
|
-
// src/apps/msafe-core/object-transfer.ts
|
|
2784
|
-
var import_sui3_utils3 = require("@msafe/sui3-utils");
|
|
2785
|
-
var ObjectTransferIntention = class _ObjectTransferIntention extends CoreBaseIntention {
|
|
2786
|
-
constructor(data) {
|
|
2787
|
-
super(data);
|
|
2788
|
-
this.data = data;
|
|
2789
|
-
}
|
|
2790
|
-
txType;
|
|
2791
|
-
txSubType;
|
|
2792
|
-
async build(input) {
|
|
2793
|
-
const { suiClient, account } = input;
|
|
2794
|
-
return (0, import_sui3_utils3.buildObjectTransferTxb)(suiClient, this.data, account.address);
|
|
2795
|
-
}
|
|
2796
|
-
static fromData(data) {
|
|
2797
|
-
return new _ObjectTransferIntention(data);
|
|
2798
|
-
}
|
|
2799
|
-
};
|
|
2800
|
-
|
|
2801
|
-
// src/apps/msafe-core/plain-payload.ts
|
|
2802
|
-
var import_sui3_utils4 = require("@msafe/sui3-utils");
|
|
2803
|
-
var import_transactions5 = require("@mysten/sui.js/transactions");
|
|
2804
|
-
var PlainPayloadIntention = class _PlainPayloadIntention extends CoreBaseIntention {
|
|
2805
|
-
constructor(data) {
|
|
2806
|
-
super(data);
|
|
2807
|
-
this.data = data;
|
|
2808
|
-
}
|
|
2809
|
-
txType;
|
|
2810
|
-
txSubType;
|
|
2811
|
-
async build(input) {
|
|
2812
|
-
const { account } = input;
|
|
2813
|
-
const tb = import_transactions5.TransactionBlock.from(this.data.content);
|
|
2814
|
-
if (!(0, import_sui3_utils4.isSameAddress)(tb.blockData.sender, account.address)) {
|
|
2815
|
-
throw new Error("Invalid sender address");
|
|
2816
|
-
}
|
|
2817
|
-
return tb;
|
|
2818
|
-
}
|
|
2819
|
-
static fromData(data) {
|
|
2820
|
-
return new _PlainPayloadIntention(data);
|
|
2821
|
-
}
|
|
2822
|
-
};
|
|
2823
|
-
|
|
2824
|
-
// src/apps/msafe-core/helper.ts
|
|
2825
|
-
var CoreHelper = class {
|
|
2826
|
-
application;
|
|
2827
|
-
constructor() {
|
|
2828
|
-
this.application = import_sui3_utils5.TransactionDefaultApplication;
|
|
2829
|
-
}
|
|
2830
|
-
deserialize() {
|
|
2831
|
-
throw new Error("MSafe core transaction intention should be build from API");
|
|
2832
|
-
}
|
|
2833
|
-
async build(input) {
|
|
2834
|
-
const { suiClient, account } = input;
|
|
2835
|
-
let intention;
|
|
2836
|
-
switch (input.txSubType) {
|
|
2837
|
-
case import_sui3_utils5.TransactionSubTypes.assets.coin.send:
|
|
2838
|
-
intention = CoinTransferIntention.fromData(input.intentionData);
|
|
2839
|
-
break;
|
|
2840
|
-
case import_sui3_utils5.TransactionSubTypes.assets.object.send:
|
|
2841
|
-
intention = ObjectTransferIntention.fromData(input.intentionData);
|
|
2842
|
-
break;
|
|
2843
|
-
case import_sui3_utils5.TransactionSubTypes.others.plain:
|
|
2844
|
-
intention = PlainPayloadIntention.fromData(input.intentionData);
|
|
2845
|
-
break;
|
|
2846
|
-
default:
|
|
2847
|
-
throw new Error("not implemented");
|
|
2848
|
-
}
|
|
2849
|
-
return intention.build({ suiClient, account });
|
|
2850
|
-
}
|
|
2851
|
-
};
|
|
2852
|
-
|
|
2853
|
-
// src/apps/registry.ts
|
|
2854
|
-
var MSafeApps = class {
|
|
2855
|
-
apps;
|
|
2856
|
-
constructor(apps) {
|
|
2857
|
-
this.apps = new Map(apps.map((app) => [app.application, app]));
|
|
2858
|
-
}
|
|
2859
|
-
getAppHelper(appName) {
|
|
2860
|
-
const app = this.apps.get(appName);
|
|
2861
|
-
if (!app) {
|
|
2862
|
-
throw new Error(`${appName} not registered`);
|
|
2863
|
-
}
|
|
2864
|
-
return app;
|
|
2865
|
-
}
|
|
2866
|
-
};
|
|
2867
|
-
|
|
2868
|
-
// src/apps/plain-transaction/helper.ts
|
|
2869
|
-
var import_sui3_utils6 = require("@msafe/sui3-utils");
|
|
2870
|
-
var import_transactions6 = require("@mysten/sui.js/transactions");
|
|
2871
|
-
var import_utils15 = require("@mysten/sui.js/utils");
|
|
2872
|
-
var import_sort_keys_recursive2 = __toESM(require("sort-keys-recursive"));
|
|
2873
|
-
var PlainTransactionApplication = "msafe-plain-tx";
|
|
2874
|
-
var PlainTransactionType = import_sui3_utils6.TransactionSubTypes.others.plain;
|
|
2875
|
-
var PlainTransactionHelper = class {
|
|
2876
|
-
application;
|
|
2877
|
-
constructor() {
|
|
2878
|
-
this.application = PlainTransactionApplication;
|
|
2879
|
-
}
|
|
2880
|
-
async deserialize(input) {
|
|
2881
|
-
const { transactionBlock, suiClient } = input;
|
|
2882
|
-
const content = await transactionBlock.build({ client: suiClient });
|
|
2883
|
-
return {
|
|
2884
|
-
txType: import_sui3_utils6.TransactionType.Other,
|
|
2885
|
-
txSubType: PlainTransactionType,
|
|
2886
|
-
intentionData: { content: (0, import_utils15.toHEX)(content) }
|
|
2887
|
-
};
|
|
2888
|
-
}
|
|
2889
|
-
async build(input) {
|
|
2890
|
-
const { suiClient, account } = input;
|
|
2891
|
-
const txb = import_transactions6.TransactionBlock.from((0, import_utils15.fromHEX)(input.intentionData.content));
|
|
2892
|
-
const inspectResult = await suiClient.devInspectTransactionBlock({
|
|
2893
|
-
transactionBlock: txb,
|
|
2894
|
-
sender: account.address
|
|
2895
|
-
});
|
|
2896
|
-
const success = inspectResult.effects.status.status === "success";
|
|
2897
|
-
if (!success) {
|
|
2898
|
-
throw new Error(inspectResult.effects.status.error);
|
|
2899
|
-
}
|
|
2900
|
-
return txb;
|
|
2901
|
-
}
|
|
2902
|
-
};
|
|
2903
|
-
|
|
2904
|
-
// src/index.ts
|
|
2905
|
-
var appHelpers = new MSafeApps([new CoreHelper(), new MPayAppHelper(), new PlainTransactionHelper()]);
|
|
2906
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
2907
|
-
0 && (module.exports = {
|
|
2908
|
-
appHelpers
|
|
2909
|
-
});
|
|
1
|
+
"use strict";var Ge=Object.create;var rt=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var qe=Object.getPrototypeOf,Ue=Object.prototype.hasOwnProperty;var _t=(n,t)=>{for(var e in t)rt(n,e,{get:t[e],enumerable:!0})},me=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of We(t))!Ue.call(n,a)&&a!==e&&rt(n,a,{get:()=>t[a],enumerable:!(r=Le(t,a))||r.enumerable});return n};var Gt=(n,t,e)=>(e=n!=null?Ge(qe(n)):{},me(t||!n||!n.__esModule?rt(e,"default",{value:n,enumerable:!0}):e,n)),$e=n=>me(rt({},"__esModule",{value:!0}),n);var kr={};_t(kr,{appHelpers:()=>Mr});module.exports=$e(kr);var G=require("@msafe/sui3-utils");var le=Gt(require("sort-keys-recursive")),p=class{constructor(t){this.data=t}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,le.default)(this.data))}};var Lt={};_t(Lt,{contractId:()=>Qe,default:()=>Ke,feeObjId:()=>Ye,roleObjId:()=>Je,status:()=>He,transaction:()=>ze,upgradeCapObjId:()=>Xe,vaultObjId:()=>Ve});var ze="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",He="success",Qe="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Je="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",Ve="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",Ye="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Xe="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",Ke={transaction:ze,status:He,contractId:Qe,roleObjId:Je,vaultObjId:Ve,feeObjId:Ye,upgradeCapObjId:Xe};var Wt={};_t(Wt,{contractId:()=>er,default:()=>ir,feeObjId:()=>ar,roleObjId:()=>rr,status:()=>tr,transaction:()=>Ze,upgradeCapObjId:()=>or,vaultObjId:()=>nr});var Ze="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",tr="success",er="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",rr="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",nr="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",ar="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",or="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",ir={transaction:Ze,status:tr,contractId:er,roleObjId:rr,vaultObjId:nr,feeObjId:ar,upgradeCapObjId:or};var sr="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",cr="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",mr="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",lr="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",ur="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",pr="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",dr="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",fr="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",ue=Lt,pe=Wt,gr=new Map([["dev",{env:"dev",rpc:{url:sr},backend:{url:ur},contract:ue}],["stg",{env:"stg",rpc:{url:cr},backend:{url:pr},contract:ue}],["prev",{env:"prev",rpc:{url:mr},backend:{url:dr},contract:pe}],["prod",{env:"prod",rpc:{url:lr},backend:{url:fr},contract:pe}]]);function de(n,t){let e=gr.get(n);if(!e)throw new Error(`Env not supported: ${n}`);return t&&t.rpc&&(e.rpc=t.rpc),t&&t.backend&&(e.backend=t.backend),t&&t.contract&&(e.contract=t.contract),e}var fe=require("@mysten/sui.js/client");var c=class extends Error{mpayErrorCode;context;constructor(t,e,r={}){let{cause:a,context:o}=r;a?super(`[MPay] ${e}: ${a}`):super(`[MPay] ${e}`),this.mpayErrorCode=t,this.context=o}};var nt=class extends c{constructor(){super(11,"Backend is not specified")}};var at=class extends c{constructor(){super(1,"Wallet not connected")}};var b=Gt(require("axios"));var E=class extends c{constructor(t,e){super(10,t,{context:e})}};var ot=class n{constructor(t){this.apiURL=t}static parseResponseData(t){if(t instanceof b.AxiosError)throw new E(t.response?.statusText);if(t.status===200){if(t.data.success)return t.data.data;throw new E(t.data.code)}throw new E(t.status.toString())}async getIncomingStreams(t,e){let r=await b.default.post(`${this.apiURL}/stream`,{recipient:t,...e});return n.parseResponseData(r)}async getOutgoingStreams(t,e){let r=await b.default.post(`${this.apiURL}/stream`,{sender:t,...e});return n.parseResponseData(r)}async getStreamHistory(t){let e=await b.default.post(`${this.apiURL}/stream-events`,t),r=n.parseResponseData(e);return r.data.forEach(a=>{let o=a;return o.data.type==="create_stream"?o.data.balance=BigInt(o.data.balance):o.data.type==="cancel_stream"?o.data.withdrawAmount=BigInt(o.data.withdrawAmount):o.data.type==="claim"||o.data.type==="auto_claim"?o.data.claimAmount=BigInt(o.data.claimAmount):o.data.type==="set_auto_claim"&&(o.data.enabled=!!o.data.enabled),o.createdAt=new Date(o.createdAt),o}),r}async getAllCoinTypes(t){let e=await b.default.post(`${this.apiURL}/stream-info`,{address:t});return n.parseResponseData(e)}async getAllRecipients(t,e){let r=await b.default.post(`${this.apiURL}/stream-info`,{sender:t,status:e});return n.parseResponseData(r)}async getAllSenders(t,e){let r=await b.default.post(`${this.apiURL}/stream-info`,{recipient:t,status:e});return n.parseResponseData(r)}};var M=class n{signer;suiClient;envConfig;_backend;constructor(t){this.envConfig=t,this.suiClient=new fe.SuiClient({url:t.rpc.url}),t.backend&&(this._backend=new ot(t.backend.url))}static new(t,e){let r=de(t,e);return new n(r)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new nt;return this._backend}set backend(t){this._backend=t}connectWallet(t){this.signer=t}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new at;return this.signer}async walletAddress(){return this.wallet.address()}};var D=require("@mysten/sui.js/utils");var B=require("@mysten/sui.js/utils"),Jt=require("luxon");var H=require("@mysten/sui.js/transactions");var Ht=require("@mysten/sui.js/transactions"),z=require("@mysten/sui.js/utils");var qt=50n,it=10000n,ge=25n,Ut=100000000n;var h=class{constructor(t){this.object=t}moveArg(t){return t.object(this.object)}},W=class{constructor(t){this.objects=t}moveArgs(t){return t.makeMoveVec({objects:this.objects.map(e=>t.object(e))})}},T=class n{constructor(t){this.result=t;return new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(e,r){if(r in e)return Reflect.get(e,r);let a=i=>new n(e.result[i]);if(r===Symbol.iterator)return function*(){let i=0;for(;;)yield a(i),i++};if(typeof r=="symbol")return;let o=parseInt(r,10);if(!(Number.isNaN(o)||o<0))return a(o)}})}moveArg(){return this.result}};var $t=require("buffer"),he=require("@mysten/sui.js/utils");var q=class extends c{constructor(t,e){super(3,t,{context:e})}};var st=class{constructor(t){this.results=t}callResult(t){return this.results.results[t]}returnValue(t,e){return t.returnValues[e]}getValue(t=0,e=0){let r=this.callResult(t);return this.returnValue(r,e)}getAddress(t=0,e=0){let[r,a]=this.getValue(t,e);if(a!=="address")throw new q("Invalid contract return type.",{ctx:{expectType:"address",gotType:a}});return(0,he.normalizeSuiAddress)($t.Buffer.from(r).toString("hex"))}getU64(t=0,e=0){let[r,a]=this.getValue(t,e);if(a!=="u64")throw new q("Invalid contract return type.",{ctx:{expectType:"u64",gotType:a}});return $t.Buffer.from(r).readBigInt64LE()}};var zt=require("@mysten/sui.js/bcs");var m=class extends c{constructor(t,e,r){super(2,`Invalid input: ${t}`,{context:{fieldKey:e,fieldValue:r}})}};var be={groupId:"string",name:"string"},hr=64;function ye(n){return Ce(n),zt.bcs.ser(be,n).toString("base64")}function U(n){let t=zt.bcs.de(be,n,"base64");return Ce(t),t}function Ce(n){if(!Se(n.name))throw new m("Invalid metadata: Name contains unknown character");if(!Se(n.groupId))throw new m("Invalid metadata: Group ID contains unknown character");if(n.name.length>hr)throw new m("Invalid metadata: Name exceed max length 64")}function Se(n){return/^[\x00-\x7F]+$/.test(n)}var $=require("@mysten/sui.js/utils");function ct(n,t){return(0,$.normalizeStructTag)(n)===(0,$.normalizeStructTag)(t)}function w(n,t){return(0,$.normalizeStructTag)(n)===(0,$.normalizeStructTag)(t)}var mt="txn.gas";var Ie=require("nanoid");function Te(){return(0,Ie.nanoid)()}var O=class n{constructor(t,e,r){this.globals=t;this.feeContract=e;this.streamContract=r}static convertCreateStreamInfoToInternal(t){return{metadata:ye({name:t.name,groupId:Te()}),coinType:(0,z.normalizeStructTag)(t.coinType),recipients:t.recipients.map(e=>({address:e.address,cliffAmount:e.cliffAmount,amountPerEpoch:e.amountPerStep})),epochInterval:t.interval,numberEpoch:t.steps,startTime:t.startTimeMs,cancelable:t.cancelable}}async buildCreateStreamTransactionBlock(t){let e=new Ht.TransactionBlock,r=this.calculateFeesInternal(t),a=this.getCreateStreamCoinRequests(t,r),o=await this.wallet.requestCoins(a),i=await this.addMergeCoins(e,o[0]),s;a.length>1?s=await this.addMergeCoins(e,o[1]):s=i;for(let l=0;l<t.recipients.length;l++){let P=t.recipients[l],et=this.amountForRecipient(P,t.numberEpoch),Nt=this.getStreamFeeLocal(et),[Ft]=e.splitCoins(i,[e.pure(et+Nt,"u64")]),[_e]=e.splitCoins(s,[e.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(e,{paymentCoin:new T(Ft),flatFeeCoin:new T(_e),metadata:t.metadata,recipient:P.address,timeStart:t.startTime,cliff:P.cliffAmount,epochInterval:t.epochInterval,numEpoch:t.numberEpoch,amountPerEpoch:P.amountPerEpoch,cancelable:t.cancelable,coinType:t.coinType})}return e}calculateCreateStreamFees(t){let e=n.convertCreateStreamInfoToInternal(t);return this.calculateFeesInternal(e)}feeParams(){return{createFeePercent:{numerator:qt,denominator:it},claimFeePercent:{numerator:ge,denominator:it},flatFeePerStream:Ut}}async addMergeCoins(t,e){let r;return e.mergedCoins&&e.mergedCoins.length?(t.mergeCoins(t.object(e.primaryCoin),e.mergedCoins.map(a=>t.object(a))),r=t.object(e.primaryCoin)):e.primaryCoin===mt?r=t.gas:r=t.object(e.primaryCoin),r}getCreateStreamCoinRequests(t,e){let r=t.coinType;return ct(r,z.SUI_TYPE_ARG)?[{coinType:r,amount:e.totalAmount+e.streamFeeAmount+e.flatFeeAmount}]:[{coinType:r,amount:e.totalAmount+e.streamFeeAmount},{coinType:z.SUI_TYPE_ARG,amount:e.flatFeeAmount}]}calculateFeesInternal(t){let e=t.recipients.reduce((a,o)=>{let i=this.amountForRecipient(o,t.numberEpoch),s=this.getStreamFeeLocal(i);return{totalAmount:a.totalAmount+i,streamFeeAmount:a.streamFeeAmount+s}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(t.recipients.length)*this.flatSuiFee,...e}}amountForRecipient(t,e){return BigInt(t.amountPerEpoch)*BigInt(e)+BigInt(t.cliffAmount)}get flatSuiFee(){return Ut}getStreamFeeLocal(t){return t*qt/it}async getStreamFeeRemote(t){let e=this.feeContract.streamingFee(new Ht.TransactionBlock,t),r=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:e});return new st(r).getU64()}get wallet(){return this.globals.wallet}};var Qt=require("@mysten/sui.js/transactions");var we="0x0000000000000000000000000000000000000000000000000000000000000006";var k=class{constructor(t,e,r){this.moduleName=t;this.config=e;this.globals=r}addContractCall(t,e){let r=`${this.config.contractId}::${this.moduleName}::${e.method}`;return t.add(Qt.Transactions.MoveCall({target:r,arguments:e.arguments.map(a=>a instanceof W?a.moveArgs(t):a instanceof h?a.moveArg(t):a instanceof T?a.moveArg():t.pure(a)),typeArguments:e.typeArgs})),t}addTransactionBlock(t,e,r=[],a=[]){t.add(Qt.Transactions.MoveCall({target:e,arguments:r.map(o=>o instanceof W?o.moveArgs(t):o instanceof h?o.moveArg(t):o instanceof T?o.moveArg():t.pure(o)),typeArguments:a}))}makeObject(t){return typeof t=="string"?new h(t):t}vaultObject(){return new h(this.config.vaultObjId)}roleObject(){return new h(this.config.roleObjId)}feeObject(){return new h(this.config.feeObjId)}clockObject(){return new h(we)}};var R=class n extends k{constructor(e,r){super(n.ModuleName,e,r);this.config=e;this.globals=r}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,r){let a=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:n.MethodName.set_streaming_fee,arguments:[a,o,r],typeArgs:[]})}setStreamingFlatFee(e,r){let a=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:n.MethodName.set_streaming_flat_fee,arguments:[a,o,r],typeArgs:[]})}setClaimFee(e,r){let a=this.roleObject(),o=this.feeObject();return this.addContractCall(e,{method:n.MethodName.set_claim_fee,arguments:[a,o,r],typeArgs:[]})}streamingFee(e,r){let a=this.feeObject();return this.addContractCall(e,{method:n.MethodName.streaming_fee,arguments:[a,r],typeArgs:[]})}claimFee(e,r){return this.addContractCall(e,{method:n.MethodName.claim_fee,arguments:[this.feeObject(),r],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:n.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}};var S=class n extends k{constructor(e,r){super(n.ModuleName,e,r);this.config=e;this.globals=r}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,r){let a=this.feeObject(),o=this.vaultObject(),i=this.makeObject(r.paymentCoin),s=this.makeObject(r.flatFeeCoin),l=this.clockObject();return this.addContractCall(e,{method:n.MethodName.create_stream,arguments:[a,o,i,s,r.metadata,r.recipient,r.timeStart,r.cliff,r.epochInterval,r.numEpoch,r.amountPerEpoch,r.cancelable,l],typeArgs:[r.coinType]})}setAutoClaim(e,r){let a=this.makeObject(r.streamId);return this.addContractCall(e,{method:n.MethodName.set_auto_claim,arguments:[a,r.enabled],typeArgs:[r.coinType]})}cancelStream(e,r){let a=this.makeObject(r.streamId),o=this.clockObject();return this.addContractCall(e,{method:n.MethodName.cancel_stream,arguments:[a,o],typeArgs:[r.coinType]})}claimStream(e,r){let a=this.makeObject(r.streamId),o=this.clockObject();return this.addContractCall(e,{method:n.MethodName.claim_stream,arguments:[a,o],typeArgs:[r.coinType]})}claimStreamByProxy(e,r){let a=this.makeObject(r.streamId),o=this.vaultObject(),i=this.feeObject(),s=this.clockObject();return this.addContractCall(e,{method:n.MethodName.claim_stream_by_proxy,arguments:[a,o,i,s],typeArgs:[r.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${n.ModuleName}::${n.MethodName.claim_stream_by_proxy}`}};var j=class{constructor(t){this.globals=t;let e=t.envConfig.contract;this.feeContract=new R(e,t),this.streamContract=new S(e,t)}feeContract;streamContract;async createStreams(t){let e=O.convertCreateStreamInfoToInternal(t);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new O(this.globals,this.feeContract,this.streamContract)}setAutoClaim(t,e,r){let a=new H.TransactionBlock;return this.streamContract.setAutoClaim(a,{streamId:t,enabled:e,coinType:r})}claimStream(t,e){let r=new H.TransactionBlock;return this.streamContract.claimStream(r,{streamId:t,coinType:e})}claimStreamByProxy(t,e){let r=new H.TransactionBlock;return this.streamContract.claimStreamByProxy(r,{streamId:t,coinType:e})}cancelStream(t,e){let r=new H.TransactionBlock;return this.streamContract.cancelStream(r,{streamId:t,coinType:e}),r}};var lt=class extends c{constructor(t,e){super(12,`Transaction failed: ${e}`,{context:{status:t,msg:e}})}};var Sr=1e3,ut=class{constructor(t){this.globals=t;this.coinMetaHelper=new Vt(t.suiClient),this.createStreamHelper=new j(t).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(t){if(t.effects?.status.status!=="success")throw new lt(t.effects?.status.status,t.effects?.status.error);return t.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(t){return this.createStreamHelper.calculateCreateStreamFees(t)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(t){if(t.steps===0n)throw new m("Invalid stream steps: 0");let e=t.cliff?t.cliff:{numerator:0n,denominator:100n},r=t.totalAmount*e.numerator/e.denominator,a=(t.totalAmount-r)/t.steps,i={realTotalAmount:a*t.steps+r,cliffAmount:r,amountPerStep:a};return this.validateStreamAmount(i,t.totalAmount),i}calculateTimelineByInterval(t){if(t.steps===0n)throw new m("Invalid stream steps: 0");let e=t.timeStart.plus(t.interval.toMillis()*Number(t.steps)),r={timeStart:t.timeStart,timeEnd:e,interval:t.interval,steps:t.steps};return this.validateTimeline(r),r}calculateTimelineByTotalDuration(t){if(t.steps===0n)throw new m("Invalid stream steps: 0");let e=BigInt(t.total.toMillis())/t.steps,r=t.timeStart.plus(Jt.Duration.fromMillis(Number(e*t.steps))),a={timeStart:t.timeStart,timeEnd:r,interval:Jt.Duration.fromMillis(Number(e)),steps:t.steps};return this.validateTimeline(a),a}async getBalance(t,e){let r=await this.globals.suiClient.getBalance({owner:t,coinType:e}),a=await this.getCoinMeta(e);return{...r,coinType:(0,B.normalizeStructTag)(r.coinType),coinMeta:a}}async getAllBalance(t){let e=await this.globals.suiClient.getAllBalances({owner:t}),r=await Promise.all(e.map(a=>this.getCoinMeta(a.coinType)));return e.map((a,o)=>({...a,coinType:(0,B.normalizeStructTag)(a.coinType),coinMeta:r[o]}))}async getCoinMeta(t){return this.coinMetaHelper.getCoinMeta(t)}async simulateTransactionBlock(t){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:t,sender:await this.globals.wallet.address()})}validateStreamAmount(t,e){if(t.amountPerStep===0n)throw new m("Stream amount too small","totalAmount",e);if(t.cliffAmount>t.realTotalAmount)throw new m("Invalid cliff settings")}validateTimeline(t){if(t.interval.toMillis()<Sr)throw new m("Interval shall be at least 1 second","interval",t.interval)}},Vt=class{constructor(t){this.suiClient=t;this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(t){let e=(0,B.normalizeStructTag)(t||B.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let r=await this.queryCoinMeta(e);return r&&this.coinMetaReg.set(e,r),r}async queryCoinMeta(t){return await this.suiClient.getCoinMetadata({coinType:t})||void 0}};var A=require("@mysten/sui.js/utils"),re=require("luxon");var V=require("@mysten/sui.js/transactions"),Y=require("@mysten/sui.js/utils"),Ae=require("luxon");var pt=class extends c{constructor(){super(7,"Connected wallet is not creator")}};var Q=class extends c{constructor(){super(8,"Connected wallet is not recipient")}};var J=class extends c{constructor(t,e){super(6,t,{context:e})}};var u=class extends c{constructor(t,e={}){super(0,t,e)}};var dt=class extends c{constructor(t){super(5,"Stream not found",{context:{streamId:t}})}};var gt=require("luxon"),xe=(1n<<64n)-1n,ft=1e3;function Yt(n){let t;typeof n=="number"?t=n:typeof n=="bigint"?t=Number(n):t=n.toMillis();let e=Math.round(t/ft);return gt.DateTime.fromMillis(e*ft)}function Xt(n){let t;typeof n=="number"?t=n:typeof n=="bigint"?t=Number(n):t=n.toMillis();let e=Math.round(t/ft);return gt.Duration.fromMillis(e*ft)}var x=class n{constructor(t,e,r){this.globals=t;this.streamId=e;this.rawData=r;this.streamContract=new S(t.envConfig.contract,t)}streamContract;type="Stream";static async new(t,e){let r=await n.fetchStreamData(t,e);return new n(t,e,r)}static fromObjectData(t,e,r){let a=n.parseRawStreamData(e,r);return new n(t,e,a)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await n.fetchStreamData(this.globals,this.streamId)}refreshWithData(t){if(t.data?.objectId!==this.streamId)throw new u("Object Id does not align");this.rawData=n.parseRawStreamData(this.streamId,t)}async historyEvents(t){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:t})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new pt;let t=new V.TransactionBlock;return this.streamContract.cancelStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new Q;let t=new V.TransactionBlock;return this.streamContract.claimStream(t,{streamId:this.streamId,coinType:this.coinType}),t}async setAutoClaim(t){if(await this.globals.walletAddress()!==this.recipient)throw new Q;let e=new V.TransactionBlock;return this.streamContract.setAutoClaim(e,{streamId:this.streamId,coinType:this.coinType,enabled:t}),e}async claimByProxy(){let t=new V.TransactionBlock;return this.streamContract.claimStreamByProxy(t,{streamId:this.streamId,coinType:this.coinType}),t}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return(0,Y.normalizeStructTag)(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return Xt(this.rawData.config.epochInterval)}get groupId(){let{metadata:t}=this.rawData.config;return U(t).groupId}get name(){let{metadata:t}=this.rawData.config;return U(t).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Yt(this.rawData.config.timeStart)}get duration(){let t=this.rawData.config,e=t.epochInterval*t.totalEpoch;return Xt(e)}get timeEnd(){return this.timeStart.plus(this.duration)}get totalSteps(){return this.rawData.config.totalEpoch}get claimable(){return this.streamedAmount-this.claimedAmount}get nextReleaseDate(){return this.currentEpoch===-1n?this.timeStart:this.currentEpoch>=this.totalSteps||this.isCanceled?null:Yt((this.currentEpoch+1n)*this.rawData.config.epochInterval+this.rawData.config.timeStart)}get nextReleaseAmount(){return this.currentEpoch===-1n?this.cliff:this.currentEpoch>=this.totalSteps||this.isCanceled?null:this.amountPerEpoch}get streamStatus(){let t=this.rawData.status.status;return t===16?"CANCELED":t===17?"SETTLED":t===1?"COMPLETED":this.currentEpoch>=this.totalSteps?"STREAMED":"STREAMING"}get streamedAmount(){return this.currentEpoch===-1n?0n:this.isCanceled?this.rawData.status.epochCanceled*this.amountPerEpoch+this.cliff:this.currentEpoch*this.amountPerEpoch+this.cliff}get claimedAmount(){return this.rawData.status.epochClaimed===xe?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let t=Ae.DateTime.now().toMillis(),e=this.timeStart.toMillis();if(t<e)return-1n;let r=Math.floor((t-e)/Number(this.rawData.config.epochInterval));return BigInt(r)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(r)}get totalAmount(){let t=this.rawData.config;return t.amountPerEpoch*t.totalEpoch+t.cliff}get isCanceled(){let t=this.rawData.status.status;return t===16||t===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(t,e){let r=await t.suiClient.getObject({id:e,options:{showContent:!0,showType:!0}});return n.parseRawStreamData(e,r)}static parseRawStreamData(t,e){if(e.error)throw e.error.code==="notExists"?new dt(t):new J(`get stream data: ${e.error.code}`,{streamId:t,...e.error});let r=e.data.content;if(r.dataType!=="moveObject")throw new J("Unexpected object type",{gotType:r.dataType});let{typeParams:a}=(0,Y.parseStructTag)(r.type),o=(0,Y.normalizeStructTag)(a[0]),i=r.fields,s=i.config.fields,l=i.status.fields;return{coinType:o,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(s.amount_per_epoch),cancelable:s.cancelable,cliff:BigInt(s.cliff),creator:s.creator,epochInterval:BigInt(s.epoch_interval),metadata:s.metadata,recipient:s.recipient,timeStart:BigInt(s.time_start),totalEpoch:BigInt(s.total_epoch)},status:{status:l.status,epochCanceled:BigInt(l.epoch_canceled),epochClaimed:BigInt(l.epoch_claimed)}}}};var N=class extends c{constructor(t,e){super(9,`Invalid stream group: ${t}`,{context:e})}};async function Zt(n){let t=[];for(;await n.hasNext();){let e=await n.next();t.push(e)}return t&&Array.isArray(t[0])?t.flat(1):t}var Kt=class{constructor(t){this.requester=t;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},F=class{constructor(t){this.requester=t;this.pager=new Kt(t),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};var br=25;async function ee(n,t,e){let r=new X(t),a=new K(n,r,e);return await Zt(a)}var X=class{constructor(t){this.ids=t;this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},K=class extends F{constructor(e,r,a){super(new te(e,r,a));this.suiClient=e;this.idIter=r;this.options=a}},te=class{constructor(t,e,r){this.suiClient=t;this.stringIter=e;this.options=r;this.filter=r?.filter,this.pageSize=r?.pageSize||br,this.objectOptions=r?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let t=[];for(;t.length<this.pageSize&&await this.stringIter.hasNext();){let o=await this.stringIter.next();o&&t.push(o)}let e=await this.suiClient.multiGetObjects({ids:t,options:this.objectOptions}),r;if(this.filter){let{filter:a}=this;r=e.filter(o=>a?.(o))}else r=e;return{data:r,hasNext:await this.stringIter.hasNext()}}};var ht=class n{constructor(t,e){this.globals=t;this.streams=e;if(e.length===0)throw new N("stream size 0");let r=e.map(o=>o.groupId);if(new Set(r).size!==1)throw new m("Stream does not have same group ID")}type="StreamGroup";static async new(t,e){let r=await ee(t.suiClient,e);return r.forEach(a=>{if(!a)throw new u("stream group object data undefined")}),n.newFromObjectResponse(t,e,r)}static async newFromObjectResponse(t,e,r){let a=await n.parseGroupStreams(t,e,r);return new n(t,a)}static checkStreamGroup(t){let e=t.map(o=>o.groupCommonInfo),r=e[0],a=!0;return e.forEach(o=>{yr(r,o)||(a=!1)}),a}async refresh(){let t=await ee(this.globals.suiClient,this.streams.map(e=>e.streamId));this.streams.forEach((e,r)=>{e.refreshWithData(t[r])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(t=>t.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((t,e)=>t+e.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((t,e)=>t+e.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((t,e)=>e.nextReleaseAmount===null?t:t+e.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((t,e)=>t+e.totalAmount,0n),streamed:this.streams.reduce((t,e)=>t+e.streamedAmount,0n),claimed:this.streams.reduce((t,e)=>t+e.claimedAmount,0n),claimable:this.streams.reduce((t,e)=>t+e.claimable,0n),canceled:this.streams.reduce((t,e)=>t+e.canceledAmount,0n)}}async historyEvents(t){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:t})}static async parseGroupStreams(t,e,r){let a=r.map((o,i)=>x.fromObjectData(t,e[i],o)).filter(o=>!!o);if(new Set(a.map(o=>o.groupId)).size!==1)throw new N("Not same group ID");if(!this.checkStreamGroup(a))throw new N("Not same stream settings");return a}};function yr(n,t){return n.name===t.name&&n.groupId===t.groupId&&n.creator===t.creator&&n.start.toMillis()===t.start.toMillis()&&n.interval.toMillis()===t.interval.toMillis()&&n.steps===t.steps&&n.cancelable===t.cancelable}var Z=class n{constructor(t,e){this.it=t;this.pageSize=e}static async newIncoming(t){let e=await St.newIncoming(t);return new n(e,t.pageSize)}static async newOutgoing(t){let e=await St.newOutgoing(t);return new n(e,t.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let t=[];for(;t.length<this.pageSize&&await this.it.hasNext();)t.push(await this.it.next());return t}},St=class n{constructor(t){this.requester=t}cachedNext;static async newIncoming(t){let e=await bt.newIncomingQuery(t);return new n(e)}static async newOutgoing(t){let e=await bt.newOutgoingQuery(t);return new n(e)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let e=await this.requester.doNextRequest();if(e===null)throw new u("No more results");return e}let t=this.cachedNext;if(this.cachedNext=void 0,t===null)throw new u("No more results");return t}},bt=class n{constructor(t,e,r,a){this.globals=t;this.recipient=e;this.groupRefs=r;this.query=a;this.current=0;let o=new X(r.flat().map(i=>i.streamId));this.objectIter=new K(t.suiClient,o)}current=0;objectIter;static async newIncomingQuery(t){let e=xr(t.query),r=await t.globals.walletAddress(),o=(await t.globals.backend.getIncomingStreams(r,e)).filter(s=>(0,A.normalizeSuiAddress)(s.recipient)===(0,A.normalizeSuiAddress)(r)),i=ve(o);return new n(t.globals,r,i,t.query)}static async newOutgoingQuery(t){let e=Ar(t.query),r=await t.globals.walletAddress(),a=await t.globals.backend.getOutgoingStreams(r,e),o=ve(a);return new n(t.globals,r,o,t.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let t=this.groupRefs[this.current];if(t.length===1){let e=await Tr(this.globals,t[0].streamId,this.objectIter);return this.current++,Oe(e,this.query)?e:this.doNextRequest()}if(t.length>1){let e=await wr(this.globals,t.map(r=>r.streamId),this.objectIter);return this.current++,Ir(e,this.query)?e:this.doNextRequest()}throw new u("Stream group with no stream")}};function ve(n){let t=new Map;return n.forEach(e=>{let r=t.get(e.groupId);r?(r.push(e),t.set(e.groupId,r)):t.set(e.groupId,[e])}),Array.from(t.values()).sort((e,r)=>re.DateTime.fromISO(r[0].createDate).toMillis()-re.DateTime.fromISO(e[0].createDate).toMillis())}function Oe(n,t){if(t===void 0)return!0;let e=Cr(n,t.status);if(t&&"claimable"in t&&t.claimable!==void 0){let r=t.claimable?n.progress.claimable!==0n:n.progress.claimable===0n;return e&&r}return e}function Cr(n,t){return t===void 0?!0:Array.isArray(t)?t.includes(n.progress.status):n.progress.status===t}function Ir(n,t){if(!t)return!0;let e=!1;return n.streams.forEach(r=>{Oe(r,t)&&(e=!0)}),e}async function Tr(n,t,e){let r=await De(e,t);return x.fromObjectData(n,t,r)}async function wr(n,t,e){let r=[];for(;r.length<t.length;){let a=await De(e,t[r.length]);r.push(a)}return ht.newFromObjectResponse(n,t,r)}async function De(n,t){if(!await n.hasNext())throw new u("object iterator has been consumed");let e=await n.next();if(!e||e.error||e.data===void 0||e.data===null)throw new u("object iterator undefined response",{cause:e?.error});if(e?.data?.objectId!==t)throw new u("stream id not aligned");return e}function xr(n){return{status:ne(n?.status),coinType:Pe(n?.coinType),sender:Ee(n?.sender)}}function Ar(n){return{status:ne(n?.status),coinType:Pe(n?.coinType),recipient:Ee(n?.recipient)}}function ne(n){return n===void 0||n.length===0?"all":Array.isArray(n)?n.reduce((t,e)=>{let r=ne(e);return!t||t===r?r:"all"},void 0):vr(n)}function vr(n){switch(n){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new m("Unknown stream filtered status")}}function Pe(n){if(n)return Array.isArray(n)?n.length!==0?n.map(t=>(0,A.normalizeStructTag)(t)):void 0:(0,A.normalizeStructTag)(n)}function Ee(n){if(n)return Array.isArray(n)?n.length!==0?n.map(t=>(0,A.normalizeSuiAddress)(t)):void 0:(0,A.normalizeSuiAddress)(n)}var yt=class extends c{constructor(e,r,a){super(4,`Not enough balance: ${e}`,{context:{coinType:e,requestAmount:r,gotAmount:a}});this.coinType=e;this.requestAmount=r;this.gotAmount=a}};var Or=25;async function Me(n,t,e,r="0x2::sui::SUI",a=Or){let o=new ae(n,t,r,a),i=BigInt(0),s=[];for(;await o.hasNext()&&i<e;){let l=await o.next();l&&(s.push(l),i+=BigInt(l.balance))}if(i<e)throw new yt(r,e,i);return s}var ae=class extends F{constructor(e,r,a,o){super(new oe(e,r,a,o));this.suiClient=e;this.owner=r;this.coinType=a;this.reqPageSize=o}},oe=class{constructor(t,e,r,a){this.suiClient=t;this.owner=e;this.coinType=r;this.reqPageSize=a;if(a<=0)throw new u("Invalid reqPageSize")}nextCursor;async doNextRequest(){let t=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=t.nextCursor,{data:t.data,hasNext:t.hasNextPage}}};var ie=class{constructor(t){this.msafe=t}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(t){return this.msafe.requestCoins(t)}},f=class{constructor(t){this.account=t}async address(){return this.account.address}},se=class{constructor(t,e){this.singleWallet=t;this.suiClient=e}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(t){return Promise.all(t.map(e=>this.requestCoin(e)))}async requestCoin(t){if(ct(t.coinType,D.SUI_TYPE_ARG))return{primaryCoin:mt};if(t.amount<=0)throw new m("Invalid coin request","coinAmount",t.amount);let e=await Me(this.suiClient,await this.address(),t.amount,t.coinType);if(e.length===0)throw new u("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(r=>r.coinObjectId)}}},g=class{globals;helper;constructor(t,e){this.globals=M.new(t,e),this.helper=new ut(this.globals)}connectSingleWallet(t){let e=new se(t,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(t){let e=new ie(t);this.globals.connectWallet(e)}async createStream(t){return this.builder().createStreams(t)}async getStream(t){return x.new(this.globals,t)}async getIncomingStreams(t,e=10){return Z.newIncoming({globals:this.globals,query:t,pageSize:e})}async getOutgoingStreams(t,e=10){return Z.newOutgoing({globals:this.globals,query:t,pageSize:e})}async getCoinTypesForStreamFilter(){let t=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(t)).map(r=>(0,D.normalizeStructTag)(r))}async getRecipientsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,t)).map(a=>(0,D.normalizeSuiAddress)(a))}async getCreatorsForStreamFilter(t){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,t)).map(a=>(0,D.normalizeSuiAddress)(a))}get wallet(){return this.globals.wallet}builder(){return new j(this.globals)}};var Ct=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{network:r,account:a}=e,o=new g(r==="sui:mainnet"?"prod":"dev");return o.connectSingleWallet(new f(a)),await(await o.getStream(this.data.streamId)).cancel()}static fromData(e){return new n(e)}};var It=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{network:r,account:a}=e,o=new g(r==="sui:mainnet"?"prod":"dev");return o.connectSingleWallet(new f(a)),await(await o.getStream(this.data.streamId)).claimByProxy()}static fromData(e){return new n(e)}};var Tt=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{network:r,account:a}=e,o=new g(r==="sui:mainnet"?"prod":"dev");return o.connectSingleWallet(new f(a)),await(await o.getStream(this.data.streamId)).claim()}static fromData(e){return new n(e)}};var wt=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{network:r,account:a}=e,o=new g(r==="sui:mainnet"?"prod":"dev");return o.connectSingleWallet(new f(a)),await o.createStream(this.data)}static fromData(e){return new n(e)}};var _=require("@mysten/sui.js/utils");var ce=require("@mysten/sui.js/bcs"),v=require("@mysten/sui.js/utils"),y=class n{constructor(t,e){this.moveCall=t;this.txb=e}decodeSharedObjectId(t){let e=this.getInputParam(t);return n.getSharedObjectId(e)}decodeOwnedObjectId(t){let e=this.getInputParam(t);return n.getOwnedObjectId(e)}decodeInputU64(t){let e=this.decodePureArg(t,"u64");return BigInt(e)}decodeInputAddress(t){let e=this.decodePureArg(t,"address");return(0,v.normalizeSuiAddress)(e)}decodeInputString(t){return this.decodePureArg(t,"string")}decodeInputBool(t){return this.decodePureArg(t,"bool")}decodePureArg(t,e){let r=this.getInputParam(t);return n.getPureInputValue(r,e)}getInputParam(t){let e=this.moveCall.arguments[t];if(e.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[e.index]}static getPureInputValue(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value=="object"&&"Pure"in t.value){let r=t.value.Pure;return ce.bcs.de(e,new Uint8Array(r))}return t.value}static getOwnedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value=="object"){if(!("Object"in t.value)||!("ImmOrOwned"in t.value.Object))throw new Error("not ImmOrOwned");return(0,v.normalizeSuiAddress)(t.value.Object.ImmOrOwned.objectId)}return(0,v.normalizeSuiAddress)(t.value)}static getSharedObjectId(t){if(t.type!=="object")throw new Error(`not object argument: ${JSON.stringify(t)}`);if(typeof t.value!="object")return(0,v.normalizeSuiAddress)(t.value);if(!("Object"in t.value)||!("Shared"in t.value.Object))throw new Error("not Shared");return(0,v.normalizeSuiAddress)(t.value.Object.Shared.objectId)}static getPureInput(t,e){if(t.type!=="pure")throw new Error("not pure argument");if(typeof t.value!="object")return t.value;if(!("Pure"in t.value))throw new Error("Pure not in value");let r=t.value.Pure;return ce.bcs.de(e,new Uint8Array(r))}typeArg(t){return(0,v.normalizeStructTag)(this.moveCall.typeArguments[t])}txArg(t){return this.moveCall.arguments[t]}};var xt=class{constructor(t,e){this.globals=t;this.txb=e}decode(){let t=this.decodeCreateStreamInfo(),e=this.createStreamHelper().calculateCreateStreamFees(t),r=this.getCoinMerges();return{type:"CreateStream",info:t,fees:e,coinMerges:r}}decodeCreateStreamInfo(){let e=this.createStreamTransactions().map(r=>this.getCreationInfoFromMoveCall(r));return this.aggregateGroupStreamInfo(e)}createStreamTransactions(){let t=this.transactions.filter(e=>e.kind==="MoveCall"&&w(e.target,this.contract.createStreamTarget));if(t.length===0)throw new u("No create stream transactions");return t.map(e=>new y(e,this.txb))}getCreationInfoFromMoveCall(t){let e=t.decodeInputString(4),{name:r,groupId:a}=U(e),o=t.decodeInputAddress(5),i=t.decodeInputU64(6),s=t.decodeInputU64(7),l=t.decodeInputU64(8),P=t.decodeInputU64(9),et=t.decodeInputU64(10),Nt=t.decodeInputBool(11),Ft=t.typeArg(0);return{name:r,groupId:a,recipient:o,timeStart:i,cliff:s,epochInterval:l,totalEpoch:P,amountPerEpoch:et,cancelable:Nt,coinType:Ft}}aggregateGroupStreamInfo(t){if(new Set(t.map(a=>JSON.stringify({name:a.name,groupId:a.groupId,timeStart:String(a.timeStart),epochInterval:String(a.epochInterval),totalEpoch:String(a.totalEpoch),cancelable:a.cancelable,coinType:a.coinType}))).size!==1)throw new m("Stream group not have common info");let r=t.map(a=>({address:a.recipient,amountPerStep:a.amountPerEpoch,cliffAmount:a.cliff}));return{name:t[0].name,coinType:t[0].coinType,recipients:r,interval:t[0].epochInterval,steps:t[0].totalEpoch,startTimeMs:t[0].timeStart,cancelable:t[0].cancelable}}getCoinMerges(){let t=this.createStreamTransactions()[0];return this.getCoinMergeForCreateStream(t)}getCoinMergeForCreateStream(t){let e=t.typeArg(0),r=t.txArg(2),a=this.getCoinMergeFromNestedResult(r,e,t);if(e===(0,_.normalizeStructTag)(_.SUI_TYPE_ARG))return[a];let o=t.txArg(3),i=this.getCoinMergeFromNestedResult(o,(0,_.normalizeStructTag)(_.SUI_TYPE_ARG),t);return[a,i]}getCoinMergeFromNestedResult(t,e,r){if(t.kind==="GasCoin")return{primary:"GAS",coinType:e};if(t.kind==="Input"){let a=this.getInputArg(t),o=y.getOwnedObjectId(a),i=this.transactions.find(s=>{if(s.kind!=="MergeCoins")return!1;if(s.destination.kind!=="Input")throw new Error("merge coin destination not Input type");let l=this.getInputArg(s.destination);return y.getOwnedObjectId(l)===o});return i?{primary:o,merged:i.sources.map(s=>{let l=this.getInputArg(s);return y.getOwnedObjectId(l)}),coinType:e}:{primary:o,coinType:e}}if(t.kind==="NestedResult"){let a=this.transactions[t.index];if(a.kind!=="SplitCoins")throw new m(`Transaction type not expected. Expect SplitCoins, got ${a.kind}`);return this.getCoinMergeFromNestedResult(a.coin,e,r)}throw t.kind==="Result"?new Error("Result type not expected for coin inputs"):new Error("Unknown argument kind")}mergeCoinTransactions(){return this.transactions.filter(t=>t.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new S(this.globals.envConfig.contract,this.globals)}get feeContract(){return new R(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new O(this.globals,this.feeContract,this.contract)}getInputArg(t){if(t.kind!=="Input")throw new Error("not input type");return"value"in t?t:this.txb.blockData.inputs[t.index]}};var At=class{constructor(t,e){this.globals=t;this.txb=e;this.contract=new S(t.envConfig.contract,t)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction()}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(e=>e.kind==="MoveCall"&&w(e.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&w(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&w(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&w(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&w(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new xt(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let t=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:t,enabled:e}}decodeClaimTransaction(){let t=this.helper.decodeSharedObjectId(0);return{type:"Claim",streamId:t}}decodeClaimByProxyTransaction(){let t=this.helper.decodeSharedObjectId(0);return{type:"ClaimByProxy",streamId:t}}decodeCancelStreamTransaction(){let t=this.helper.decodeSharedObjectId(0);return{type:"Cancel",streamId:t}}get helper(){let t=this.transactions[0];return new y(t,this.txb)}};var vt=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{network:r,account:a}=e,o=new g(r==="sui:mainnet"?"prod":"dev");return o.connectSingleWallet(new f(a)),await(await o.getStream(this.data.streamId)).setAutoClaim(!0)}static fromData(e){return new n(e)}};var Ot=class{application="mpay";async deserialize(t){let{chain:e,transactionBlock:r}=t,a=M.new(e==="sui:mainnet"?"prod":"dev"),i=new At(a,r).decode();if(i.type==="CreateStream")return{txType:G.TransactionType.Stream,txSubType:i.type,intentionData:i.info};if(i.type==="Claim")return{txType:G.TransactionType.Stream,txSubType:i.type,intentionData:{streamId:i.streamId}};if(i.type==="ClaimByProxy")return{txType:G.TransactionType.Stream,txSubType:i.type,intentionData:{streamId:i.streamId}};if(i.type==="SetAutoClaim")return{txType:G.TransactionType.Stream,txSubType:i.type,intentionData:{streamId:i.streamId,enabled:i.enabled}};if(i.type==="Cancel")return{txType:G.TransactionType.Stream,txSubType:i.type,intentionData:{streamId:i.streamId}};throw new Error(`Unknown transaction type: ${i}`)}async build(t){let{network:e,intentionData:r,suiClient:a,account:o}=t,i;switch(t.txSubType){case"CreateStream":i=wt.fromData(r);break;case"Claim":i=Tt.fromData(r);break;case"ClaimByProxy":i=It.fromData(r);break;case"SetAutoClaim":i=vt.fromData(r);break;case"Cancel":i=Ct.fromData(r);break;default:throw new Error("not implemented")}return i.build({network:e,suiClient:a,account:o})}};var L=require("@msafe/sui3-utils");var Re=require("@msafe/sui3-utils");var Dt=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e;return(0,Re.buildCoinTransferTxb)(r,this.data,a.address)}static fromData(e){return new n(e)}};var je=require("@msafe/sui3-utils");var Pt=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{suiClient:r,account:a}=e;return(0,je.buildObjectTransferTxb)(r,this.data,a.address)}static fromData(e){return new n(e)}};var Be=require("@msafe/sui3-utils"),Ne=require("@mysten/sui.js/transactions");var Et=class n extends p{constructor(e){super(e);this.data=e}txType;txSubType;async build(e){let{account:r}=e,a=Ne.TransactionBlock.from(this.data.content);if(!(0,Be.isSameAddress)(a.blockData.sender,r.address))throw new Error("Invalid sender address");return a}static fromData(e){return new n(e)}};var Mt=class{application;constructor(){this.application=L.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(t){let{suiClient:e,account:r}=t,a;switch(t.txSubType){case L.TransactionSubTypes.assets.coin.send:a=Dt.fromData(t.intentionData);break;case L.TransactionSubTypes.assets.object.send:a=Pt.fromData(t.intentionData);break;case L.TransactionSubTypes.others.plain:a=Et.fromData(t.intentionData);break;default:throw new Error("not implemented")}return a.build({suiClient:e,account:r})}};var kt=class{apps;constructor(t){this.apps=new Map(t.map(e=>[e.application,e]))}getAppHelper(t){let e=this.apps.get(t);if(!e)throw new Error(`${t} not registered`);return e}};var jt=require("@msafe/sui3-utils"),Fe=require("@mysten/sui.js/transactions"),Bt=require("@mysten/sui.js/utils"),Dr=Gt(require("sort-keys-recursive")),Pr="msafe-plain-tx",Er=jt.TransactionSubTypes.others.plain;var Rt=class{application;constructor(){this.application=Pr}async deserialize(t){let{transactionBlock:e,suiClient:r}=t,a=await e.build({client:r});return{txType:jt.TransactionType.Other,txSubType:Er,intentionData:{content:(0,Bt.toHEX)(a)}}}async build(t){let{suiClient:e,account:r}=t,a=Fe.TransactionBlock.from((0,Bt.fromHEX)(t.intentionData.content)),o=await e.devInspectTransactionBlock({transactionBlock:a,sender:r.address});if(!(o.effects.status.status==="success"))throw new Error(o.effects.status.error);return a}};var Mr=new kt([new Mt,new Ot,new Rt]);
|
|
2910
2
|
//# sourceMappingURL=index.js.map
|