@msafe/sui3-sdk 0.0.4-pre-113020e.0 → 0.0.4

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 CHANGED
@@ -1,29 +1,5 @@
1
- // src/core/CreateHelper.ts
2
- import {
3
- createAccountCreationMessage,
4
- MultisigAccountManager,
5
- validateCreateAccountRequest
6
- } from "@msafe/sui3-utils";
7
-
8
- // src/utils/crypto.ts
9
- import {
10
- SIGNATURE_FLAG_TO_SCHEME
11
- } from "@mysten/sui.js/cryptography";
12
- import { Ed25519PublicKey } from "@mysten/sui.js/keypairs/ed25519";
13
- import { Secp256k1PublicKey } from "@mysten/sui.js/keypairs/secp256k1";
14
- import { Secp256r1PublicKey } from "@mysten/sui.js/keypairs/secp256r1";
15
- import { verifyPersonalMessage, verifyTransactionBlock } from "@mysten/sui.js/verify";
16
-
17
- // src/utils/buffer.ts
18
- function stringToBuffer(s) {
19
- return Buffer.from(s, "utf-8");
20
- }
21
- function Uint8ArrayToHex(b) {
22
- return `0x${Array.prototype.map.call(b, (x) => `0${x.toString(16)}`.slice(-2)).join("")}`;
23
- }
24
- function HexToUint8Array(hex) {
25
- return Uint8Array.from(Buffer.from(hex.startsWith("0x") ? hex.slice(2) : hex, "hex"));
26
- }
1
+ // src/transactions/coin-transfer.ts
2
+ import { TransactionBlock } from "@mysten/sui.js/transactions";
27
3
 
28
4
  // src/utils/format.ts
29
5
  import { normalizeSuiAddress, normalizeStructTag as normalizeStructTag2 } from "@mysten/sui.js/utils";
@@ -99,6 +75,30 @@ var Formatter = class {
99
75
  }
100
76
  };
101
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
102
  // src/utils/crypto.ts
103
103
  var SignatureVerifier = class _SignatureVerifier {
104
104
  static async getPublicKeyFromSignature(input) {
@@ -158,78 +158,7 @@ var PublicKeySerde = class {
158
158
  }
159
159
  };
160
160
 
161
- // src/core/CreateHelper.ts
162
- var CreateHelper = class {
163
- constructor(globals, pkHelper) {
164
- this.globals = globals;
165
- this.pkHelper = pkHelper;
166
- }
167
- async getPublicKeyBatch(addresses) {
168
- return this.pkHelper.getPublicKeyBatch(addresses);
169
- }
170
- async calculateMSafeAddress(info) {
171
- const msConfig = await this.reduceCreationInfoToRawConfig(info);
172
- const ms = new MultisigAccountManager(msConfig);
173
- return ms.address;
174
- }
175
- // Validate the create info and return the msafe address.
176
- async validateCreateInfo(createInfo) {
177
- const rawConfig = await this.reduceCreationInfoToRawConfig(createInfo);
178
- validateCreateAccountRequest(rawConfig);
179
- return this.calculateMSafeAddress(createInfo);
180
- }
181
- async submitMSafeCreation(creationInfo) {
182
- const msafeAddress = await this.validateCreateInfo(creationInfo);
183
- const signingMessage = createAccountCreationMessage(msafeAddress);
184
- const signature = await this.globals.wallet.signPersonalMessage({ messageStr: signingMessage });
185
- await this.submitToBackend(creationInfo, signature.signature);
186
- return msafeAddress;
187
- }
188
- async reduceCreationInfoToRawConfig(info) {
189
- const publicKeys = await this.getPublicKeyBatch(info.ownerWithWeight.map((oww) => oww.address));
190
- publicKeys.forEach((pk, i) => {
191
- if (pk === void 0) {
192
- throw new Error(`Unknown public key for address: ${info.ownerWithWeight[i].address}`);
193
- }
194
- });
195
- return {
196
- threshold: info.threshold,
197
- ownersWithWeight: info.ownerWithWeight.map((owner, i) => ({
198
- publicKey: publicKeys[i],
199
- weight: owner.weight
200
- })),
201
- creationNonce: info.creationNonce
202
- };
203
- }
204
- async submitToBackend(createInfo, signature) {
205
- const pks = await this.pkHelper.getPublicKeyBatch(createInfo.ownerWithWeight.map((owner) => owner.address));
206
- await this.globals.backend.createMSafeAccount({
207
- ownersWithWeightPKEncoded: createInfo.ownerWithWeight.map((owner, i) => {
208
- const publicKeySer = PublicKeySerde.ser(pks[i]);
209
- return {
210
- address: owner.address,
211
- weight: owner.weight,
212
- publicKeyEncoded: publicKeySer.publicKey,
213
- schema: publicKeySer.scheme
214
- };
215
- }),
216
- threshold: createInfo.threshold,
217
- name: createInfo.name,
218
- // name validation is deferred to backend
219
- description: createInfo.description,
220
- // description validation is deferred to backend
221
- creationNonce: createInfo.creationNonce,
222
- signature
223
- });
224
- }
225
- };
226
-
227
- // src/transactions/coin-transfer.ts
228
- import { TransactionBlock } from "@mysten/sui.js/transactions";
229
-
230
161
  // src/utils/sui.ts
231
- import { parseSerializedSignature } from "@mysten/sui.js/cryptography";
232
- import { MultiSigPublicKey } from "@mysten/sui.js/multisig";
233
162
  var SUI_COIN = "0x2::sui::SUI";
234
163
  async function getPublicKeyFromChain(suiClient, address) {
235
164
  let txs;
@@ -497,19 +426,165 @@ var MessageHelper = class {
497
426
  }
498
427
  };
499
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
+
500
580
  // src/core/MSafeAccount.ts
501
- import { MultisigAccountManager as MultisigAccountManager2 } from "@msafe/sui3-utils";
502
581
  var MSafeAccount = class _MSafeAccount {
503
582
  constructor(globals, info) {
504
583
  this.globals = globals;
505
584
  this.info = info;
506
- this.multisigManager = new MultisigAccountManager2({
507
- threshold: info.threshold,
508
- ownersWithWeight: info.ownersWithWeightPK,
509
- creationNonce: info.creationNonce
510
- });
585
+ this.rawMultiSig = RawMultiSig.fromMSafeAccountInfo(info);
511
586
  }
512
- multisigManager;
587
+ rawMultiSig;
513
588
  static async new(globals, address) {
514
589
  const info = await globals.backend.getMSafeAccountInfo(address);
515
590
  return new _MSafeAccount(globals, info);
@@ -618,7 +693,7 @@ var MSafeAccount = class _MSafeAccount {
618
693
  sigs.push(signature);
619
694
  }
620
695
  }
621
- const multiSignature = this.multisigManager.combinePartialSignatures(sigs);
696
+ const multiSignature = this.rawMultiSig.combinePartialSignatures(sigs);
622
697
  return this.suiClient.executeTransactionBlock({
623
698
  transactionBlock: HexToUint8Array(pending.payload),
624
699
  signature: multiSignature,
@@ -711,6 +786,762 @@ var PublicKeyHelper = class {
711
786
  // src/globals/MSafeGlobals.ts
712
787
  import { SuiClient } from "@mysten/sui.js/client";
713
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
+ processed: tx.processed,
1139
+ status: tx.status,
1140
+ statusRemark: tx.statusRemark,
1141
+ creator: tx.creator,
1142
+ createdAt: tx.createdAt
1143
+ }));
1144
+ }
1145
+ async proposeIntention(input) {
1146
+ const userMSafe = await this.model.userMSafe.findOneBy({
1147
+ msafeAddress: input.msafeAddress,
1148
+ userAddress: input.userAddress
1149
+ });
1150
+ if (!userMSafe) {
1151
+ throw new Error("User does not have permission to propose intention");
1152
+ }
1153
+ const verified = await SignatureVerifier.verifyPersonalSignature({
1154
+ messageStr: MessageHelper.proposeIntentionMessage({ intention: input.intention, sn: input.sequenceNumber }),
1155
+ signature: input.signature,
1156
+ targetAddress: input.userAddress
1157
+ });
1158
+ if (!verified) {
1159
+ throw new Error("Invalid signature");
1160
+ }
1161
+ const sequenceNumber = await this.model.transactionIntention.count({
1162
+ where: {
1163
+ msafeAddress: input.msafeAddress
1164
+ }
1165
+ });
1166
+ if (sequenceNumber !== input.sequenceNumber) {
1167
+ throw new Error("Sequence number not expected");
1168
+ }
1169
+ const intention = {
1170
+ msafeAddress: input.msafeAddress,
1171
+ sequenceNumber,
1172
+ processed: false,
1173
+ ...IntentionHelper.getTxType(input.intention),
1174
+ data: IntentionHelper.ser(input.intention),
1175
+ status: "NEW",
1176
+ creator: input.userAddress
1177
+ };
1178
+ await this.model.transactionIntention.save(intention);
1179
+ }
1180
+ // Propose a pending transaction. Require the msafe account
1181
+ // Does not have any pending transactions.
1182
+ async proposePendingTransaction(input) {
1183
+ const userMSafe = await this.model.userMSafe.findOneBy({
1184
+ msafeAddress: input.msafeAddress,
1185
+ userAddress: input.userAddress
1186
+ });
1187
+ if (userMSafe === null) {
1188
+ throw new Error("Unauthorized");
1189
+ }
1190
+ const msafePendings = await this.model.pendingTransaction.findBy({
1191
+ msafeAddress: input.msafeAddress
1192
+ });
1193
+ if (msafePendings.length !== 0) {
1194
+ throw new Error("Still have pending transaction");
1195
+ }
1196
+ const txb = await IntentionHelper.buildTxb({
1197
+ suiClient: this._suiClient,
1198
+ intention: input.intention,
1199
+ sender: input.msafeAddress
1200
+ });
1201
+ const payload = await txb.build({ client: this._suiClient });
1202
+ const txDigest = await txb.getDigest({ client: this._suiClient });
1203
+ if (txDigest !== input.digest) {
1204
+ throw new Error("Transaction digest un-match");
1205
+ }
1206
+ const verified = await SignatureVerifier.verifyTransactionSignature({
1207
+ payload,
1208
+ targetAddress: input.userAddress,
1209
+ signature: input.signature
1210
+ });
1211
+ if (!verified) {
1212
+ throw new Error("Failed to verify signature");
1213
+ }
1214
+ const maxSNHistory = await this.model.historyTransaction.findOne({
1215
+ where: { msafeAddress: input.msafeAddress },
1216
+ order: { sequenceNumber: "desc" }
1217
+ });
1218
+ const sequenceNumber = maxSNHistory === null ? 0 : maxSNHistory.sequenceNumber + 1;
1219
+ const intention = {
1220
+ msafeAddress: input.msafeAddress,
1221
+ sequenceNumber,
1222
+ processed: false,
1223
+ ...IntentionHelper.getTxType(input.intention),
1224
+ data: IntentionHelper.ser(input.intention),
1225
+ status: "SUCCESS",
1226
+ creator: input.userAddress
1227
+ };
1228
+ await this.model.transactionIntention.save(intention);
1229
+ const pendingTx = {
1230
+ digest: txDigest,
1231
+ msafeAddress: input.msafeAddress,
1232
+ payload: Uint8ArrayToHex(payload),
1233
+ sequenceNumber,
1234
+ isRejectTx: false,
1235
+ creator: input.userAddress
1236
+ };
1237
+ await this.model.pendingTransaction.save(pendingTx);
1238
+ const userVote = {
1239
+ userAddress: input.userAddress,
1240
+ txDigest,
1241
+ msafeAddress: input.msafeAddress,
1242
+ signature: input.signature,
1243
+ isValid: true
1244
+ };
1245
+ await this.model.userVote.save(userVote);
1246
+ }
1247
+ // Calls for the first reject transaction
1248
+ async rejectCurrentTx(input) {
1249
+ const userMSafe = await this.model.userMSafe.findOneBy({
1250
+ userAddress: input.userAddress,
1251
+ msafeAddress: input.msafeAddress
1252
+ });
1253
+ if (userMSafe === null) {
1254
+ throw new Error("User does not have permission to MSafe");
1255
+ }
1256
+ const currentPending = await this.model.pendingTransaction.findOneBy({
1257
+ msafeAddress: input.msafeAddress,
1258
+ isRejectTx: false
1259
+ });
1260
+ if (currentPending === null) {
1261
+ throw new Error("No active pending transaction");
1262
+ }
1263
+ const txb = await IntentionHelper.buildRejectTransaction({
1264
+ msafeAddress: input.msafeAddress,
1265
+ payloadToReject: currentPending.payload
1266
+ });
1267
+ const payload = await txb.build({ client: this._suiClient });
1268
+ const digest = await txb.getDigest({ client: this._suiClient });
1269
+ if (input.digest !== digest) {
1270
+ throw new Error("Digest not match");
1271
+ }
1272
+ const verified = await SignatureVerifier.verifyTransactionSignature({
1273
+ payload,
1274
+ targetAddress: input.userAddress,
1275
+ signature: input.signature
1276
+ });
1277
+ if (!verified) {
1278
+ throw new Error("Signature unverified");
1279
+ }
1280
+ const existPendingReject = await this.model.pendingTransaction.findOneBy({
1281
+ msafeAddress: input.msafeAddress,
1282
+ isRejectTx: true
1283
+ });
1284
+ if (existPendingReject !== null) {
1285
+ await this.voteForTransaction({
1286
+ txDigest: existPendingReject.digest,
1287
+ msafeAddress: input.msafeAddress,
1288
+ userAddress: input.userAddress,
1289
+ signature: input.signature
1290
+ });
1291
+ return;
1292
+ }
1293
+ const rejectPayloadStr = Uint8ArrayToHex(payload);
1294
+ const rejectDigest = await txb.getDigest({ client: this._suiClient });
1295
+ const rejectPending = {
1296
+ msafeAddress: input.msafeAddress,
1297
+ digest: rejectDigest,
1298
+ payload: rejectPayloadStr,
1299
+ sequenceNumber: currentPending.sequenceNumber,
1300
+ isRejectTx: true,
1301
+ creator: input.userAddress
1302
+ };
1303
+ await this.model.pendingTransaction.save(rejectPending);
1304
+ const rejectVote = {
1305
+ userAddress: input.userAddress,
1306
+ msafeAddress: input.msafeAddress,
1307
+ txDigest: rejectDigest,
1308
+ signature: input.signature,
1309
+ isValid: true
1310
+ };
1311
+ await this.model.userVote.save(rejectVote);
1312
+ const existVote = await this.model.userVote.findOneBy({
1313
+ txDigest: currentPending.digest,
1314
+ userAddress: input.userAddress
1315
+ });
1316
+ if (existVote !== null) {
1317
+ await this.model.userVote.update(
1318
+ { userAddress: input.userAddress, txDigest: currentPending.digest },
1319
+ { isValid: false }
1320
+ );
1321
+ }
1322
+ }
1323
+ async voteForTransaction(input) {
1324
+ const pendingTx = await this.model.pendingTransaction.findOneBy({ digest: input.txDigest });
1325
+ if (!pendingTx) {
1326
+ throw new Error(`Pending transaction not found: ${input.txDigest}`);
1327
+ }
1328
+ if (pendingTx.msafeAddress !== input.msafeAddress) {
1329
+ throw new Error("MSafe address not match");
1330
+ }
1331
+ const userMSafe = await this.model.userMSafe.findOneBy({
1332
+ userAddress: input.userAddress,
1333
+ msafeAddress: input.msafeAddress
1334
+ });
1335
+ if (userMSafe === null) {
1336
+ throw new Error(`User (${input.userAddress}) does not have permission on MSafe account (${input.msafeAddress})`);
1337
+ }
1338
+ const payload = HexToUint8Array(pendingTx.payload);
1339
+ const verified = await SignatureVerifier.verifyTransactionSignature({
1340
+ payload,
1341
+ targetAddress: input.userAddress,
1342
+ signature: input.signature
1343
+ });
1344
+ if (!verified) {
1345
+ throw new Error("Invalid signature");
1346
+ }
1347
+ const rejectPendingTx = await this.model.pendingTransaction.findOneBy({
1348
+ msafeAddress: input.msafeAddress,
1349
+ sequenceNumber: pendingTx.sequenceNumber,
1350
+ isRejectTx: !pendingTx.isRejectTx
1351
+ });
1352
+ if (rejectPendingTx !== null) {
1353
+ await this.model.userVote.update(
1354
+ {
1355
+ userAddress: input.userAddress,
1356
+ txDigest: rejectPendingTx.digest,
1357
+ isValid: true
1358
+ },
1359
+ { isValid: false }
1360
+ );
1361
+ }
1362
+ const existVote = await this.model.userVote.exist({
1363
+ where: {
1364
+ txDigest: input.txDigest,
1365
+ userAddress: input.userAddress
1366
+ }
1367
+ });
1368
+ if (!existVote) {
1369
+ const userVote = {
1370
+ txDigest: input.txDigest,
1371
+ userAddress: input.userAddress,
1372
+ msafeAddress: input.msafeAddress,
1373
+ signature: input.signature,
1374
+ isValid: true
1375
+ };
1376
+ await this.model.userVote.save(userVote);
1377
+ } else {
1378
+ await this.model.userVote.update(
1379
+ {
1380
+ txDigest: input.txDigest,
1381
+ userAddress: input.userAddress
1382
+ },
1383
+ { isValid: true }
1384
+ );
1385
+ }
1386
+ }
1387
+ // Mock the process of an executed transaction
1388
+ // Here only the essential logic of transaction processing logic
1389
+ // is implemented. Need more transaction parsing from the fetcher
1390
+ // module.
1391
+ //
1392
+ // TODO: User queryRunner to make the transaction atomic.
1393
+ async processExecutedTransaction(digest) {
1394
+ const historyTx = await this.model.historyTransaction.findOneBy({ digest });
1395
+ if (historyTx) {
1396
+ return;
1397
+ }
1398
+ const pendingTx = await this.model.pendingTransaction.findOneBy({ digest });
1399
+ if (!pendingTx) {
1400
+ throw new Error("Transaction digest not found");
1401
+ }
1402
+ await this.model.transactionIntention.update(
1403
+ { msafeAddress: pendingTx.msafeAddress, sequenceNumber: pendingTx.sequenceNumber },
1404
+ { processed: true }
1405
+ );
1406
+ const pendings = await this.model.pendingTransaction.findBy({
1407
+ msafeAddress: pendingTx.msafeAddress,
1408
+ sequenceNumber: pendingTx.sequenceNumber
1409
+ });
1410
+ if (pendings.length === 0) {
1411
+ throw new Error("Pending transaction not found");
1412
+ }
1413
+ const executionResult = "success";
1414
+ for (let i = 0; i !== pendings.length; i++) {
1415
+ const pending = pendings[i];
1416
+ const history = {
1417
+ digest: pending.digest,
1418
+ payload: pending.payload,
1419
+ msafeAddress: pending.msafeAddress,
1420
+ sequenceNumber: pending.sequenceNumber,
1421
+ isRejectTx: pending.isRejectTx,
1422
+ creator: pending.creator,
1423
+ createdAt: pending.createdAt,
1424
+ // TODO: Fill in this field based on transaction processing result
1425
+ status: pending.digest === digest ? executionResult : "rejected"
1426
+ };
1427
+ await this.model.historyTransaction.save(history);
1428
+ await this.model.pendingTransaction.delete({ digest: pending.digest });
1429
+ }
1430
+ }
1431
+ /**
1432
+ * Build the next transaction intention, and add the built transaction to pendings.
1433
+ * @param input
1434
+ */
1435
+ async buildNextIntentionAndAddToPending(input) {
1436
+ const maxSNHistory = await this.model.historyTransaction.findOne({
1437
+ where: { msafeAddress: input.msafeAddress },
1438
+ order: { sequenceNumber: "desc" }
1439
+ });
1440
+ const nextSequenceNumber = maxSNHistory ? maxSNHistory.sequenceNumber + 1 : 0;
1441
+ const currentPendings = await this.model.pendingTransaction.findBy({
1442
+ msafeAddress: input.msafeAddress
1443
+ });
1444
+ if (currentPendings.length !== 0) {
1445
+ throw new Error("Still have pendings");
1446
+ }
1447
+ const nextTx = await this.model.transactionIntention.findOneBy({
1448
+ msafeAddress: input.msafeAddress,
1449
+ sequenceNumber: nextSequenceNumber
1450
+ });
1451
+ if (nextTx === null) {
1452
+ throw new Error("No future intentions to build");
1453
+ }
1454
+ const nextIntention = IntentionHelper.de(nextTx.data);
1455
+ try {
1456
+ const newTxb = await IntentionHelper.buildTxb({
1457
+ suiClient: this._suiClient,
1458
+ sender: input.msafeAddress,
1459
+ intention: nextIntention
1460
+ });
1461
+ const payload = await newTxb.build({ client: this._suiClient });
1462
+ const newDigest = await newTxb.getDigest({ client: this._suiClient });
1463
+ const newPending = {
1464
+ digest: newDigest,
1465
+ payload: Uint8ArrayToHex(payload),
1466
+ msafeAddress: input.msafeAddress,
1467
+ sequenceNumber: nextTx.sequenceNumber,
1468
+ isRejectTx: false,
1469
+ creator: nextTx.creator
1470
+ };
1471
+ await this.model.pendingTransaction.save(newPending);
1472
+ await this.model.transactionIntention.update(
1473
+ {
1474
+ msafeAddress: input.msafeAddress,
1475
+ sequenceNumber: nextSequenceNumber
1476
+ },
1477
+ {
1478
+ status: "SUCCESS"
1479
+ }
1480
+ );
1481
+ } catch (e) {
1482
+ await this.model.transactionIntention.update(
1483
+ {
1484
+ msafeAddress: input.msafeAddress,
1485
+ sequenceNumber: nextSequenceNumber
1486
+ },
1487
+ {
1488
+ status: "FAILED",
1489
+ statusRemark: e.toString()
1490
+ }
1491
+ );
1492
+ throw new Error(`Intention build failed: {sequenceNumber: ${nextSequenceNumber}}`);
1493
+ }
1494
+ }
1495
+ /**
1496
+ * Skip next failed transaction if build of the intention has been failed before.
1497
+ */
1498
+ async skipNextFailedIntention(input) {
1499
+ const userMSafe = await this.model.userMSafe.findOneBy({
1500
+ msafeAddress: input.msafeAddress,
1501
+ userAddress: input.userAddress
1502
+ });
1503
+ if (userMSafe === null) {
1504
+ throw new Error("user does not have permission to MSafe");
1505
+ }
1506
+ const curSequenceNumber = await this.model.historyTransaction.findOne({
1507
+ where: { msafeAddress: input.msafeAddress },
1508
+ order: { sequenceNumber: "desc" }
1509
+ });
1510
+ const nextSequenceNumber = curSequenceNumber ? curSequenceNumber.sequenceNumber + 1 : 0;
1511
+ const failedIntention = await this.model.transactionIntention.findOneBy({
1512
+ msafeAddress: input.msafeAddress,
1513
+ sequenceNumber: nextSequenceNumber
1514
+ });
1515
+ if (failedIntention === null) {
1516
+ throw new Error("Next intention not found");
1517
+ }
1518
+ if (failedIntention.status !== "FAILED") {
1519
+ throw new Error("Next intention not failed");
1520
+ }
1521
+ const history = {
1522
+ msafeAddress: input.msafeAddress,
1523
+ digest: "0x0",
1524
+ // Special case for build has been failed,
1525
+ payload: "",
1526
+ sequenceNumber: nextSequenceNumber,
1527
+ creator: failedIntention.creator,
1528
+ isRejectTx: false,
1529
+ status: "build-failed"
1530
+ };
1531
+ await this.model.historyTransaction.save(history);
1532
+ await this.model.transactionIntention.update(
1533
+ { msafeAddress: input.msafeAddress, sequenceNumber: nextSequenceNumber },
1534
+ { processed: true }
1535
+ );
1536
+ }
1537
+ async getUser(address) {
1538
+ return this.model.user.findOneBy({ address });
1539
+ }
1540
+ get model() {
1541
+ return this.db.coreModel;
1542
+ }
1543
+ };
1544
+
714
1545
  // src/globals/const.ts
715
1546
  var MSafeEnv = /* @__PURE__ */ ((MSafeEnv3) => {
716
1547
  MSafeEnv3["local"] = "local";
@@ -745,8 +1576,6 @@ var DEV_DATABASE_CONFIG = {
745
1576
  };
746
1577
  var TESTNET_RPC_URL = "https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD";
747
1578
  var MAINNET_RPC_URL = "https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7";
748
- var LOCAL_API_URL = "http://127.0.0.1:3000";
749
- var DEV_API_URL = "http://13.56.226.148";
750
1579
  var ENV_CONFIGS = /* @__PURE__ */ new Map([
751
1580
  [
752
1581
  "unit" /* unit */,
@@ -754,8 +1583,7 @@ var ENV_CONFIGS = /* @__PURE__ */ new Map([
754
1583
  suiClient: {
755
1584
  url: TESTNET_RPC_URL
756
1585
  },
757
- backend: LOCAL_DATABASE_CONFIG,
758
- apiURL: LOCAL_API_URL
1586
+ backend: UNIT_DATABASE_CONFIG
759
1587
  }
760
1588
  ],
761
1589
  [
@@ -764,8 +1592,7 @@ var ENV_CONFIGS = /* @__PURE__ */ new Map([
764
1592
  suiClient: {
765
1593
  url: TESTNET_RPC_URL
766
1594
  },
767
- backend: LOCAL_DATABASE_CONFIG,
768
- apiURL: LOCAL_API_URL
1595
+ backend: LOCAL_DATABASE_CONFIG
769
1596
  }
770
1597
  ],
771
1598
  [
@@ -774,8 +1601,7 @@ var ENV_CONFIGS = /* @__PURE__ */ new Map([
774
1601
  suiClient: {
775
1602
  url: TESTNET_RPC_URL
776
1603
  },
777
- backend: DEV_DATABASE_CONFIG,
778
- apiURL: DEV_API_URL
1604
+ backend: DEV_DATABASE_CONFIG
779
1605
  }
780
1606
  ]
781
1607
  ]);
@@ -794,140 +1620,6 @@ function getMSafeConfig(env, options) {
794
1620
  }
795
1621
  var AUTH_SIGN_MESSAGE = "Welcome to MSafe";
796
1622
 
797
- // src/backend/BackendImpl.ts
798
- import axios from "axios";
799
- var BackendImpl = class {
800
- constructor(apiURL) {
801
- this.apiURL = apiURL;
802
- }
803
- _token;
804
- async authSign(input) {
805
- const res = await axios.post(`${this.apiURL}/auth/login`, input);
806
- if (res.status !== 200 && res.status !== 201) {
807
- throw new Error(`invalid authSign return: ${res}`);
808
- }
809
- this._token = res.data.accessToken;
810
- return this._token;
811
- }
812
- setJWTToken(token) {
813
- this._token = token;
814
- }
815
- async getPublicKey(address) {
816
- return (await this.getPublicKeyBatch([address]))[0];
817
- }
818
- async getPublicKeyBatch(addresses) {
819
- const res = await axios.post(
820
- `${this.apiURL}/account/getPublicKeyBatch`,
821
- addresses,
822
- {
823
- headers: this.headers()
824
- }
825
- );
826
- if (res.status !== 200 && res.status !== 201) {
827
- throw new Error(`invalid getPublicKeyBatch return: ${res}`);
828
- }
829
- return res.data?.map(
830
- (publicKeyWithSchema) => publicKeyWithSchema ? PublicKeySerde.de({ ...publicKeyWithSchema }) : void 0
831
- );
832
- }
833
- async getMSafeAccountInfo(msafeAddress) {
834
- const res = await axios.get(
835
- `${this.apiURL}/account/getMSafeAccountInfo/${msafeAddress}`,
836
- {
837
- headers: this.headers()
838
- }
839
- );
840
- if (res.status !== 200 && res.status !== 201) {
841
- throw new Error(`invalid getPublicKeyBatch return: ${res}`);
842
- }
843
- const msafeResp = res.data;
844
- return {
845
- address: msafeResp.address,
846
- ownersWithWeightPK: msafeResp.ownersWithWeightPKEncoded.map(
847
- (owner) => ({
848
- publicKey: PublicKeySerde.de({ publicKey: owner.publicKeyEncoded, scheme: owner.schema }),
849
- address: owner.address,
850
- weight: owner.weight
851
- })
852
- ),
853
- threshold: msafeResp.threshold,
854
- name: msafeResp.name,
855
- description: msafeResp.description,
856
- creationNonce: msafeResp.creationNonce
857
- };
858
- }
859
- async getUserInfo(userAddress) {
860
- const res = await axios.get(`${this.apiURL}/account/user/${userAddress}`, {
861
- headers: this.headers()
862
- });
863
- if (res.status !== 200 && res.status !== 201) {
864
- throw new Error(`invalid getPublicKeyBatch return: ${res}`);
865
- }
866
- return {
867
- address: res.data.address,
868
- publicKey: res.data.publicKey,
869
- schema: res.data.schema,
870
- creationNonce: res.data.creationNonce,
871
- ownedMSafe: res.data.ownedMSafe.map(
872
- (msafe) => ({
873
- address: msafe.address,
874
- ownersWithWeightPK: msafe.ownersWithWeightPKEncoded.map(
875
- (owner) => ({
876
- publicKey: PublicKeySerde.de({ publicKey: owner.publicKeyEncoded, scheme: owner.schema }),
877
- address: owner.address,
878
- weight: owner.weight
879
- })
880
- ),
881
- threshold: msafe.threshold,
882
- name: msafe.name,
883
- description: msafe.description,
884
- creationNonce: msafe.creationNonce
885
- })
886
- )
887
- };
888
- }
889
- async getPendingTransactions(msafeAddress) {
890
- return [];
891
- }
892
- async getHistoryTransactions(msafeAddress) {
893
- return [];
894
- }
895
- async getFutureIntentions(msafeAddress) {
896
- return [];
897
- }
898
- async getCurrentSequenceNumber(msafeAddress) {
899
- return 0;
900
- }
901
- async getNextSequenceNumber(msafeAddress) {
902
- return 0;
903
- }
904
- async createMSafeAccount(input) {
905
- const res = await axios.post(`${this.apiURL}/account`, input, {
906
- headers: this.headers()
907
- });
908
- if (res.status !== 200 && res.status !== 201) {
909
- throw new Error(`invalid createMSafeAccount return: ${res}`);
910
- }
911
- }
912
- async proposeIntention(input) {
913
- }
914
- async proposePendingTransaction(input) {
915
- }
916
- async rejectCurrentTx(input) {
917
- }
918
- async voteForTransaction(input) {
919
- }
920
- async buildNextIntentionAndAddToPending(input) {
921
- }
922
- async skipNextFailedIntention(input) {
923
- }
924
- async processExecutedTransaction(digest) {
925
- }
926
- headers() {
927
- return { Authorization: `Bearer ${this._token}` };
928
- }
929
- };
930
-
931
1623
  // src/globals/MSafeGlobals.ts
932
1624
  var MSafeGlobals = class _MSafeGlobals {
933
1625
  backend;
@@ -942,7 +1634,7 @@ var MSafeGlobals = class _MSafeGlobals {
942
1634
  static async New(env, options) {
943
1635
  const config = getMSafeConfig(env, options);
944
1636
  const suiClient = new SuiClient(config.suiClient);
945
- const backend = new BackendImpl(config.apiURL);
1637
+ const backend = await PseudoBackend.New(config.backend, suiClient);
946
1638
  return new _MSafeGlobals({
947
1639
  backend,
948
1640
  suiClient,
@@ -976,6 +1668,11 @@ var MSafeClient = class _MSafeClient {
976
1668
  }
977
1669
  async connectWallet(input) {
978
1670
  this.globals.wallet = input.wallet;
1671
+ const isValidJWT = input.jwtToken && await this.backend.isJWTTokenValid(input.jwtToken);
1672
+ if (isValidJWT) {
1673
+ this.backend.setJWTToken(input.jwtToken);
1674
+ return input.jwtToken;
1675
+ }
979
1676
  const messageStr = MessageHelper.welcomeMessage((/* @__PURE__ */ new Date()).toUTCString());
980
1677
  const sig = await input.wallet.signPersonalMessage({
981
1678
  messageStr
@@ -1033,21 +1730,28 @@ export {
1033
1730
  Coin,
1034
1731
  CoinHelper,
1035
1732
  CreateHelper,
1036
- DEV_API_URL,
1037
1733
  DEV_DATABASE_CONFIG,
1038
1734
  ENV_CONFIGS,
1039
1735
  Formatter,
1040
1736
  HexToUint8Array,
1041
1737
  IntentionHelper,
1042
- LOCAL_API_URL,
1043
1738
  LOCAL_DATABASE_CONFIG,
1044
1739
  MAINNET_RPC_URL,
1740
+ MAX_OWNER_WITHOUT_NONCE,
1741
+ MAX_OWNER_WITH_NONCE,
1742
+ MAX_WEIGHT,
1743
+ MIN_THRESHOLD,
1744
+ MIN_WEIGHT,
1045
1745
  MSafeAccount,
1046
1746
  MSafeClient,
1047
1747
  MSafeEnv,
1048
1748
  MSafeGlobals,
1049
1749
  MessageHelper,
1750
+ NONCE_PK_PREFIX,
1751
+ NONCE_PK_WEIGHT,
1752
+ NONCE_PREFIX_MAX_SIZE,
1050
1753
  PublicKeySerde,
1754
+ RawMultiSig,
1051
1755
  SUI_COIN,
1052
1756
  SignatureVerifier,
1053
1757
  TESTNET_RPC_URL,
@@ -1055,7 +1759,10 @@ export {
1055
1759
  Uint8ArrayToHex,
1056
1760
  getAllCoins,
1057
1761
  getMSafeConfig,
1762
+ getMultiSigPublicKey,
1058
1763
  getPublicKeyFromChain,
1059
- stringToBuffer
1764
+ makeNoncePublicKey,
1765
+ stringToBuffer,
1766
+ validateMultiSigConfig
1060
1767
  };
1061
1768
  //# sourceMappingURL=index.js.map