@msafe/sui3-sdk 0.0.2-pre-9f39791.0 → 0.0.2

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 ADDED
@@ -0,0 +1,1750 @@
1
+ // src/transactions/coin-transfer.ts
2
+ import { TransactionBlock } from "@mysten/sui.js/transactions";
3
+
4
+ // src/utils/format.ts
5
+ import { normalizeSuiAddress, normalizeStructTag as normalizeStructTag2 } from "@mysten/sui.js/utils";
6
+
7
+ // src/utils/coin.ts
8
+ import { normalizeStructTag } from "@mysten/sui.js/utils";
9
+ var CoinHelper = class {
10
+ _client;
11
+ _coinMetaReg;
12
+ constructor(client) {
13
+ this._client = client;
14
+ this._coinMetaReg = /* @__PURE__ */ new Map();
15
+ }
16
+ async getCoinMeta(coinType) {
17
+ const normalized = normalizeStructTag(coinType);
18
+ if (this._coinMetaReg.has(normalized)) {
19
+ return this._coinMetaReg.get(normalized);
20
+ }
21
+ const meta = await this.queryCoinMeta(normalized);
22
+ if (meta) {
23
+ this._coinMetaReg.set(normalized, meta);
24
+ }
25
+ return meta;
26
+ }
27
+ async queryCoinMeta(coinType) {
28
+ const res = await this._client.getCoinMetadata({ coinType });
29
+ return res || void 0;
30
+ }
31
+ };
32
+ var COIN_TYPE_ARG_REGEX = /^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/;
33
+ var Coin = class _Coin {
34
+ static isCoin(type) {
35
+ if (!type) {
36
+ return false;
37
+ }
38
+ return normalizeStructTag(type).match(COIN_TYPE_ARG_REGEX) != null;
39
+ }
40
+ static getCoinType(type) {
41
+ const [, res] = normalizeStructTag(type).match(COIN_TYPE_ARG_REGEX) ?? [];
42
+ return res || null;
43
+ }
44
+ static getBalance(data) {
45
+ if (!_Coin.isCoin(data.type)) {
46
+ return void 0;
47
+ }
48
+ if (data.content?.dataType !== "moveObject") {
49
+ return void 0;
50
+ }
51
+ const { balance } = data.content?.fields;
52
+ if (balance === void 0) {
53
+ return void 0;
54
+ }
55
+ return BigInt(balance);
56
+ }
57
+ };
58
+
59
+ // src/utils/format.ts
60
+ var Formatter = class {
61
+ static normalizeSuiAddress(addr) {
62
+ return normalizeSuiAddress(addr);
63
+ }
64
+ static normalizeStructTag(struct) {
65
+ return normalizeStructTag2(struct);
66
+ }
67
+ static isSuiAddressEqual(addr1, addr2) {
68
+ return normalizeSuiAddress(addr1) === normalizeSuiAddress(addr2);
69
+ }
70
+ static isSuiStructEqual(struct1, struct2) {
71
+ return normalizeStructTag2(struct1) === normalizeStructTag2(struct2);
72
+ }
73
+ static isCoinObjectType(struct) {
74
+ return Coin.isCoin(struct);
75
+ }
76
+ };
77
+
78
+ // src/utils/sui.ts
79
+ import { parseSerializedSignature } from "@mysten/sui.js/cryptography";
80
+ import { MultiSigPublicKey } from "@mysten/sui.js/multisig";
81
+
82
+ // src/utils/crypto.ts
83
+ import {
84
+ SIGNATURE_FLAG_TO_SCHEME
85
+ } from "@mysten/sui.js/cryptography";
86
+ import { Ed25519PublicKey } from "@mysten/sui.js/keypairs/ed25519";
87
+ import { Secp256k1PublicKey } from "@mysten/sui.js/keypairs/secp256k1";
88
+ import { Secp256r1PublicKey } from "@mysten/sui.js/keypairs/secp256r1";
89
+ import { verifyPersonalMessage, verifyTransactionBlock } from "@mysten/sui.js/verify";
90
+
91
+ // src/utils/buffer.ts
92
+ function stringToBuffer(s) {
93
+ return Buffer.from(s, "utf-8");
94
+ }
95
+ function Uint8ArrayToHex(b) {
96
+ return `0x${Array.prototype.map.call(b, (x) => `0${x.toString(16)}`.slice(-2)).join("")}`;
97
+ }
98
+ function HexToUint8Array(hex) {
99
+ return Uint8Array.from(Buffer.from(hex.startsWith("0x") ? hex.slice(2) : hex, "hex"));
100
+ }
101
+
102
+ // src/utils/crypto.ts
103
+ var SignatureVerifier = class _SignatureVerifier {
104
+ static async getPublicKeyFromSignature(input) {
105
+ if (input.messageType === "TransactionBlock") {
106
+ return verifyTransactionBlock(input.message, input.signature);
107
+ }
108
+ return verifyPersonalMessage(input.message, input.signature);
109
+ }
110
+ static async getPublicKeyFromPersonalSignature(input) {
111
+ const message = stringToBuffer(input.messageStr);
112
+ return this.getPublicKeyFromSignature({
113
+ message,
114
+ messageType: "Personal",
115
+ signature: input.signature
116
+ });
117
+ }
118
+ static async verifySignature(input) {
119
+ const publicKey = await _SignatureVerifier.getPublicKeyFromSignature(input);
120
+ return Formatter.isSuiAddressEqual(publicKey.toSuiAddress(), input.targetAddress);
121
+ }
122
+ static async verifyPersonalSignature(input) {
123
+ const message = stringToBuffer(input.messageStr);
124
+ return this.verifySignature({
125
+ message,
126
+ messageType: "Personal",
127
+ signature: input.signature,
128
+ targetAddress: input.targetAddress
129
+ });
130
+ }
131
+ static async verifyTransactionSignature(input) {
132
+ return this.verifySignature({
133
+ messageType: "TransactionBlock",
134
+ message: input.payload,
135
+ signature: input.signature,
136
+ targetAddress: input.targetAddress
137
+ });
138
+ }
139
+ };
140
+ var PublicKeySerde = class {
141
+ static ser(publicKey) {
142
+ return {
143
+ publicKey: publicKey.toBase64(),
144
+ scheme: SIGNATURE_FLAG_TO_SCHEME[publicKey.flag()]
145
+ };
146
+ }
147
+ static de(input) {
148
+ switch (input.scheme) {
149
+ case "ED25519":
150
+ return new Ed25519PublicKey(input.publicKey);
151
+ case "Secp256k1":
152
+ return new Secp256k1PublicKey(input.publicKey);
153
+ case "Secp256r1":
154
+ return new Secp256r1PublicKey(input.publicKey);
155
+ default:
156
+ throw new Error("Unsupported signature scheme: $input.scheme");
157
+ }
158
+ }
159
+ };
160
+
161
+ // src/utils/sui.ts
162
+ var SUI_COIN = "0x2::sui::SUI";
163
+ async function getPublicKeyFromChain(suiClient, address) {
164
+ let txs;
165
+ try {
166
+ txs = await suiClient.queryTransactionBlocks({
167
+ // Disable naming rule since the variable is defined by Mysten
168
+ filter: { FromAddress: address },
169
+ options: { showInput: true },
170
+ limit: 2
171
+ });
172
+ } catch (e) {
173
+ return void 0;
174
+ }
175
+ if (txs.data.length === 0 || !txs.data[0].transaction?.txSignatures) {
176
+ return void 0;
177
+ }
178
+ const tx = txs.data[0];
179
+ const signatures = tx.transaction?.txSignatures;
180
+ for (let i = 0; i !== signatures.length; i++) {
181
+ const serializedSig = signatures[i];
182
+ const pk = getAddressFromSignatures(serializedSig, address);
183
+ if (!pk) {
184
+ continue;
185
+ }
186
+ return pk;
187
+ }
188
+ return void 0;
189
+ }
190
+ function getAddressFromSignatures(serializedSig, targetAddress) {
191
+ const decoded = parseSerializedSignature(serializedSig);
192
+ switch (decoded.signatureScheme) {
193
+ case "MultiSig": {
194
+ const multiSigAddress = new MultiSigPublicKey(decoded.multisig.multisig_pk).toSuiAddress();
195
+ if (Formatter.isSuiAddressEqual(multiSigAddress, targetAddress)) {
196
+ throw new Error("multi-sig wallet cannot be owner");
197
+ }
198
+ return void 0;
199
+ }
200
+ case "ZkLogin": {
201
+ if (Formatter.isSuiAddressEqual(decoded.zkLogin.address, targetAddress)) {
202
+ throw new Error("ZkLogin wallet cannot be owner");
203
+ }
204
+ return void 0;
205
+ }
206
+ case "ED25519":
207
+ case "Secp256k1":
208
+ case "Secp256r1": {
209
+ const pk = PublicKeySerde.de({ publicKey: decoded.publicKey, scheme: decoded.signatureScheme });
210
+ if (Formatter.isSuiAddressEqual(pk.toSuiAddress(), targetAddress)) {
211
+ return pk;
212
+ }
213
+ return void 0;
214
+ }
215
+ default:
216
+ throw new Error("Unknown schema");
217
+ }
218
+ }
219
+ async function getAllCoins(input) {
220
+ let hasNext = true;
221
+ let cursor;
222
+ const res = [];
223
+ while (hasNext) {
224
+ const currentPage = await input.suiClient.getCoins({
225
+ owner: input.owner,
226
+ coinType: input.coinType,
227
+ cursor
228
+ });
229
+ res.push(...currentPage.data);
230
+ hasNext = currentPage.hasNextPage;
231
+ cursor = currentPage.nextCursor;
232
+ }
233
+ return res;
234
+ }
235
+
236
+ // src/transactions/coin-transfer.ts
237
+ async function buildCoinTransferTxb(input) {
238
+ if (Formatter.isSuiStructEqual(input.intention.coinType, SUI_COIN)) {
239
+ return buildSuiCoinTransferTxb(input);
240
+ }
241
+ return buildOtherCoinTransferTxb(input);
242
+ }
243
+ function buildSuiCoinTransferTxb(input) {
244
+ const txb = new TransactionBlock();
245
+ const [coin] = txb.splitCoins(txb.gas, [txb.pure(input.intention.amount)]);
246
+ txb.transferObjects([coin], txb.pure(input.intention.recipient));
247
+ txb.setSender(input.sender);
248
+ return txb;
249
+ }
250
+ async function buildOtherCoinTransferTxb(input) {
251
+ const { suiClient, sender, intention } = input;
252
+ const objs = await getAllCoins({
253
+ suiClient,
254
+ owner: sender,
255
+ coinType: intention.coinType
256
+ });
257
+ if (objs.length === 0) {
258
+ throw new Error("No valid coin found to send");
259
+ }
260
+ const totalBal = objs.reduce((sum, coin2) => sum + BigInt(coin2.balance), 0n);
261
+ if (totalBal < BigInt(intention.amount)) {
262
+ throw new Error("Not enough balance");
263
+ }
264
+ const txb = new TransactionBlock();
265
+ const primary = txb.object(objs[0].coinObjectId);
266
+ if (objs.length > 1) {
267
+ txb.mergeCoins(
268
+ primary,
269
+ objs.slice(1).map((obj) => txb.object(obj.coinObjectId))
270
+ );
271
+ }
272
+ const [coin] = txb.splitCoins(primary, [txb.pure(intention.amount)]);
273
+ txb.transferObjects([coin], txb.pure(intention.recipient));
274
+ txb.setSender(input.sender);
275
+ return txb;
276
+ }
277
+
278
+ // src/transactions/object-transfer.ts
279
+ import { TransactionBlock as TransactionBlock2 } from "@mysten/sui.js/transactions";
280
+ async function buildObjectTransferTxb(input) {
281
+ await validateObjectTransfer(input);
282
+ const txb = new TransactionBlock2();
283
+ txb.transferObjects([txb.object(input.intention.objectId)], txb.pure(input.intention.receiver));
284
+ txb.setSender(input.sender);
285
+ return txb;
286
+ }
287
+ async function validateObjectTransfer(input) {
288
+ const { suiClient, sender, intention } = input;
289
+ const obj = await suiClient.getObject({
290
+ id: intention.objectId
291
+ });
292
+ if (obj.data === void 0) {
293
+ throw new Error("Object not found");
294
+ }
295
+ if (!obj.data?.type) {
296
+ throw new Error("Object type is null");
297
+ }
298
+ if (!Formatter.isSuiStructEqual(obj.data.type, intention.objectType)) {
299
+ throw new Error("Object type not expected");
300
+ }
301
+ if (Formatter.isCoinObjectType(obj.data.type)) {
302
+ throw new Error("Can not transfer coin object in Object Transfer transactions");
303
+ }
304
+ const addressOwner = getAddressOwner(obj);
305
+ if (!Formatter.isSuiAddressEqual(addressOwner, sender)) {
306
+ throw new Error("Object owner not match");
307
+ }
308
+ }
309
+ function getAddressOwner(object) {
310
+ const owner = object.data?.owner;
311
+ if (!owner) {
312
+ throw new Error("Object Owner not found");
313
+ }
314
+ if (typeof owner !== "object" || !("AddressOwner" in owner)) {
315
+ throw new Error("Invalid object owner");
316
+ }
317
+ return owner.AddressOwner;
318
+ }
319
+
320
+ // src/transactions/reject.ts
321
+ import { TransactionBlock as TransactionBlock3 } from "@mysten/sui.js/transactions";
322
+ async function buildRejectTxb(input) {
323
+ const approveTxb = TransactionBlock3.from(HexToUint8Array(input.payloadToReject));
324
+ const gasPayment = approveTxb.blockData.gasConfig.payment;
325
+ if (!gasPayment) {
326
+ throw new Error("No gas payment found for approve payload");
327
+ }
328
+ const txb = new TransactionBlock3();
329
+ txb.setGasPayment(gasPayment);
330
+ txb.setSender(input.sender);
331
+ return txb;
332
+ }
333
+
334
+ // src/transactions/intention.ts
335
+ var IntentionHelper = class {
336
+ static ser(intention) {
337
+ return JSON.stringify(intention);
338
+ }
339
+ static de(val) {
340
+ const intention = JSON.parse(val);
341
+ if (typeof intention !== "object" || !("txType" in intention)) {
342
+ throw new Error(`Failed to deserialize intention: ${val}`);
343
+ }
344
+ return JSON.parse(val);
345
+ }
346
+ // TODO: Add gas option here.
347
+ static buildTxb(input) {
348
+ switch (input.intention.txType) {
349
+ case "CoinTransfer":
350
+ return buildCoinTransferTxb({
351
+ suiClient: input.suiClient,
352
+ sender: input.sender,
353
+ intention: input.intention
354
+ });
355
+ case "ObjectTransfer":
356
+ return buildObjectTransferTxb({
357
+ suiClient: input.suiClient,
358
+ sender: input.sender,
359
+ intention: input.intention
360
+ });
361
+ default:
362
+ throw new Error(`Unknown tx type: ${input.intention}`);
363
+ }
364
+ }
365
+ static getTxType(intention) {
366
+ switch (intention.txType) {
367
+ case "CoinTransfer":
368
+ return {
369
+ txType: "CoinTransfer",
370
+ txSubType: "CoinTransfer"
371
+ };
372
+ case "ObjectTransfer":
373
+ return {
374
+ txType: "ObjectTransfer",
375
+ txSubType: "ObjectTransfer"
376
+ };
377
+ default:
378
+ throw new Error("Unknown intention type");
379
+ }
380
+ }
381
+ static buildRejectTransaction(input) {
382
+ return buildRejectTxb({ sender: input.msafeAddress, payloadToReject: input.payloadToReject });
383
+ }
384
+ };
385
+
386
+ // src/core/MessageHelper.ts
387
+ var MessageHelper = class {
388
+ // Message used for MSafe creation
389
+ static createMSafeMessage(msafeAddress) {
390
+ return `Create MSafe Account: ${msafeAddress}`;
391
+ }
392
+ static deCreateMSafeMessage(msg) {
393
+ const regex = /Create MSafe Account: (.+)/;
394
+ const matches = msg.match(regex);
395
+ return matches ? matches[1] : void 0;
396
+ }
397
+ // Message to be used when user login. The timestamp string
398
+ // is used to for extra validation.
399
+ static welcomeMessage(timestamp) {
400
+ return `Welcome to MSafe. ${timestamp}`;
401
+ }
402
+ static deWelcomeMessage(msg) {
403
+ const regex = /Welcome to MSafe. (.+)/;
404
+ const matches = msg.match(regex);
405
+ return matches ? matches[1] : void 0;
406
+ }
407
+ static proposeIntentionMessage(data) {
408
+ const { intention, sn } = data;
409
+ const intentionData = IntentionHelper.ser(intention);
410
+ const msg = {
411
+ intentionData,
412
+ sequenceNumber: sn
413
+ };
414
+ return JSON.stringify(msg);
415
+ }
416
+ static deProposeIntentionMessage(s) {
417
+ const de = JSON.parse(s);
418
+ if (!("intentionData" in de) || typeof de.intentionData !== "string" || !("sequenceNumber" in de) || typeof de.sequenceNumber !== "number") {
419
+ throw new Error("Invalid intention data");
420
+ }
421
+ const { sequenceNumber, intentionData } = de;
422
+ return {
423
+ sn: sequenceNumber,
424
+ intention: IntentionHelper.de(intentionData)
425
+ };
426
+ }
427
+ };
428
+
429
+ // src/utils/multi-sig.ts
430
+ import { Ed25519PublicKey as Ed25519PublicKey2 } from "@mysten/sui.js/keypairs/ed25519";
431
+ import { MultiSigPublicKey as MultiSigPublicKey2 } from "@mysten/sui.js/multisig";
432
+ var NONCE_PK_PREFIX = "maven";
433
+ var NONCE_PREFIX_MAX_SIZE = 16;
434
+ var NONCE_PK_WEIGHT = 1;
435
+ var MAX_WEIGHT = 255;
436
+ var MIN_WEIGHT = 1;
437
+ var MAX_OWNER_WITH_NONCE = 9;
438
+ var MAX_OWNER_WITHOUT_NONCE = 10;
439
+ var MIN_THRESHOLD = 1;
440
+ var RawMultiSig = class _RawMultiSig {
441
+ constructor(config) {
442
+ this.config = config;
443
+ this.rawMsPK = getMultiSigPublicKey(config);
444
+ }
445
+ rawMsPK;
446
+ static fromMSafeAccountInfo(info) {
447
+ const parsed = {
448
+ threshold: info.threshold,
449
+ ownerWithWeight: info.ownersWithWeightPK,
450
+ creationNonce: info.creationNonce
451
+ };
452
+ return new _RawMultiSig(parsed);
453
+ }
454
+ get suiAddress() {
455
+ return this.rawMsPK.toSuiAddress();
456
+ }
457
+ get publicKeys() {
458
+ return this.rawMsPK.getPublicKeys();
459
+ }
460
+ get threshold() {
461
+ return this.config.threshold;
462
+ }
463
+ combinePartialSignatures(signatures) {
464
+ return this.rawMsPK.combinePartialSignatures(signatures);
465
+ }
466
+ async verifyPersonalMessage(messageStr, multiSigSignature) {
467
+ const message = stringToBuffer(messageStr);
468
+ return this.rawMsPK.verifyPersonalMessage(message, multiSigSignature);
469
+ }
470
+ };
471
+ function getMultiSigPublicKey(config) {
472
+ const { ownerWithWeight, threshold, creationNonce } = config;
473
+ const pks = ownerWithWeight.map((pk) => ({
474
+ publicKey: pk.publicKey,
475
+ weight: pk.weight
476
+ }));
477
+ if (creationNonce !== void 0) {
478
+ pks.push({
479
+ publicKey: makeNoncePublicKey(creationNonce),
480
+ weight: NONCE_PK_WEIGHT
481
+ });
482
+ }
483
+ return MultiSigPublicKey2.fromPublicKeys({ threshold, publicKeys: pks });
484
+ }
485
+ function makeNoncePublicKey(nonce) {
486
+ const buffer = new ArrayBuffer(Ed25519PublicKey2.SIZE);
487
+ const textEncoder = new TextEncoder();
488
+ textEncoder.encodeInto(NONCE_PK_PREFIX, new Uint8Array(buffer, 0, NONCE_PREFIX_MAX_SIZE));
489
+ const nonceView = new DataView(buffer, NONCE_PREFIX_MAX_SIZE, 4);
490
+ nonceView.setUint32(0, nonce, true);
491
+ return new Ed25519PublicKey2(new Uint8Array(buffer));
492
+ }
493
+ function validateMultiSigConfig(config) {
494
+ config.ownerWithWeight.forEach((pk) => {
495
+ const { weight } = pk;
496
+ if (weight < MIN_WEIGHT || weight > MAX_WEIGHT) {
497
+ throw new Error(`Invalid multi-sig weight: ${weight} (1-${MAX_WEIGHT})`);
498
+ }
499
+ });
500
+ const totalWeight = config.ownerWithWeight.reduce((s, pk) => s + pk.weight, 0);
501
+ if (config.threshold > totalWeight) {
502
+ throw new Error("Threshold is larger than total weight");
503
+ }
504
+ if (config.threshold < MIN_THRESHOLD) {
505
+ throw new Error("Threshold is smaller than 1");
506
+ }
507
+ const maxOwner = config.creationNonce === void 0 ? MAX_OWNER_WITHOUT_NONCE : MAX_OWNER_WITH_NONCE;
508
+ if (config.ownerWithWeight.length > maxOwner) {
509
+ throw new Error("Owner number bigger than upper cap");
510
+ }
511
+ const addressSet = new Set(config.ownerWithWeight.map((pk) => pk.publicKey.toSuiAddress()));
512
+ if (addressSet.size !== config.ownerWithWeight.length) {
513
+ throw new Error("Duplicate address detected");
514
+ }
515
+ }
516
+
517
+ // src/core/CreateHelper.ts
518
+ var CreateHelper = class {
519
+ constructor(globals, pkHelper) {
520
+ this.globals = globals;
521
+ this.pkHelper = pkHelper;
522
+ }
523
+ async getPublicKeyBatch(addresses) {
524
+ return this.pkHelper.getPublicKeyBatch(addresses);
525
+ }
526
+ async calculateMSafeAddress(info) {
527
+ const msConfig = await this.reduceCreationInfoToRawConfig(info);
528
+ const ms = new RawMultiSig(msConfig);
529
+ return ms.suiAddress;
530
+ }
531
+ // Validate the create info and return the msafe address.
532
+ async validateCreateInfo(createInfo) {
533
+ const rawConfig = await this.reduceCreationInfoToRawConfig(createInfo);
534
+ validateMultiSigConfig(rawConfig);
535
+ return this.calculateMSafeAddress(createInfo);
536
+ }
537
+ async submitMSafeCreation(creationInfo) {
538
+ const msafeAddress = await this.validateCreateInfo(creationInfo);
539
+ const signingMessage = MessageHelper.createMSafeMessage(msafeAddress);
540
+ const signature = await this.globals.wallet.signPersonalMessage({ messageStr: signingMessage });
541
+ await this.submitToBackend(creationInfo, signature.signature);
542
+ return msafeAddress;
543
+ }
544
+ async reduceCreationInfoToRawConfig(info) {
545
+ const publicKeys = await this.getPublicKeyBatch(info.ownerWithWeight.map((oww) => oww.address));
546
+ publicKeys.forEach((pk, i) => {
547
+ if (pk === void 0) {
548
+ throw new Error(`Unknown public key for address: ${info.ownerWithWeight[i].address}`);
549
+ }
550
+ });
551
+ return {
552
+ threshold: info.threshold,
553
+ ownerWithWeight: info.ownerWithWeight.map((owner, i) => ({
554
+ publicKey: publicKeys[i],
555
+ weight: owner.weight
556
+ })),
557
+ creationNonce: info.creationNonce
558
+ };
559
+ }
560
+ async submitToBackend(createInfo, signature) {
561
+ const pks = await this.pkHelper.getPublicKeyBatch(createInfo.ownerWithWeight.map((owner) => owner.address));
562
+ await this.globals.backend.createMSafeAccount({
563
+ ownerWithWeight: createInfo.ownerWithWeight.map((owner, i) => ({
564
+ address: owner.address,
565
+ weight: owner.weight,
566
+ publicKey: pks[i]
567
+ // PublicKey has been verified.
568
+ })),
569
+ threshold: createInfo.threshold,
570
+ name: createInfo.name,
571
+ // name validation is deferred to backend
572
+ description: createInfo.description,
573
+ // description validation is deferred to backend
574
+ creationNonce: createInfo.creationNonce,
575
+ signature
576
+ });
577
+ }
578
+ };
579
+
580
+ // src/core/MSafeAccount.ts
581
+ var MSafeAccount = class _MSafeAccount {
582
+ constructor(globals, info) {
583
+ this.globals = globals;
584
+ this.info = info;
585
+ this.rawMultiSig = RawMultiSig.fromMSafeAccountInfo(info);
586
+ }
587
+ rawMultiSig;
588
+ static async new(globals, address) {
589
+ const info = await globals.backend.getMSafeAccountInfo(address);
590
+ return new _MSafeAccount(globals, info);
591
+ }
592
+ async pendingTransactions() {
593
+ return this.backend.getPendingTransactions(this.address);
594
+ }
595
+ async historyTransaction() {
596
+ return this.backend.getHistoryTransactions(this.address);
597
+ }
598
+ async futureIntentions() {
599
+ return this.backend.getFutureIntentions(this.address);
600
+ }
601
+ async currentSequenceNumber() {
602
+ return this.backend.getCurrentSequenceNumber(this.address);
603
+ }
604
+ async nextSequenceNumber() {
605
+ return this.backend.getNextSequenceNumber(this.address);
606
+ }
607
+ async proposeIntention(intention, sequenceNumber) {
608
+ const message = MessageHelper.proposeIntentionMessage({ intention, sn: sequenceNumber });
609
+ const signature = await this.wallet.signPersonalMessage({
610
+ messageStr: message
611
+ });
612
+ await this.backend.proposeIntention({
613
+ intention,
614
+ sequenceNumber,
615
+ msafeAddress: this.address,
616
+ userAddress: await this.userAddress(),
617
+ signature: signature.signature
618
+ });
619
+ }
620
+ async voteForTransaction(digest, payload) {
621
+ const payloadBytes = HexToUint8Array(payload);
622
+ const signature = await this.wallet.signTransactionBlock({ transactionBlock: payloadBytes });
623
+ return this.backend.voteForTransaction({
624
+ msafeAddress: this.address,
625
+ userAddress: await this.userAddress(),
626
+ txDigest: digest,
627
+ signature: signature.signature
628
+ });
629
+ }
630
+ // Shortcut for proposing a transaction to be a pending transaction, and add user vote to it.
631
+ // Requires the multi-sig to be empty in pending transaction.
632
+ async proposePendingTransaction(intention) {
633
+ const txb = await IntentionHelper.buildTxb({
634
+ suiClient: this.suiClient,
635
+ intention,
636
+ sender: this.address
637
+ });
638
+ const payload = await txb.build({ client: this.suiClient });
639
+ const digest = await txb.getDigest({ client: this.suiClient });
640
+ const signature = await this.wallet.signTransactionBlock({ transactionBlock: payload });
641
+ return this.backend.proposePendingTransaction({
642
+ msafeAddress: this.address,
643
+ userAddress: await this.userAddress(),
644
+ intention,
645
+ digest,
646
+ signature: signature.signature
647
+ });
648
+ }
649
+ async rejectCurrentTx(pending) {
650
+ let payloadToReject;
651
+ if (pending) {
652
+ if (pending.isRejectTx) {
653
+ throw new Error("Pending not reject transaction");
654
+ }
655
+ payloadToReject = pending.payload;
656
+ } else {
657
+ const pendings = await this.pendingTransactions();
658
+ if (pendings.length !== 1 || pendings[0].isRejectTx) {
659
+ throw new Error("Already rejected");
660
+ }
661
+ payloadToReject = pendings[0].payload;
662
+ }
663
+ const rejectTxb = await IntentionHelper.buildRejectTransaction({
664
+ msafeAddress: this.address,
665
+ payloadToReject
666
+ });
667
+ const digest = await rejectTxb.getDigest({ client: this.suiClient });
668
+ const payload = await rejectTxb.build({ client: this.suiClient });
669
+ const signature = await this.wallet.signTransactionBlock({ transactionBlock: payload });
670
+ return this.backend.rejectCurrentTx({
671
+ msafeAddress: this.address,
672
+ userAddress: await this.userAddress(),
673
+ digest,
674
+ signature: signature.signature
675
+ });
676
+ }
677
+ async buildNextIntentionAndAddToPending() {
678
+ return this.backend.buildNextIntentionAndAddToPending({ msafeAddress: this.address });
679
+ }
680
+ async skipNextFailedIntention() {
681
+ return this.backend.skipNextFailedIntention({ msafeAddress: this.address, userAddress: await this.userAddress() });
682
+ }
683
+ async executePendingTx(pending) {
684
+ if (pending.votes.length < this.info.threshold) {
685
+ throw new Error("Not enough signatures");
686
+ }
687
+ const sigs = [];
688
+ const gotSigs = new Map(pending.votes.map((vote) => [vote.userAddress, vote.signature]));
689
+ for (let i = 0; i < this.info.ownersWithWeightPK.length; i++) {
690
+ const owner = this.info.ownersWithWeightPK[i];
691
+ const signature = gotSigs.get(owner.publicKey.toSuiAddress());
692
+ if (signature) {
693
+ sigs.push(signature);
694
+ }
695
+ }
696
+ const multiSignature = this.rawMultiSig.combinePartialSignatures(sigs);
697
+ return this.suiClient.executeTransactionBlock({
698
+ transactionBlock: HexToUint8Array(pending.payload),
699
+ signature: multiSignature,
700
+ options: { showEffects: true }
701
+ });
702
+ }
703
+ get address() {
704
+ return this.info.address;
705
+ }
706
+ get backend() {
707
+ return this.globals.backend;
708
+ }
709
+ get wallet() {
710
+ return this.globals.wallet;
711
+ }
712
+ async userAddress() {
713
+ return this.globals.wallet.address();
714
+ }
715
+ get suiClient() {
716
+ return this.globals.suiClient;
717
+ }
718
+ };
719
+
720
+ // src/core/PublicKeyHelper.ts
721
+ var PublicKeyHelper = class {
722
+ constructor(globals) {
723
+ this.globals = globals;
724
+ this.knownPublicKeys = /* @__PURE__ */ new Map();
725
+ }
726
+ knownPublicKeys;
727
+ async getPublicKey(address) {
728
+ const cached = this.knownPublicKeys.get(address);
729
+ if (cached) {
730
+ return cached;
731
+ }
732
+ const pk = await this._getPublicKey(address);
733
+ if (pk) {
734
+ this.knownPublicKeys.set(address, pk);
735
+ }
736
+ return pk;
737
+ }
738
+ async getPublicKeyBatch(addresses) {
739
+ const results = new Array(addresses.length).fill(void 0);
740
+ for (let i = 0; i < addresses.length; i++) {
741
+ const address = addresses[i];
742
+ results[i] = this.knownPublicKeys.get(address);
743
+ }
744
+ const emptyIndexes = results.map((elem, index) => elem === void 0 ? index : -1).filter((index) => index !== -1);
745
+ const backendResult = await this.globals.backend.getPublicKeyBatch(emptyIndexes.map((index) => addresses[index]));
746
+ for (let i = 0; i < emptyIndexes.length; i++) {
747
+ const index = emptyIndexes[i];
748
+ results[index] = backendResult[i];
749
+ }
750
+ for (let i = 0; i < results.length; i++) {
751
+ if (results[i] === void 0) {
752
+ results[i] = await this.getPublicKeyFromChain(addresses[i]);
753
+ }
754
+ }
755
+ for (let i = 0; i < addresses.length; i++) {
756
+ if (results[i]) {
757
+ this.knownPublicKeys.set(addresses[i], results[i]);
758
+ }
759
+ }
760
+ return results;
761
+ }
762
+ async _getPublicKey(address) {
763
+ const pkBackend = await this.getPublicKeyFromBackend(address);
764
+ if (pkBackend) {
765
+ return pkBackend;
766
+ }
767
+ const pkChain = await this.getPublicKeyFromChain(address);
768
+ if (pkChain) {
769
+ return pkChain;
770
+ }
771
+ return void 0;
772
+ }
773
+ async getPublicKeyFromBackend(address) {
774
+ try {
775
+ const pk = await this.globals.backend.getPublicKey(address);
776
+ return pk;
777
+ } catch (_) {
778
+ return void 0;
779
+ }
780
+ }
781
+ async getPublicKeyFromChain(address) {
782
+ return getPublicKeyFromChain(this.globals.suiClient, address);
783
+ }
784
+ };
785
+
786
+ // src/globals/MSafeGlobals.ts
787
+ import { SuiClient } from "@mysten/sui.js/client";
788
+
789
+ // src/backend/PseudoBackend.ts
790
+ import "reflect-metadata";
791
+ import { MoreThanOrEqual } from "typeorm";
792
+
793
+ // src/backend/CoreDatabase.ts
794
+ import "reflect-metadata";
795
+ import { CoreModel } from "@msafe/sui3-model/core";
796
+ var WALLET_TYPE_KEY = "wallet_type";
797
+ var CoreDB = class _CoreDB {
798
+ constructor(coreModel) {
799
+ this.coreModel = coreModel;
800
+ }
801
+ static async New(dbConfig) {
802
+ const core = await CoreModel.New(dbConfig);
803
+ return new _CoreDB(core);
804
+ }
805
+ async upsertUser(input) {
806
+ const currentUser = await this.coreModel.user.findOneBy({
807
+ address: input.address
808
+ });
809
+ if (currentUser !== null) {
810
+ currentUser.lastLogin = input.lastLogin;
811
+ await this.coreModel.user.save(currentUser);
812
+ } else {
813
+ const serializedPublicKey = PublicKeySerde.ser(input.publicKey);
814
+ const user = {
815
+ address: input.address,
816
+ publicKey: serializedPublicKey.publicKey,
817
+ schema: serializedPublicKey.scheme,
818
+ nonce: 0,
819
+ lastLogin: /* @__PURE__ */ new Date()
820
+ };
821
+ await this.coreModel.user.save(user);
822
+ }
823
+ }
824
+ async updateUserWalletType(input) {
825
+ const exist = await this.coreModel.userSetting.findOneBy({
826
+ userAddress: input.address,
827
+ key: WALLET_TYPE_KEY
828
+ });
829
+ const walletType = input.walletType.trim();
830
+ if (exist === null || exist.value !== walletType) {
831
+ const userSetting = {
832
+ userAddress: input.address,
833
+ key: WALLET_TYPE_KEY,
834
+ value: walletType
835
+ };
836
+ await this.coreModel.userSetting.save(userSetting);
837
+ }
838
+ }
839
+ };
840
+
841
+ // src/backend/PseudoBackend.ts
842
+ var PseudoBackend = class _PseudoBackend {
843
+ constructor(db, _suiClient) {
844
+ this.db = db;
845
+ this._suiClient = _suiClient;
846
+ }
847
+ _token;
848
+ static async New(dbConfig, suiClient) {
849
+ const db = await CoreDB.New(dbConfig);
850
+ return new _PseudoBackend(db, suiClient);
851
+ }
852
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars,unused-imports/no-unused-vars
853
+ async isJWTTokenValid(_jwt) {
854
+ return true;
855
+ }
856
+ async authSign(input) {
857
+ const timestamp = MessageHelper.deWelcomeMessage(input.message);
858
+ if (!timestamp) {
859
+ throw new Error("Invalid welcome message");
860
+ }
861
+ const date = Date.parse(timestamp);
862
+ if ((/* @__PURE__ */ new Date()).getTime() - date < 0) {
863
+ throw new Error("Invalid timestamp");
864
+ }
865
+ if ((/* @__PURE__ */ new Date()).getTime() - date > 10 * 1e3) {
866
+ throw new Error("Signing message expired");
867
+ }
868
+ const publicKey = await SignatureVerifier.getPublicKeyFromPersonalSignature({
869
+ messageStr: input.message,
870
+ signature: input.signature
871
+ });
872
+ if (!Formatter.isSuiAddressEqual(input.address, publicKey.toSuiAddress())) {
873
+ throw new Error("Invalid signature");
874
+ }
875
+ await this.db.upsertUser({
876
+ address: input.address,
877
+ publicKey,
878
+ lastLogin: /* @__PURE__ */ new Date()
879
+ });
880
+ await this.db.updateUserWalletType({
881
+ address: input.address,
882
+ walletType: input.walletType
883
+ });
884
+ this._token = "";
885
+ return this._token;
886
+ }
887
+ setJWTToken(token) {
888
+ this._token = token;
889
+ }
890
+ async getPublicKey(address) {
891
+ const user = await this.model.user.findOneBy({
892
+ address
893
+ });
894
+ if (user === null) {
895
+ return void 0;
896
+ }
897
+ return PublicKeySerde.de({
898
+ publicKey: user.publicKey,
899
+ scheme: user.schema
900
+ });
901
+ }
902
+ async getPublicKeyBatch(addresses) {
903
+ const res = [];
904
+ for (let i = 0; i < addresses.length; i++) {
905
+ const address = addresses[i];
906
+ const user = await this.getUser(address);
907
+ res.push(
908
+ user ? PublicKeySerde.de({
909
+ publicKey: user.publicKey,
910
+ scheme: user.schema
911
+ }) : void 0
912
+ );
913
+ }
914
+ return res;
915
+ }
916
+ async createMSafeAccount(input) {
917
+ const ms = new RawMultiSig(input);
918
+ const msafeAddr = ms.suiAddress;
919
+ const signingMsg = MessageHelper.createMSafeMessage(msafeAddr);
920
+ const targetAddr = input.ownerWithWeight[0].address;
921
+ const verifyResult = await SignatureVerifier.verifyPersonalSignature({
922
+ messageStr: signingMsg,
923
+ signature: input.signature,
924
+ targetAddress: targetAddr
925
+ });
926
+ if (!verifyResult) {
927
+ throw new Error("Signature verification failed");
928
+ }
929
+ if (input.name.length > 128) {
930
+ throw new Error("Name too long");
931
+ }
932
+ if (input.description && input.description.length > 512) {
933
+ throw new Error("Description too long");
934
+ }
935
+ const creatorAddress = input.ownerWithWeight[0].address;
936
+ const creator = await this.getUser(creatorAddress);
937
+ if (creator === null) {
938
+ throw new Error("Creator not found");
939
+ }
940
+ if (creator.nonce !== input.creationNonce) {
941
+ throw new Error("Nonce not match");
942
+ }
943
+ const msafeExistCheck = await this.model.msafe.findOneBy({
944
+ address: msafeAddr
945
+ });
946
+ if (msafeExistCheck !== null) {
947
+ throw new Error("MSafe already exist in database");
948
+ }
949
+ input.ownerWithWeight.forEach((ownerInfo) => {
950
+ if (!Formatter.isSuiAddressEqual(ownerInfo.address, ownerInfo.publicKey.toSuiAddress())) {
951
+ throw new Error("Sui address public key not match");
952
+ }
953
+ });
954
+ for (let i = 0; i !== input.ownerWithWeight.length; i++) {
955
+ const ownerInfo = input.ownerWithWeight[i];
956
+ if (i !== 0) {
957
+ const coManager = await this.getUser(ownerInfo.address);
958
+ const serPK = PublicKeySerde.ser(ownerInfo.publicKey);
959
+ if (coManager === null) {
960
+ const user = {
961
+ address: ownerInfo.address,
962
+ publicKey: serPK.publicKey,
963
+ schema: serPK.scheme,
964
+ nonce: 0,
965
+ lastLogin: /* @__PURE__ */ new Date()
966
+ };
967
+ await this.model.user.save(user);
968
+ }
969
+ }
970
+ const userMSafe = {
971
+ userAddress: ownerInfo.address,
972
+ msafeAddress: msafeAddr,
973
+ index: i,
974
+ weight: ownerInfo.weight,
975
+ status: i === 0 ? "active" : "pending"
976
+ };
977
+ await this.model.userMSafe.save(userMSafe);
978
+ }
979
+ const creationNonce = creator.nonce;
980
+ creator.nonce++;
981
+ await this.model.user.save(creator);
982
+ const msafe = {
983
+ address: msafeAddr,
984
+ creationNonce,
985
+ creator: creatorAddress,
986
+ name: input.name,
987
+ description: input.description,
988
+ threshold: input.threshold
989
+ };
990
+ await this.model.msafe.save(msafe);
991
+ }
992
+ async getMSafeAccountInfo(msafeAddress) {
993
+ const msafe = await this.model.msafe.findOneBy({ address: msafeAddress });
994
+ if (msafe === null) {
995
+ throw new Error("MSafe not found");
996
+ }
997
+ const userMSafes = await this.model.userMSafe.find({
998
+ where: {
999
+ msafeAddress
1000
+ },
1001
+ order: {
1002
+ index: "asc"
1003
+ }
1004
+ });
1005
+ if (userMSafes.length === 0) {
1006
+ throw new Error("MSafe does not have user info.");
1007
+ }
1008
+ const users = await Promise.all(userMSafes.map((um) => this.getUser(um.userAddress)));
1009
+ users.forEach((user) => {
1010
+ if (user === null) {
1011
+ throw new Error("User not found");
1012
+ }
1013
+ });
1014
+ const ownersWithWeightPK = userMSafes.map((userMSafe, i) => ({
1015
+ address: userMSafe.userAddress,
1016
+ weight: userMSafe.weight,
1017
+ publicKey: PublicKeySerde.de({ publicKey: users[i].publicKey, scheme: users[i].schema })
1018
+ }));
1019
+ return {
1020
+ address: msafeAddress,
1021
+ ownersWithWeightPK,
1022
+ threshold: msafe.threshold,
1023
+ name: msafe.name,
1024
+ description: msafe.description,
1025
+ creationNonce: msafe.creationNonce
1026
+ };
1027
+ }
1028
+ async getUserInfo(userAddress) {
1029
+ const user = await this.getUser(userAddress);
1030
+ if (user === null) {
1031
+ throw new Error("404: user not found");
1032
+ }
1033
+ const msafeAccounts = await this.model.userMSafe.findBy({ userAddress });
1034
+ const ownedMSafe = await Promise.all(
1035
+ msafeAccounts.map(async (msafeAccount) => this.getMSafeAccountInfo(msafeAccount.msafeAddress))
1036
+ );
1037
+ return {
1038
+ address: userAddress,
1039
+ publicKey: user.publicKey,
1040
+ schema: user.schema,
1041
+ creationNonce: user.nonce,
1042
+ ownedMSafe
1043
+ };
1044
+ }
1045
+ async getPendingTransactions(msafeAddress) {
1046
+ const pendings = await this.db.coreModel.pendingTransaction.findBy({
1047
+ msafeAddress
1048
+ });
1049
+ if (pendings.length === 0) {
1050
+ return [];
1051
+ }
1052
+ const votes = await Promise.all(
1053
+ pendings.map((pending) => this.db.coreModel.userVote.findBy({ txDigest: pending.digest, isValid: true }))
1054
+ );
1055
+ const intention = await this.model.transactionIntention.findOneBy({
1056
+ msafeAddress,
1057
+ sequenceNumber: pendings[0].sequenceNumber
1058
+ });
1059
+ if (intention === null) {
1060
+ throw new Error("Intention not found");
1061
+ }
1062
+ const intent = IntentionHelper.de(intention.data);
1063
+ return pendings.map((pending, i) => ({
1064
+ digest: pending.digest,
1065
+ payload: pending.payload,
1066
+ msafeAddress: pending.msafeAddress,
1067
+ isRejectTx: pending.isRejectTx,
1068
+ creator: pending.creator,
1069
+ createdAt: pending.createdAt,
1070
+ votes: votes[i].map((vote) => ({
1071
+ userAddress: vote.userAddress,
1072
+ signature: vote.signature,
1073
+ timestamp: vote.updatedAt
1074
+ })),
1075
+ sequenceNumber: pending.sequenceNumber,
1076
+ intention: pending.isRejectTx ? void 0 : intent
1077
+ }));
1078
+ }
1079
+ async getCurrentSequenceNumber(msafeAddress) {
1080
+ const maxSNHistory = await this.model.historyTransaction.findOne({
1081
+ where: { msafeAddress },
1082
+ order: { sequenceNumber: "desc" }
1083
+ });
1084
+ return maxSNHistory === null ? 0 : maxSNHistory.sequenceNumber + 1;
1085
+ }
1086
+ async getNextSequenceNumber(msafeAddress) {
1087
+ const maxSNIntention = await this.model.transactionIntention.findOne({
1088
+ where: { msafeAddress },
1089
+ order: { sequenceNumber: "desc" }
1090
+ });
1091
+ return maxSNIntention === null ? 0 : maxSNIntention.sequenceNumber + 1;
1092
+ }
1093
+ async getHistoryTransactions(msafeAddress) {
1094
+ const transactions = await this.db.coreModel.historyTransaction.find({
1095
+ where: {
1096
+ msafeAddress
1097
+ },
1098
+ order: { sequenceNumber: "desc" }
1099
+ });
1100
+ const votes = await Promise.all(
1101
+ transactions.map(
1102
+ (tx) => this.db.coreModel.userVote.findBy({
1103
+ txDigest: tx.digest,
1104
+ isValid: true
1105
+ })
1106
+ )
1107
+ );
1108
+ return transactions.map((tx, i) => ({
1109
+ digest: tx.digest,
1110
+ payload: tx.payload,
1111
+ msafeAddress: tx.msafeAddress,
1112
+ isRejectTx: tx.isRejectTx,
1113
+ status: tx.status,
1114
+ creator: tx.creator,
1115
+ createdAt: tx.createdAt,
1116
+ sequenceNumber: tx.sequenceNumber,
1117
+ votes: votes[i].map((vote) => ({
1118
+ userAddress: vote.userAddress,
1119
+ timestamp: vote.updatedAt
1120
+ }))
1121
+ }));
1122
+ }
1123
+ async getFutureIntentions(msafeAddress) {
1124
+ const currentSequenceNumber = await this.getCurrentSequenceNumber(msafeAddress);
1125
+ const hasPending = await this.model.pendingTransaction.findOneBy({ msafeAddress }) !== null;
1126
+ const futureSNStart = hasPending ? currentSequenceNumber + 1 : currentSequenceNumber;
1127
+ const futureTxs = await this.model.transactionIntention.find({
1128
+ where: { msafeAddress, sequenceNumber: MoreThanOrEqual(futureSNStart) },
1129
+ order: { sequenceNumber: "asc" }
1130
+ });
1131
+ return futureTxs.map((tx) => ({
1132
+ intention: IntentionHelper.de(tx.data),
1133
+ msafeAddress: tx.msafeAddress,
1134
+ sequenceNumber: tx.sequenceNumber,
1135
+ rawData: tx.data,
1136
+ txType: tx.txType,
1137
+ txSubType: tx.txSubType,
1138
+ status: tx.status,
1139
+ statusRemark: tx.statusRemark,
1140
+ creator: tx.creator,
1141
+ createdAt: tx.createdAt
1142
+ }));
1143
+ }
1144
+ async proposeIntention(input) {
1145
+ const userMSafe = await this.model.userMSafe.findOneBy({
1146
+ msafeAddress: input.msafeAddress,
1147
+ userAddress: input.userAddress
1148
+ });
1149
+ if (!userMSafe) {
1150
+ throw new Error("User does not have permission to propose intention");
1151
+ }
1152
+ const verified = await SignatureVerifier.verifyPersonalSignature({
1153
+ messageStr: MessageHelper.proposeIntentionMessage({ intention: input.intention, sn: input.sequenceNumber }),
1154
+ signature: input.signature,
1155
+ targetAddress: input.userAddress
1156
+ });
1157
+ if (!verified) {
1158
+ throw new Error("Invalid signature");
1159
+ }
1160
+ const sequenceNumber = await this.model.transactionIntention.count({
1161
+ where: {
1162
+ msafeAddress: input.msafeAddress
1163
+ }
1164
+ });
1165
+ if (sequenceNumber !== input.sequenceNumber) {
1166
+ throw new Error("Sequence number not expected");
1167
+ }
1168
+ const intention = {
1169
+ msafeAddress: input.msafeAddress,
1170
+ sequenceNumber,
1171
+ ...IntentionHelper.getTxType(input.intention),
1172
+ data: IntentionHelper.ser(input.intention),
1173
+ status: "future",
1174
+ creator: input.userAddress
1175
+ };
1176
+ await this.model.transactionIntention.save(intention);
1177
+ }
1178
+ // Propose a pending transaction. Require the msafe account
1179
+ // Does not have any pending transactions.
1180
+ async proposePendingTransaction(input) {
1181
+ const userMSafe = await this.model.userMSafe.findOneBy({
1182
+ msafeAddress: input.msafeAddress,
1183
+ userAddress: input.userAddress
1184
+ });
1185
+ if (userMSafe === null) {
1186
+ throw new Error("Unauthorized");
1187
+ }
1188
+ const msafePendings = await this.model.pendingTransaction.findBy({
1189
+ msafeAddress: input.msafeAddress
1190
+ });
1191
+ if (msafePendings.length !== 0) {
1192
+ throw new Error("Still have pending transaction");
1193
+ }
1194
+ const txb = await IntentionHelper.buildTxb({
1195
+ suiClient: this._suiClient,
1196
+ intention: input.intention,
1197
+ sender: input.msafeAddress
1198
+ });
1199
+ const payload = await txb.build({ client: this._suiClient });
1200
+ const txDigest = await txb.getDigest({ client: this._suiClient });
1201
+ if (txDigest !== input.digest) {
1202
+ throw new Error("Transaction digest un-match");
1203
+ }
1204
+ const verified = await SignatureVerifier.verifyTransactionSignature({
1205
+ payload,
1206
+ targetAddress: input.userAddress,
1207
+ signature: input.signature
1208
+ });
1209
+ if (!verified) {
1210
+ throw new Error("Failed to verify signature");
1211
+ }
1212
+ const maxSNHistory = await this.model.historyTransaction.findOne({
1213
+ where: { msafeAddress: input.msafeAddress },
1214
+ order: { sequenceNumber: "desc" }
1215
+ });
1216
+ const sequenceNumber = maxSNHistory === null ? 0 : maxSNHistory.sequenceNumber + 1;
1217
+ const intention = {
1218
+ msafeAddress: input.msafeAddress,
1219
+ sequenceNumber,
1220
+ ...IntentionHelper.getTxType(input.intention),
1221
+ data: IntentionHelper.ser(input.intention),
1222
+ status: "future",
1223
+ creator: input.userAddress
1224
+ };
1225
+ await this.model.transactionIntention.save(intention);
1226
+ const pendingTx = {
1227
+ digest: txDigest,
1228
+ msafeAddress: input.msafeAddress,
1229
+ payload: Uint8ArrayToHex(payload),
1230
+ sequenceNumber,
1231
+ isRejectTx: false,
1232
+ creator: input.userAddress
1233
+ };
1234
+ await this.model.pendingTransaction.save(pendingTx);
1235
+ const userVote = {
1236
+ userAddress: input.userAddress,
1237
+ txDigest,
1238
+ msafeAddress: input.msafeAddress,
1239
+ signature: input.signature,
1240
+ isValid: true
1241
+ };
1242
+ await this.model.userVote.save(userVote);
1243
+ }
1244
+ // Calls for the first reject transaction
1245
+ async rejectCurrentTx(input) {
1246
+ const userMSafe = await this.model.userMSafe.findOneBy({
1247
+ userAddress: input.userAddress,
1248
+ msafeAddress: input.msafeAddress
1249
+ });
1250
+ if (userMSafe === null) {
1251
+ throw new Error("User does not have permission to MSafe");
1252
+ }
1253
+ const currentPending = await this.model.pendingTransaction.findOneBy({
1254
+ msafeAddress: input.msafeAddress,
1255
+ isRejectTx: false
1256
+ });
1257
+ if (currentPending === null) {
1258
+ throw new Error("No active pending transaction");
1259
+ }
1260
+ const txb = await IntentionHelper.buildRejectTransaction({
1261
+ msafeAddress: input.msafeAddress,
1262
+ payloadToReject: currentPending.payload
1263
+ });
1264
+ const payload = await txb.build({ client: this._suiClient });
1265
+ const digest = await txb.getDigest({ client: this._suiClient });
1266
+ if (input.digest !== digest) {
1267
+ throw new Error("Digest not match");
1268
+ }
1269
+ const verified = await SignatureVerifier.verifyTransactionSignature({
1270
+ payload,
1271
+ targetAddress: input.userAddress,
1272
+ signature: input.signature
1273
+ });
1274
+ if (!verified) {
1275
+ throw new Error("Signature unverified");
1276
+ }
1277
+ const existPendingReject = await this.model.pendingTransaction.findOneBy({
1278
+ msafeAddress: input.msafeAddress,
1279
+ isRejectTx: true
1280
+ });
1281
+ if (existPendingReject !== null) {
1282
+ await this.voteForTransaction({
1283
+ txDigest: existPendingReject.digest,
1284
+ msafeAddress: input.msafeAddress,
1285
+ userAddress: input.userAddress,
1286
+ signature: input.signature
1287
+ });
1288
+ return;
1289
+ }
1290
+ const rejectPayloadStr = Uint8ArrayToHex(payload);
1291
+ const rejectDigest = await txb.getDigest({ client: this._suiClient });
1292
+ const rejectPending = {
1293
+ msafeAddress: input.msafeAddress,
1294
+ digest: rejectDigest,
1295
+ payload: rejectPayloadStr,
1296
+ sequenceNumber: currentPending.sequenceNumber,
1297
+ isRejectTx: true,
1298
+ creator: input.userAddress
1299
+ };
1300
+ await this.model.pendingTransaction.save(rejectPending);
1301
+ const rejectVote = {
1302
+ userAddress: input.userAddress,
1303
+ msafeAddress: input.msafeAddress,
1304
+ txDigest: rejectDigest,
1305
+ signature: input.signature,
1306
+ isValid: true
1307
+ };
1308
+ await this.model.userVote.save(rejectVote);
1309
+ const existVote = await this.model.userVote.findOneBy({
1310
+ txDigest: currentPending.digest,
1311
+ userAddress: input.userAddress
1312
+ });
1313
+ if (existVote !== null) {
1314
+ await this.model.userVote.update(
1315
+ { userAddress: input.userAddress, txDigest: currentPending.digest },
1316
+ { isValid: false }
1317
+ );
1318
+ }
1319
+ }
1320
+ async voteForTransaction(input) {
1321
+ const pendingTx = await this.model.pendingTransaction.findOneBy({ digest: input.txDigest });
1322
+ if (!pendingTx) {
1323
+ throw new Error(`Pending transaction not found: ${input.txDigest}`);
1324
+ }
1325
+ if (pendingTx.msafeAddress !== input.msafeAddress) {
1326
+ throw new Error("MSafe address not match");
1327
+ }
1328
+ const userMSafe = await this.model.userMSafe.findOneBy({
1329
+ userAddress: input.userAddress,
1330
+ msafeAddress: input.msafeAddress
1331
+ });
1332
+ if (userMSafe === null) {
1333
+ throw new Error(`User (${input.userAddress}) does not have permission on MSafe account (${input.msafeAddress})`);
1334
+ }
1335
+ const payload = HexToUint8Array(pendingTx.payload);
1336
+ const verified = await SignatureVerifier.verifyTransactionSignature({
1337
+ payload,
1338
+ targetAddress: input.userAddress,
1339
+ signature: input.signature
1340
+ });
1341
+ if (!verified) {
1342
+ throw new Error("Invalid signature");
1343
+ }
1344
+ const rejectPendingTx = await this.model.pendingTransaction.findOneBy({
1345
+ msafeAddress: input.msafeAddress,
1346
+ sequenceNumber: pendingTx.sequenceNumber,
1347
+ isRejectTx: !pendingTx.isRejectTx
1348
+ });
1349
+ if (rejectPendingTx !== null) {
1350
+ await this.model.userVote.update(
1351
+ {
1352
+ userAddress: input.userAddress,
1353
+ txDigest: rejectPendingTx.digest,
1354
+ isValid: true
1355
+ },
1356
+ { isValid: false }
1357
+ );
1358
+ }
1359
+ const existVote = await this.model.userVote.exist({
1360
+ where: {
1361
+ txDigest: input.txDigest,
1362
+ userAddress: input.userAddress
1363
+ }
1364
+ });
1365
+ if (!existVote) {
1366
+ const userVote = {
1367
+ txDigest: input.txDigest,
1368
+ userAddress: input.userAddress,
1369
+ msafeAddress: input.msafeAddress,
1370
+ signature: input.signature,
1371
+ isValid: true
1372
+ };
1373
+ await this.model.userVote.save(userVote);
1374
+ } else {
1375
+ await this.model.userVote.update(
1376
+ {
1377
+ txDigest: input.txDigest,
1378
+ userAddress: input.userAddress
1379
+ },
1380
+ { isValid: true }
1381
+ );
1382
+ }
1383
+ }
1384
+ // Mock the process of an executed transaction
1385
+ // Here only the essential logic of transaction processing logic
1386
+ // is implemented. Need more transaction parsing from the fetcher
1387
+ // module.
1388
+ //
1389
+ // TODO: User queryRunner to make the transaction atomic.
1390
+ async processExecutedTransaction(digest) {
1391
+ const historyTx = await this.model.historyTransaction.findOneBy({ digest });
1392
+ if (historyTx) {
1393
+ const allHistories = await this.model.historyTransaction.findBy({
1394
+ msafeAddress: historyTx.msafeAddress
1395
+ });
1396
+ console.log(allHistories);
1397
+ return;
1398
+ }
1399
+ const pendingTx = await this.model.pendingTransaction.findOneBy({ digest });
1400
+ if (!pendingTx) {
1401
+ throw new Error("Transaction digest not found");
1402
+ }
1403
+ await this.model.transactionIntention.update(
1404
+ { msafeAddress: pendingTx.msafeAddress, sequenceNumber: pendingTx.sequenceNumber },
1405
+ { status: "processed" }
1406
+ );
1407
+ const pendings = await this.model.pendingTransaction.findBy({
1408
+ msafeAddress: pendingTx.msafeAddress,
1409
+ sequenceNumber: pendingTx.sequenceNumber
1410
+ });
1411
+ if (pendings.length === 0) {
1412
+ throw new Error("Pending transaction not found");
1413
+ }
1414
+ const executionResult = "success";
1415
+ for (let i = 0; i !== pendings.length; i++) {
1416
+ const pending = pendings[i];
1417
+ const history = {
1418
+ digest: pending.digest,
1419
+ payload: pending.payload,
1420
+ msafeAddress: pending.msafeAddress,
1421
+ sequenceNumber: pending.sequenceNumber,
1422
+ isRejectTx: pending.isRejectTx,
1423
+ creator: pending.creator,
1424
+ createdAt: pending.createdAt,
1425
+ // TODO: Fill in this field based on transaction processing result
1426
+ status: pending.digest === digest ? executionResult : "rejected"
1427
+ };
1428
+ await this.model.historyTransaction.save(history);
1429
+ await this.model.pendingTransaction.delete({ digest: pending.digest });
1430
+ }
1431
+ }
1432
+ /**
1433
+ * Build the next transaction intention, and add the built transaction to pendings.
1434
+ * @param input
1435
+ */
1436
+ async buildNextIntentionAndAddToPending(input) {
1437
+ const maxSNHistory = await this.model.historyTransaction.findOne({
1438
+ where: { msafeAddress: input.msafeAddress },
1439
+ order: { sequenceNumber: "desc" }
1440
+ });
1441
+ const nextSequenceNumber = maxSNHistory ? maxSNHistory.sequenceNumber + 1 : 0;
1442
+ const currentPendings = await this.model.pendingTransaction.findBy({
1443
+ msafeAddress: input.msafeAddress
1444
+ });
1445
+ if (currentPendings.length !== 0) {
1446
+ throw new Error("Still have pendings");
1447
+ }
1448
+ const nextTx = await this.model.transactionIntention.findOneBy({
1449
+ msafeAddress: input.msafeAddress,
1450
+ sequenceNumber: nextSequenceNumber
1451
+ });
1452
+ if (nextTx === null) {
1453
+ throw new Error("No future intentions to build");
1454
+ }
1455
+ const nextIntention = IntentionHelper.de(nextTx.data);
1456
+ try {
1457
+ const newTxb = await IntentionHelper.buildTxb({
1458
+ suiClient: this._suiClient,
1459
+ sender: input.msafeAddress,
1460
+ intention: nextIntention
1461
+ });
1462
+ const payload = await newTxb.build({ client: this._suiClient });
1463
+ const newDigest = await newTxb.getDigest({ client: this._suiClient });
1464
+ const newPending = {
1465
+ digest: newDigest,
1466
+ payload: Uint8ArrayToHex(payload),
1467
+ msafeAddress: input.msafeAddress,
1468
+ sequenceNumber: nextTx.sequenceNumber,
1469
+ isRejectTx: false,
1470
+ creator: nextTx.creator
1471
+ };
1472
+ await this.model.pendingTransaction.save(newPending);
1473
+ } catch (e) {
1474
+ await this.model.transactionIntention.update(
1475
+ {
1476
+ msafeAddress: input.msafeAddress,
1477
+ sequenceNumber: nextSequenceNumber
1478
+ },
1479
+ {
1480
+ status: "failed",
1481
+ statusRemark: e.toString()
1482
+ }
1483
+ );
1484
+ throw new Error(`Intention build failed: {sequenceNumber: ${nextSequenceNumber}}`);
1485
+ }
1486
+ }
1487
+ /**
1488
+ * Skip next failed transaction if build of the intention has been failed before.
1489
+ */
1490
+ async skipNextFailedIntention(input) {
1491
+ const userMSafe = await this.model.userMSafe.findOneBy({
1492
+ msafeAddress: input.msafeAddress,
1493
+ userAddress: input.userAddress
1494
+ });
1495
+ if (userMSafe === null) {
1496
+ throw new Error("user does not have permission to MSafe");
1497
+ }
1498
+ const curSequenceNumber = await this.model.historyTransaction.findOne({
1499
+ where: { msafeAddress: input.msafeAddress },
1500
+ order: { sequenceNumber: "desc" }
1501
+ });
1502
+ const nextSequenceNumber = curSequenceNumber ? curSequenceNumber.sequenceNumber + 1 : 0;
1503
+ const failedIntention = await this.model.transactionIntention.findOneBy({
1504
+ msafeAddress: input.msafeAddress,
1505
+ sequenceNumber: nextSequenceNumber
1506
+ });
1507
+ if (failedIntention === null) {
1508
+ throw new Error("Next intention not found");
1509
+ }
1510
+ if (failedIntention.status !== "failed") {
1511
+ throw new Error("Next intention not failed");
1512
+ }
1513
+ const history = {
1514
+ msafeAddress: input.msafeAddress,
1515
+ digest: "0x0",
1516
+ // Special case for build has been failed,
1517
+ payload: "",
1518
+ sequenceNumber: nextSequenceNumber,
1519
+ creator: failedIntention.creator,
1520
+ isRejectTx: false,
1521
+ status: "build-failed"
1522
+ };
1523
+ await this.model.historyTransaction.save(history);
1524
+ }
1525
+ async getUser(address) {
1526
+ return this.model.user.findOneBy({ address });
1527
+ }
1528
+ get model() {
1529
+ return this.db.coreModel;
1530
+ }
1531
+ };
1532
+
1533
+ // src/globals/const.ts
1534
+ var MSafeEnv = /* @__PURE__ */ ((MSafeEnv3) => {
1535
+ MSafeEnv3["local"] = "local";
1536
+ MSafeEnv3["unit"] = "unit";
1537
+ MSafeEnv3["dev"] = "dev";
1538
+ MSafeEnv3["prev"] = "prev";
1539
+ MSafeEnv3["prod"] = "prod";
1540
+ return MSafeEnv3;
1541
+ })(MSafeEnv || {});
1542
+ var LOCAL_DATABASE_CONFIG = {
1543
+ type: "mysql",
1544
+ host: "127.0.0.1",
1545
+ port: 3306,
1546
+ username: "msafe",
1547
+ password: "msafe",
1548
+ database: "msafe_sui_local",
1549
+ logging: false
1550
+ };
1551
+ var DEV_DATABASE_CONFIG = {
1552
+ type: "mysql",
1553
+ host: "msafe-dev-database.cluster-caos3ssocrx6.us-west-1.rds.amazonaws.com",
1554
+ port: 3306,
1555
+ username: "msafe",
1556
+ password: "Momentum.Safe2022",
1557
+ database: "msafe_sui_dev",
1558
+ logging: false
1559
+ };
1560
+ var TESTNET_RPC_URL = "https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD";
1561
+ var MAINNET_RPC_URL = "https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7";
1562
+ var ENV_CONFIGS = /* @__PURE__ */ new Map([
1563
+ [
1564
+ "unit" /* unit */,
1565
+ {
1566
+ suiClient: {
1567
+ url: TESTNET_RPC_URL
1568
+ },
1569
+ backend: LOCAL_DATABASE_CONFIG
1570
+ }
1571
+ ],
1572
+ [
1573
+ "local" /* local */,
1574
+ {
1575
+ suiClient: {
1576
+ url: TESTNET_RPC_URL
1577
+ },
1578
+ backend: LOCAL_DATABASE_CONFIG
1579
+ }
1580
+ ],
1581
+ [
1582
+ "dev" /* dev */,
1583
+ {
1584
+ suiClient: {
1585
+ url: TESTNET_RPC_URL
1586
+ },
1587
+ backend: DEV_DATABASE_CONFIG
1588
+ }
1589
+ ]
1590
+ ]);
1591
+ function getMSafeConfig(env, options) {
1592
+ const config = ENV_CONFIGS.get(env);
1593
+ if (!config) {
1594
+ throw new Error("Unknown environment");
1595
+ }
1596
+ if (options?.suiClient?.url) {
1597
+ config.suiClient.url = options.suiClient.url;
1598
+ }
1599
+ if (options?.backend) {
1600
+ config.backend = options.backend;
1601
+ }
1602
+ return config;
1603
+ }
1604
+ var AUTH_SIGN_MESSAGE = "Welcome to MSafe";
1605
+
1606
+ // src/globals/MSafeGlobals.ts
1607
+ var MSafeGlobals = class _MSafeGlobals {
1608
+ backend;
1609
+ suiClient;
1610
+ config;
1611
+ _wallet;
1612
+ constructor(input) {
1613
+ this.backend = input.backend;
1614
+ this.suiClient = input.suiClient;
1615
+ this.config = input.config;
1616
+ }
1617
+ static async New(env, options) {
1618
+ const config = getMSafeConfig(env, options);
1619
+ const suiClient = new SuiClient(config.suiClient);
1620
+ const backend = await PseudoBackend.New(config.backend, suiClient);
1621
+ return new _MSafeGlobals({
1622
+ backend,
1623
+ suiClient,
1624
+ config
1625
+ });
1626
+ }
1627
+ connectWallet(wallet) {
1628
+ this._wallet = wallet;
1629
+ }
1630
+ get wallet() {
1631
+ if (!this._wallet) {
1632
+ throw new Error("wallet not connected");
1633
+ }
1634
+ return this._wallet;
1635
+ }
1636
+ set wallet(val) {
1637
+ this._wallet = val;
1638
+ }
1639
+ };
1640
+
1641
+ // src/core/MSafeClient.ts
1642
+ var MSafeClient = class _MSafeClient {
1643
+ constructor(globals) {
1644
+ this.globals = globals;
1645
+ }
1646
+ _creationHelper;
1647
+ _publicKeyHelper;
1648
+ static async New(env, options) {
1649
+ const globals = await MSafeGlobals.New(env, options);
1650
+ return new _MSafeClient(globals);
1651
+ }
1652
+ async connectWallet(input) {
1653
+ this.globals.wallet = input.wallet;
1654
+ const isValidJWT = input.jwtToken && await this.backend.isJWTTokenValid(input.jwtToken);
1655
+ if (isValidJWT) {
1656
+ this.backend.setJWTToken(input.jwtToken);
1657
+ return input.jwtToken;
1658
+ }
1659
+ const messageStr = MessageHelper.welcomeMessage((/* @__PURE__ */ new Date()).toUTCString());
1660
+ const sig = await input.wallet.signPersonalMessage({
1661
+ messageStr
1662
+ });
1663
+ return this.backend.authSign({
1664
+ address: await input.wallet.address(),
1665
+ message: messageStr,
1666
+ signature: sig.signature,
1667
+ walletType: input.wallet.walletType
1668
+ });
1669
+ }
1670
+ async userInfo() {
1671
+ return this.globals.backend.getUserInfo(await this.walletAddress());
1672
+ }
1673
+ async createAccount(info) {
1674
+ return this.creationHelper.submitMSafeCreation(info);
1675
+ }
1676
+ getMSafeAccount(info) {
1677
+ return new MSafeAccount(this.globals, info);
1678
+ }
1679
+ async getMSafeAccountFromAddress(msafeAddress) {
1680
+ const info = await this.backend.getMSafeAccountInfo(msafeAddress);
1681
+ return new MSafeAccount(this.globals, info);
1682
+ }
1683
+ // Get the creation helper to calculate the msafe account address,
1684
+ // validation, and more.
1685
+ get creationHelper() {
1686
+ if (!this._creationHelper) {
1687
+ this._creationHelper = new CreateHelper(this.globals, this.publicKeyHelper);
1688
+ }
1689
+ return this._creationHelper;
1690
+ }
1691
+ get publicKeyHelper() {
1692
+ if (!this._publicKeyHelper) {
1693
+ this._publicKeyHelper = new PublicKeyHelper(this.globals);
1694
+ }
1695
+ return this._publicKeyHelper;
1696
+ }
1697
+ get config() {
1698
+ return this.globals.config;
1699
+ }
1700
+ get backend() {
1701
+ return this.globals.backend;
1702
+ }
1703
+ get wallet() {
1704
+ return this.globals.wallet;
1705
+ }
1706
+ async walletAddress() {
1707
+ return this.wallet.address();
1708
+ }
1709
+ };
1710
+ export {
1711
+ AUTH_SIGN_MESSAGE,
1712
+ COIN_TYPE_ARG_REGEX,
1713
+ Coin,
1714
+ CoinHelper,
1715
+ CreateHelper,
1716
+ DEV_DATABASE_CONFIG,
1717
+ ENV_CONFIGS,
1718
+ Formatter,
1719
+ HexToUint8Array,
1720
+ IntentionHelper,
1721
+ LOCAL_DATABASE_CONFIG,
1722
+ MAINNET_RPC_URL,
1723
+ MAX_OWNER_WITHOUT_NONCE,
1724
+ MAX_OWNER_WITH_NONCE,
1725
+ MAX_WEIGHT,
1726
+ MIN_THRESHOLD,
1727
+ MIN_WEIGHT,
1728
+ MSafeAccount,
1729
+ MSafeClient,
1730
+ MSafeEnv,
1731
+ MSafeGlobals,
1732
+ MessageHelper,
1733
+ NONCE_PK_PREFIX,
1734
+ NONCE_PK_WEIGHT,
1735
+ NONCE_PREFIX_MAX_SIZE,
1736
+ PublicKeySerde,
1737
+ RawMultiSig,
1738
+ SUI_COIN,
1739
+ SignatureVerifier,
1740
+ TESTNET_RPC_URL,
1741
+ Uint8ArrayToHex,
1742
+ getAllCoins,
1743
+ getMSafeConfig,
1744
+ getMultiSigPublicKey,
1745
+ getPublicKeyFromChain,
1746
+ makeNoncePublicKey,
1747
+ stringToBuffer,
1748
+ validateMultiSigConfig
1749
+ };
1750
+ //# sourceMappingURL=index.js.map