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