@msafe/sui3-sdk 0.0.11 → 0.0.12-pre-84adfec.0

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
@@ -480,11 +480,12 @@ var MessageHelper = class {
480
480
  return matches ? matches[1] : void 0;
481
481
  }
482
482
  static proposeIntentionMessage(data) {
483
- const { intention, sn } = data;
483
+ const { msafeAddress, intention, sn } = data;
484
484
  const intentionData = IntentionHelper.ser(intention);
485
485
  const msg = {
486
486
  intentionData,
487
- sequenceNumber: sn
487
+ sequenceNumber: sn,
488
+ msafeAddress
488
489
  };
489
490
  return JSON.stringify(msg);
490
491
  }
@@ -493,8 +494,9 @@ var MessageHelper = class {
493
494
  if (!("intentionData" in de) || typeof de.intentionData !== "string" || !("sequenceNumber" in de) || typeof de.sequenceNumber !== "number") {
494
495
  throw new Error("Invalid intention data");
495
496
  }
496
- const { sequenceNumber, intentionData } = de;
497
+ const { msafeAddress, sequenceNumber, intentionData } = de;
497
498
  return {
499
+ msafeAddress,
498
500
  sn: sequenceNumber,
499
501
  intention: IntentionHelper.de(intentionData)
500
502
  };
@@ -534,749 +536,376 @@ var AddressBookSDK = class {
534
536
  };
535
537
 
536
538
  // src/core/MSafeAccount.ts
537
- import { MultisigAccountManager as MultisigAccountManager2 } from "@msafe/sui3-utils";
539
+ import {
540
+ buildIntentionTransaction,
541
+ getIntentionType,
542
+ MultisigAccountManager as MultisigAccountManager2
543
+ } from "@msafe/sui3-utils";
538
544
  import { normalizeStructTag as normalizeStructTag3 } from "@mysten/sui.js/utils";
539
545
 
540
- // src/utils/iter/iterator.ts
541
- var REQUEST_PAGE_SIZE = 25;
542
- async function getAllFromIterator(it) {
543
- const res = [];
544
- while (await it.hasNext()) {
545
- const val = await it.next();
546
- res.push(val);
546
+ // src/globals/const.ts
547
+ var MSafeEnv = /* @__PURE__ */ ((MSafeEnv3) => {
548
+ MSafeEnv3["local"] = "local";
549
+ MSafeEnv3["unit"] = "unit";
550
+ MSafeEnv3["dev"] = "dev";
551
+ MSafeEnv3["prev"] = "prev";
552
+ MSafeEnv3["prod"] = "prod";
553
+ return MSafeEnv3;
554
+ })(MSafeEnv || {});
555
+ var UNIT_DATABASE_CONFIG = {
556
+ type: "sqlite",
557
+ database: ":memory:",
558
+ logging: false
559
+ };
560
+ var LOCAL_DATABASE_CONFIG = {
561
+ type: "mysql",
562
+ host: "127.0.0.1",
563
+ port: 3306,
564
+ username: "msafe",
565
+ password: "msafe",
566
+ database: "msafe_sui_local",
567
+ logging: false
568
+ };
569
+ var DEV_DATABASE_CONFIG = {
570
+ type: "mysql",
571
+ host: "msafe-dev-database.cluster-caos3ssocrx6.us-west-1.rds.amazonaws.com",
572
+ port: 3306,
573
+ username: "msafe",
574
+ password: "Momentum.Safe2022",
575
+ database: "msafe_sui_dev",
576
+ logging: false
577
+ };
578
+ var MSAFE_APPLICATION = "msafe";
579
+ var TESTNET_RPC_URL = "https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD";
580
+ var MAINNET_RPC_URL = "https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7";
581
+ var LOCAL_API_URL = "http://127.0.0.1:3000";
582
+ var LOCAL_SYNCING_URL = "http://127.0.0.1:3001";
583
+ var DEV_API_URL = "http://13.56.226.148";
584
+ var DEV_SYNCING_URL = "http://52.53.228.20";
585
+ var ENV_CONFIGS = /* @__PURE__ */ new Map([
586
+ [
587
+ "unit" /* unit */,
588
+ {
589
+ suiClient: {
590
+ url: TESTNET_RPC_URL
591
+ },
592
+ backend: LOCAL_DATABASE_CONFIG,
593
+ apiURL: LOCAL_API_URL,
594
+ syncingURL: LOCAL_SYNCING_URL
595
+ }
596
+ ],
597
+ [
598
+ "local" /* local */,
599
+ {
600
+ suiClient: {
601
+ url: TESTNET_RPC_URL
602
+ },
603
+ backend: LOCAL_DATABASE_CONFIG,
604
+ apiURL: LOCAL_API_URL,
605
+ syncingURL: LOCAL_SYNCING_URL
606
+ }
607
+ ],
608
+ [
609
+ "dev" /* dev */,
610
+ {
611
+ suiClient: {
612
+ url: TESTNET_RPC_URL
613
+ },
614
+ backend: DEV_DATABASE_CONFIG,
615
+ apiURL: DEV_API_URL,
616
+ syncingURL: DEV_SYNCING_URL
617
+ }
618
+ ]
619
+ ]);
620
+ function getMSafeConfig(env, options) {
621
+ const config = ENV_CONFIGS.get(env);
622
+ if (!config) {
623
+ throw new Error("Unknown environment");
547
624
  }
548
- if (res && Array.isArray(res[0])) {
549
- return res.flat(1);
625
+ if (options?.suiClient?.url) {
626
+ config.suiClient.url = options.suiClient.url;
550
627
  }
551
- return res;
628
+ if (options?.backend) {
629
+ config.backend = options.backend;
630
+ }
631
+ return config;
552
632
  }
553
- var PagedIterator = class {
554
- constructor(requester) {
555
- this.requester = requester;
556
- this.curPage = void 0;
557
- this.init = true;
633
+ var AUTH_SIGN_MESSAGE = "Welcome to MSafe";
634
+
635
+ // src/globals/MSafeGlobals.ts
636
+ import { SuiClient } from "@mysten/sui.js/client";
637
+
638
+ // src/backend/BackendImpl.ts
639
+ import axios from "axios";
640
+ var BackendImpl = class {
641
+ constructor(apiURL) {
642
+ this.apiURL = apiURL;
558
643
  }
559
- curPage;
560
- init;
561
- async hasNext() {
562
- if (this.init) {
563
- if (!this.curPage) {
564
- this.curPage = await this.requester.doNextRequest();
565
- }
566
- return !!this.curPage.data?.length || this.curPage.hasNext;
567
- }
568
- if (!this.curPage) {
569
- throw new Error("invalid implementation of iterator");
644
+ _token;
645
+ async authSign(input) {
646
+ const res = await axios.post(`${this.apiURL}/auth/login`, input);
647
+ if (res.status !== 200 && res.status !== 201) {
648
+ throw new Error(`invalid authSign return: ${res}`);
570
649
  }
571
- return this.curPage.hasNext;
650
+ this._token = res.data.accessToken;
651
+ return this._token;
572
652
  }
573
- async next() {
574
- if (this.init) {
575
- this.init = false;
576
- if (!this.curPage) {
577
- this.curPage = await this.requester.doNextRequest();
578
- }
579
- return this.curPage.data;
653
+ async verifyToken(jwt) {
654
+ try {
655
+ const res = await axios.get(`${this.apiURL}/auth`, { headers: this.headers(jwt) });
656
+ return res.status === 200;
657
+ } catch (_) {
658
+ return false;
580
659
  }
581
- this.curPage = await this.requester.doNextRequest();
582
- return this.curPage.data;
583
660
  }
584
- };
585
- var EntryIterator = class {
586
- constructor(requester) {
587
- this.requester = requester;
588
- this.pager = new PagedIterator(requester);
589
- this.curData = [];
590
- this.cursor = 0;
661
+ setJWTToken(token) {
662
+ this._token = token;
591
663
  }
592
- cursor;
593
- pager;
594
- curData;
595
- async hasNext() {
596
- if (this.cursor < this.curData.length - 1) {
597
- return true;
598
- }
599
- return this.pager.hasNext();
664
+ async getPublicKey(address) {
665
+ return (await this.getPublicKeyBatch([address]))[0];
600
666
  }
601
- async next() {
602
- this.cursor += 1;
603
- while (this.cursor >= this.curData.length) {
604
- if (!await this.pager.hasNext()) {
605
- throw new Error("not more data");
606
- } else {
607
- this.curData = await this.pager.next();
608
- this.cursor = 0;
667
+ async getPublicKeyBatch(addresses) {
668
+ const res = await axios.post(
669
+ `${this.apiURL}/account/getPublicKeyBatch`,
670
+ addresses,
671
+ {
672
+ headers: this.headers()
609
673
  }
674
+ );
675
+ if (res.status !== 200 && res.status !== 201) {
676
+ throw new Error(`invalid getPublicKeyBatch return: ${res}`);
610
677
  }
611
- return this.curData[this.cursor];
612
- }
613
- };
614
-
615
- // src/utils/iter/object.ts
616
- async function getAllOwnedObjects(provider, owner, options) {
617
- const iter = new OwnedObjectIterator(provider, owner, options);
618
- return await getAllFromIterator(iter);
619
- }
620
- var OwnedObjectIterator = class extends EntryIterator {
621
- constructor(provider, owner, options) {
622
- super(new OwnedObjectRequester(provider, owner, options));
623
- this.provider = provider;
624
- this.owner = owner;
625
- this.options = options;
678
+ return res.data?.map(
679
+ (publicKeyWithSchema) => publicKeyWithSchema ? PublicKeySerde.de({ ...publicKeyWithSchema }) : void 0
680
+ );
626
681
  }
627
- };
628
- var OwnedObjectRequester = class {
629
- constructor(provider, owner, options) {
630
- this.provider = provider;
631
- this.owner = owner;
632
- this.options = options;
633
- this.nextCursor = null;
634
- this.filter = options?.filter;
635
- this.pageSize = options?.pageSize || REQUEST_PAGE_SIZE;
636
- this.objectOptions = options?.objectOptions || {
637
- showType: true,
638
- showContent: true
682
+ async getMSafeAccountInfo(msafeAddress) {
683
+ const res = await axios.get(
684
+ `${this.apiURL}/account/getMSafeAccountInfo/${msafeAddress}`,
685
+ {
686
+ headers: this.headers()
687
+ }
688
+ );
689
+ if (res.status !== 200 && res.status !== 201) {
690
+ throw new Error(`invalid getPublicKeyBatch return: ${res}`);
691
+ }
692
+ const msafeResp = res.data;
693
+ return {
694
+ address: msafeResp.address,
695
+ ownersWithWeightPK: msafeResp.ownersWithWeightPKEncoded.map(
696
+ (owner) => ({
697
+ publicKey: PublicKeySerde.de({ publicKey: owner.publicKeyEncoded, scheme: owner.schema }),
698
+ address: owner.address,
699
+ weight: owner.weight
700
+ })
701
+ ),
702
+ threshold: msafeResp.threshold,
703
+ name: msafeResp.name,
704
+ description: msafeResp.description,
705
+ creationNonce: msafeResp.creationNonce
639
706
  };
640
707
  }
641
- nextCursor;
642
- filter;
643
- pageSize;
644
- objectOptions;
645
- async doNextRequest() {
646
- const res = await this.provider.getOwnedObjects({
647
- owner: this.owner,
648
- options: this.objectOptions,
649
- cursor: this.nextCursor,
650
- limit: this.pageSize
708
+ async getUserInfo(userAddress) {
709
+ const res = await axios.get(`${this.apiURL}/account/user/${userAddress}`, {
710
+ headers: this.headers()
651
711
  });
652
- this.nextCursor = res.nextCursor;
653
- let filtered;
654
- if (this.filter) {
655
- const { filter } = this;
656
- filtered = res.data.filter((obj) => filter?.(obj));
657
- } else {
658
- filtered = res.data;
712
+ if (res.status !== 200 && res.status !== 201) {
713
+ throw new Error(`invalid getPublicKeyBatch return: ${res}`);
659
714
  }
660
715
  return {
661
- data: filtered.map((r) => r.data).filter((data) => data),
662
- hasNext: res.hasNextPage
716
+ address: res.data.address,
717
+ publicKey: res.data.publicKey,
718
+ schema: res.data.schema,
719
+ creationNonce: res.data.creationNonce,
720
+ ownedMSafe: res.data.ownedMSafe.map(
721
+ (msafe) => ({
722
+ address: msafe.address,
723
+ ownersWithWeightPK: msafe.ownersWithWeightPKEncoded.map(
724
+ (owner) => ({
725
+ publicKey: PublicKeySerde.de({ publicKey: owner.publicKeyEncoded, scheme: owner.schema }),
726
+ address: owner.address,
727
+ weight: owner.weight
728
+ })
729
+ ),
730
+ threshold: msafe.threshold,
731
+ name: msafe.name,
732
+ description: msafe.description,
733
+ creationNonce: msafe.creationNonce
734
+ })
735
+ )
663
736
  };
664
737
  }
665
- };
666
-
667
- // src/core/MSafeAccount.ts
668
- var MSafeAccount = class {
669
- constructor(globals, info) {
670
- this.globals = globals;
671
- this.info = info;
672
- this.multisigManager = new MultisigAccountManager2({
673
- threshold: info.threshold,
674
- ownersWithWeight: info.ownersWithWeightPK,
675
- creationNonce: info.creationNonce
738
+ async getPendingTransactions(msafeAddress) {
739
+ const res = await axios.get(`${this.apiURL}/transaction/pending/${msafeAddress}`, {
740
+ headers: this.headers()
676
741
  });
677
- this.coinHelper = new CoinHelper(this.suiClient);
678
- }
679
- multisigManager;
680
- coinHelper;
681
- static async new(globals, address) {
682
- return globals.backend.getMSafeAccountInfo(address);
742
+ if (res.status !== 200 && res.status !== 201) {
743
+ throw new Error(`invalid getPublicKeyBatch return: ${res}`);
744
+ }
745
+ return res.data;
683
746
  }
684
- async ownedCoins() {
685
- const balances = await this.suiClient.getAllBalances({ owner: this.address });
686
- return Promise.all(
687
- balances.map(async (balance) => {
688
- const meta = await this.coinHelper.getCoinMeta(balance.coinType);
689
- const unlockedBalance = balance.lockedBalance.number ? BigInt(balance.totalBalance) - BigInt(balance.lockedBalance.number) : BigInt(balance.totalBalance);
690
- return {
691
- type: normalizeStructTag3(balance.coinType),
692
- balance: BigInt(unlockedBalance),
693
- metadata: meta
694
- };
695
- })
747
+ async getHistoryTransactions(msafeAddress, paginationOption) {
748
+ const res = await axios.get(
749
+ `${this.apiURL}/transaction/history?address=${msafeAddress}`,
750
+ {
751
+ params: {
752
+ page: paginationOption?.page,
753
+ limit: paginationOption?.limit
754
+ },
755
+ headers: this.headers()
756
+ }
696
757
  );
697
- }
698
- async ownedObjects(options) {
699
- return getAllOwnedObjects(this.suiClient, this.address, options);
700
- }
701
- async pendingTransactions() {
702
- return this.backend.getPendingTransactions(this.address);
703
- }
704
- async pendingTransaction() {
705
- const pendings = await this.backend.getPendingTransactions(this.address);
706
- if (pendings.length > 2) {
707
- throw new Error(`invalid backend getPendingTransactions resp, length should not > 2: ${pendings}`);
708
- }
709
- if (pendings.length === 0) {
710
- return void 0;
711
- }
712
- if (pendings.length === 1) {
713
- return pendings[0];
758
+ if (res.status !== 200 && res.status !== 201) {
759
+ throw new Error(`invalid getCurrentSequenceNumber return: ${res}`);
714
760
  }
715
- const [rejectPending, pendingTx] = pendings[0].isRejectTx ? [pendings[0], pendings[1]] : [pendings[1], pendings[0]];
716
- pendingTx.rejectDigest = rejectPending.digest;
717
- pendingTx.rejectPayload = rejectPending.payload;
718
- pendingTx.rejectVotes = rejectPending.votes;
719
- return pendingTx;
720
- }
721
- async historyTransaction(paginationOption) {
722
- const paginatedHistoryTransactions = await this.backend.getHistoryTransactions(this.address, paginationOption);
723
- return paginatedHistoryTransactions.data;
724
- }
725
- async futureIntentions(paginationOption) {
726
- const paginatedIntentions = await this.backend.getFutureIntentions(this.address, paginationOption);
727
- return paginatedIntentions.data;
728
- }
729
- async currentSequenceNumber() {
730
- return this.backend.getCurrentSequenceNumber(this.address);
731
- }
732
- async nextSequenceNumber() {
733
- return this.backend.getNextSequenceNumber(this.address);
761
+ return res.data;
734
762
  }
735
- async proposeIntention(intention, sequenceNumber) {
736
- const message = MessageHelper.proposeIntentionMessage({ intention, sn: sequenceNumber });
737
- const signature = await this.wallet.signPersonalMessage({
738
- messageStr: message
739
- });
740
- await this.backend.proposeIntention({
741
- intention,
742
- sequenceNumber,
743
- msafeAddress: this.address,
744
- userAddress: await this.userAddress(),
745
- signature: signature.signature
763
+ async getFutureIntentions(msafeAddress, paginationOption) {
764
+ const res = await axios.get(`${this.apiURL}/transaction/intention/${msafeAddress}`, {
765
+ params: {
766
+ page: paginationOption?.page,
767
+ limit: paginationOption?.limit
768
+ },
769
+ headers: this.headers()
746
770
  });
771
+ if (res.status !== 200 && res.status !== 201) {
772
+ throw new Error(`invalid getCurrentSequenceNumber return: ${res}`);
773
+ }
774
+ return res.data;
747
775
  }
748
- async voteForTransaction(digest, payload) {
749
- const payloadBytes = HexToUint8Array(payload);
750
- const signature = await this.wallet.signTransactionBlock({ transactionBlock: payloadBytes });
751
- return this.backend.voteForTransaction({
752
- msafeAddress: this.address,
753
- userAddress: await this.userAddress(),
754
- txDigest: digest,
755
- signature: signature.signature
776
+ async getCurrentSequenceNumber(msafeAddress) {
777
+ const res = await axios.get(`${this.apiURL}/transaction/sn/current/${msafeAddress}`, {
778
+ headers: this.headers()
756
779
  });
780
+ if (res.status !== 200 && res.status !== 201) {
781
+ throw new Error(`invalid getCurrentSequenceNumber return: ${res}`);
782
+ }
783
+ return res.data;
757
784
  }
758
- // Shortcut for proposing a transaction to be a pending transaction, and add user vote to it.
759
- // Requires the multi-sig to be empty in pending transaction.
760
- async proposePendingTransaction(intention) {
761
- const txb = await IntentionHelper.buildTxb({
762
- suiClient: this.suiClient,
763
- intention,
764
- sender: this.address
785
+ async getNextSequenceNumber(msafeAddress) {
786
+ const res = await axios.get(`${this.apiURL}/transaction/sn/next/${msafeAddress}`, {
787
+ headers: this.headers()
765
788
  });
766
- const payload = await txb.build({ client: this.suiClient });
767
- const digest = await txb.getDigest({ client: this.suiClient });
768
- const signature = await this.wallet.signTransactionBlock({ transactionBlock: payload });
769
- return this.backend.proposePendingTransaction({
770
- msafeAddress: this.address,
771
- userAddress: await this.userAddress(),
772
- intention,
773
- digest,
774
- signature: signature.signature
789
+ if (res.status !== 200 && res.status !== 201) {
790
+ throw new Error(`invalid getNextSequenceNumber return: ${res}`);
791
+ }
792
+ return res.data;
793
+ }
794
+ async createMSafeAccount(input) {
795
+ const res = await axios.post(`${this.apiURL}/account`, input, {
796
+ headers: this.headers()
775
797
  });
798
+ if (res.status !== 200 && res.status !== 201) {
799
+ throw new Error(`invalid createMSafeAccount return: ${res}`);
800
+ }
776
801
  }
777
- async rejectCurrentTx(pending) {
778
- let payloadToReject;
779
- if (pending) {
780
- if (pending.isRejectTx) {
781
- throw new Error("Pending not reject transaction");
782
- }
783
- payloadToReject = pending.payload;
784
- } else {
785
- const pendingTx = await this.pendingTransaction();
786
- if (!pendingTx || pendingTx?.rejectDigest !== void 0) {
787
- throw new Error("Already rejected");
802
+ async proposeIntention(input) {
803
+ try {
804
+ const res = await axios.post(
805
+ `${this.apiURL}/transaction/intention`,
806
+ {
807
+ intention: input.intention,
808
+ sequenceNumber: input.sequenceNumber,
809
+ address: input.msafeAddress,
810
+ signature: input.signature,
811
+ application: input.application,
812
+ txType: input.txType,
813
+ txSubType: input.txSubType
814
+ },
815
+ { headers: this.headers() }
816
+ );
817
+ if (res.status !== 200 && res.status !== 201) {
818
+ throw new Error(`invalid proposeIntention return: ${res}`);
788
819
  }
789
- payloadToReject = pendingTx.payload;
820
+ } catch (e) {
821
+ console.log(e);
790
822
  }
791
- const rejectTxb = await IntentionHelper.buildRejectTransaction({
792
- msafeAddress: this.address,
793
- payloadToReject
794
- });
795
- const digest = await rejectTxb.getDigest({ client: this.suiClient });
796
- const payload = await rejectTxb.build({ client: this.suiClient });
797
- const signature = await this.wallet.signTransactionBlock({ transactionBlock: payload });
798
- return this.backend.rejectCurrentTx({
799
- msafeAddress: this.address,
800
- userAddress: await this.userAddress(),
801
- digest,
802
- signature: signature.signature
803
- });
804
823
  }
805
- async buildNextIntentionAndAddToPending() {
806
- return this.backend.buildNextIntentionAndAddToPending({ msafeAddress: this.address });
807
- }
808
- async skipNextFailedIntention() {
809
- return this.backend.skipNextFailedIntention({ msafeAddress: this.address, userAddress: await this.userAddress() });
824
+ // TODO later
825
+ async proposePendingTransaction(input) {
810
826
  }
811
- async executePendingTx(pending) {
812
- let gotSigs;
813
- let payload;
814
- if (pending.votes.length >= this.info.threshold) {
815
- gotSigs = new Map(pending.votes.map((vote) => [vote.userAddress, vote.signature]));
816
- payload = pending.payload;
817
- } else if (pending.rejectVotes && pending.rejectPayload && pending.rejectVotes?.length >= this.info.threshold) {
818
- gotSigs = new Map(pending.rejectVotes.map((vote) => [vote.userAddress, vote.signature]));
819
- payload = pending.rejectPayload;
820
- } else {
821
- throw new Error("Not enough signatures");
822
- }
823
- const sigs = [];
824
- for (let i = 0; i < this.info.ownersWithWeightPK.length; i++) {
825
- const owner = this.info.ownersWithWeightPK[i];
826
- const signature = gotSigs.get(owner.publicKey.toSuiAddress());
827
- if (signature) {
828
- sigs.push(signature);
827
+ async rejectCurrentTx(input) {
828
+ try {
829
+ const res = await axios.post(
830
+ `${this.apiURL}/transaction/pending/reject`,
831
+ {
832
+ address: input.msafeAddress,
833
+ digest: input.digest,
834
+ signature: input.signature
835
+ },
836
+ {
837
+ headers: this.headers()
838
+ }
839
+ );
840
+ if (res.status !== 200 && res.status !== 201) {
841
+ throw new Error(`invalid voteForTransaction return: ${res}`);
829
842
  }
843
+ } catch (e) {
844
+ console.log("e:", e);
830
845
  }
831
- const multiSignature = this.multisigManager.combinePartialSignatures(sigs);
832
- return this.suiClient.executeTransactionBlock({
833
- transactionBlock: HexToUint8Array(payload),
834
- signature: multiSignature,
835
- options: { showEffects: true }
836
- });
837
846
  }
838
- get address() {
839
- return this.info.address;
840
- }
841
- get backend() {
842
- return this.globals.backend;
843
- }
844
- get wallet() {
845
- return this.globals.wallet;
846
- }
847
- async userAddress() {
848
- return this.globals.wallet.address();
849
- }
850
- get suiClient() {
851
- return this.globals.suiClient;
852
- }
853
- };
854
-
855
- // src/core/PublicKeyHelper.ts
856
- var PublicKeyHelper = class {
857
- constructor(globals) {
858
- this.globals = globals;
859
- this.knownPublicKeys = /* @__PURE__ */ new Map();
860
- }
861
- knownPublicKeys;
862
- async getPublicKey(address) {
863
- const cached = this.knownPublicKeys.get(address);
864
- if (cached) {
865
- return cached;
866
- }
867
- const pk = await this._getPublicKey(address);
868
- if (pk) {
869
- this.knownPublicKeys.set(address, pk);
870
- }
871
- return pk;
872
- }
873
- async getPublicKeyBatch(addresses) {
874
- const results = new Array(addresses.length).fill(void 0);
875
- for (let i = 0; i < addresses.length; i++) {
876
- const address = addresses[i];
877
- results[i] = this.knownPublicKeys.get(address);
878
- }
879
- const emptyIndexes = results.map((elem, index) => elem === void 0 ? index : -1).filter((index) => index !== -1);
880
- const backendResult = await this.globals.backend.getPublicKeyBatch(emptyIndexes.map((index) => addresses[index]));
881
- for (let i = 0; i < emptyIndexes.length; i++) {
882
- const index = emptyIndexes[i];
883
- results[index] = backendResult[i];
884
- }
885
- for (let i = 0; i < results.length; i++) {
886
- if (results[i] === void 0) {
887
- results[i] = await this.getPublicKeyFromChain(addresses[i]);
888
- }
889
- }
890
- for (let i = 0; i < addresses.length; i++) {
891
- if (results[i]) {
892
- this.knownPublicKeys.set(addresses[i], results[i]);
893
- }
894
- }
895
- return results;
896
- }
897
- async _getPublicKey(address) {
898
- const pkBackend = await this.getPublicKeyFromBackend(address);
899
- if (pkBackend) {
900
- return pkBackend;
901
- }
902
- const pkChain = await this.getPublicKeyFromChain(address);
903
- if (pkChain) {
904
- return pkChain;
905
- }
906
- return void 0;
907
- }
908
- async getPublicKeyFromBackend(address) {
909
- try {
910
- const pk = await this.globals.backend.getPublicKey(address);
911
- return pk;
912
- } catch (_) {
913
- return void 0;
914
- }
915
- }
916
- async getPublicKeyFromChain(address) {
917
- return getPublicKeyFromChain(this.globals.suiClient, address);
918
- }
919
- };
920
-
921
- // src/globals/MSafeGlobals.ts
922
- import { SuiClient } from "@mysten/sui.js/client";
923
-
924
- // src/backend/BackendImpl.ts
925
- import axios from "axios";
926
- var BackendImpl = class {
927
- constructor(apiURL) {
928
- this.apiURL = apiURL;
929
- }
930
- _token;
931
- async authSign(input) {
932
- const res = await axios.post(`${this.apiURL}/auth/login`, input);
933
- if (res.status !== 200 && res.status !== 201) {
934
- throw new Error(`invalid authSign return: ${res}`);
935
- }
936
- this._token = res.data.accessToken;
937
- return this._token;
938
- }
939
- async verifyToken(jwt) {
940
- try {
941
- const res = await axios.get(`${this.apiURL}/auth`, { headers: this.headers(jwt) });
942
- return res.status === 200;
943
- } catch (_) {
944
- return false;
945
- }
946
- }
947
- setJWTToken(token) {
948
- this._token = token;
949
- }
950
- async getPublicKey(address) {
951
- return (await this.getPublicKeyBatch([address]))[0];
952
- }
953
- async getPublicKeyBatch(addresses) {
847
+ async voteForTransaction(input) {
954
848
  const res = await axios.post(
955
- `${this.apiURL}/account/getPublicKeyBatch`,
956
- addresses,
849
+ `${this.apiURL}/transaction/pending/vote`,
850
+ {
851
+ address: input.msafeAddress,
852
+ digest: input.txDigest,
853
+ signature: input.signature
854
+ },
957
855
  {
958
856
  headers: this.headers()
959
857
  }
960
858
  );
961
859
  if (res.status !== 200 && res.status !== 201) {
962
- throw new Error(`invalid getPublicKeyBatch return: ${res}`);
860
+ throw new Error(`invalid voteForTransaction return: ${res}`);
963
861
  }
964
- return res.data?.map(
965
- (publicKeyWithSchema) => publicKeyWithSchema ? PublicKeySerde.de({ ...publicKeyWithSchema }) : void 0
966
- );
967
862
  }
968
- async getMSafeAccountInfo(msafeAddress) {
969
- const res = await axios.get(
970
- `${this.apiURL}/account/getMSafeAccountInfo/${msafeAddress}`,
863
+ async buildNextIntentionAndAddToPending(input) {
864
+ const res = await axios.post(
865
+ `${this.apiURL}/transaction/pending/build`,
971
866
  {
972
- headers: this.headers()
973
- }
867
+ address: input.msafeAddress
868
+ },
869
+ { headers: this.headers() }
974
870
  );
975
871
  if (res.status !== 200 && res.status !== 201) {
976
- throw new Error(`invalid getPublicKeyBatch return: ${res}`);
977
- }
978
- const msafeResp = res.data;
979
- return {
980
- address: msafeResp.address,
981
- ownersWithWeightPK: msafeResp.ownersWithWeightPKEncoded.map(
982
- (owner) => ({
983
- publicKey: PublicKeySerde.de({ publicKey: owner.publicKeyEncoded, scheme: owner.schema }),
984
- address: owner.address,
985
- weight: owner.weight
986
- })
987
- ),
988
- threshold: msafeResp.threshold,
989
- name: msafeResp.name,
990
- description: msafeResp.description,
991
- creationNonce: msafeResp.creationNonce
992
- };
993
- }
994
- async getUserInfo(userAddress) {
995
- const res = await axios.get(`${this.apiURL}/account/user/${userAddress}`, {
996
- headers: this.headers()
997
- });
998
- if (res.status !== 200 && res.status !== 201) {
999
- throw new Error(`invalid getPublicKeyBatch return: ${res}`);
1000
- }
1001
- return {
1002
- address: res.data.address,
1003
- publicKey: res.data.publicKey,
1004
- schema: res.data.schema,
1005
- creationNonce: res.data.creationNonce,
1006
- ownedMSafe: res.data.ownedMSafe.map(
1007
- (msafe) => ({
1008
- address: msafe.address,
1009
- ownersWithWeightPK: msafe.ownersWithWeightPKEncoded.map(
1010
- (owner) => ({
1011
- publicKey: PublicKeySerde.de({ publicKey: owner.publicKeyEncoded, scheme: owner.schema }),
1012
- address: owner.address,
1013
- weight: owner.weight
1014
- })
1015
- ),
1016
- threshold: msafe.threshold,
1017
- name: msafe.name,
1018
- description: msafe.description,
1019
- creationNonce: msafe.creationNonce
1020
- })
1021
- )
1022
- };
1023
- }
1024
- async getPendingTransactions(msafeAddress) {
1025
- const res = await axios.get(`${this.apiURL}/transaction/pending/${msafeAddress}`, {
1026
- headers: this.headers()
1027
- });
1028
- if (res.status !== 200 && res.status !== 201) {
1029
- throw new Error(`invalid getPublicKeyBatch return: ${res}`);
872
+ throw new Error(`invalid buildNextIntentionAndAddToPending return: ${res}`);
1030
873
  }
1031
- return res.data;
1032
874
  }
1033
- async getHistoryTransactions(msafeAddress, paginationOption) {
1034
- const res = await axios.get(
1035
- `${this.apiURL}/transaction/history?address=${msafeAddress}`,
875
+ async skipNextFailedIntention(input) {
876
+ const res = await axios.post(
877
+ `${this.apiURL}/transaction/pending/skip`,
1036
878
  {
1037
- params: {
1038
- page: paginationOption?.page,
1039
- limit: paginationOption?.limit
1040
- },
1041
- headers: this.headers()
1042
- }
879
+ msafeAddress: input.msafeAddress
880
+ },
881
+ { headers: this.headers() }
1043
882
  );
1044
883
  if (res.status !== 200 && res.status !== 201) {
1045
- throw new Error(`invalid getCurrentSequenceNumber return: ${res}`);
884
+ throw new Error(`invalid skipNextFailedIntention return: ${res}`);
1046
885
  }
1047
- return res.data;
1048
886
  }
1049
- async getFutureIntentions(msafeAddress, paginationOption) {
1050
- const res = await axios.get(`${this.apiURL}/transaction/intention/${msafeAddress}`, {
1051
- params: {
1052
- page: paginationOption?.page,
1053
- limit: paginationOption?.limit
1054
- },
1055
- headers: this.headers()
887
+ async getAddressBookEntries(pagination) {
888
+ const res = await axios.get(`${this.apiURL}/address-book`, {
889
+ headers: this.headers(),
890
+ params: pagination
1056
891
  });
1057
- if (res.status !== 200 && res.status !== 201) {
1058
- throw new Error(`invalid getCurrentSequenceNumber return: ${res}`);
892
+ if (res.status !== 200) {
893
+ throw new Error(`Invalid address-book return: ${res}`);
1059
894
  }
1060
895
  return res.data;
1061
896
  }
1062
- async getCurrentSequenceNumber(msafeAddress) {
1063
- const res = await axios.get(`${this.apiURL}/transaction/sn/current/${msafeAddress}`, {
1064
- headers: this.headers()
1065
- });
897
+ async updateAddressBook(input) {
898
+ const res = await axios.post(`${this.apiURL}/address-book`, input, { headers: this.headers() });
1066
899
  if (res.status !== 200 && res.status !== 201) {
1067
- throw new Error(`invalid getCurrentSequenceNumber return: ${res}`);
900
+ throw new Error(`invalid updateAddressBook return: ${res}`);
1068
901
  }
1069
- return res.data;
1070
902
  }
1071
- async getNextSequenceNumber(msafeAddress) {
1072
- const res = await axios.get(`${this.apiURL}/transaction/sn/next/${msafeAddress}`, {
1073
- headers: this.headers()
1074
- });
1075
- if (res.status !== 200 && res.status !== 201) {
1076
- throw new Error(`invalid getNextSequenceNumber return: ${res}`);
1077
- }
1078
- return res.data;
903
+ async processExecutedTransaction(digest) {
1079
904
  }
1080
- async createMSafeAccount(input) {
1081
- const res = await axios.post(`${this.apiURL}/account`, input, {
1082
- headers: this.headers()
1083
- });
1084
- if (res.status !== 200 && res.status !== 201) {
1085
- throw new Error(`invalid createMSafeAccount return: ${res}`);
1086
- }
905
+ headers(token) {
906
+ return { Authorization: `Bearer ${token || this._token}` };
1087
907
  }
1088
- async proposeIntention(input) {
1089
- try {
1090
- const res = await axios.post(
1091
- `${this.apiURL}/transaction/intention`,
1092
- {
1093
- intention: input.intention,
1094
- sequenceNumber: input.sequenceNumber,
1095
- address: input.msafeAddress,
1096
- signature: input.signature
1097
- },
1098
- { headers: this.headers() }
1099
- );
1100
- if (res.status !== 200 && res.status !== 201) {
1101
- throw new Error(`invalid proposeIntention return: ${res}`);
1102
- }
1103
- } catch (e) {
1104
- console.log(e);
1105
- }
1106
- }
1107
- // TODO later
1108
- async proposePendingTransaction(input) {
1109
- }
1110
- async rejectCurrentTx(input) {
1111
- try {
1112
- const res = await axios.post(
1113
- `${this.apiURL}/transaction/pending/reject`,
1114
- {
1115
- address: input.msafeAddress,
1116
- digest: input.digest,
1117
- signature: input.signature
1118
- },
1119
- {
1120
- headers: this.headers()
1121
- }
1122
- );
1123
- if (res.status !== 200 && res.status !== 201) {
1124
- throw new Error(`invalid voteForTransaction return: ${res}`);
1125
- }
1126
- } catch (e) {
1127
- console.log("e:", e);
1128
- }
1129
- }
1130
- async voteForTransaction(input) {
1131
- const res = await axios.post(
1132
- `${this.apiURL}/transaction/pending/vote`,
1133
- {
1134
- address: input.msafeAddress,
1135
- digest: input.txDigest,
1136
- signature: input.signature
1137
- },
1138
- {
1139
- headers: this.headers()
1140
- }
1141
- );
1142
- if (res.status !== 200 && res.status !== 201) {
1143
- throw new Error(`invalid voteForTransaction return: ${res}`);
1144
- }
1145
- }
1146
- async buildNextIntentionAndAddToPending(input) {
1147
- const res = await axios.post(
1148
- `${this.apiURL}/transaction/pending/build`,
1149
- {
1150
- address: input.msafeAddress
1151
- },
1152
- { headers: this.headers() }
1153
- );
1154
- if (res.status !== 200 && res.status !== 201) {
1155
- throw new Error(`invalid buildNextIntentionAndAddToPending return: ${res}`);
1156
- }
1157
- }
1158
- async skipNextFailedIntention(input) {
1159
- const res = await axios.post(
1160
- `${this.apiURL}/transaction/pending/skip`,
1161
- {
1162
- msafeAddress: input.msafeAddress
1163
- },
1164
- { headers: this.headers() }
1165
- );
1166
- if (res.status !== 200 && res.status !== 201) {
1167
- throw new Error(`invalid skipNextFailedIntention return: ${res}`);
1168
- }
1169
- }
1170
- async getAddressBookEntries(pagination) {
1171
- const res = await axios.get(`${this.apiURL}/address-book`, {
1172
- headers: this.headers(),
1173
- params: pagination
1174
- });
1175
- if (res.status !== 200) {
1176
- throw new Error(`Invalid address-book return: ${res}`);
1177
- }
1178
- return res.data;
1179
- }
1180
- async updateAddressBook(input) {
1181
- const res = await axios.post(`${this.apiURL}/address-book`, input, { headers: this.headers() });
1182
- if (res.status !== 200 && res.status !== 201) {
1183
- throw new Error(`invalid updateAddressBook return: ${res}`);
1184
- }
1185
- }
1186
- async processExecutedTransaction(digest) {
1187
- }
1188
- headers(token) {
1189
- return { Authorization: `Bearer ${token || this._token}` };
1190
- }
1191
- };
1192
-
1193
- // src/globals/const.ts
1194
- var MSafeEnv = /* @__PURE__ */ ((MSafeEnv3) => {
1195
- MSafeEnv3["local"] = "local";
1196
- MSafeEnv3["unit"] = "unit";
1197
- MSafeEnv3["dev"] = "dev";
1198
- MSafeEnv3["prev"] = "prev";
1199
- MSafeEnv3["prod"] = "prod";
1200
- return MSafeEnv3;
1201
- })(MSafeEnv || {});
1202
- var UNIT_DATABASE_CONFIG = {
1203
- type: "sqlite",
1204
- database: ":memory:",
1205
- logging: false
1206
- };
1207
- var LOCAL_DATABASE_CONFIG = {
1208
- type: "mysql",
1209
- host: "127.0.0.1",
1210
- port: 3306,
1211
- username: "msafe",
1212
- password: "msafe",
1213
- database: "msafe_sui_local",
1214
- logging: false
1215
- };
1216
- var DEV_DATABASE_CONFIG = {
1217
- type: "mysql",
1218
- host: "msafe-dev-database.cluster-caos3ssocrx6.us-west-1.rds.amazonaws.com",
1219
- port: 3306,
1220
- username: "msafe",
1221
- password: "Momentum.Safe2022",
1222
- database: "msafe_sui_dev",
1223
- logging: false
1224
908
  };
1225
- var TESTNET_RPC_URL = "https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD";
1226
- var MAINNET_RPC_URL = "https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7";
1227
- var LOCAL_API_URL = "http://127.0.0.1:3000";
1228
- var LOCAL_SYNCING_URL = "http://127.0.0.1:3001";
1229
- var DEV_API_URL = "http://13.56.226.148";
1230
- var DEV_SYNCING_URL = "http://52.53.228.20";
1231
- var ENV_CONFIGS = /* @__PURE__ */ new Map([
1232
- [
1233
- "unit" /* unit */,
1234
- {
1235
- suiClient: {
1236
- url: TESTNET_RPC_URL
1237
- },
1238
- backend: LOCAL_DATABASE_CONFIG,
1239
- apiURL: LOCAL_API_URL,
1240
- syncingURL: LOCAL_SYNCING_URL
1241
- }
1242
- ],
1243
- [
1244
- "local" /* local */,
1245
- {
1246
- suiClient: {
1247
- url: TESTNET_RPC_URL
1248
- },
1249
- backend: LOCAL_DATABASE_CONFIG,
1250
- apiURL: LOCAL_API_URL,
1251
- syncingURL: LOCAL_SYNCING_URL
1252
- }
1253
- ],
1254
- [
1255
- "dev" /* dev */,
1256
- {
1257
- suiClient: {
1258
- url: TESTNET_RPC_URL
1259
- },
1260
- backend: DEV_DATABASE_CONFIG,
1261
- apiURL: DEV_API_URL,
1262
- syncingURL: DEV_SYNCING_URL
1263
- }
1264
- ]
1265
- ]);
1266
- function getMSafeConfig(env, options) {
1267
- const config = ENV_CONFIGS.get(env);
1268
- if (!config) {
1269
- throw new Error("Unknown environment");
1270
- }
1271
- if (options?.suiClient?.url) {
1272
- config.suiClient.url = options.suiClient.url;
1273
- }
1274
- if (options?.backend) {
1275
- config.backend = options.backend;
1276
- }
1277
- return config;
1278
- }
1279
- var AUTH_SIGN_MESSAGE = "Welcome to MSafe";
1280
909
 
1281
910
  // src/globals/MSafeGlobals.ts
1282
911
  var MSafeGlobals = class _MSafeGlobals {
@@ -1313,6 +942,415 @@ var MSafeGlobals = class _MSafeGlobals {
1313
942
  }
1314
943
  };
1315
944
 
945
+ // src/utils/iter/iterator.ts
946
+ var REQUEST_PAGE_SIZE = 25;
947
+ async function getAllFromIterator(it) {
948
+ const res = [];
949
+ while (await it.hasNext()) {
950
+ const val = await it.next();
951
+ res.push(val);
952
+ }
953
+ if (res && Array.isArray(res[0])) {
954
+ return res.flat(1);
955
+ }
956
+ return res;
957
+ }
958
+ var PagedIterator = class {
959
+ constructor(requester) {
960
+ this.requester = requester;
961
+ this.curPage = void 0;
962
+ this.init = true;
963
+ }
964
+ curPage;
965
+ init;
966
+ async hasNext() {
967
+ if (this.init) {
968
+ if (!this.curPage) {
969
+ this.curPage = await this.requester.doNextRequest();
970
+ }
971
+ return !!this.curPage.data?.length || this.curPage.hasNext;
972
+ }
973
+ if (!this.curPage) {
974
+ throw new Error("invalid implementation of iterator");
975
+ }
976
+ return this.curPage.hasNext;
977
+ }
978
+ async next() {
979
+ if (this.init) {
980
+ this.init = false;
981
+ if (!this.curPage) {
982
+ this.curPage = await this.requester.doNextRequest();
983
+ }
984
+ return this.curPage.data;
985
+ }
986
+ this.curPage = await this.requester.doNextRequest();
987
+ return this.curPage.data;
988
+ }
989
+ };
990
+ var EntryIterator = class {
991
+ constructor(requester) {
992
+ this.requester = requester;
993
+ this.pager = new PagedIterator(requester);
994
+ this.curData = [];
995
+ this.cursor = 0;
996
+ }
997
+ cursor;
998
+ pager;
999
+ curData;
1000
+ async hasNext() {
1001
+ if (this.cursor < this.curData.length - 1) {
1002
+ return true;
1003
+ }
1004
+ return this.pager.hasNext();
1005
+ }
1006
+ async next() {
1007
+ this.cursor += 1;
1008
+ while (this.cursor >= this.curData.length) {
1009
+ if (!await this.pager.hasNext()) {
1010
+ throw new Error("not more data");
1011
+ } else {
1012
+ this.curData = await this.pager.next();
1013
+ this.cursor = 0;
1014
+ }
1015
+ }
1016
+ return this.curData[this.cursor];
1017
+ }
1018
+ };
1019
+
1020
+ // src/utils/iter/object.ts
1021
+ async function getAllOwnedObjects(provider, owner, options) {
1022
+ const iter = new OwnedObjectIterator(provider, owner, options);
1023
+ return await getAllFromIterator(iter);
1024
+ }
1025
+ var OwnedObjectIterator = class extends EntryIterator {
1026
+ constructor(provider, owner, options) {
1027
+ super(new OwnedObjectRequester(provider, owner, options));
1028
+ this.provider = provider;
1029
+ this.owner = owner;
1030
+ this.options = options;
1031
+ }
1032
+ };
1033
+ var OwnedObjectRequester = class {
1034
+ constructor(provider, owner, options) {
1035
+ this.provider = provider;
1036
+ this.owner = owner;
1037
+ this.options = options;
1038
+ this.nextCursor = null;
1039
+ this.filter = options?.filter;
1040
+ this.pageSize = options?.pageSize || REQUEST_PAGE_SIZE;
1041
+ this.objectOptions = options?.objectOptions || {
1042
+ showType: true,
1043
+ showContent: true
1044
+ };
1045
+ }
1046
+ nextCursor;
1047
+ filter;
1048
+ pageSize;
1049
+ objectOptions;
1050
+ async doNextRequest() {
1051
+ const res = await this.provider.getOwnedObjects({
1052
+ owner: this.owner,
1053
+ options: this.objectOptions,
1054
+ cursor: this.nextCursor,
1055
+ limit: this.pageSize
1056
+ });
1057
+ this.nextCursor = res.nextCursor;
1058
+ let filtered;
1059
+ if (this.filter) {
1060
+ const { filter } = this;
1061
+ filtered = res.data.filter((obj) => filter?.(obj));
1062
+ } else {
1063
+ filtered = res.data;
1064
+ }
1065
+ return {
1066
+ data: filtered.map((r) => r.data).filter((data) => data),
1067
+ hasNext: res.hasNextPage
1068
+ };
1069
+ }
1070
+ };
1071
+
1072
+ // src/core/MSafeAccount.ts
1073
+ var MSafeAccount = class {
1074
+ constructor(globals, info) {
1075
+ this.globals = globals;
1076
+ this.info = info;
1077
+ this.multisigManager = new MultisigAccountManager2({
1078
+ threshold: info.threshold,
1079
+ ownersWithWeight: info.ownersWithWeightPK,
1080
+ creationNonce: info.creationNonce
1081
+ });
1082
+ this.coinHelper = new CoinHelper(this.suiClient);
1083
+ }
1084
+ multisigManager;
1085
+ coinHelper;
1086
+ static async new(globals, address) {
1087
+ return globals.backend.getMSafeAccountInfo(address);
1088
+ }
1089
+ async ownedCoins() {
1090
+ const balances = await this.suiClient.getAllBalances({ owner: this.address });
1091
+ return Promise.all(
1092
+ balances.map(async (balance) => {
1093
+ const meta = await this.coinHelper.getCoinMeta(balance.coinType);
1094
+ const unlockedBalance = balance.lockedBalance.number ? BigInt(balance.totalBalance) - BigInt(balance.lockedBalance.number) : BigInt(balance.totalBalance);
1095
+ return {
1096
+ type: normalizeStructTag3(balance.coinType),
1097
+ balance: BigInt(unlockedBalance),
1098
+ metadata: meta
1099
+ };
1100
+ })
1101
+ );
1102
+ }
1103
+ async ownedObjects(options) {
1104
+ const filterCoinObjectOptions = {
1105
+ filter: (objRes) => !objRes?.data?.type?.startsWith("0x2::coin::Coin"),
1106
+ ...options
1107
+ };
1108
+ return getAllOwnedObjects(this.suiClient, this.address, filterCoinObjectOptions);
1109
+ }
1110
+ async pendingTransaction() {
1111
+ const pendings = await this.backend.getPendingTransactions(this.address);
1112
+ if (pendings.length > 2) {
1113
+ throw new Error(`invalid backend getPendingTransactions resp, length should not > 2: ${pendings}`);
1114
+ }
1115
+ if (pendings.length === 0) {
1116
+ return void 0;
1117
+ }
1118
+ const pendingTx = pendings.find((tx) => !tx.isRejectTx);
1119
+ const rejectPending = pendings.find((tx) => tx.isRejectTx);
1120
+ return {
1121
+ ...pendingTx,
1122
+ rejectDigest: rejectPending?.digest ?? "",
1123
+ rejectPayload: rejectPending?.payload ?? "",
1124
+ rejectVotes: rejectPending?.votes ?? []
1125
+ };
1126
+ }
1127
+ async historyTransaction(paginationOption) {
1128
+ return this.backend.getHistoryTransactions(this.address, paginationOption);
1129
+ }
1130
+ async futureIntentions(paginationOption) {
1131
+ const paginatedIntentions = await this.backend.getFutureIntentions(this.address, paginationOption);
1132
+ return paginatedIntentions.data;
1133
+ }
1134
+ async currentSequenceNumber() {
1135
+ return this.backend.getCurrentSequenceNumber(this.address);
1136
+ }
1137
+ async nextSequenceNumber() {
1138
+ return this.backend.getNextSequenceNumber(this.address);
1139
+ }
1140
+ async proposeIntention(intention, sequenceNumber) {
1141
+ const message = MessageHelper.proposeIntentionMessage({
1142
+ intention,
1143
+ sn: sequenceNumber,
1144
+ msafeAddress: this.address
1145
+ });
1146
+ const signature = await this.wallet.signPersonalMessage({
1147
+ messageStr: message
1148
+ });
1149
+ const txType = getIntentionType(intention);
1150
+ await this.backend.proposeIntention({
1151
+ intention,
1152
+ sequenceNumber,
1153
+ msafeAddress: this.address,
1154
+ userAddress: await this.userAddress(),
1155
+ signature: signature.signature,
1156
+ application: MSAFE_APPLICATION,
1157
+ txType: txType.txType,
1158
+ txSubType: txType.txSubType
1159
+ });
1160
+ }
1161
+ async voteForTransaction(digest, payload) {
1162
+ const payloadBytes = HexToUint8Array(payload);
1163
+ const signature = await this.wallet.signTransactionBlock({ transactionBlock: payloadBytes });
1164
+ return this.backend.voteForTransaction({
1165
+ msafeAddress: this.address,
1166
+ userAddress: await this.userAddress(),
1167
+ txDigest: digest,
1168
+ signature: signature.signature
1169
+ });
1170
+ }
1171
+ // Shortcut for proposing a transaction to be a pending transaction, and add user vote to it.
1172
+ // Requires the multi-sig to be empty in pending transaction.
1173
+ async proposePendingTransaction(intention) {
1174
+ const txb = await IntentionHelper.buildTxb({
1175
+ suiClient: this.suiClient,
1176
+ intention,
1177
+ sender: this.address
1178
+ });
1179
+ const payload = await txb.build({ client: this.suiClient });
1180
+ const digest = await txb.getDigest({ client: this.suiClient });
1181
+ const signature = await this.wallet.signTransactionBlock({ transactionBlock: payload });
1182
+ return this.backend.proposePendingTransaction({
1183
+ msafeAddress: this.address,
1184
+ userAddress: await this.userAddress(),
1185
+ intention,
1186
+ digest,
1187
+ signature: signature.signature
1188
+ });
1189
+ }
1190
+ async rejectCurrentTx(pending) {
1191
+ let payloadToReject;
1192
+ if (pending) {
1193
+ if (pending.isRejectTx) {
1194
+ throw new Error("Pending not reject transaction");
1195
+ }
1196
+ payloadToReject = pending.payload;
1197
+ } else {
1198
+ const pendingTx = await this.pendingTransaction();
1199
+ if (!pendingTx || pendingTx.rejectDigest !== "") {
1200
+ throw new Error("Already rejected");
1201
+ }
1202
+ payloadToReject = pendingTx.payload;
1203
+ }
1204
+ const rejectTxb = await IntentionHelper.buildRejectTransaction({
1205
+ msafeAddress: this.address,
1206
+ payloadToReject
1207
+ });
1208
+ const digest = await rejectTxb.getDigest({ client: this.suiClient });
1209
+ const payload = await rejectTxb.build({ client: this.suiClient });
1210
+ const signature = await this.wallet.signTransactionBlock({ transactionBlock: payload });
1211
+ return this.backend.rejectCurrentTx({
1212
+ msafeAddress: this.address,
1213
+ userAddress: await this.userAddress(),
1214
+ digest,
1215
+ signature: signature.signature
1216
+ });
1217
+ }
1218
+ async buildNextIntentionAndAddToPending() {
1219
+ return this.backend.buildNextIntentionAndAddToPending({ msafeAddress: this.address });
1220
+ }
1221
+ async skipNextFailedIntention() {
1222
+ return this.backend.skipNextFailedIntention({ msafeAddress: this.address, userAddress: await this.userAddress() });
1223
+ }
1224
+ async simulateIntention(intention) {
1225
+ const txb = await buildIntentionTransaction(this.suiClient, intention, this.address);
1226
+ if (!txb.blockData.gasConfig.price) {
1227
+ const refGas = await this.suiClient.getReferenceGasPrice();
1228
+ txb.setGasPrice(refGas);
1229
+ }
1230
+ const payload = await txb.build({ client: this.suiClient });
1231
+ const dryRunResult = await this.suiClient.dryRunTransactionBlock({ transactionBlock: payload });
1232
+ const success = dryRunResult.effects.status.status === "success";
1233
+ const errorMsg = dryRunResult.effects.status.error;
1234
+ const gasPrice = BigInt(txb.blockData.gasConfig.price);
1235
+ const { gasUsed } = dryRunResult.effects;
1236
+ return {
1237
+ success,
1238
+ errorMsg,
1239
+ gasPrice,
1240
+ gasUsed,
1241
+ dryRunResult
1242
+ };
1243
+ }
1244
+ async executePendingTx(pending) {
1245
+ let gotSigs;
1246
+ let payload;
1247
+ if (pending.votes.length >= this.info.threshold) {
1248
+ gotSigs = new Map(pending.votes.map((vote) => [vote.userAddress, vote.signature]));
1249
+ payload = pending.payload;
1250
+ } else if (pending.rejectVotes && pending.rejectPayload && pending.rejectVotes?.length >= this.info.threshold) {
1251
+ gotSigs = new Map(pending.rejectVotes.map((vote) => [vote.userAddress, vote.signature]));
1252
+ payload = pending.rejectPayload;
1253
+ } else {
1254
+ throw new Error("Not enough signatures");
1255
+ }
1256
+ const sigs = [];
1257
+ for (let i = 0; i < this.info.ownersWithWeightPK.length; i++) {
1258
+ const owner = this.info.ownersWithWeightPK[i];
1259
+ const signature = gotSigs.get(owner.publicKey.toSuiAddress());
1260
+ if (signature) {
1261
+ sigs.push(signature);
1262
+ }
1263
+ }
1264
+ const multiSignature = this.multisigManager.combinePartialSignatures(sigs);
1265
+ return this.suiClient.executeTransactionBlock({
1266
+ transactionBlock: HexToUint8Array(payload),
1267
+ signature: multiSignature,
1268
+ options: { showEffects: true }
1269
+ });
1270
+ }
1271
+ get address() {
1272
+ return this.info.address;
1273
+ }
1274
+ get backend() {
1275
+ return this.globals.backend;
1276
+ }
1277
+ get wallet() {
1278
+ return this.globals.wallet;
1279
+ }
1280
+ async userAddress() {
1281
+ return this.globals.wallet.address();
1282
+ }
1283
+ get suiClient() {
1284
+ return this.globals.suiClient;
1285
+ }
1286
+ };
1287
+
1288
+ // src/core/PublicKeyHelper.ts
1289
+ var PublicKeyHelper = class {
1290
+ constructor(globals) {
1291
+ this.globals = globals;
1292
+ this.knownPublicKeys = /* @__PURE__ */ new Map();
1293
+ }
1294
+ knownPublicKeys;
1295
+ async getPublicKey(address) {
1296
+ const cached = this.knownPublicKeys.get(address);
1297
+ if (cached) {
1298
+ return cached;
1299
+ }
1300
+ const pk = await this._getPublicKey(address);
1301
+ if (pk) {
1302
+ this.knownPublicKeys.set(address, pk);
1303
+ }
1304
+ return pk;
1305
+ }
1306
+ async getPublicKeyBatch(addresses) {
1307
+ const results = new Array(addresses.length).fill(void 0);
1308
+ for (let i = 0; i < addresses.length; i++) {
1309
+ const address = addresses[i];
1310
+ results[i] = this.knownPublicKeys.get(address);
1311
+ }
1312
+ const emptyIndexes = results.map((elem, index) => elem === void 0 ? index : -1).filter((index) => index !== -1);
1313
+ const backendResult = await this.globals.backend.getPublicKeyBatch(emptyIndexes.map((index) => addresses[index]));
1314
+ for (let i = 0; i < emptyIndexes.length; i++) {
1315
+ const index = emptyIndexes[i];
1316
+ results[index] = backendResult[i];
1317
+ }
1318
+ for (let i = 0; i < results.length; i++) {
1319
+ if (results[i] === void 0) {
1320
+ results[i] = await this.getPublicKeyFromChain(addresses[i]);
1321
+ }
1322
+ }
1323
+ for (let i = 0; i < addresses.length; i++) {
1324
+ if (results[i]) {
1325
+ this.knownPublicKeys.set(addresses[i], results[i]);
1326
+ }
1327
+ }
1328
+ return results;
1329
+ }
1330
+ async _getPublicKey(address) {
1331
+ const pkBackend = await this.getPublicKeyFromBackend(address);
1332
+ if (pkBackend) {
1333
+ return pkBackend;
1334
+ }
1335
+ const pkChain = await this.getPublicKeyFromChain(address);
1336
+ if (pkChain) {
1337
+ return pkChain;
1338
+ }
1339
+ return void 0;
1340
+ }
1341
+ async getPublicKeyFromBackend(address) {
1342
+ try {
1343
+ const pk = await this.globals.backend.getPublicKey(address);
1344
+ return pk;
1345
+ } catch (_) {
1346
+ return void 0;
1347
+ }
1348
+ }
1349
+ async getPublicKeyFromChain(address) {
1350
+ return getPublicKeyFromChain(this.globals.suiClient, address);
1351
+ }
1352
+ };
1353
+
1316
1354
  // src/core/MSafeClient.ts
1317
1355
  var MSafeClient = class _MSafeClient {
1318
1356
  constructor(globals) {
@@ -1418,6 +1456,7 @@ export {
1418
1456
  LOCAL_DATABASE_CONFIG,
1419
1457
  LOCAL_SYNCING_URL,
1420
1458
  MAINNET_RPC_URL,
1459
+ MSAFE_APPLICATION,
1421
1460
  MSafeAccount,
1422
1461
  MSafeClient,
1423
1462
  MSafeEnv,