@fuel-ts/account 0.0.0-pr-1699-20240202183346 → 0.0.0-pr-1699-20240202203055

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.

Potentially problematic release.


This version of @fuel-ts/account might be problematic. Click here for more details.

package/dist/index.js CHANGED
@@ -59,18 +59,34 @@ var src_exports = {};
59
59
  __export(src_exports, {
60
60
  Account: () => Account,
61
61
  AddressType: () => AddressType,
62
+ BACKGROUND_SCRIPT_NAME: () => BACKGROUND_SCRIPT_NAME,
62
63
  BaseTransactionRequest: () => BaseTransactionRequest,
63
64
  BaseWalletUnlocked: () => BaseWalletUnlocked,
65
+ CONNECTOR_SCRIPT: () => CONNECTOR_SCRIPT,
66
+ CONTENT_SCRIPT_NAME: () => CONTENT_SCRIPT_NAME,
64
67
  ChainName: () => ChainName,
65
68
  ChangeOutputCollisionError: () => ChangeOutputCollisionError,
66
69
  CreateTransactionRequest: () => CreateTransactionRequest,
70
+ EVENT_MESSAGE: () => EVENT_MESSAGE,
71
+ Fuel: () => Fuel,
72
+ FuelConnector: () => FuelConnector,
73
+ FuelConnectorEventType: () => FuelConnectorEventType,
74
+ FuelConnectorEventTypes: () => FuelConnectorEventTypes,
75
+ FuelConnectorMethods: () => FuelConnectorMethods,
76
+ FuelWalletConnector: () => FuelWalletConnector,
77
+ FuelWalletDevelopmentConnector: () => FuelWalletDevelopmentConnector,
78
+ FuelWalletLocked: () => FuelWalletLocked,
79
+ FuelWalletProvider: () => FuelWalletProvider,
80
+ FueletWalletConnector: () => FueletWalletConnector,
67
81
  HDWallet: () => hdwallet_default,
68
82
  Language: () => Language,
69
83
  MNEMONIC_SIZES: () => MNEMONIC_SIZES,
84
+ MessageTypes: () => MessageTypes,
70
85
  Mnemonic: () => mnemonic_default,
71
86
  NoWitnessAtIndexError: () => NoWitnessAtIndexError,
72
87
  NoWitnessByOwnerError: () => NoWitnessByOwnerError,
73
88
  OperationName: () => OperationName,
89
+ POPUP_SCRIPT_NAME: () => POPUP_SCRIPT_NAME,
74
90
  Predicate: () => Predicate,
75
91
  Provider: () => Provider,
76
92
  ScriptTransactionRequest: () => ScriptTransactionRequest,
@@ -80,6 +96,7 @@ __export(src_exports, {
80
96
  TransactionStatus: () => TransactionStatus,
81
97
  TransactionType: () => import_transactions5.TransactionType,
82
98
  TransactionTypeName: () => TransactionTypeName,
99
+ VAULT_SCRIPT_NAME: () => VAULT_SCRIPT_NAME,
83
100
  Vault: () => Vault,
84
101
  Wallet: () => Wallet,
85
102
  WalletLocked: () => WalletLocked,
@@ -90,11 +107,15 @@ __export(src_exports, {
90
107
  assembleReceiptByType: () => assembleReceiptByType,
91
108
  assembleTransactionSummary: () => assembleTransactionSummary,
92
109
  buildBlockExplorerUrl: () => buildBlockExplorerUrl,
110
+ cacheFor: () => cacheFor,
93
111
  calculateMetadataGasForTxCreate: () => calculateMetadataGasForTxCreate,
94
112
  calculateMetadataGasForTxScript: () => calculateMetadataGasForTxScript,
95
113
  calculatePriceWithFactor: () => calculatePriceWithFactor,
96
114
  calculateTransactionFee: () => calculateTransactionFee,
97
115
  coinQuantityfy: () => coinQuantityfy,
116
+ defaultConnectors: () => defaultConnectors,
117
+ deferPromise: () => deferPromise,
118
+ dispatchFuelConnectorEvent: () => dispatchFuelConnectorEvent,
98
119
  english: () => english,
99
120
  extractBurnedAssetsFromReceipts: () => extractBurnedAssetsFromReceipts,
100
121
  extractMintedAssetsFromReceipts: () => extractMintedAssetsFromReceipts,
@@ -103,6 +124,7 @@ __export(src_exports, {
103
124
  fromTai64ToUnix: () => fromTai64ToUnix,
104
125
  fromUnixToTai64: () => fromUnixToTai64,
105
126
  gasUsedByInputs: () => gasUsedByInputs,
127
+ getAssetByChain: () => getAssetByChain,
106
128
  getContractCallOperations: () => getContractCallOperations,
107
129
  getContractCreatedOperations: () => getContractCreatedOperations,
108
130
  getContractTransferOperations: () => getContractTransferOperations,
@@ -158,6 +180,7 @@ __export(src_exports, {
158
180
  returnZeroScript: () => returnZeroScript,
159
181
  sleep: () => sleep,
160
182
  transactionRequestify: () => transactionRequestify,
183
+ withTimeout: () => withTimeout,
161
184
  withdrawScript: () => withdrawScript
162
185
  });
163
186
  module.exports = __toCommonJS(src_exports);
@@ -8620,22 +8643,1011 @@ var Predicate = class extends Account {
8620
8643
  return mutatedBytes;
8621
8644
  }
8622
8645
  };
8646
+
8647
+ // src/connectors/fuel-wallet-connector.ts
8648
+ var import_json_rpc_2 = require("json-rpc-2.0");
8649
+ var import_uuid2 = require("uuid");
8650
+
8651
+ // src/connectors/fuel-connector.ts
8652
+ var import_events2 = require("events");
8653
+
8654
+ // src/connectors/types/connector-types.ts
8655
+ var FuelConnectorMethods = /* @__PURE__ */ ((FuelConnectorMethods2) => {
8656
+ FuelConnectorMethods2["ping"] = "ping";
8657
+ FuelConnectorMethods2["version"] = "version";
8658
+ FuelConnectorMethods2["connect"] = "connect";
8659
+ FuelConnectorMethods2["disconnect"] = "disconnect";
8660
+ FuelConnectorMethods2["isConnected"] = "isConnected";
8661
+ FuelConnectorMethods2["accounts"] = "accounts";
8662
+ FuelConnectorMethods2["currentAccount"] = "currentAccount";
8663
+ FuelConnectorMethods2["signMessage"] = "signMessage";
8664
+ FuelConnectorMethods2["sendTransaction"] = "sendTransaction";
8665
+ FuelConnectorMethods2["assets"] = "assets";
8666
+ FuelConnectorMethods2["addAsset"] = "addAsset";
8667
+ FuelConnectorMethods2["addAssets"] = "addAssets";
8668
+ FuelConnectorMethods2["networks"] = "networks";
8669
+ FuelConnectorMethods2["currentNetwork"] = "currentNetwork";
8670
+ FuelConnectorMethods2["addNetwork"] = "addNetwork";
8671
+ FuelConnectorMethods2["selectNetwork"] = "selectNetwork";
8672
+ FuelConnectorMethods2["addABI"] = "addABI";
8673
+ FuelConnectorMethods2["getABI"] = "getABI";
8674
+ FuelConnectorMethods2["hasABI"] = "hasABI";
8675
+ return FuelConnectorMethods2;
8676
+ })(FuelConnectorMethods || {});
8677
+ var FuelConnectorEventTypes = /* @__PURE__ */ ((FuelConnectorEventTypes2) => {
8678
+ FuelConnectorEventTypes2["connectors"] = "connectors";
8679
+ FuelConnectorEventTypes2["currentConnector"] = "currentConnector";
8680
+ FuelConnectorEventTypes2["connection"] = "connection";
8681
+ FuelConnectorEventTypes2["accounts"] = "accounts";
8682
+ FuelConnectorEventTypes2["currentAccount"] = "currentAccount";
8683
+ FuelConnectorEventTypes2["networks"] = "networks";
8684
+ FuelConnectorEventTypes2["currentNetwork"] = "currentNetwork";
8685
+ FuelConnectorEventTypes2["assets"] = "assets";
8686
+ FuelConnectorEventTypes2["abis"] = "abis";
8687
+ return FuelConnectorEventTypes2;
8688
+ })(FuelConnectorEventTypes || {});
8689
+ var FuelConnectorEventType = "FuelConnector";
8690
+
8691
+ // src/connectors/types/constants.ts
8692
+ var CONNECTOR_SCRIPT = "FuelConnectorScript";
8693
+ var CONTENT_SCRIPT_NAME = "FuelContentScript";
8694
+ var BACKGROUND_SCRIPT_NAME = "FuelBackgroundScript";
8695
+ var POPUP_SCRIPT_NAME = "FuelPopUpScript";
8696
+ var VAULT_SCRIPT_NAME = "FuelVaultScript";
8697
+ var EVENT_MESSAGE = "message";
8698
+
8699
+ // src/connectors/types/data-type.ts
8700
+ var MessageTypes = /* @__PURE__ */ ((MessageTypes2) => {
8701
+ MessageTypes2["ping"] = "ping";
8702
+ MessageTypes2["uiEvent"] = "uiEvent";
8703
+ MessageTypes2["event"] = "event";
8704
+ MessageTypes2["request"] = "request";
8705
+ MessageTypes2["response"] = "response";
8706
+ MessageTypes2["removeConnection"] = "removeConnection";
8707
+ return MessageTypes2;
8708
+ })(MessageTypes || {});
8709
+
8710
+ // src/connectors/fuel-connector.ts
8711
+ var FuelConnector = class extends import_events2.EventEmitter {
8712
+ name = "";
8713
+ metadata = {};
8714
+ connected = false;
8715
+ installed = false;
8716
+ events = FuelConnectorEventTypes;
8717
+ /**
8718
+ * Should return true if the connector is loaded
8719
+ * in less then one second.
8720
+ *
8721
+ * @returns Always true.
8722
+ */
8723
+ async ping() {
8724
+ throw new Error("Method not implemented.");
8725
+ }
8726
+ /**
8727
+ * Should return the current version of the connector
8728
+ * and the network version that is compatible.
8729
+ *
8730
+ * @returns boolean - connection status.
8731
+ */
8732
+ async version() {
8733
+ throw new Error("Method not implemented.");
8734
+ }
8735
+ /**
8736
+ * Should return true if the connector is connected
8737
+ * to any of the accounts available.
8738
+ *
8739
+ * @returns The connection status.
8740
+ */
8741
+ async isConnected() {
8742
+ throw new Error("Method not implemented.");
8743
+ }
8744
+ /**
8745
+ * Should return all the accounts authorized for the
8746
+ * current connection.
8747
+ *
8748
+ * @returns The accounts addresses strings
8749
+ */
8750
+ async accounts() {
8751
+ throw new Error("Method not implemented.");
8752
+ }
8753
+ /**
8754
+ * Should start the connection process and return
8755
+ * true if the account authorize the connection.
8756
+ *
8757
+ * and return false if the user reject the connection.
8758
+ *
8759
+ * @emits accounts
8760
+ * @returns boolean - connection status.
8761
+ */
8762
+ async connect() {
8763
+ throw new Error("Method not implemented.");
8764
+ }
8765
+ /**
8766
+ * Should disconnect the current connection and
8767
+ * return false if the disconnection was successful.
8768
+ *
8769
+ * @emits assets connection
8770
+ * @returns The connection status.
8771
+ */
8772
+ async disconnect() {
8773
+ throw new Error("Method not implemented.");
8774
+ }
8775
+ /**
8776
+ * Should start the sign message process and return
8777
+ * the signed message.
8778
+ *
8779
+ * @param address - The address to sign the message
8780
+ * @param message - The message to sign all text will be treated as text utf-8
8781
+ *
8782
+ * @returns Message signature
8783
+ */
8784
+ async signMessage(_address, _message) {
8785
+ throw new Error("Method not implemented.");
8786
+ }
8787
+ /**
8788
+ * Should start the send transaction process and return
8789
+ * the transaction id submitted to the network.
8790
+ *
8791
+ * If the network is not available for the connection
8792
+ * it should throw an error to avoid the transaction
8793
+ * to be sent to the wrong network and lost.
8794
+ *
8795
+ * @param address - The address to sign the transaction
8796
+ * @param transaction - The transaction to send
8797
+ *
8798
+ * @returns The transaction id
8799
+ */
8800
+ async sendTransaction(_address, _transaction) {
8801
+ throw new Error("Method not implemented.");
8802
+ }
8803
+ /**
8804
+ * Should return the current account selected inside the connector, if the account
8805
+ * is authorized for the connection.
8806
+ *
8807
+ * If the account is not authorized it should return null.
8808
+ *
8809
+ * @returns The current account selected otherwise null.
8810
+ */
8811
+ async currentAccount() {
8812
+ throw new Error("Method not implemented.");
8813
+ }
8814
+ /**
8815
+ * Should add the the assets metadata to the connector and return true if the asset
8816
+ * was added successfully.
8817
+ *
8818
+ * If the asset already exists it should throw an error.
8819
+ *
8820
+ * @emits assets
8821
+ * @param assets - The assets to add the metadata to the connection.
8822
+ * @throws Error if the asset already exists
8823
+ * @returns True if the asset was added successfully
8824
+ */
8825
+ async addAssets(_assets) {
8826
+ throw new Error("Method not implemented.");
8827
+ }
8828
+ /**
8829
+ * Should add the the asset metadata to the connector and return true if the asset
8830
+ * was added successfully.
8831
+ *
8832
+ * If the asset already exists it should throw an error.
8833
+ *
8834
+ * @emits assets
8835
+ * @param asset - The asset to add the metadata to the connection.
8836
+ * @throws Error if the asset already exists
8837
+ * @returns True if the asset was added successfully
8838
+ */
8839
+ async addAsset(_asset) {
8840
+ throw new Error("Method not implemented.");
8841
+ }
8842
+ /**
8843
+ * Should return all the assets added to the connector. If a connection is already established.
8844
+ *
8845
+ * @returns Array of assets metadata from the connector vinculated to the all accounts from a specific Wallet.
8846
+ */
8847
+ async assets() {
8848
+ throw new Error("Method not implemented.");
8849
+ }
8850
+ /**
8851
+ * Should start the add network process and return true if the network was added successfully.
8852
+ *
8853
+ * @emits networks
8854
+ * @throws Error if the network already exists
8855
+ * @param networkUrl - The URL of the network to be added.
8856
+ * @returns Return true if the network was added successfully
8857
+ */
8858
+ async addNetwork(_networkUrl) {
8859
+ throw new Error("Method not implemented.");
8860
+ }
8861
+ /**
8862
+ * Should start the select network process and return true if the network has change successfully.
8863
+ *
8864
+ * @emits networks
8865
+ * @throws Error if the network already exists
8866
+ * @param network - The network to be selected.
8867
+ * @returns Return true if the network was added successfully
8868
+ */
8869
+ async selectNetwork(_network) {
8870
+ throw new Error("Method not implemented.");
8871
+ }
8872
+ /**
8873
+ * Should return all the networks available from the connector. If the connection is already established.
8874
+ *
8875
+ * @returns Return all the networks added to the connector.
8876
+ */
8877
+ async networks() {
8878
+ throw new Error("Method not implemented.");
8879
+ }
8880
+ /**
8881
+ * Should return the current network selected inside the connector. Even if the connection is not established.
8882
+ *
8883
+ * @returns Return the current network selected inside the connector.
8884
+ */
8885
+ async currentNetwork() {
8886
+ throw new Error("Method not implemented.");
8887
+ }
8888
+ /**
8889
+ * Should add the ABI to the connector and return true if the ABI was added successfully.
8890
+ *
8891
+ * @param contractId - The contract id to add the ABI.
8892
+ * @param abi - The JSON ABI that represents a contract.
8893
+ * @returns Return true if the ABI was added successfully.
8894
+ */
8895
+ async addABI(_contractId, _abi) {
8896
+ throw new Error("Method not implemented.");
8897
+ }
8898
+ /**
8899
+ * Should return the ABI from the connector vinculated to the all accounts from a specific Wallet.
8900
+ *
8901
+ * @param id - The contract id to get the ABI.
8902
+ * @returns The ABI if it exists, otherwise return null.
8903
+ */
8904
+ async getABI(_id) {
8905
+ throw new Error("Method not implemented.");
8906
+ }
8907
+ /**
8908
+ * Should return true if the abi exists in the connector vinculated to the all accounts from a specific Wallet.
8909
+ *
8910
+ * @param id - The contract id to get the abi
8911
+ * @returns Returns true if the abi exists or false if not.
8912
+ */
8913
+ async hasABI(_id) {
8914
+ throw new Error("Method not implemented.");
8915
+ }
8916
+ /**
8917
+ * Event listener for the connector.
8918
+ *
8919
+ * @param eventName - The event name to listen
8920
+ * @param listener - The listener function
8921
+ */
8922
+ on(eventName, listener) {
8923
+ super.on(eventName, listener);
8924
+ return this;
8925
+ }
8926
+ };
8927
+
8928
+ // src/connectors/fuel-wallet-connector.ts
8929
+ var { warn } = console;
8930
+ var FuelWalletConnector = class extends FuelConnector {
8931
+ name = "";
8932
+ connected = false;
8933
+ installed = false;
8934
+ events = FuelConnectorEventTypes;
8935
+ metadata = {
8936
+ image: "/connectors/fuel-wallet.svg",
8937
+ install: {
8938
+ action: "Install",
8939
+ description: "To connect your Fuel Wallet, install the browser extension.",
8940
+ link: "https://chrome.google.com/webstore/detail/fuel-wallet/dldjpboieedgcmpkchcjcbijingjcgok"
8941
+ }
8942
+ };
8943
+ client;
8944
+ constructor(name = "Fuel Wallet") {
8945
+ super();
8946
+ this.name = name;
8947
+ this.setMaxListeners(100);
8948
+ this.client = new import_json_rpc_2.JSONRPCClient(this.sendRequest.bind(this), this.createRequestId);
8949
+ this.setupListener();
8950
+ this.setupConnector();
8951
+ }
8952
+ /**
8953
+ * ============================================================
8954
+ * Application communication methods
8955
+ * ============================================================
8956
+ */
8957
+ async setupConnector() {
8958
+ if (typeof window !== "undefined") {
8959
+ try {
8960
+ await this.ping();
8961
+ window.dispatchEvent(new CustomEvent("FuelConnector", { detail: this }));
8962
+ } catch (e) {
8963
+ warn(e);
8964
+ }
8965
+ }
8966
+ }
8967
+ acceptMessage(message) {
8968
+ const { data: event } = message;
8969
+ return message.origin === window.origin && event.type !== "request" /* request */ && event.connectorName === this.name && event.target === CONNECTOR_SCRIPT;
8970
+ }
8971
+ setupListener() {
8972
+ if (typeof window === "undefined") {
8973
+ return;
8974
+ }
8975
+ window.addEventListener(EVENT_MESSAGE, this.onMessage.bind(this));
8976
+ }
8977
+ createRequestId() {
8978
+ return (0, import_uuid2.v4)();
8979
+ }
8980
+ postMessage(message, origin) {
8981
+ window.postMessage(message, origin || window.origin);
8982
+ }
8983
+ // eslint-disable-next-line @typescript-eslint/require-await
8984
+ async sendRequest(request) {
8985
+ if (!request) {
8986
+ return;
8987
+ }
8988
+ this.postMessage({
8989
+ type: "request" /* request */,
8990
+ target: CONTENT_SCRIPT_NAME,
8991
+ connectorName: this.name,
8992
+ request
8993
+ });
8994
+ }
8995
+ onResponse(message) {
8996
+ this.client.receive(message.response);
8997
+ }
8998
+ onEvent(message) {
8999
+ message.events.forEach((eventData) => {
9000
+ if (eventData.event === "start") {
9001
+ this.setupConnector();
9002
+ } else {
9003
+ this.emit(eventData.event, ...eventData.params);
9004
+ }
9005
+ });
9006
+ }
9007
+ onMessage = (message) => {
9008
+ const messageFroze = Object.freeze(message);
9009
+ if (!this.acceptMessage(messageFroze)) {
9010
+ return;
9011
+ }
9012
+ const { data: event } = messageFroze;
9013
+ this.onCommunicationMessage(event);
9014
+ };
9015
+ onCommunicationMessage = (message) => {
9016
+ switch (message.type) {
9017
+ case "response" /* response */:
9018
+ this.onResponse(message);
9019
+ break;
9020
+ case "event" /* event */:
9021
+ this.onEvent(message);
9022
+ break;
9023
+ default:
9024
+ }
9025
+ };
9026
+ /**
9027
+ * ============================================================
9028
+ * Connector methods
9029
+ * ============================================================
9030
+ */
9031
+ async ping() {
9032
+ return this.client.timeout(800).request("ping", {});
9033
+ }
9034
+ async isConnected() {
9035
+ try {
9036
+ return await this.client.request("isConnected", {});
9037
+ } catch {
9038
+ return false;
9039
+ }
9040
+ }
9041
+ async connect() {
9042
+ return this.client.request("connect", {});
9043
+ }
9044
+ async disconnect() {
9045
+ return this.client.request("disconnect", {});
9046
+ }
9047
+ async accounts() {
9048
+ return this.client.request("accounts", {});
9049
+ }
9050
+ async currentAccount() {
9051
+ return this.client.request("currentAccount", {});
9052
+ }
9053
+ async signMessage(address, message) {
9054
+ if (!message.trim()) {
9055
+ throw new Error("Message is required");
9056
+ }
9057
+ return this.client.request("signMessage", {
9058
+ address,
9059
+ message
9060
+ });
9061
+ }
9062
+ async sendTransaction(address, transaction) {
9063
+ if (!transaction) {
9064
+ throw new Error("Transaction is required");
9065
+ }
9066
+ const txRequest = transactionRequestify(transaction);
9067
+ const network = await this.currentNetwork();
9068
+ const provider = {
9069
+ url: network.url
9070
+ };
9071
+ return this.client.request("sendTransaction", {
9072
+ address,
9073
+ transaction: JSON.stringify(txRequest),
9074
+ provider
9075
+ });
9076
+ }
9077
+ async assets() {
9078
+ return this.client.request("assets", {});
9079
+ }
9080
+ async addAsset(asset) {
9081
+ return this.addAssets([asset]);
9082
+ }
9083
+ async addAssets(assets) {
9084
+ const assetsData = assets.map((asset) => {
9085
+ const fuelNetworkAsset = asset.networks.find((n) => n.type === "fuel");
9086
+ if (!fuelNetworkAsset) {
9087
+ throw new Error("Asset for Fuel Network not found!");
9088
+ }
9089
+ return {
9090
+ ...asset,
9091
+ imageUrl: asset.icon,
9092
+ decimals: fuelNetworkAsset.decimals,
9093
+ assetId: fuelNetworkAsset.assetId
9094
+ };
9095
+ });
9096
+ return this.client.request("addAssets", {
9097
+ assets: assetsData
9098
+ });
9099
+ }
9100
+ async addABI(contractId, abi) {
9101
+ return this.client.request("addAbi", {
9102
+ abiMap: {
9103
+ [contractId]: abi
9104
+ }
9105
+ });
9106
+ }
9107
+ async getABI(contractId) {
9108
+ return this.client.request("getAbi", {
9109
+ contractId
9110
+ });
9111
+ }
9112
+ async hasABI(contractId) {
9113
+ const abi = await this.getABI(contractId);
9114
+ return !!abi;
9115
+ }
9116
+ async currentNetwork() {
9117
+ return this.client.request("network", {});
9118
+ }
9119
+ // eslint-disable-next-line @typescript-eslint/require-await
9120
+ async selectNetwork(_network) {
9121
+ throw new Error("Method not implemented.");
9122
+ }
9123
+ async networks() {
9124
+ return this.client.request("networks", {});
9125
+ }
9126
+ async addNetwork(networkUrl) {
9127
+ const provider = await Provider.create(networkUrl);
9128
+ return this.client.request("addNetwork", {
9129
+ network: {
9130
+ url: provider.url,
9131
+ name: provider.getChain().name
9132
+ }
9133
+ });
9134
+ }
9135
+ async version() {
9136
+ return this.client.request("version", {
9137
+ app: "0.0.0",
9138
+ network: "0.0.0"
9139
+ });
9140
+ }
9141
+ };
9142
+
9143
+ // src/connectors/fuel-wallet-development-connector.ts
9144
+ var FuelWalletDevelopmentConnector = class extends FuelWalletConnector {
9145
+ metadata = {
9146
+ image: "/connectors/fuel-wallet-dev.svg",
9147
+ install: {
9148
+ action: "Install",
9149
+ description: "To connect your Fuel Wallet, you need to install the browser extension first.",
9150
+ link: "https://chrome.google.com/webstore/detail/fuel-wallet-development/hcgmehahnlbhpilepakbdinkhhaackmc"
9151
+ }
9152
+ };
9153
+ constructor() {
9154
+ super("Fuel Wallet Development");
9155
+ }
9156
+ };
9157
+
9158
+ // src/connectors/fuelet-wallet-connector.ts
9159
+ var FueletWalletConnector = class extends FuelWalletConnector {
9160
+ name = "Fuelet Wallet";
9161
+ metadata = {
9162
+ image: {
9163
+ light: "/connectors/fuelet-light.svg",
9164
+ dark: "/connectors/fuelet-dark.svg"
9165
+ },
9166
+ install: {
9167
+ action: "Install",
9168
+ description: "Install Fuelet Wallet in order to connect it.",
9169
+ link: "https://fuelet.app/download/"
9170
+ }
9171
+ };
9172
+ constructor() {
9173
+ super("Fuelet Wallet");
9174
+ }
9175
+ };
9176
+
9177
+ // src/connectors/default-connector.ts
9178
+ function defaultConnectors({ devMode } = {}) {
9179
+ const connectors = [new FuelWalletConnector(), new FueletWalletConnector()];
9180
+ if (devMode) {
9181
+ connectors.push(new FuelWalletDevelopmentConnector());
9182
+ }
9183
+ return connectors;
9184
+ }
9185
+
9186
+ // src/connectors/fuel-wallet-locked.ts
9187
+ var FuelWalletLocked = class extends WalletLocked {
9188
+ connector;
9189
+ _provider;
9190
+ constructor(address, connector, provider) {
9191
+ super(address, provider);
9192
+ this.connector = connector;
9193
+ this._provider = provider;
9194
+ }
9195
+ async signMessage(message) {
9196
+ return this.connector.signMessage(this.address.toString(), message);
9197
+ }
9198
+ async sendTransaction(transaction) {
9199
+ const transactionId = await this.connector.sendTransaction(
9200
+ this.address.toString(),
9201
+ transaction
9202
+ );
9203
+ return this.provider.getTransactionResponse(transactionId);
9204
+ }
9205
+ };
9206
+
9207
+ // src/connectors/fuel-wallet-provider.ts
9208
+ var FuelWalletProvider = class extends Provider {
9209
+ static async create(url, options) {
9210
+ const provider = new FuelWalletProvider(url, options);
9211
+ await provider.fetchChainAndNodeInfo();
9212
+ return provider;
9213
+ }
9214
+ // eslint-disable-next-line @typescript-eslint/require-await
9215
+ async getTransactionResponse(transactionId) {
9216
+ return new TransactionResponse(transactionId, this);
9217
+ }
9218
+ };
9219
+
9220
+ // src/connectors/utils/cache.ts
9221
+ function cacheFor(fn, { cache: cache2, cacheTime, key }) {
9222
+ return async (...args) => {
9223
+ if (cache2[key] && cache2[key]?.value) {
9224
+ return cache2[key]?.value;
9225
+ }
9226
+ clearTimeout(cache2[key]?.timeout);
9227
+ const result = await fn(...args);
9228
+ cache2[key] = {
9229
+ timeout: Number(
9230
+ setTimeout(() => {
9231
+ cache2[key] = null;
9232
+ }, cacheTime)
9233
+ ),
9234
+ value: result
9235
+ };
9236
+ return result;
9237
+ };
9238
+ }
9239
+
9240
+ // src/connectors/utils/dispatch-fuel-connector-event.ts
9241
+ function dispatchFuelConnectorEvent(connector) {
9242
+ window.dispatchEvent(
9243
+ new CustomEvent(FuelConnectorEventType, {
9244
+ detail: connector
9245
+ })
9246
+ );
9247
+ }
9248
+
9249
+ // src/connectors/utils/get-asset-by-chain.ts
9250
+ function getAssetByChain(asset, chainId, network = "fuel") {
9251
+ const assetFuelNetwork = asset.networks.find(
9252
+ (item) => item.chainId === chainId && item.type === network
9253
+ );
9254
+ if (!assetFuelNetwork) {
9255
+ throw new Error("Asset not found for the given chain and network.");
9256
+ }
9257
+ return {
9258
+ ...asset,
9259
+ assetId: assetFuelNetwork.assetId,
9260
+ decimals: assetFuelNetwork.decimals,
9261
+ chainId: assetFuelNetwork.chainId,
9262
+ network: assetFuelNetwork.type
9263
+ };
9264
+ }
9265
+
9266
+ // src/connectors/utils/promises.ts
9267
+ function deferPromise() {
9268
+ const defer = {};
9269
+ defer.promise = new Promise((resolve, reject) => {
9270
+ defer.reject = reject;
9271
+ defer.resolve = resolve;
9272
+ });
9273
+ return defer;
9274
+ }
9275
+ async function withTimeout(promise, timeout = 1050) {
9276
+ const timeoutPromise = new Promise((resolve, reject) => {
9277
+ setTimeout(() => {
9278
+ reject(new Error("Promise timed out"));
9279
+ }, timeout);
9280
+ });
9281
+ return Promise.race([timeoutPromise, promise]);
9282
+ }
9283
+
9284
+ // src/connectors/fuel.ts
9285
+ var HAS_CONNECTOR_TIMEOUT = 2e3;
9286
+ var PING_CACHE_TIME = 5e3;
9287
+ var _Fuel = class extends FuelConnector {
9288
+ _storage = null;
9289
+ _connectors = [];
9290
+ _targetObject = null;
9291
+ _unsubscribes = [];
9292
+ _targetUnsubscribe;
9293
+ _pingCache = {};
9294
+ _currentConnector;
9295
+ constructor(config = _Fuel.defaultConfig) {
9296
+ super();
9297
+ this.setMaxListeners(1e3);
9298
+ this._connectors = config.connectors ?? defaultConnectors({
9299
+ devMode: config.devMode
9300
+ });
9301
+ this._targetObject = this.getTargetObject(config.targetObject);
9302
+ this._storage = config.storage === void 0 ? this.getStorage() : config.storage;
9303
+ this.setupMethods();
9304
+ this.setDefaultConnector();
9305
+ this._targetUnsubscribe = this.setupConnectorListener();
9306
+ }
9307
+ /**
9308
+ * Return the target object to listen for global events.
9309
+ */
9310
+ getTargetObject(targetObject) {
9311
+ if (targetObject) {
9312
+ return targetObject;
9313
+ }
9314
+ if (typeof window !== "undefined") {
9315
+ return window;
9316
+ }
9317
+ if (typeof document !== "undefined") {
9318
+ return document;
9319
+ }
9320
+ return null;
9321
+ }
9322
+ /**
9323
+ * Return the storage used.
9324
+ */
9325
+ getStorage() {
9326
+ if (typeof window !== "undefined") {
9327
+ return window.localStorage;
9328
+ }
9329
+ return void 0;
9330
+ }
9331
+ /**
9332
+ * Setup the default connector from the storage.
9333
+ */
9334
+ setDefaultConnector() {
9335
+ const connectorName = this._storage?.getItem(_Fuel.STORAGE_KEY) || this._connectors[0]?.name;
9336
+ if (connectorName) {
9337
+ return this.selectConnector(connectorName, {
9338
+ emitEvents: false
9339
+ });
9340
+ }
9341
+ return void 0;
9342
+ }
9343
+ /**
9344
+ * Start listener for all the events of the current
9345
+ * connector and emit them to the Fuel instance
9346
+ */
9347
+ setupConnectorEvents(events) {
9348
+ if (!this._currentConnector) {
9349
+ return;
9350
+ }
9351
+ const currentConnector = this._currentConnector;
9352
+ this._unsubscribes.map((unSub) => unSub());
9353
+ this._unsubscribes = events.map((event) => {
9354
+ const handler = (...args) => this.emit(event, ...args);
9355
+ currentConnector.on(event, handler);
9356
+ return () => currentConnector.off(event, handler);
9357
+ });
9358
+ }
9359
+ /**
9360
+ * Call method from the current connector.
9361
+ */
9362
+ async callMethod(method, ...args) {
9363
+ const hasConnector = await this.hasConnector();
9364
+ await this.pingConnector();
9365
+ if (!this._currentConnector || !hasConnector) {
9366
+ throw new Error(
9367
+ `No connector selected for calling ${method}. Use hasConnector before executing other methods.`
9368
+ );
9369
+ }
9370
+ if (typeof this._currentConnector[method] === "function") {
9371
+ return this._currentConnector[method](...args);
9372
+ }
9373
+ return void 0;
9374
+ }
9375
+ /**
9376
+ * Create a method for each method proxy that is available on the Common interface
9377
+ * and call the method from the current connector.
9378
+ */
9379
+ setupMethods() {
9380
+ Object.values(FuelConnectorMethods).forEach((method) => {
9381
+ this[method] = async (...args) => this.callMethod(method, ...args);
9382
+ });
9383
+ }
9384
+ /**
9385
+ * Fetch the status of a connector and set the installed and connected
9386
+ * status.
9387
+ */
9388
+ async fetchConnectorStatus(connector) {
9389
+ const requestTimestamp = Date.now();
9390
+ const [isConnected, ping] = await Promise.allSettled([
9391
+ withTimeout(connector.isConnected()),
9392
+ withTimeout(this.pingConnector(connector))
9393
+ ]);
9394
+ const isStale = requestTimestamp < (connector._latestUpdate || 0);
9395
+ if (!isStale) {
9396
+ connector._latestUpdate = Date.now();
9397
+ connector.installed = ping.status === "fulfilled" && ping.value;
9398
+ connector.connected = isConnected.status === "fulfilled" && isConnected.value;
9399
+ }
9400
+ return {
9401
+ installed: connector.installed,
9402
+ connected: connector.connected
9403
+ };
9404
+ }
9405
+ /**
9406
+ * Fetch the status of all connectors and set the installed and connected
9407
+ * status.
9408
+ */
9409
+ async fetchConnectorsStatus() {
9410
+ return Promise.all(
9411
+ this._connectors.map(async (connector) => this.fetchConnectorStatus(connector))
9412
+ );
9413
+ }
9414
+ /**
9415
+ * Fetch the status of a connector and set the installed and connected
9416
+ * status. If no connector is provided it will ping the current connector.
9417
+ */
9418
+ async pingConnector(connector) {
9419
+ const curConnector = connector || this._currentConnector;
9420
+ if (!curConnector) {
9421
+ return false;
9422
+ }
9423
+ try {
9424
+ return await cacheFor(async () => withTimeout(curConnector.ping()), {
9425
+ key: curConnector.name,
9426
+ cache: this._pingCache,
9427
+ cacheTime: PING_CACHE_TIME
9428
+ })();
9429
+ } catch {
9430
+ throw new Error("Current connector is not available.");
9431
+ }
9432
+ }
9433
+ /**
9434
+ * Setup a listener for the FuelConnector event and add the connector
9435
+ * to the list of new connectors.
9436
+ */
9437
+ setupConnectorListener = () => {
9438
+ const { _targetObject: targetObject } = this;
9439
+ const eventName = FuelConnectorEventType;
9440
+ if (targetObject?.on) {
9441
+ targetObject.on(eventName, this.addConnector);
9442
+ return () => {
9443
+ targetObject.off?.(eventName, this.addConnector);
9444
+ };
9445
+ }
9446
+ if (targetObject?.addEventListener) {
9447
+ const handler = (e) => {
9448
+ this.addConnector(e.detail);
9449
+ };
9450
+ targetObject.addEventListener(eventName, handler);
9451
+ return () => {
9452
+ targetObject.removeEventListener?.(eventName, handler);
9453
+ };
9454
+ }
9455
+ return () => {
9456
+ };
9457
+ };
9458
+ /**
9459
+ * Add a new connector to the list of connectors.
9460
+ */
9461
+ addConnector = async (connector) => {
9462
+ if (!this.getConnector(connector)) {
9463
+ this._connectors.push(connector);
9464
+ }
9465
+ await this.fetchConnectorStatus(connector);
9466
+ this.emit(this.events.connectors, this._connectors);
9467
+ if (!this._currentConnector) {
9468
+ await this.selectConnector(connector.name, {
9469
+ emitEvents: false
9470
+ });
9471
+ }
9472
+ };
9473
+ triggerConnectorEvents = async () => {
9474
+ const [isConnected, networks, currentNetwork] = await Promise.all([
9475
+ this.isConnected(),
9476
+ this.networks(),
9477
+ this.currentNetwork()
9478
+ ]);
9479
+ this.emit(this.events.connection, isConnected);
9480
+ this.emit(this.events.networks, networks);
9481
+ this.emit(this.events.currentNetwork, currentNetwork);
9482
+ if (isConnected) {
9483
+ const [accounts, currentAccount] = await Promise.all([
9484
+ this.accounts(),
9485
+ this.currentAccount()
9486
+ ]);
9487
+ this.emit(this.events.accounts, accounts);
9488
+ this.emit(this.events.currentAccount, currentAccount);
9489
+ }
9490
+ };
9491
+ /**
9492
+ * Get a connector from the list of connectors.
9493
+ */
9494
+ getConnector = (connector) => this._connectors.find((c) => {
9495
+ const connectorName = typeof connector === "string" ? connector : connector.name;
9496
+ return c.name === connectorName || c === connector;
9497
+ }) || null;
9498
+ /**
9499
+ * Return the list of connectors with the status of installed and connected.
9500
+ */
9501
+ async connectors() {
9502
+ await this.fetchConnectorsStatus();
9503
+ return this._connectors;
9504
+ }
9505
+ /**
9506
+ * Set the current connector to be used.
9507
+ */
9508
+ async selectConnector(connectorName, options = {
9509
+ emitEvents: true
9510
+ }) {
9511
+ const connector = this.getConnector(connectorName);
9512
+ if (!connector) {
9513
+ return false;
9514
+ }
9515
+ if (this._currentConnector?.name === connectorName) {
9516
+ return true;
9517
+ }
9518
+ const { installed } = await this.fetchConnectorStatus(connector);
9519
+ if (installed) {
9520
+ this._currentConnector = connector;
9521
+ this.emit(this.events.currentConnector, connector);
9522
+ this.setupConnectorEvents(Object.values(FuelConnectorEventTypes));
9523
+ this._storage?.setItem(_Fuel.STORAGE_KEY, connector.name);
9524
+ if (options.emitEvents) {
9525
+ this.triggerConnectorEvents();
9526
+ }
9527
+ return true;
9528
+ }
9529
+ return false;
9530
+ }
9531
+ /**
9532
+ * Return the current selected connector.
9533
+ */
9534
+ currentConnector() {
9535
+ return this._currentConnector;
9536
+ }
9537
+ /**
9538
+ * Return true if any connector is available.
9539
+ */
9540
+ async hasConnector() {
9541
+ if (this._currentConnector) {
9542
+ return true;
9543
+ }
9544
+ const defer = deferPromise();
9545
+ this.once(this.events.currentConnector, () => {
9546
+ defer.resolve(true);
9547
+ });
9548
+ return withTimeout(defer.promise, HAS_CONNECTOR_TIMEOUT).then(() => true).catch(() => false);
9549
+ }
9550
+ async hasWallet() {
9551
+ return this.hasConnector();
9552
+ }
9553
+ /**
9554
+ * Return a Fuel Provider instance with extends features to work with
9555
+ * connectors.
9556
+ *
9557
+ * @deprecated Provider is going to be deprecated in the future.
9558
+ */
9559
+ async getProvider(providerOrNetwork) {
9560
+ if (process.env.NODE_ENV !== "production") {
9561
+ console.warn(
9562
+ "Get provider is deprecated, use getWallet instead. Provider is going to be removed in the future."
9563
+ );
9564
+ }
9565
+ return this._getProvider(providerOrNetwork);
9566
+ }
9567
+ /**
9568
+ * Return a Fuel Provider instance with extends features to work with
9569
+ * connectors.
9570
+ */
9571
+ async _getProvider(providerOrNetwork) {
9572
+ let provider;
9573
+ if (providerOrNetwork && "getTransactionResponse" in providerOrNetwork) {
9574
+ provider = providerOrNetwork;
9575
+ } else if (providerOrNetwork && "chainId" in providerOrNetwork && "url" in providerOrNetwork) {
9576
+ provider = await FuelWalletProvider.create(providerOrNetwork.url);
9577
+ } else if (!providerOrNetwork) {
9578
+ const currentNetwork = await this.currentNetwork();
9579
+ provider = await FuelWalletProvider.create(currentNetwork.url);
9580
+ } else {
9581
+ throw new Error("Provider is not valid.");
9582
+ }
9583
+ return provider;
9584
+ }
9585
+ /**
9586
+ * Return a Fuel Wallet Locked instance with extends features to work with
9587
+ * connectors.
9588
+ */
9589
+ async getWallet(address, providerOrNetwork) {
9590
+ const provider = await this._getProvider(providerOrNetwork);
9591
+ return new FuelWalletLocked(address, this, provider);
9592
+ }
9593
+ /**
9594
+ * Remove all open listeners this is useful when you want to
9595
+ * remove the Fuel instance and avoid memory leaks.
9596
+ */
9597
+ unsubscribe() {
9598
+ this._unsubscribes.map((unSub) => unSub());
9599
+ this._targetUnsubscribe();
9600
+ this.removeAllListeners();
9601
+ }
9602
+ /**
9603
+ * Clean all the data from the storage.
9604
+ */
9605
+ clean() {
9606
+ this._storage?.removeItem(_Fuel.STORAGE_KEY);
9607
+ }
9608
+ /**
9609
+ * Removes all listeners and cleans the storage.
9610
+ */
9611
+ destroy() {
9612
+ this.unsubscribe();
9613
+ this.clean();
9614
+ }
9615
+ };
9616
+ var Fuel = _Fuel;
9617
+ __publicField(Fuel, "STORAGE_KEY", "fuel-current-connector");
9618
+ __publicField(Fuel, "defaultConfig", {});
8623
9619
  // Annotate the CommonJS export names for ESM import in node:
8624
9620
  0 && (module.exports = {
8625
9621
  Account,
8626
9622
  AddressType,
9623
+ BACKGROUND_SCRIPT_NAME,
8627
9624
  BaseTransactionRequest,
8628
9625
  BaseWalletUnlocked,
9626
+ CONNECTOR_SCRIPT,
9627
+ CONTENT_SCRIPT_NAME,
8629
9628
  ChainName,
8630
9629
  ChangeOutputCollisionError,
8631
9630
  CreateTransactionRequest,
9631
+ EVENT_MESSAGE,
9632
+ Fuel,
9633
+ FuelConnector,
9634
+ FuelConnectorEventType,
9635
+ FuelConnectorEventTypes,
9636
+ FuelConnectorMethods,
9637
+ FuelWalletConnector,
9638
+ FuelWalletDevelopmentConnector,
9639
+ FuelWalletLocked,
9640
+ FuelWalletProvider,
9641
+ FueletWalletConnector,
8632
9642
  HDWallet,
8633
9643
  Language,
8634
9644
  MNEMONIC_SIZES,
9645
+ MessageTypes,
8635
9646
  Mnemonic,
8636
9647
  NoWitnessAtIndexError,
8637
9648
  NoWitnessByOwnerError,
8638
9649
  OperationName,
9650
+ POPUP_SCRIPT_NAME,
8639
9651
  Predicate,
8640
9652
  Provider,
8641
9653
  ScriptTransactionRequest,
@@ -8645,6 +9657,7 @@ var Predicate = class extends Account {
8645
9657
  TransactionStatus,
8646
9658
  TransactionType,
8647
9659
  TransactionTypeName,
9660
+ VAULT_SCRIPT_NAME,
8648
9661
  Vault,
8649
9662
  Wallet,
8650
9663
  WalletLocked,
@@ -8655,11 +9668,15 @@ var Predicate = class extends Account {
8655
9668
  assembleReceiptByType,
8656
9669
  assembleTransactionSummary,
8657
9670
  buildBlockExplorerUrl,
9671
+ cacheFor,
8658
9672
  calculateMetadataGasForTxCreate,
8659
9673
  calculateMetadataGasForTxScript,
8660
9674
  calculatePriceWithFactor,
8661
9675
  calculateTransactionFee,
8662
9676
  coinQuantityfy,
9677
+ defaultConnectors,
9678
+ deferPromise,
9679
+ dispatchFuelConnectorEvent,
8663
9680
  english,
8664
9681
  extractBurnedAssetsFromReceipts,
8665
9682
  extractMintedAssetsFromReceipts,
@@ -8668,6 +9685,7 @@ var Predicate = class extends Account {
8668
9685
  fromTai64ToUnix,
8669
9686
  fromUnixToTai64,
8670
9687
  gasUsedByInputs,
9688
+ getAssetByChain,
8671
9689
  getContractCallOperations,
8672
9690
  getContractCreatedOperations,
8673
9691
  getContractTransferOperations,
@@ -8723,6 +9741,7 @@ var Predicate = class extends Account {
8723
9741
  returnZeroScript,
8724
9742
  sleep,
8725
9743
  transactionRequestify,
9744
+ withTimeout,
8726
9745
  withdrawScript
8727
9746
  });
8728
9747
  //# sourceMappingURL=index.js.map