@msafe/sui3-sdk 0.0.12 → 0.0.14

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.cjs CHANGED
@@ -30,21 +30,18 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
- AUTH_SIGN_MESSAGE: () => AUTH_SIGN_MESSAGE,
34
33
  AddressBookSDK: () => AddressBookSDK,
35
34
  COIN_TYPE_ARG_REGEX: () => COIN_TYPE_ARG_REGEX,
36
35
  Coin: () => Coin,
37
36
  CoinHelper: () => CoinHelper,
38
37
  CreateHelper: () => CreateHelper,
39
38
  DEV_API_URL: () => DEV_API_URL,
40
- DEV_DATABASE_CONFIG: () => DEV_DATABASE_CONFIG,
41
39
  DEV_SYNCING_URL: () => DEV_SYNCING_URL,
42
40
  ENV_CONFIGS: () => ENV_CONFIGS,
43
41
  Formatter: () => Formatter,
44
42
  HexToUint8Array: () => HexToUint8Array,
45
43
  IntentionHelper: () => IntentionHelper,
46
44
  LOCAL_API_URL: () => LOCAL_API_URL,
47
- LOCAL_DATABASE_CONFIG: () => LOCAL_DATABASE_CONFIG,
48
45
  LOCAL_SYNCING_URL: () => LOCAL_SYNCING_URL,
49
46
  MAINNET_RPC_URL: () => MAINNET_RPC_URL,
50
47
  MSAFE_APPLICATION: () => MSAFE_APPLICATION,
@@ -52,13 +49,9 @@ __export(src_exports, {
52
49
  MSafeClient: () => MSafeClient,
53
50
  MSafeEnv: () => MSafeEnv,
54
51
  MSafeGlobals: () => MSafeGlobals,
55
- MessageHelper: () => MessageHelper,
56
- OpAddressBookType: () => OpAddressBookType,
57
- PublicKeySerde: () => PublicKeySerde,
58
52
  SUI_COIN: () => SUI_COIN,
59
53
  SignatureVerifier: () => SignatureVerifier,
60
54
  TESTNET_RPC_URL: () => TESTNET_RPC_URL,
61
- UNIT_DATABASE_CONFIG: () => UNIT_DATABASE_CONFIG,
62
55
  Uint8ArrayToHex: () => Uint8ArrayToHex,
63
56
  getAllCoins: () => getAllCoins,
64
57
  getMSafeConfig: () => getMSafeConfig,
@@ -69,24 +62,103 @@ module.exports = __toCommonJS(src_exports);
69
62
 
70
63
  // src/core/CreateHelper.ts
71
64
  var import_sui3_utils = require("@msafe/sui3-utils");
65
+ var CreateHelper = class {
66
+ constructor(globals, pkHelper) {
67
+ this.globals = globals;
68
+ this.pkHelper = pkHelper;
69
+ }
70
+ async getPublicKeyBatch(addresses) {
71
+ return this.pkHelper.getPublicKeyBatch(addresses);
72
+ }
73
+ async calculateMSafeAddress(info) {
74
+ const msConfig = await this.reduceCreationInfoToRawConfig(info);
75
+ const ms = new import_sui3_utils.MultiSigAccount(msConfig);
76
+ return ms.address;
77
+ }
78
+ // Validate the create info and return the msafe address.
79
+ async validateCreateInfo(createInfo) {
80
+ return this.calculateMSafeAddress(createInfo);
81
+ }
82
+ async submitMSafeCreation(creationInfo) {
83
+ const msafeAddress = await this.validateCreateInfo(creationInfo);
84
+ const signingMessage = import_sui3_utils.SigningMessageHelper.createMSafeMessage(msafeAddress);
85
+ const signature = await this.globals.wallet.signPersonalMessage({ messageStr: signingMessage });
86
+ await this.submitToBackend(creationInfo, signature.signature);
87
+ return msafeAddress;
88
+ }
89
+ async reduceCreationInfoToRawConfig(info) {
90
+ const publicKeys = await this.getPublicKeyBatch(info.owners.map((owner) => owner.address));
91
+ publicKeys.forEach((pk, i) => {
92
+ if (pk === void 0) {
93
+ throw new Error(`Unknown public key for address: ${info.owners[i].address}`);
94
+ }
95
+ });
96
+ return {
97
+ threshold: info.threshold,
98
+ ownersWithWeight: info.owners.map((owner, i) => ({
99
+ publicKey: publicKeys[i],
100
+ weight: owner.weight
101
+ })),
102
+ creationNonce: info.creationNonce
103
+ };
104
+ }
105
+ async submitToBackend(createInfo, signature) {
106
+ const pks = await this.pkHelper.getPublicKeyBatch(createInfo.owners.map((owner) => owner.address));
107
+ await this.globals.backend.createMSafeAccount({
108
+ owners: createInfo.owners.map((owner, i) => ({
109
+ address: owner.address,
110
+ weight: owner.weight,
111
+ ...import_sui3_utils.PublicKeySerde.ser(pks[i])
112
+ })),
113
+ threshold: createInfo.threshold,
114
+ name: createInfo.name,
115
+ // name validation is deferred to backend
116
+ description: createInfo.description,
117
+ // description validation is deferred to backend
118
+ creationNonce: createInfo.creationNonce,
119
+ signature
120
+ });
121
+ }
122
+ };
72
123
 
73
- // src/utils/crypto.ts
74
- var import_cryptography = require("@mysten/sui.js/cryptography");
75
- var import_ed25519 = require("@mysten/sui.js/keypairs/ed25519");
76
- var import_secp256k1 = require("@mysten/sui.js/keypairs/secp256k1");
77
- var import_secp256r1 = require("@mysten/sui.js/keypairs/secp256r1");
78
- var import_verify = require("@mysten/sui.js/verify");
124
+ // src/core/MSafeClient.ts
125
+ var import_sui3_utils6 = require("@msafe/sui3-utils");
79
126
 
80
- // src/utils/buffer.ts
81
- function stringToBuffer(s) {
82
- return Buffer.from(s, "utf-8");
83
- }
84
- function Uint8ArrayToHex(b) {
85
- return `0x${Array.prototype.map.call(b, (x) => `0${x.toString(16)}`.slice(-2)).join("")}`;
86
- }
87
- function HexToUint8Array(hex) {
88
- return Uint8Array.from(Buffer.from(hex.startsWith("0x") ? hex.slice(2) : hex, "hex"));
89
- }
127
+ // src/core/AddressBookSDK.ts
128
+ var import_sui3_utils2 = require("@msafe/sui3-utils");
129
+ var AddressBookSDK = class {
130
+ constructor(globals) {
131
+ this.globals = globals;
132
+ }
133
+ async getEntries(pagination) {
134
+ return this.globals.backend.getAddressBookEntries(pagination);
135
+ }
136
+ async update(updates) {
137
+ const messageStr = import_sui3_utils2.SigningMessageHelper.updateAddressBookMessage(updates);
138
+ const sig = await this.globals.wallet.signPersonalMessage({ messageStr });
139
+ return this.globals.backend.updateAddressBook({ updates, signature: sig.signature });
140
+ }
141
+ };
142
+
143
+ // src/core/InvitationSDK.ts
144
+ var InvitationSDK = class {
145
+ constructor(globals) {
146
+ this.globals = globals;
147
+ }
148
+ async getMSafeByStatus(status, pagination) {
149
+ return this.globals.backend.getOwnedMSafeByStatus({ status, pagination });
150
+ }
151
+ async updateMSafeStatus(msafeAddress, status) {
152
+ return this.globals.backend.updateMSafeStatus({ msafeAddress, status });
153
+ }
154
+ };
155
+
156
+ // src/core/MSafeAccount.ts
157
+ var import_sui3_utils4 = require("@msafe/sui3-utils");
158
+ var import_utils3 = require("@mysten/sui.js/utils");
159
+
160
+ // src/transactions/coin-transfer.ts
161
+ var import_transactions = require("@mysten/sui.js/transactions");
90
162
 
91
163
  // src/utils/format.ts
92
164
  var import_utils2 = require("@mysten/sui.js/utils");
@@ -162,140 +234,9 @@ var Formatter = class {
162
234
  }
163
235
  };
164
236
 
165
- // src/utils/crypto.ts
166
- var SignatureVerifier = class _SignatureVerifier {
167
- static async getPublicKeyFromSignature(input) {
168
- if (input.messageType === "TransactionBlock") {
169
- return (0, import_verify.verifyTransactionBlock)(input.message, input.signature);
170
- }
171
- return (0, import_verify.verifyPersonalMessage)(input.message, input.signature);
172
- }
173
- static async getPublicKeyFromPersonalSignature(input) {
174
- const message = stringToBuffer(input.messageStr);
175
- return this.getPublicKeyFromSignature({
176
- message,
177
- messageType: "Personal",
178
- signature: input.signature
179
- });
180
- }
181
- static async verifySignature(input) {
182
- const publicKey = await _SignatureVerifier.getPublicKeyFromSignature(input);
183
- return Formatter.isSuiAddressEqual(publicKey.toSuiAddress(), input.targetAddress);
184
- }
185
- static async verifyPersonalSignature(input) {
186
- const message = stringToBuffer(input.messageStr);
187
- return this.verifySignature({
188
- message,
189
- messageType: "Personal",
190
- signature: input.signature,
191
- targetAddress: input.targetAddress
192
- });
193
- }
194
- static async verifyTransactionSignature(input) {
195
- return this.verifySignature({
196
- messageType: "TransactionBlock",
197
- message: input.payload,
198
- signature: input.signature,
199
- targetAddress: input.targetAddress
200
- });
201
- }
202
- };
203
- var PublicKeySerde = class {
204
- static ser(publicKey) {
205
- return {
206
- publicKey: publicKey.toBase64(),
207
- scheme: import_cryptography.SIGNATURE_FLAG_TO_SCHEME[publicKey.flag()]
208
- };
209
- }
210
- static de(input) {
211
- switch (input.scheme) {
212
- case "ED25519":
213
- return new import_ed25519.Ed25519PublicKey(input.publicKey);
214
- case "Secp256k1":
215
- return new import_secp256k1.Secp256k1PublicKey(input.publicKey);
216
- case "Secp256r1":
217
- return new import_secp256r1.Secp256r1PublicKey(input.publicKey);
218
- default:
219
- throw new Error("Unsupported signature scheme: $input.scheme");
220
- }
221
- }
222
- };
223
-
224
- // src/core/CreateHelper.ts
225
- var CreateHelper = class {
226
- constructor(globals, pkHelper) {
227
- this.globals = globals;
228
- this.pkHelper = pkHelper;
229
- }
230
- async getPublicKeyBatch(addresses) {
231
- return this.pkHelper.getPublicKeyBatch(addresses);
232
- }
233
- async calculateMSafeAddress(info) {
234
- const msConfig = await this.reduceCreationInfoToRawConfig(info);
235
- const ms = new import_sui3_utils.MultisigAccountManager(msConfig);
236
- return ms.address;
237
- }
238
- // Validate the create info and return the msafe address.
239
- async validateCreateInfo(createInfo) {
240
- const rawConfig = await this.reduceCreationInfoToRawConfig(createInfo);
241
- (0, import_sui3_utils.validateCreateAccountRequest)(rawConfig);
242
- return this.calculateMSafeAddress(createInfo);
243
- }
244
- async submitMSafeCreation(creationInfo) {
245
- const msafeAddress = await this.validateCreateInfo(creationInfo);
246
- const signingMessage = (0, import_sui3_utils.createAccountCreationMessage)(msafeAddress);
247
- const signature = await this.globals.wallet.signPersonalMessage({ messageStr: signingMessage });
248
- await this.submitToBackend(creationInfo, signature.signature);
249
- return msafeAddress;
250
- }
251
- async reduceCreationInfoToRawConfig(info) {
252
- const publicKeys = await this.getPublicKeyBatch(info.ownerWithWeight.map((oww) => oww.address));
253
- publicKeys.forEach((pk, i) => {
254
- if (pk === void 0) {
255
- throw new Error(`Unknown public key for address: ${info.ownerWithWeight[i].address}`);
256
- }
257
- });
258
- return {
259
- threshold: info.threshold,
260
- ownersWithWeight: info.ownerWithWeight.map((owner, i) => ({
261
- publicKey: publicKeys[i],
262
- weight: owner.weight
263
- })),
264
- creationNonce: info.creationNonce
265
- };
266
- }
267
- async submitToBackend(createInfo, signature) {
268
- const pks = await this.pkHelper.getPublicKeyBatch(createInfo.ownerWithWeight.map((owner) => owner.address));
269
- await this.globals.backend.createMSafeAccount({
270
- ownersWithWeightPKEncoded: createInfo.ownerWithWeight.map((owner, i) => {
271
- const publicKeySer = PublicKeySerde.ser(pks[i]);
272
- return {
273
- address: owner.address,
274
- weight: owner.weight,
275
- publicKeyEncoded: publicKeySer.publicKey,
276
- schema: publicKeySer.scheme
277
- };
278
- }),
279
- threshold: createInfo.threshold,
280
- name: createInfo.name,
281
- // name validation is deferred to backend
282
- description: createInfo.description,
283
- // description validation is deferred to backend
284
- creationNonce: createInfo.creationNonce,
285
- signature
286
- });
287
- }
288
- };
289
-
290
- // src/core/MessageHelper.ts
291
- var import_utils3 = require("@mysten/sui.js/utils");
292
- var import_crypto_js = require("crypto-js");
293
-
294
- // src/transactions/coin-transfer.ts
295
- var import_transactions = require("@mysten/sui.js/transactions");
296
-
297
237
  // src/utils/sui.ts
298
- var import_cryptography2 = require("@mysten/sui.js/cryptography");
238
+ var import_sui3_utils3 = require("@msafe/sui3-utils");
239
+ var import_cryptography = require("@mysten/sui.js/cryptography");
299
240
  var import_multisig = require("@mysten/sui.js/multisig");
300
241
  var SUI_COIN = "0x2::sui::SUI";
301
242
  async function getPublicKeyFromChain(suiClient, address) {
@@ -326,7 +267,7 @@ async function getPublicKeyFromChain(suiClient, address) {
326
267
  return void 0;
327
268
  }
328
269
  function getAddressFromSignatures(serializedSig, targetAddress) {
329
- const decoded = (0, import_cryptography2.parseSerializedSignature)(serializedSig);
270
+ const decoded = (0, import_cryptography.parseSerializedSignature)(serializedSig);
330
271
  switch (decoded.signatureScheme) {
331
272
  case "MultiSig": {
332
273
  const multiSigAddress = new import_multisig.MultiSigPublicKey(decoded.multisig.multisig_pk).toSuiAddress();
@@ -344,7 +285,7 @@ function getAddressFromSignatures(serializedSig, targetAddress) {
344
285
  case "ED25519":
345
286
  case "Secp256k1":
346
287
  case "Secp256r1": {
347
- const pk = PublicKeySerde.de({ publicKey: decoded.publicKey, scheme: decoded.signatureScheme });
288
+ const pk = import_sui3_utils3.PublicKeySerde.de({ publicKeyEncoded: decoded.publicKey, schema: decoded.signatureScheme });
348
289
  if (Formatter.isSuiAddressEqual(pk.toSuiAddress(), targetAddress)) {
349
290
  return pk;
350
291
  }
@@ -457,6 +398,19 @@ function getAddressOwner(object) {
457
398
 
458
399
  // src/transactions/reject.ts
459
400
  var import_transactions3 = require("@mysten/sui.js/transactions");
401
+
402
+ // src/utils/buffer.ts
403
+ function stringToBuffer(s) {
404
+ return Buffer.from(s, "utf-8");
405
+ }
406
+ function Uint8ArrayToHex(b) {
407
+ return `0x${Array.prototype.map.call(b, (x) => `0${x.toString(16)}`.slice(-2)).join("")}`;
408
+ }
409
+ function HexToUint8Array(hex) {
410
+ return Uint8Array.from(Buffer.from(hex.startsWith("0x") ? hex.slice(2) : hex, "hex"));
411
+ }
412
+
413
+ // src/transactions/reject.ts
460
414
  async function buildRejectTxb(input) {
461
415
  const approveTxb = import_transactions3.TransactionBlock.from(HexToUint8Array(input.payloadToReject));
462
416
  const gasPayment = approveTxb.blockData.gasConfig.payment;
@@ -521,483 +475,43 @@ var IntentionHelper = class {
521
475
  }
522
476
  };
523
477
 
524
- // src/core/MessageHelper.ts
525
- var MessageHelper = class {
526
- // Message used for MSafe creation
527
- static createMSafeMessage(msafeAddress) {
528
- return `Create MSafe Account: ${msafeAddress}`;
529
- }
530
- static deCreateMSafeMessage(msg) {
531
- const regex = /Create MSafe Account: (.+)/;
532
- const matches = msg.match(regex);
533
- return matches ? matches[1] : void 0;
534
- }
535
- // Message to be used when user login. The timestamp string
536
- // is used to for extra validation.
537
- static welcomeMessage(timestamp) {
538
- return `Welcome to MSafe. ${timestamp}`;
539
- }
540
- static deWelcomeMessage(msg) {
541
- const regex = /Welcome to MSafe. (.+)/;
542
- const matches = msg.match(regex);
543
- return matches ? matches[1] : void 0;
544
- }
545
- static proposeIntentionMessage(data) {
546
- const { msafeAddress, intention, sn } = data;
547
- const intentionData = IntentionHelper.ser(intention);
548
- const msg = {
549
- intentionData,
550
- sequenceNumber: sn,
551
- msafeAddress
552
- };
553
- return JSON.stringify(msg);
554
- }
555
- static deProposeIntentionMessage(s) {
556
- const de = JSON.parse(s);
557
- if (!("intentionData" in de) || typeof de.intentionData !== "string" || !("sequenceNumber" in de) || typeof de.sequenceNumber !== "number") {
558
- throw new Error("Invalid intention data");
478
+ // src/utils/crypto.ts
479
+ var import_verify = require("@mysten/sui.js/verify");
480
+ var SignatureVerifier = class _SignatureVerifier {
481
+ static async getPublicKeyFromSignature(input) {
482
+ if (input.messageType === "TransactionBlock") {
483
+ return (0, import_verify.verifyTransactionBlock)(input.message, input.signature);
559
484
  }
560
- const { msafeAddress, sequenceNumber, intentionData } = de;
561
- return {
562
- msafeAddress,
563
- sn: sequenceNumber,
564
- intention: IntentionHelper.de(intentionData)
565
- };
485
+ return (0, import_verify.verifyPersonalMessage)(input.message, input.signature);
566
486
  }
567
- static updateAddressBookMessage(updates) {
568
- const normalized = updates.map((update) => ({
569
- ...update,
570
- address: (0, import_utils3.normalizeSuiAddress)(update.address)
571
- }));
572
- function sortObjectKeys(obj) {
573
- return Object.keys(obj).sort().reduce((result, key) => ({ ...result, [key]: obj[key] }), {});
574
- }
575
- const sortedUpdates = normalized.map((update) => sortObjectKeys(update));
576
- const raw = JSON.stringify(sortedUpdates, null, 2);
577
- const encoded = stringToBuffer(raw);
578
- if (encoded.length <= 1024) {
579
- return raw;
580
- }
581
- const md5 = (0, import_crypto_js.MD5)(raw);
582
- return `Bulk address book update: ${md5}`;
487
+ static async getPublicKeyFromPersonalSignature(input) {
488
+ const message = stringToBuffer(input.messageStr);
489
+ return this.getPublicKeyFromSignature({
490
+ message,
491
+ messageType: "Personal",
492
+ signature: input.signature
493
+ });
583
494
  }
584
- };
585
-
586
- // src/core/AddressBookSDK.ts
587
- var AddressBookSDK = class {
588
- constructor(globals) {
589
- this.globals = globals;
495
+ static async verifySignature(input) {
496
+ const publicKey = await _SignatureVerifier.getPublicKeyFromSignature(input);
497
+ return Formatter.isSuiAddressEqual(publicKey.toSuiAddress(), input.targetAddress);
590
498
  }
591
- async getEntries(pagination) {
592
- return this.globals.backend.getAddressBookEntries(pagination);
499
+ static async verifyPersonalSignature(input) {
500
+ const message = stringToBuffer(input.messageStr);
501
+ return this.verifySignature({
502
+ message,
503
+ messageType: "Personal",
504
+ signature: input.signature,
505
+ targetAddress: input.targetAddress
506
+ });
593
507
  }
594
- async update(updates) {
595
- const messageStr = MessageHelper.updateAddressBookMessage(updates);
596
- const sig = await this.globals.wallet.signPersonalMessage({ messageStr });
597
- return this.globals.backend.updateAddressBook({ updates, signature: sig.signature });
598
- }
599
- };
600
-
601
- // src/core/MSafeAccount.ts
602
- var import_sui3_utils2 = require("@msafe/sui3-utils");
603
- var import_utils5 = require("@mysten/sui.js/utils");
604
-
605
- // src/globals/const.ts
606
- var MSafeEnv = /* @__PURE__ */ ((MSafeEnv3) => {
607
- MSafeEnv3["local"] = "local";
608
- MSafeEnv3["unit"] = "unit";
609
- MSafeEnv3["dev"] = "dev";
610
- MSafeEnv3["prev"] = "prev";
611
- MSafeEnv3["prod"] = "prod";
612
- return MSafeEnv3;
613
- })(MSafeEnv || {});
614
- var UNIT_DATABASE_CONFIG = {
615
- type: "sqlite",
616
- database: ":memory:",
617
- logging: false
618
- };
619
- var LOCAL_DATABASE_CONFIG = {
620
- type: "mysql",
621
- host: "127.0.0.1",
622
- port: 3306,
623
- username: "msafe",
624
- password: "msafe",
625
- database: "msafe_sui_local",
626
- logging: false
627
- };
628
- var DEV_DATABASE_CONFIG = {
629
- type: "mysql",
630
- host: "msafe-dev-database.cluster-caos3ssocrx6.us-west-1.rds.amazonaws.com",
631
- port: 3306,
632
- username: "msafe",
633
- password: "Momentum.Safe2022",
634
- database: "msafe_sui_dev",
635
- logging: false
636
- };
637
- var MSAFE_APPLICATION = "msafe";
638
- var TESTNET_RPC_URL = "https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD";
639
- var MAINNET_RPC_URL = "https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7";
640
- var LOCAL_API_URL = "http://127.0.0.1:3000";
641
- var LOCAL_SYNCING_URL = "http://127.0.0.1:3001";
642
- var DEV_API_URL = "http://13.56.226.148";
643
- var DEV_SYNCING_URL = "http://52.53.228.20";
644
- var ENV_CONFIGS = /* @__PURE__ */ new Map([
645
- [
646
- "unit" /* unit */,
647
- {
648
- suiClient: {
649
- url: TESTNET_RPC_URL
650
- },
651
- backend: LOCAL_DATABASE_CONFIG,
652
- apiURL: LOCAL_API_URL,
653
- syncingURL: LOCAL_SYNCING_URL
654
- }
655
- ],
656
- [
657
- "local" /* local */,
658
- {
659
- suiClient: {
660
- url: TESTNET_RPC_URL
661
- },
662
- backend: LOCAL_DATABASE_CONFIG,
663
- apiURL: LOCAL_API_URL,
664
- syncingURL: LOCAL_SYNCING_URL
665
- }
666
- ],
667
- [
668
- "dev" /* dev */,
669
- {
670
- suiClient: {
671
- url: TESTNET_RPC_URL
672
- },
673
- backend: DEV_DATABASE_CONFIG,
674
- apiURL: DEV_API_URL,
675
- syncingURL: DEV_SYNCING_URL
676
- }
677
- ]
678
- ]);
679
- function getMSafeConfig(env, options) {
680
- const config = ENV_CONFIGS.get(env);
681
- if (!config) {
682
- throw new Error("Unknown environment");
683
- }
684
- if (options?.suiClient?.url) {
685
- config.suiClient.url = options.suiClient.url;
686
- }
687
- if (options?.backend) {
688
- config.backend = options.backend;
689
- }
690
- return config;
691
- }
692
- var AUTH_SIGN_MESSAGE = "Welcome to MSafe";
693
-
694
- // src/globals/MSafeGlobals.ts
695
- var import_client = require("@mysten/sui.js/client");
696
-
697
- // src/backend/BackendImpl.ts
698
- var import_axios = __toESM(require("axios"), 1);
699
- var BackendImpl = class {
700
- constructor(apiURL) {
701
- this.apiURL = apiURL;
702
- }
703
- _token;
704
- async authSign(input) {
705
- const res = await import_axios.default.post(`${this.apiURL}/auth/login`, input);
706
- if (res.status !== 200 && res.status !== 201) {
707
- throw new Error(`invalid authSign return: ${res}`);
708
- }
709
- this._token = res.data.accessToken;
710
- return this._token;
711
- }
712
- async verifyToken(jwt) {
713
- try {
714
- const res = await import_axios.default.get(`${this.apiURL}/auth`, { headers: this.headers(jwt) });
715
- return res.status === 200;
716
- } catch (_) {
717
- return false;
718
- }
719
- }
720
- setJWTToken(token) {
721
- this._token = token;
722
- }
723
- async getPublicKey(address) {
724
- return (await this.getPublicKeyBatch([address]))[0];
725
- }
726
- async getPublicKeyBatch(addresses) {
727
- const res = await import_axios.default.post(
728
- `${this.apiURL}/account/getPublicKeyBatch`,
729
- addresses,
730
- {
731
- headers: this.headers()
732
- }
733
- );
734
- if (res.status !== 200 && res.status !== 201) {
735
- throw new Error(`invalid getPublicKeyBatch return: ${res}`);
736
- }
737
- return res.data?.map(
738
- (publicKeyWithSchema) => publicKeyWithSchema ? PublicKeySerde.de({ ...publicKeyWithSchema }) : void 0
739
- );
740
- }
741
- async getMSafeAccountInfo(msafeAddress) {
742
- const res = await import_axios.default.get(
743
- `${this.apiURL}/account/getMSafeAccountInfo/${msafeAddress}`,
744
- {
745
- headers: this.headers()
746
- }
747
- );
748
- if (res.status !== 200 && res.status !== 201) {
749
- throw new Error(`invalid getPublicKeyBatch return: ${res}`);
750
- }
751
- const msafeResp = res.data;
752
- return {
753
- address: msafeResp.address,
754
- ownersWithWeightPK: msafeResp.ownersWithWeightPKEncoded.map(
755
- (owner) => ({
756
- publicKey: PublicKeySerde.de({ publicKey: owner.publicKeyEncoded, scheme: owner.schema }),
757
- address: owner.address,
758
- weight: owner.weight
759
- })
760
- ),
761
- threshold: msafeResp.threshold,
762
- name: msafeResp.name,
763
- description: msafeResp.description,
764
- creationNonce: msafeResp.creationNonce
765
- };
766
- }
767
- async getUserInfo(userAddress) {
768
- const res = await import_axios.default.get(`${this.apiURL}/account/user/${userAddress}`, {
769
- headers: this.headers()
770
- });
771
- if (res.status !== 200 && res.status !== 201) {
772
- throw new Error(`invalid getPublicKeyBatch return: ${res}`);
773
- }
774
- return {
775
- address: res.data.address,
776
- publicKey: res.data.publicKey,
777
- schema: res.data.schema,
778
- creationNonce: res.data.creationNonce,
779
- ownedMSafe: res.data.ownedMSafe.map(
780
- (msafe) => ({
781
- address: msafe.address,
782
- ownersWithWeightPK: msafe.ownersWithWeightPKEncoded.map(
783
- (owner) => ({
784
- publicKey: PublicKeySerde.de({ publicKey: owner.publicKeyEncoded, scheme: owner.schema }),
785
- address: owner.address,
786
- weight: owner.weight
787
- })
788
- ),
789
- threshold: msafe.threshold,
790
- name: msafe.name,
791
- description: msafe.description,
792
- creationNonce: msafe.creationNonce
793
- })
794
- )
795
- };
796
- }
797
- async getPendingTransactions(msafeAddress) {
798
- const res = await import_axios.default.get(`${this.apiURL}/transaction/pending/${msafeAddress}`, {
799
- headers: this.headers()
800
- });
801
- if (res.status !== 200 && res.status !== 201) {
802
- throw new Error(`invalid getPublicKeyBatch return: ${res}`);
803
- }
804
- return res.data;
805
- }
806
- async getHistoryTransactions(msafeAddress, paginationOption) {
807
- const res = await import_axios.default.get(
808
- `${this.apiURL}/transaction/history?address=${msafeAddress}`,
809
- {
810
- params: {
811
- page: paginationOption?.page,
812
- limit: paginationOption?.limit
813
- },
814
- headers: this.headers()
815
- }
816
- );
817
- if (res.status !== 200 && res.status !== 201) {
818
- throw new Error(`invalid getCurrentSequenceNumber return: ${res}`);
819
- }
820
- return res.data;
821
- }
822
- async getFutureIntentions(msafeAddress, paginationOption) {
823
- const res = await import_axios.default.get(`${this.apiURL}/transaction/intention/${msafeAddress}`, {
824
- params: {
825
- page: paginationOption?.page,
826
- limit: paginationOption?.limit
827
- },
828
- headers: this.headers()
829
- });
830
- if (res.status !== 200 && res.status !== 201) {
831
- throw new Error(`invalid getCurrentSequenceNumber return: ${res}`);
832
- }
833
- return res.data;
834
- }
835
- async getCurrentSequenceNumber(msafeAddress) {
836
- const res = await import_axios.default.get(`${this.apiURL}/transaction/sn/current/${msafeAddress}`, {
837
- headers: this.headers()
838
- });
839
- if (res.status !== 200 && res.status !== 201) {
840
- throw new Error(`invalid getCurrentSequenceNumber return: ${res}`);
841
- }
842
- return res.data;
843
- }
844
- async getNextSequenceNumber(msafeAddress) {
845
- const res = await import_axios.default.get(`${this.apiURL}/transaction/sn/next/${msafeAddress}`, {
846
- headers: this.headers()
847
- });
848
- if (res.status !== 200 && res.status !== 201) {
849
- throw new Error(`invalid getNextSequenceNumber return: ${res}`);
850
- }
851
- return res.data;
852
- }
853
- async createMSafeAccount(input) {
854
- const res = await import_axios.default.post(`${this.apiURL}/account`, input, {
855
- headers: this.headers()
856
- });
857
- if (res.status !== 200 && res.status !== 201) {
858
- throw new Error(`invalid createMSafeAccount return: ${res}`);
859
- }
860
- }
861
- async proposeIntention(input) {
862
- try {
863
- const res = await import_axios.default.post(
864
- `${this.apiURL}/transaction/intention`,
865
- {
866
- intention: input.intention,
867
- sequenceNumber: input.sequenceNumber,
868
- address: input.msafeAddress,
869
- signature: input.signature,
870
- application: input.application,
871
- txType: input.txType,
872
- txSubType: input.txSubType
873
- },
874
- { headers: this.headers() }
875
- );
876
- if (res.status !== 200 && res.status !== 201) {
877
- throw new Error(`invalid proposeIntention return: ${res}`);
878
- }
879
- } catch (e) {
880
- console.log(e);
881
- }
882
- }
883
- // TODO later
884
- async proposePendingTransaction(input) {
885
- }
886
- async rejectCurrentTx(input) {
887
- try {
888
- const res = await import_axios.default.post(
889
- `${this.apiURL}/transaction/pending/reject`,
890
- {
891
- address: input.msafeAddress,
892
- digest: input.digest,
893
- signature: input.signature
894
- },
895
- {
896
- headers: this.headers()
897
- }
898
- );
899
- if (res.status !== 200 && res.status !== 201) {
900
- throw new Error(`invalid voteForTransaction return: ${res}`);
901
- }
902
- } catch (e) {
903
- console.log("e:", e);
904
- }
905
- }
906
- async voteForTransaction(input) {
907
- const res = await import_axios.default.post(
908
- `${this.apiURL}/transaction/pending/vote`,
909
- {
910
- address: input.msafeAddress,
911
- digest: input.txDigest,
912
- signature: input.signature
913
- },
914
- {
915
- headers: this.headers()
916
- }
917
- );
918
- if (res.status !== 200 && res.status !== 201) {
919
- throw new Error(`invalid voteForTransaction return: ${res}`);
920
- }
921
- }
922
- async buildNextIntentionAndAddToPending(input) {
923
- const res = await import_axios.default.post(
924
- `${this.apiURL}/transaction/pending/build`,
925
- {
926
- address: input.msafeAddress
927
- },
928
- { headers: this.headers() }
929
- );
930
- if (res.status !== 200 && res.status !== 201) {
931
- throw new Error(`invalid buildNextIntentionAndAddToPending return: ${res}`);
932
- }
933
- }
934
- async skipNextFailedIntention(input) {
935
- const res = await import_axios.default.post(
936
- `${this.apiURL}/transaction/pending/skip`,
937
- {
938
- msafeAddress: input.msafeAddress
939
- },
940
- { headers: this.headers() }
941
- );
942
- if (res.status !== 200 && res.status !== 201) {
943
- throw new Error(`invalid skipNextFailedIntention return: ${res}`);
944
- }
945
- }
946
- async getAddressBookEntries(pagination) {
947
- const res = await import_axios.default.get(`${this.apiURL}/address-book`, {
948
- headers: this.headers(),
949
- params: pagination
950
- });
951
- if (res.status !== 200) {
952
- throw new Error(`Invalid address-book return: ${res}`);
953
- }
954
- return res.data;
955
- }
956
- async updateAddressBook(input) {
957
- const res = await import_axios.default.post(`${this.apiURL}/address-book`, input, { headers: this.headers() });
958
- if (res.status !== 200 && res.status !== 201) {
959
- throw new Error(`invalid updateAddressBook return: ${res}`);
960
- }
961
- }
962
- async processExecutedTransaction(digest) {
963
- }
964
- headers(token) {
965
- return { Authorization: `Bearer ${token || this._token}` };
966
- }
967
- };
968
-
969
- // src/globals/MSafeGlobals.ts
970
- var MSafeGlobals = class _MSafeGlobals {
971
- backend;
972
- suiClient;
973
- config;
974
- _wallet;
975
- constructor(input) {
976
- this.backend = input.backend;
977
- this.suiClient = input.suiClient;
978
- this.config = input.config;
979
- }
980
- static async New(env, options) {
981
- const config = getMSafeConfig(env, options);
982
- const suiClient = new import_client.SuiClient(config.suiClient);
983
- const backend = new BackendImpl(config.apiURL);
984
- return new _MSafeGlobals({
985
- backend,
986
- suiClient,
987
- config
988
- });
989
- }
990
- connectWallet(wallet) {
991
- this._wallet = wallet;
992
- }
993
- get wallet() {
994
- if (!this._wallet) {
995
- throw new Error("wallet not connected");
996
- }
997
- return this._wallet;
998
- }
999
- set wallet(val) {
1000
- this._wallet = val;
508
+ static async verifyTransactionSignature(input) {
509
+ return this.verifySignature({
510
+ messageType: "TransactionBlock",
511
+ message: input.payload,
512
+ signature: input.signature,
513
+ targetAddress: input.targetAddress
514
+ });
1001
515
  }
1002
516
  };
1003
517
 
@@ -1129,21 +643,29 @@ var OwnedObjectRequester = class {
1129
643
  };
1130
644
 
1131
645
  // src/core/MSafeAccount.ts
1132
- var MSafeAccount = class {
646
+ var MSafeAccount = class _MSafeAccount {
1133
647
  constructor(globals, info) {
1134
648
  this.globals = globals;
1135
649
  this.info = info;
1136
- this.multisigManager = new import_sui3_utils2.MultisigAccountManager({
650
+ this.multiSig = new import_sui3_utils4.MultiSigAccount({
1137
651
  threshold: info.threshold,
1138
- ownersWithWeight: info.ownersWithWeightPK,
652
+ ownersWithWeight: info.owners.map((owner) => ({
653
+ address: owner.address,
654
+ weight: owner.weight,
655
+ publicKey: import_sui3_utils4.PublicKeySerde.de({ publicKeyEncoded: owner.publicKeyEncoded, schema: owner.schema })
656
+ })),
1139
657
  creationNonce: info.creationNonce
1140
658
  });
1141
659
  this.coinHelper = new CoinHelper(this.suiClient);
1142
660
  }
1143
- multisigManager;
661
+ multiSig;
1144
662
  coinHelper;
1145
- static async new(globals, address) {
1146
- return globals.backend.getMSafeAccountInfo(address);
663
+ static async New(globals, address) {
664
+ const info = await globals.backend.getMSafeAccountInfo(address);
665
+ const ms = new _MSafeAccount(globals, info);
666
+ if (ms.address !== address) {
667
+ throw new Error("Invalid msafe config with address");
668
+ }
1147
669
  }
1148
670
  async ownedCoins() {
1149
671
  const balances = await this.suiClient.getAllBalances({ owner: this.address });
@@ -1152,7 +674,7 @@ var MSafeAccount = class {
1152
674
  const meta = await this.coinHelper.getCoinMeta(balance.coinType);
1153
675
  const unlockedBalance = balance.lockedBalance.number ? BigInt(balance.totalBalance) - BigInt(balance.lockedBalance.number) : BigInt(balance.totalBalance);
1154
676
  return {
1155
- type: (0, import_utils5.normalizeStructTag)(balance.coinType),
677
+ type: (0, import_utils3.normalizeStructTag)(balance.coinType),
1156
678
  balance: BigInt(unlockedBalance),
1157
679
  metadata: meta
1158
680
  };
@@ -1196,25 +718,20 @@ var MSafeAccount = class {
1196
718
  async nextSequenceNumber() {
1197
719
  return this.backend.getNextSequenceNumber(this.address);
1198
720
  }
1199
- async proposeIntention(intention, sequenceNumber) {
1200
- const message = MessageHelper.proposeIntentionMessage({
1201
- intention,
1202
- sn: sequenceNumber,
1203
- msafeAddress: this.address
721
+ async proposeIntention(input) {
722
+ const message = import_sui3_utils4.SigningMessageHelper.proposeIntentionMessage({
723
+ msafeAddress: this.address,
724
+ intention: input.intention,
725
+ sn: input.sequenceNumber
1204
726
  });
1205
727
  const signature = await this.wallet.signPersonalMessage({
1206
728
  messageStr: message
1207
729
  });
1208
- const txType = (0, import_sui3_utils2.getIntentionType)(intention);
1209
730
  await this.backend.proposeIntention({
1210
- intention,
1211
- sequenceNumber,
731
+ ...input,
1212
732
  msafeAddress: this.address,
1213
733
  userAddress: await this.userAddress(),
1214
- signature: signature.signature,
1215
- application: MSAFE_APPLICATION,
1216
- txType: txType.txType,
1217
- txSubType: txType.txSubType
734
+ signature: signature.signature
1218
735
  });
1219
736
  }
1220
737
  async voteForTransaction(digest, payload) {
@@ -1281,7 +798,7 @@ var MSafeAccount = class {
1281
798
  return this.backend.skipNextFailedIntention({ msafeAddress: this.address, userAddress: await this.userAddress() });
1282
799
  }
1283
800
  async simulateIntention(intention) {
1284
- const txb = await (0, import_sui3_utils2.buildIntentionTransaction)(this.suiClient, intention, this.address);
801
+ const txb = await (0, import_sui3_utils4.buildIntentionTransaction)(this.suiClient, intention, this.address);
1285
802
  if (!txb.blockData.gasConfig.price) {
1286
803
  const refGas = await this.suiClient.getReferenceGasPrice();
1287
804
  txb.setGasPrice(refGas);
@@ -1312,101 +829,457 @@ var MSafeAccount = class {
1312
829
  } else {
1313
830
  throw new Error("Not enough signatures");
1314
831
  }
1315
- const sigs = [];
1316
- for (let i = 0; i < this.info.ownersWithWeightPK.length; i++) {
1317
- const owner = this.info.ownersWithWeightPK[i];
1318
- const signature = gotSigs.get(owner.publicKey.toSuiAddress());
1319
- if (signature) {
1320
- sigs.push(signature);
1321
- }
832
+ const sigs = [];
833
+ for (let i = 0; i < this.info.owners.length; i++) {
834
+ const owner = this.info.owners[i];
835
+ const signature = gotSigs.get(owner.address);
836
+ if (signature) {
837
+ sigs.push(signature);
838
+ }
839
+ }
840
+ const multiSignature = this.multiSig.combinePartialSignatures(sigs);
841
+ return this.suiClient.executeTransactionBlock({
842
+ transactionBlock: HexToUint8Array(payload),
843
+ signature: multiSignature,
844
+ options: { showEffects: true }
845
+ });
846
+ }
847
+ get address() {
848
+ return this.multiSig.address;
849
+ }
850
+ get backend() {
851
+ return this.globals.backend;
852
+ }
853
+ get wallet() {
854
+ return this.globals.wallet;
855
+ }
856
+ async userAddress() {
857
+ return this.globals.wallet.address();
858
+ }
859
+ get suiClient() {
860
+ return this.globals.suiClient;
861
+ }
862
+ };
863
+
864
+ // src/core/PublicKeyHelper.ts
865
+ var PublicKeyHelper = class {
866
+ constructor(globals) {
867
+ this.globals = globals;
868
+ this.knownPublicKeys = /* @__PURE__ */ new Map();
869
+ }
870
+ knownPublicKeys;
871
+ async getPublicKey(address) {
872
+ const cached = this.knownPublicKeys.get(address);
873
+ if (cached) {
874
+ return cached;
875
+ }
876
+ const pk = await this._getPublicKey(address);
877
+ if (pk) {
878
+ this.knownPublicKeys.set(address, pk);
879
+ }
880
+ return pk;
881
+ }
882
+ async getPublicKeyBatch(addresses) {
883
+ const results = new Array(addresses.length).fill(void 0);
884
+ for (let i = 0; i < addresses.length; i++) {
885
+ const address = addresses[i];
886
+ results[i] = this.knownPublicKeys.get(address);
887
+ }
888
+ const emptyIndexes = results.map((elem, index) => elem === void 0 ? index : -1).filter((index) => index !== -1);
889
+ if (emptyIndexes.length === 0) {
890
+ return results;
891
+ }
892
+ const backendResult = await this.globals.backend.getPublicKeyBatch(emptyIndexes.map((index) => addresses[index]));
893
+ for (let i = 0; i < emptyIndexes.length; i++) {
894
+ const index = emptyIndexes[i];
895
+ results[index] = backendResult[i];
896
+ }
897
+ for (let i = 0; i < results.length; i++) {
898
+ if (results[i] === void 0) {
899
+ results[i] = await this.getPublicKeyFromChain(addresses[i]);
900
+ }
901
+ }
902
+ for (let i = 0; i < addresses.length; i++) {
903
+ if (results[i]) {
904
+ this.knownPublicKeys.set(addresses[i], results[i]);
905
+ }
906
+ }
907
+ return results;
908
+ }
909
+ async _getPublicKey(address) {
910
+ const pkBackend = await this.getPublicKeyFromBackend(address);
911
+ if (pkBackend) {
912
+ return pkBackend;
913
+ }
914
+ const pkChain = await this.getPublicKeyFromChain(address);
915
+ if (pkChain) {
916
+ return pkChain;
917
+ }
918
+ return void 0;
919
+ }
920
+ async getPublicKeyFromBackend(address) {
921
+ try {
922
+ const pk = await this.globals.backend.getPublicKey(address);
923
+ return pk;
924
+ } catch (_) {
925
+ return void 0;
926
+ }
927
+ }
928
+ async getPublicKeyFromChain(address) {
929
+ return getPublicKeyFromChain(this.globals.suiClient, address);
930
+ }
931
+ };
932
+
933
+ // src/globals/MSafeGlobals.ts
934
+ var import_client = require("@mysten/sui.js/client");
935
+
936
+ // src/backend/BackendImpl.ts
937
+ var import_sui3_utils5 = require("@msafe/sui3-utils");
938
+ var import_axios = __toESM(require("axios"), 1);
939
+ var BackendImpl = class {
940
+ constructor(apiURL) {
941
+ this.apiURL = apiURL;
942
+ }
943
+ _token;
944
+ async authSign(input) {
945
+ const res = await import_axios.default.post(`${this.apiURL}/auth/login`, input);
946
+ if (res.status !== 200 && res.status !== 201) {
947
+ throw new Error(`invalid authSign return: ${res}`);
948
+ }
949
+ this._token = res.data.accessToken;
950
+ return this._token;
951
+ }
952
+ async verifyToken(jwt) {
953
+ try {
954
+ const res = await import_axios.default.get(`${this.apiURL}/auth`, { headers: this.headers(jwt) });
955
+ return res.status === 200;
956
+ } catch (_) {
957
+ return false;
958
+ }
959
+ }
960
+ setJWTToken(token) {
961
+ this._token = token;
962
+ }
963
+ async getPublicKey(address) {
964
+ return (await this.getPublicKeyBatch([address]))[0];
965
+ }
966
+ async getPublicKeyBatch(addresses) {
967
+ const query = {
968
+ userAddressList: addresses
969
+ };
970
+ const res = await import_axios.default.get(`${this.apiURL}/user/public-keys`, {
971
+ params: query,
972
+ headers: this.headers()
973
+ });
974
+ if (res.status !== 200 && res.status !== 201) {
975
+ throw new Error(`invalid getPublicKeyBatch return: ${res}`);
976
+ }
977
+ return res.data?.map(
978
+ (publicKeyWithSchema) => publicKeyWithSchema ? import_sui3_utils5.PublicKeySerde.de(publicKeyWithSchema) : void 0
979
+ );
980
+ }
981
+ async getMSafeAccountInfo(msafeAddress) {
982
+ const q = {
983
+ msafeAddress
984
+ };
985
+ const res = await import_axios.default.get(`${this.apiURL}/msafe`, {
986
+ params: q,
987
+ headers: this.headers()
988
+ });
989
+ if (res.status !== 200 && res.status !== 201) {
990
+ throw new Error(`invalid getPublicKeyBatch return: ${res}`);
991
+ }
992
+ return res.data;
993
+ }
994
+ async getUserInfo() {
995
+ const userRes = await import_axios.default.get(`${this.apiURL}/user`, {
996
+ headers: this.headers()
997
+ });
998
+ if (userRes.status !== 200 && userRes.status !== 201) {
999
+ throw new Error(`invalid getPublicKeyBatch return: ${userRes}`);
1000
+ }
1001
+ return userRes.data;
1002
+ }
1003
+ async getOwnedMSafeByStatus(input) {
1004
+ const q = {
1005
+ status: input.status ?? import_sui3_utils5.UserMSafeStatus.active,
1006
+ ...input.pagination ? {
1007
+ page: input.pagination.page.toString(),
1008
+ limit: input.pagination.limit.toString()
1009
+ } : {}
1010
+ };
1011
+ const res = await import_axios.default.get(`${this.apiURL}/msafe/owned`, {
1012
+ params: q,
1013
+ headers: this.headers()
1014
+ });
1015
+ if (res.status !== 200 && res.status !== 201) {
1016
+ throw new Error(`invalid getOwnedMSafeByStatus return: ${res}`);
1017
+ }
1018
+ return res.data;
1019
+ }
1020
+ async updateMSafeStatus(input) {
1021
+ const p = input;
1022
+ const res = await import_axios.default.post(`${this.apiURL}/msafe/status`, p, { headers: this.headers() });
1023
+ if (res.status !== 200 && res.status !== 201) {
1024
+ throw new Error(`Invalid updateMSafeStatus return: ${res}`);
1025
+ }
1026
+ }
1027
+ async getPendingTransactions(msafeAddress) {
1028
+ const res = await import_axios.default.get(`${this.apiURL}/transaction/pending/${msafeAddress}`, {
1029
+ headers: this.headers()
1030
+ });
1031
+ if (res.status !== 200 && res.status !== 201) {
1032
+ throw new Error(`invalid getPublicKeyBatch return: ${res}`);
1033
+ }
1034
+ return res.data;
1035
+ }
1036
+ async getHistoryTransactions(msafeAddress, paginationOption) {
1037
+ const res = await import_axios.default.get(
1038
+ `${this.apiURL}/transaction/history?address=${msafeAddress}`,
1039
+ {
1040
+ params: {
1041
+ page: paginationOption?.page,
1042
+ limit: paginationOption?.limit
1043
+ },
1044
+ headers: this.headers()
1045
+ }
1046
+ );
1047
+ if (res.status !== 200 && res.status !== 201) {
1048
+ throw new Error(`invalid getCurrentSequenceNumber return: ${res}`);
1049
+ }
1050
+ return res.data;
1051
+ }
1052
+ async getFutureIntentions(msafeAddress, paginationOption) {
1053
+ const res = await import_axios.default.get(`${this.apiURL}/transaction/intention/${msafeAddress}`, {
1054
+ params: {
1055
+ page: paginationOption?.page,
1056
+ limit: paginationOption?.limit
1057
+ },
1058
+ headers: this.headers()
1059
+ });
1060
+ if (res.status !== 200 && res.status !== 201) {
1061
+ throw new Error(`invalid getCurrentSequenceNumber return: ${res}`);
1062
+ }
1063
+ return res.data;
1064
+ }
1065
+ async getCurrentSequenceNumber(msafeAddress) {
1066
+ const res = await import_axios.default.get(`${this.apiURL}/transaction/sn/current/${msafeAddress}`, {
1067
+ headers: this.headers()
1068
+ });
1069
+ if (res.status !== 200 && res.status !== 201) {
1070
+ throw new Error(`invalid getCurrentSequenceNumber return: ${res}`);
1322
1071
  }
1323
- const multiSignature = this.multisigManager.combinePartialSignatures(sigs);
1324
- return this.suiClient.executeTransactionBlock({
1325
- transactionBlock: HexToUint8Array(payload),
1326
- signature: multiSignature,
1327
- options: { showEffects: true }
1072
+ return res.data;
1073
+ }
1074
+ async getNextSequenceNumber(msafeAddress) {
1075
+ const res = await import_axios.default.get(`${this.apiURL}/transaction/sn/next/${msafeAddress}`, {
1076
+ headers: this.headers()
1328
1077
  });
1078
+ if (res.status !== 200 && res.status !== 201) {
1079
+ throw new Error(`invalid getNextSequenceNumber return: ${res}`);
1080
+ }
1081
+ return res.data;
1329
1082
  }
1330
- get address() {
1331
- return this.info.address;
1083
+ async createMSafeAccount(input) {
1084
+ const res = await import_axios.default.post(`${this.apiURL}/msafe/create`, input, {
1085
+ headers: this.headers()
1086
+ });
1087
+ if (res.status !== 200 && res.status !== 201) {
1088
+ throw new Error(`invalid createMSafeAccount return: ${res}`);
1089
+ }
1332
1090
  }
1333
- get backend() {
1334
- return this.globals.backend;
1091
+ async proposeIntention(input) {
1092
+ const res = await import_axios.default.post(`${this.apiURL}/transaction/intention`, input, { headers: this.headers() });
1093
+ if (res.status !== 200 && res.status !== 201) {
1094
+ throw new Error(`invalid proposeIntention return: ${res}`);
1095
+ }
1335
1096
  }
1336
- get wallet() {
1337
- return this.globals.wallet;
1097
+ // TODO later
1098
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1099
+ async proposePendingTransaction(_input) {
1100
+ return void 0;
1338
1101
  }
1339
- async userAddress() {
1340
- return this.globals.wallet.address();
1102
+ async rejectCurrentTx(input) {
1103
+ const res = await import_axios.default.post(
1104
+ `${this.apiURL}/transaction/pending/reject`,
1105
+ {
1106
+ address: input.msafeAddress,
1107
+ digest: input.digest,
1108
+ signature: input.signature
1109
+ },
1110
+ {
1111
+ headers: this.headers()
1112
+ }
1113
+ );
1114
+ if (res.status !== 200 && res.status !== 201) {
1115
+ throw new Error(`invalid voteForTransaction return: ${res}`);
1116
+ }
1341
1117
  }
1342
- get suiClient() {
1343
- return this.globals.suiClient;
1118
+ async voteForTransaction(input) {
1119
+ const res = await import_axios.default.post(
1120
+ `${this.apiURL}/transaction/pending/vote`,
1121
+ {
1122
+ address: input.msafeAddress,
1123
+ digest: input.txDigest,
1124
+ signature: input.signature
1125
+ },
1126
+ {
1127
+ headers: this.headers()
1128
+ }
1129
+ );
1130
+ if (res.status !== 200 && res.status !== 201) {
1131
+ throw new Error(`invalid voteForTransaction return: ${res}`);
1132
+ }
1344
1133
  }
1345
- };
1346
-
1347
- // src/core/PublicKeyHelper.ts
1348
- var PublicKeyHelper = class {
1349
- constructor(globals) {
1350
- this.globals = globals;
1351
- this.knownPublicKeys = /* @__PURE__ */ new Map();
1134
+ async buildNextIntentionAndAddToPending(input) {
1135
+ const res = await import_axios.default.post(
1136
+ `${this.apiURL}/transaction/pending/build`,
1137
+ {
1138
+ address: input.msafeAddress
1139
+ },
1140
+ { headers: this.headers() }
1141
+ );
1142
+ if (res.status !== 200 && res.status !== 201) {
1143
+ throw new Error(`invalid buildNextIntentionAndAddToPending return: ${res}`);
1144
+ }
1352
1145
  }
1353
- knownPublicKeys;
1354
- async getPublicKey(address) {
1355
- const cached = this.knownPublicKeys.get(address);
1356
- if (cached) {
1357
- return cached;
1146
+ async skipNextFailedIntention(input) {
1147
+ const res = await import_axios.default.post(
1148
+ `${this.apiURL}/transaction/pending/skip`,
1149
+ {
1150
+ msafeAddress: input.msafeAddress
1151
+ },
1152
+ { headers: this.headers() }
1153
+ );
1154
+ if (res.status !== 200 && res.status !== 201) {
1155
+ throw new Error(`invalid skipNextFailedIntention return: ${res}`);
1358
1156
  }
1359
- const pk = await this._getPublicKey(address);
1360
- if (pk) {
1361
- this.knownPublicKeys.set(address, pk);
1157
+ }
1158
+ async getAddressBookEntries(pagination) {
1159
+ const res = await import_axios.default.get(`${this.apiURL}/address-book`, {
1160
+ headers: this.headers(),
1161
+ params: pagination
1162
+ });
1163
+ if (res.status !== 200) {
1164
+ throw new Error(`Invalid address-book return: ${res}`);
1362
1165
  }
1363
- return pk;
1166
+ return res.data;
1364
1167
  }
1365
- async getPublicKeyBatch(addresses) {
1366
- const results = new Array(addresses.length).fill(void 0);
1367
- for (let i = 0; i < addresses.length; i++) {
1368
- const address = addresses[i];
1369
- results[i] = this.knownPublicKeys.get(address);
1168
+ async updateAddressBook(input) {
1169
+ const res = await import_axios.default.post(`${this.apiURL}/address-book`, input, { headers: this.headers() });
1170
+ if (res.status !== 200 && res.status !== 201) {
1171
+ throw new Error(`invalid updateAddressBook return: ${res}`);
1370
1172
  }
1371
- const emptyIndexes = results.map((elem, index) => elem === void 0 ? index : -1).filter((index) => index !== -1);
1372
- const backendResult = await this.globals.backend.getPublicKeyBatch(emptyIndexes.map((index) => addresses[index]));
1373
- for (let i = 0; i < emptyIndexes.length; i++) {
1374
- const index = emptyIndexes[i];
1375
- results[index] = backendResult[i];
1173
+ }
1174
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1175
+ async processExecutedTransaction(_digest) {
1176
+ return void 0;
1177
+ }
1178
+ headers(token) {
1179
+ return { Authorization: `Bearer ${token || this._token}` };
1180
+ }
1181
+ };
1182
+
1183
+ // src/globals/const.ts
1184
+ var MSafeEnv = /* @__PURE__ */ ((MSafeEnv3) => {
1185
+ MSafeEnv3["local"] = "local";
1186
+ MSafeEnv3["unit"] = "unit";
1187
+ MSafeEnv3["dev"] = "dev";
1188
+ MSafeEnv3["prev"] = "prev";
1189
+ MSafeEnv3["prod"] = "prod";
1190
+ return MSafeEnv3;
1191
+ })(MSafeEnv || {});
1192
+ var MSAFE_APPLICATION = "msafe";
1193
+ var TESTNET_RPC_URL = "https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD";
1194
+ var MAINNET_RPC_URL = "https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7";
1195
+ var LOCAL_API_URL = "http://127.0.0.1:3000";
1196
+ var LOCAL_SYNCING_URL = "http://127.0.0.1:3001";
1197
+ var DEV_API_URL = "http://13.56.226.148";
1198
+ var DEV_SYNCING_URL = "http://52.53.228.20";
1199
+ var ENV_CONFIGS = /* @__PURE__ */ new Map([
1200
+ [
1201
+ "unit" /* unit */,
1202
+ {
1203
+ suiClient: {
1204
+ url: TESTNET_RPC_URL
1205
+ },
1206
+ backend: {
1207
+ url: LOCAL_API_URL
1208
+ },
1209
+ syncingURL: LOCAL_SYNCING_URL
1376
1210
  }
1377
- for (let i = 0; i < results.length; i++) {
1378
- if (results[i] === void 0) {
1379
- results[i] = await this.getPublicKeyFromChain(addresses[i]);
1380
- }
1211
+ ],
1212
+ [
1213
+ "local" /* local */,
1214
+ {
1215
+ suiClient: {
1216
+ url: TESTNET_RPC_URL
1217
+ },
1218
+ backend: {
1219
+ url: LOCAL_API_URL
1220
+ },
1221
+ syncingURL: LOCAL_SYNCING_URL
1381
1222
  }
1382
- for (let i = 0; i < addresses.length; i++) {
1383
- if (results[i]) {
1384
- this.knownPublicKeys.set(addresses[i], results[i]);
1385
- }
1223
+ ],
1224
+ [
1225
+ "dev" /* dev */,
1226
+ {
1227
+ suiClient: {
1228
+ url: TESTNET_RPC_URL
1229
+ },
1230
+ backend: {
1231
+ url: DEV_API_URL
1232
+ },
1233
+ syncingURL: DEV_SYNCING_URL
1386
1234
  }
1387
- return results;
1235
+ ]
1236
+ ]);
1237
+ function getMSafeConfig(env, options) {
1238
+ const config = ENV_CONFIGS.get(env);
1239
+ if (!config) {
1240
+ throw new Error("Unknown environment");
1388
1241
  }
1389
- async _getPublicKey(address) {
1390
- const pkBackend = await this.getPublicKeyFromBackend(address);
1391
- if (pkBackend) {
1392
- return pkBackend;
1393
- }
1394
- const pkChain = await this.getPublicKeyFromChain(address);
1395
- if (pkChain) {
1396
- return pkChain;
1397
- }
1398
- return void 0;
1242
+ if (options?.suiClient?.url) {
1243
+ config.suiClient.url = options.suiClient.url;
1399
1244
  }
1400
- async getPublicKeyFromBackend(address) {
1401
- try {
1402
- const pk = await this.globals.backend.getPublicKey(address);
1403
- return pk;
1404
- } catch (_) {
1405
- return void 0;
1245
+ if (options?.backend?.url) {
1246
+ config.backend.url = options.backend.url;
1247
+ }
1248
+ return config;
1249
+ }
1250
+
1251
+ // src/globals/MSafeGlobals.ts
1252
+ var MSafeGlobals = class _MSafeGlobals {
1253
+ backend;
1254
+ suiClient;
1255
+ config;
1256
+ _wallet;
1257
+ constructor(input) {
1258
+ this.backend = input.backend;
1259
+ this.suiClient = input.suiClient;
1260
+ this.config = input.config;
1261
+ }
1262
+ static async New(env, options) {
1263
+ const config = getMSafeConfig(env, options);
1264
+ const suiClient = new import_client.SuiClient(config.suiClient);
1265
+ const backend = new BackendImpl(config.backend.url);
1266
+ return new _MSafeGlobals({
1267
+ backend,
1268
+ suiClient,
1269
+ config
1270
+ });
1271
+ }
1272
+ connectWallet(wallet) {
1273
+ this._wallet = wallet;
1274
+ }
1275
+ get wallet() {
1276
+ if (!this._wallet) {
1277
+ throw new Error("wallet not connected");
1406
1278
  }
1279
+ return this._wallet;
1407
1280
  }
1408
- async getPublicKeyFromChain(address) {
1409
- return getPublicKeyFromChain(this.globals.suiClient, address);
1281
+ set wallet(val) {
1282
+ this._wallet = val;
1410
1283
  }
1411
1284
  };
1412
1285
 
@@ -1436,7 +1309,7 @@ var MSafeClient = class _MSafeClient {
1436
1309
  return jwt;
1437
1310
  }
1438
1311
  async authSign(wallet) {
1439
- const messageStr = MessageHelper.welcomeMessage((/* @__PURE__ */ new Date()).toUTCString());
1312
+ const messageStr = import_sui3_utils6.SigningMessageHelper.loginMessageWithTimestamp((/* @__PURE__ */ new Date()).toUTCString());
1440
1313
  const sig = await wallet.signPersonalMessage({
1441
1314
  messageStr
1442
1315
  });
@@ -1448,7 +1321,10 @@ var MSafeClient = class _MSafeClient {
1448
1321
  });
1449
1322
  }
1450
1323
  async userInfo() {
1451
- return this.globals.backend.getUserInfo(await this.walletAddress());
1324
+ return this.globals.backend.getUserInfo();
1325
+ }
1326
+ async ownedMSafe(pagination) {
1327
+ return this.globals.backend.getOwnedMSafeByStatus({ status: import_sui3_utils6.UserMSafeStatus.active, pagination });
1452
1328
  }
1453
1329
  async createAccount(info) {
1454
1330
  return this.creationHelper.submitMSafeCreation(info);
@@ -1486,34 +1362,27 @@ var MSafeClient = class _MSafeClient {
1486
1362
  get AddressBook() {
1487
1363
  return new AddressBookSDK(this.globals);
1488
1364
  }
1365
+ get Invitation() {
1366
+ return new InvitationSDK(this.globals);
1367
+ }
1489
1368
  async walletAddress() {
1490
1369
  return this.wallet.address();
1491
1370
  }
1492
1371
  };
1493
-
1494
- // src/types/address-book.ts
1495
- var OpAddressBookType = /* @__PURE__ */ ((OpAddressBookType2) => {
1496
- OpAddressBookType2["Delete"] = "delete";
1497
- OpAddressBookType2["Upsert"] = "upsert";
1498
- return OpAddressBookType2;
1499
- })(OpAddressBookType || {});
1500
1372
  // Annotate the CommonJS export names for ESM import in node:
1501
1373
  0 && (module.exports = {
1502
- AUTH_SIGN_MESSAGE,
1503
1374
  AddressBookSDK,
1504
1375
  COIN_TYPE_ARG_REGEX,
1505
1376
  Coin,
1506
1377
  CoinHelper,
1507
1378
  CreateHelper,
1508
1379
  DEV_API_URL,
1509
- DEV_DATABASE_CONFIG,
1510
1380
  DEV_SYNCING_URL,
1511
1381
  ENV_CONFIGS,
1512
1382
  Formatter,
1513
1383
  HexToUint8Array,
1514
1384
  IntentionHelper,
1515
1385
  LOCAL_API_URL,
1516
- LOCAL_DATABASE_CONFIG,
1517
1386
  LOCAL_SYNCING_URL,
1518
1387
  MAINNET_RPC_URL,
1519
1388
  MSAFE_APPLICATION,
@@ -1521,13 +1390,9 @@ var OpAddressBookType = /* @__PURE__ */ ((OpAddressBookType2) => {
1521
1390
  MSafeClient,
1522
1391
  MSafeEnv,
1523
1392
  MSafeGlobals,
1524
- MessageHelper,
1525
- OpAddressBookType,
1526
- PublicKeySerde,
1527
1393
  SUI_COIN,
1528
1394
  SignatureVerifier,
1529
1395
  TESTNET_RPC_URL,
1530
- UNIT_DATABASE_CONFIG,
1531
1396
  Uint8ArrayToHex,
1532
1397
  getAllCoins,
1533
1398
  getMSafeConfig,