@tonconnect/sdk 3.4.0-beta.0 → 3.4.0-beta.2

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/lib/esm/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { CONNECT_EVENT_ERROR_CODES, SEND_TRANSACTION_ERROR_CODES, SIGN_DATA_ERROR_CODES, Base64, SessionCrypto, hexToByteArray, CONNECT_ITEM_ERROR_CODES } from '@tonconnect/protocol';
1
+ import { CONNECT_EVENT_ERROR_CODES, SEND_TRANSACTION_ERROR_CODES, SIGN_DATA_ERROR_CODES, Base64, SessionCrypto, hexToByteArray, DISCONNECT_ERROR_CODES, CONNECT_ITEM_ERROR_CODES } from '@tonconnect/protocol';
2
2
  export { CHAIN, CONNECT_EVENT_ERROR_CODES, CONNECT_ITEM_ERROR_CODES, SEND_TRANSACTION_ERROR_CODES, SIGN_DATA_ERROR_CODES, SessionCrypto } from '@tonconnect/protocol';
3
3
  import '@tonconnect/isomorphic-eventsource';
4
4
  import '@tonconnect/isomorphic-fetch';
@@ -166,9 +166,20 @@ class WalletMissingRequiredFeaturesError extends TonConnectError {
166
166
  }
167
167
  }
168
168
 
169
+ class WalletWrongNetworkError extends TonConnectError {
170
+ constructor(message, options) {
171
+ super(message, options);
172
+ this.name = 'WalletWrongNetworkError';
173
+ Object.setPrototypeOf(this, WalletWrongNetworkError.prototype);
174
+ }
175
+ }
176
+
169
177
  function isWalletConnectionSourceJS(value) {
170
178
  return 'jsBridgeKey' in value;
171
179
  }
180
+ function isWalletConnectionSourceWalletConnect(value) {
181
+ return 'type' in value && value.type === 'wallet-connect';
182
+ }
172
183
 
173
184
  /**
174
185
  * Thrown when user rejects the action in the wallet.
@@ -912,7 +923,7 @@ class BridgeConnectionStorage {
912
923
  }
913
924
  storeConnection(connection) {
914
925
  return __awaiter(this, void 0, void 0, function* () {
915
- if (connection.type === 'injected') {
926
+ if (connection.type === 'injected' || connection.type === 'wallet-connect') {
916
927
  return this.storage.setItem(this.storeKey, JSON.stringify(connection));
917
928
  }
918
929
  if (!isPendingConnectionHttp(connection)) {
@@ -951,7 +962,7 @@ class BridgeConnectionStorage {
951
962
  return null;
952
963
  }
953
964
  const connection = JSON.parse(stored);
954
- if (connection.type === 'injected') {
965
+ if (connection.type === 'injected' || connection.type === 'wallet-connect') {
955
966
  return connection;
956
967
  }
957
968
  if (!isPendingConnectionHttpRaw(connection)) {
@@ -985,8 +996,8 @@ class BridgeConnectionStorage {
985
996
  if (!connection) {
986
997
  throw new TonConnectError('Trying to read HTTP connection source while nothing is stored');
987
998
  }
988
- if (connection.type === 'injected') {
989
- throw new TonConnectError('Trying to read HTTP connection source while injected connection is stored');
999
+ if (connection.type !== 'http') {
1000
+ throw new TonConnectError(`Trying to read HTTP connection source while ${connection.type} connection is stored`);
990
1001
  }
991
1002
  return connection;
992
1003
  });
@@ -997,8 +1008,8 @@ class BridgeConnectionStorage {
997
1008
  if (!connection) {
998
1009
  throw new TonConnectError('Trying to read HTTP connection source while nothing is stored');
999
1010
  }
1000
- if (connection.type === 'injected') {
1001
- throw new TonConnectError('Trying to read HTTP connection source while injected connection is stored');
1011
+ if (connection.type !== 'http') {
1012
+ throw new TonConnectError(`Trying to read HTTP connection source while ${connection.type} connection is stored`);
1002
1013
  }
1003
1014
  if (!isPendingConnectionHttp(connection)) {
1004
1015
  throw new TonConnectError('Trying to read HTTP-pending connection while http connection is stored');
@@ -1012,8 +1023,20 @@ class BridgeConnectionStorage {
1012
1023
  if (!connection) {
1013
1024
  throw new TonConnectError('Trying to read Injected bridge connection source while nothing is stored');
1014
1025
  }
1015
- if ((connection === null || connection === void 0 ? void 0 : connection.type) === 'http') {
1016
- throw new TonConnectError('Trying to read Injected bridge connection source while HTTP connection is stored');
1026
+ if ((connection === null || connection === void 0 ? void 0 : connection.type) !== 'injected') {
1027
+ throw new TonConnectError(`Trying to read Injected bridge connection source while ${connection.type} connection is stored`);
1028
+ }
1029
+ return connection;
1030
+ });
1031
+ }
1032
+ getWalletConnectConnection() {
1033
+ return __awaiter(this, void 0, void 0, function* () {
1034
+ const connection = yield this.getConnection();
1035
+ if (!connection) {
1036
+ throw new TonConnectError('Trying to read wallet connect bridge connection source while nothing is stored');
1037
+ }
1038
+ if ((connection === null || connection === void 0 ? void 0 : connection.type) !== 'wallet-connect') {
1039
+ throw new TonConnectError(`Trying to read wallet connect bridge connection source while ${connection.type} connection is stored`);
1017
1040
  }
1018
1041
  return connection;
1019
1042
  });
@@ -3783,7 +3806,7 @@ class TonConnectTracker {
3783
3806
  }
3784
3807
  }
3785
3808
 
3786
- const tonConnectSdkVersion = "3.4.0-beta.0";
3809
+ const tonConnectSdkVersion = "3.4.0-beta.2";
3787
3810
 
3788
3811
  const bounceableTag = 0x11;
3789
3812
  const noBounceableTag = 0x51;
@@ -3837,6 +3860,9 @@ function isValidRawAddress(address) {
3837
3860
  return false;
3838
3861
  }
3839
3862
  }
3863
+ function toRawAddress({ wc, hex }) {
3864
+ return `${wc}:${hex}`;
3865
+ }
3840
3866
  /**
3841
3867
  * Parses user-friendly address and returns its components.
3842
3868
  * @param address user-friendly address
@@ -4679,6 +4705,518 @@ class DefaultEnvironment {
4679
4705
  }
4680
4706
  }
4681
4707
 
4708
+ const state = {};
4709
+ /**
4710
+ * Initializes the WalletConnect integration.
4711
+ *
4712
+ * This function must be called once before using WalletConnect features.
4713
+ * A second call will throw an error to prevent accidental re-initialization.
4714
+ *
4715
+ * @param UniversalConnectorCls - A UniversalConnector class imported from '@reown/appkit-universal-connector'
4716
+ * @param {WalletConnectOptions} walletConnectOptions - Configuration options used for initializing WalletConnect.
4717
+ * @example
4718
+ * import { UniversalConnector } from '@reown/appkit-universal-connector';
4719
+ *
4720
+ * initializeWalletConnect(UniversalConnector, {
4721
+ * projectId: 'abcd1234abcd1234abcd1234abcd1234',
4722
+ * metadata: {
4723
+ * name: 'Demo DApp',
4724
+ * icons: [
4725
+ * 'https://example.com/my-icon.png'
4726
+ * ],
4727
+ * url: window.location.origin,
4728
+ * description: 'Demo DApp'
4729
+ * }
4730
+ * });
4731
+ */
4732
+ function initializeWalletConnect(UniversalConnectorCls, walletConnectOptions) {
4733
+ if ((state === null || state === void 0 ? void 0 : state.walletConnectOptions) !== undefined || (state === null || state === void 0 ? void 0 : state.UniversalConnectorCls) !== undefined) {
4734
+ throw new TonConnectError('Wallet Connect already initialized.');
4735
+ }
4736
+ if (typeof UniversalConnectorCls !== 'function' || !('init' in UniversalConnectorCls)) {
4737
+ throw new TonConnectError('Initialize UniversalConnectorCls must be set');
4738
+ }
4739
+ state.UniversalConnectorCls = UniversalConnectorCls;
4740
+ state.walletConnectOptions = walletConnectOptions;
4741
+ }
4742
+ function isWalletConnectInitialized() {
4743
+ return state.UniversalConnectorCls !== undefined && state.walletConnectOptions !== undefined;
4744
+ }
4745
+ function getUniversalConnector() {
4746
+ if (state.UniversalConnectorCls === undefined) {
4747
+ throw new TonConnectError('Wallet Connect is not initialized.');
4748
+ }
4749
+ return state.UniversalConnectorCls;
4750
+ }
4751
+ function getWalletConnectOptions() {
4752
+ if (state.walletConnectOptions === undefined) {
4753
+ throw new TonConnectError('Wallet Connect is not initialized.');
4754
+ }
4755
+ return state.walletConnectOptions;
4756
+ }
4757
+
4758
+ const DEFAULT_REQUEST_ID = '0';
4759
+ const DEFAULT_EVENT_ID = 0;
4760
+ class WalletConnectProvider {
4761
+ constructor(storage) {
4762
+ this.type = 'injected';
4763
+ this.listeners = [];
4764
+ this.connector = undefined;
4765
+ this.connectionStorage = new BridgeConnectionStorage(storage);
4766
+ const { projectId, metadata } = getWalletConnectOptions();
4767
+ this.config = {
4768
+ networks: [
4769
+ {
4770
+ namespace: 'ton',
4771
+ chains: [
4772
+ {
4773
+ id: -239,
4774
+ chainNamespace: 'ton',
4775
+ caipNetworkId: 'ton:-239',
4776
+ name: 'TON',
4777
+ nativeCurrency: { name: 'TON', symbol: 'TON', decimals: 9 },
4778
+ rpcUrls: { default: { http: [] } }
4779
+ },
4780
+ {
4781
+ id: -3,
4782
+ chainNamespace: 'ton',
4783
+ caipNetworkId: 'ton:-3',
4784
+ name: 'TON',
4785
+ nativeCurrency: { name: 'TON', symbol: 'TON', decimals: 9 },
4786
+ rpcUrls: { default: { http: [] } }
4787
+ }
4788
+ ],
4789
+ methods: ['ton_sendMessage', 'ton_signData'],
4790
+ events: []
4791
+ }
4792
+ ],
4793
+ projectId,
4794
+ metadata
4795
+ };
4796
+ }
4797
+ static fromStorage(storage) {
4798
+ return __awaiter(this, void 0, void 0, function* () {
4799
+ return new WalletConnectProvider(storage);
4800
+ });
4801
+ }
4802
+ initialize() {
4803
+ return __awaiter(this, void 0, void 0, function* () {
4804
+ if (!this.connector) {
4805
+ this.connector = yield getUniversalConnector().init(this.config);
4806
+ }
4807
+ return this.connector;
4808
+ });
4809
+ }
4810
+ connect(message, options) {
4811
+ var _a, _b;
4812
+ const traceId = (_a = options === null || options === void 0 ? void 0 : options.traceId) !== null && _a !== void 0 ? _a : UUIDv7();
4813
+ const abortController = createAbortController(options === null || options === void 0 ? void 0 : options.signal);
4814
+ (_b = this.abortController) === null || _b === void 0 ? void 0 : _b.abort();
4815
+ this.abortController = abortController;
4816
+ void this._connect(message, {
4817
+ traceId,
4818
+ signal: abortController.signal,
4819
+ abortController
4820
+ }).catch(error => logDebug('WalletConnect connect unexpected error', error));
4821
+ }
4822
+ _connect(message, options) {
4823
+ return __awaiter(this, void 0, void 0, function* () {
4824
+ var _a, _b;
4825
+ const connector = yield this.initialize();
4826
+ if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
4827
+ logDebug('WalletConnect connect aborted before start');
4828
+ this.clearAbortController(options.abortController);
4829
+ return;
4830
+ }
4831
+ const tonProof = message.items.find(item => item.name === 'ton_proof');
4832
+ const authentication = tonProof
4833
+ ? [
4834
+ {
4835
+ domain: new URL(this.config.metadata.url).hostname,
4836
+ chains: ['ton:-239'],
4837
+ nonce: '',
4838
+ uri: 'ton_proof',
4839
+ ttl: 0,
4840
+ statement: tonProof.payload
4841
+ }
4842
+ ]
4843
+ : undefined;
4844
+ logDebug('Connecting through this.connector.connect');
4845
+ try {
4846
+ yield connector.connect({ authentication });
4847
+ }
4848
+ catch (error) {
4849
+ if ((_b = options.signal) === null || _b === void 0 ? void 0 : _b.aborted) {
4850
+ logDebug('WalletConnect connect aborted via signal');
4851
+ this.clearAbortController(options.abortController);
4852
+ return;
4853
+ }
4854
+ logDebug('WalletConnect connect error', error);
4855
+ const event = {
4856
+ id: DEFAULT_EVENT_ID,
4857
+ event: 'connect_error',
4858
+ traceId: options.traceId,
4859
+ payload: {
4860
+ code: CONNECT_EVENT_ERROR_CODES.USER_REJECTS_ERROR,
4861
+ message: 'User declined the connection'
4862
+ }
4863
+ };
4864
+ logDebug('WalletConnect connect response:', event);
4865
+ this.emit(event);
4866
+ this.clearAbortController(options.abortController);
4867
+ return;
4868
+ }
4869
+ logDebug('Connected through this.connector.connect');
4870
+ try {
4871
+ yield this.onConnect(connector, Object.assign(Object.assign({}, options), { includeTonProof: true }));
4872
+ }
4873
+ catch (error) {
4874
+ logDebug('WalletConnect onConnect error', error);
4875
+ yield this.disconnect({ traceId: options.traceId, signal: options.signal });
4876
+ }
4877
+ finally {
4878
+ this.clearAbortController(options.abortController);
4879
+ }
4880
+ });
4881
+ }
4882
+ restoreConnection(options) {
4883
+ return __awaiter(this, void 0, void 0, function* () {
4884
+ var _a, _b;
4885
+ const traceId = (_a = options === null || options === void 0 ? void 0 : options.traceId) !== null && _a !== void 0 ? _a : UUIDv7();
4886
+ const abortController = createAbortController(options === null || options === void 0 ? void 0 : options.signal);
4887
+ (_b = this.abortController) === null || _b === void 0 ? void 0 : _b.abort();
4888
+ this.abortController = abortController;
4889
+ if (abortController.signal.aborted) {
4890
+ return;
4891
+ }
4892
+ try {
4893
+ logDebug('Restoring WalletConnect connection...');
4894
+ const storedConnection = yield this.connectionStorage.getWalletConnectConnection();
4895
+ if (!storedConnection || abortController.signal.aborted) {
4896
+ return;
4897
+ }
4898
+ const connector = yield this.initialize();
4899
+ if (abortController.signal.aborted) {
4900
+ return;
4901
+ }
4902
+ yield this.onConnect(connector, {
4903
+ includeTonProof: false,
4904
+ traceId,
4905
+ signal: abortController.signal
4906
+ });
4907
+ logDebug('WalletConnect successfully restored.');
4908
+ }
4909
+ catch (error) {
4910
+ logDebug('WalletConnect restore error', error);
4911
+ yield this.disconnect({ traceId, signal: abortController.signal });
4912
+ }
4913
+ finally {
4914
+ this.clearAbortController(abortController);
4915
+ }
4916
+ });
4917
+ }
4918
+ closeConnection() {
4919
+ var _a;
4920
+ (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
4921
+ this.abortController = undefined;
4922
+ void this.disconnect();
4923
+ }
4924
+ disconnect(options) {
4925
+ return __awaiter(this, void 0, void 0, function* () {
4926
+ var _a, _b;
4927
+ const abortController = createAbortController(options === null || options === void 0 ? void 0 : options.signal);
4928
+ (_a = this.abortController) === null || _a === void 0 ? void 0 : _a.abort();
4929
+ this.abortController = abortController;
4930
+ if (abortController.signal.aborted) {
4931
+ return;
4932
+ }
4933
+ try {
4934
+ yield this.connectionStorage.removeConnection();
4935
+ if (abortController.signal.aborted) {
4936
+ return;
4937
+ }
4938
+ yield ((_b = this.connector) === null || _b === void 0 ? void 0 : _b.disconnect());
4939
+ }
4940
+ catch (error) {
4941
+ logDebug('WalletConnect disconnect error', error);
4942
+ }
4943
+ finally {
4944
+ this.clearAbortController(abortController);
4945
+ }
4946
+ });
4947
+ }
4948
+ sendRequest(request, optionsOrOnRequestSent) {
4949
+ return __awaiter(this, void 0, void 0, function* () {
4950
+ var _a, _b, _c, _d;
4951
+ if (!this.connector) {
4952
+ throw new TonConnectError('Wallet Connect not initialized');
4953
+ }
4954
+ const options = {};
4955
+ if (typeof optionsOrOnRequestSent === 'function') {
4956
+ options.onRequestSent = optionsOrOnRequestSent;
4957
+ }
4958
+ else {
4959
+ options.onRequestSent = optionsOrOnRequestSent === null || optionsOrOnRequestSent === void 0 ? void 0 : optionsOrOnRequestSent.onRequestSent;
4960
+ options.signal = optionsOrOnRequestSent === null || optionsOrOnRequestSent === void 0 ? void 0 : optionsOrOnRequestSent.signal;
4961
+ options.attempts = optionsOrOnRequestSent === null || optionsOrOnRequestSent === void 0 ? void 0 : optionsOrOnRequestSent.attempts;
4962
+ options.traceId = optionsOrOnRequestSent === null || optionsOrOnRequestSent === void 0 ? void 0 : optionsOrOnRequestSent.traceId;
4963
+ }
4964
+ (_a = options.traceId) !== null && _a !== void 0 ? _a : (options.traceId = UUIDv7());
4965
+ try {
4966
+ if ((_b = options.signal) === null || _b === void 0 ? void 0 : _b.aborted) {
4967
+ throw new TonConnectError('WalletConnect request aborted');
4968
+ }
4969
+ logDebug('Send wallet-connect request:', Object.assign(Object.assign({}, request), { id: DEFAULT_REQUEST_ID }));
4970
+ if (request.method === 'sendTransaction') {
4971
+ const _e = JSON.parse(request.params[0]), { network } = _e, sendTransactionPayload = __rest(_e, ["network"]);
4972
+ const promise = this.connector.request({
4973
+ method: 'ton_sendMessage',
4974
+ params: sendTransactionPayload
4975
+ }, `ton:${network}`);
4976
+ (_c = options === null || options === void 0 ? void 0 : options.onRequestSent) === null || _c === void 0 ? void 0 : _c.call(options);
4977
+ const result = (yield promise);
4978
+ logDebug('Wallet message received:', { result, id: DEFAULT_REQUEST_ID });
4979
+ return {
4980
+ result,
4981
+ id: DEFAULT_REQUEST_ID,
4982
+ traceId: options.traceId
4983
+ };
4984
+ }
4985
+ else if (request.method === 'signData') {
4986
+ const _f = JSON.parse(request.params[0]), { network } = _f, signDataPayload = __rest(_f, ["network"]);
4987
+ const promise = this.connector.request({
4988
+ method: 'ton_signData',
4989
+ params: signDataPayload
4990
+ }, `ton:${network}`);
4991
+ (_d = options === null || options === void 0 ? void 0 : options.onRequestSent) === null || _d === void 0 ? void 0 : _d.call(options);
4992
+ const result = (yield promise);
4993
+ logDebug('Wallet message received:', { result, id: DEFAULT_REQUEST_ID });
4994
+ return { result, traceId: options.traceId, id: DEFAULT_REQUEST_ID };
4995
+ }
4996
+ else if (request.method === 'disconnect') {
4997
+ return {
4998
+ id: DEFAULT_REQUEST_ID,
4999
+ traceId: options.traceId
5000
+ };
5001
+ }
5002
+ }
5003
+ catch (error) {
5004
+ logDebug('WalletConnect request error', error, error.stack);
5005
+ const result = (yield this.handleWalletConnectError(error, {
5006
+ traceId: options.traceId
5007
+ }));
5008
+ logDebug('Wallet message received:', result);
5009
+ return result;
5010
+ }
5011
+ return {
5012
+ id: DEFAULT_REQUEST_ID,
5013
+ error: { code: DISCONNECT_ERROR_CODES.UNKNOWN_ERROR, message: 'Not implemented.' },
5014
+ traceId: options.traceId
5015
+ };
5016
+ });
5017
+ }
5018
+ handleWalletConnectError(error, options) {
5019
+ return __awaiter(this, void 0, void 0, function* () {
5020
+ if (typeof error === 'object' && error !== null) {
5021
+ const message = String('message' in error ? error.message : 'msg' in error ? error.msg : error);
5022
+ if (message.toLowerCase().includes('reject')) {
5023
+ return {
5024
+ id: DEFAULT_REQUEST_ID,
5025
+ traceId: options.traceId,
5026
+ error: {
5027
+ code: SEND_TRANSACTION_ERROR_CODES.USER_REJECTS_ERROR,
5028
+ message
5029
+ }
5030
+ };
5031
+ }
5032
+ if (message.toLowerCase().includes('tonvalidationerror')) {
5033
+ return {
5034
+ id: DEFAULT_REQUEST_ID,
5035
+ traceId: options.traceId,
5036
+ error: {
5037
+ code: SEND_TRANSACTION_ERROR_CODES.BAD_REQUEST_ERROR,
5038
+ message
5039
+ }
5040
+ };
5041
+ }
5042
+ return {
5043
+ id: DEFAULT_REQUEST_ID,
5044
+ traceId: options.traceId,
5045
+ error: {
5046
+ code: SEND_TRANSACTION_ERROR_CODES.UNKNOWN_ERROR,
5047
+ message
5048
+ }
5049
+ };
5050
+ }
5051
+ return {
5052
+ id: DEFAULT_REQUEST_ID,
5053
+ traceId: options.traceId,
5054
+ error: {
5055
+ code: SEND_TRANSACTION_ERROR_CODES.UNKNOWN_ERROR,
5056
+ message: String(error)
5057
+ }
5058
+ };
5059
+ });
5060
+ }
5061
+ listen(callback) {
5062
+ this.listeners.push(callback);
5063
+ return () => (this.listeners = this.listeners.filter(listener => listener !== callback));
5064
+ }
5065
+ buildTonProof(connector) {
5066
+ var _a, _b, _c;
5067
+ const auth = (_a = connector.provider.session.authentication) === null || _a === void 0 ? void 0 : _a[0];
5068
+ const iat = (_b = auth === null || auth === void 0 ? void 0 : auth.p) === null || _b === void 0 ? void 0 : _b.iat;
5069
+ const statement = (_c = auth === null || auth === void 0 ? void 0 : auth.p) === null || _c === void 0 ? void 0 : _c.statement;
5070
+ if (!iat || !statement) {
5071
+ return;
5072
+ }
5073
+ const domain = auth.p.domain;
5074
+ return {
5075
+ name: 'ton_proof',
5076
+ proof: {
5077
+ timestamp: Math.floor(new Date(iat).getTime() / 1000),
5078
+ domain: {
5079
+ lengthBytes: domain.length,
5080
+ value: domain
5081
+ },
5082
+ payload: statement,
5083
+ signature: auth.s.s
5084
+ }
5085
+ };
5086
+ }
5087
+ onConnect(connector, options) {
5088
+ return __awaiter(this, void 0, void 0, function* () {
5089
+ var _a, _b, _c, _d;
5090
+ if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) {
5091
+ logDebug('WalletConnect onConnect aborted');
5092
+ return;
5093
+ }
5094
+ const session = connector.provider.session;
5095
+ const tonNamespace = session.namespaces['ton'];
5096
+ if (!((_b = tonNamespace === null || tonNamespace === void 0 ? void 0 : tonNamespace.accounts) === null || _b === void 0 ? void 0 : _b[0])) {
5097
+ yield this.disconnectWithError({
5098
+ traceId: options.traceId,
5099
+ code: CONNECT_EVENT_ERROR_CODES.BAD_REQUEST_ERROR,
5100
+ message: 'Connection error. No TON accounts connected.'
5101
+ });
5102
+ return;
5103
+ }
5104
+ const account = tonNamespace.accounts[0];
5105
+ const [, network, address] = account.split(':', 3);
5106
+ const publicKey = (_c = session.sessionProperties) === null || _c === void 0 ? void 0 : _c.ton_getPublicKey;
5107
+ if (!publicKey) {
5108
+ yield this.disconnectWithError({
5109
+ traceId: options.traceId,
5110
+ code: CONNECT_EVENT_ERROR_CODES.BAD_REQUEST_ERROR,
5111
+ message: 'Connection error. No sessionProperties.ton_getPublicKey provided.'
5112
+ });
5113
+ return;
5114
+ }
5115
+ const stateInit = (_d = session.sessionProperties) === null || _d === void 0 ? void 0 : _d.ton_getStateInit;
5116
+ if (!stateInit) {
5117
+ yield this.disconnectWithError({
5118
+ traceId: options.traceId,
5119
+ code: CONNECT_EVENT_ERROR_CODES.BAD_REQUEST_ERROR,
5120
+ message: 'Connection error. No sessionProperties.ton_getStateInit provided.'
5121
+ });
5122
+ return;
5123
+ }
5124
+ connector.provider.once('session_delete', () => __awaiter(this, void 0, void 0, function* () {
5125
+ try {
5126
+ yield this.connectionStorage.removeConnection();
5127
+ const event = {
5128
+ event: 'disconnect',
5129
+ traceId: UUIDv7(),
5130
+ payload: {}
5131
+ };
5132
+ logDebug('Wallet message received:', event);
5133
+ this.emit(event);
5134
+ }
5135
+ catch (err) {
5136
+ logDebug('Error while deleting session', err);
5137
+ }
5138
+ }));
5139
+ const tonProof = (options === null || options === void 0 ? void 0 : options.includeTonProof) ? this.buildTonProof(connector) : undefined;
5140
+ const parsedAddress = isValidUserFriendlyAddress(address)
5141
+ ? toRawAddress(parseUserFriendlyAddress(address))
5142
+ : address;
5143
+ const features = this.buildFeatureList(tonNamespace.methods);
5144
+ const payload = {
5145
+ items: [
5146
+ {
5147
+ name: 'ton_addr',
5148
+ address: parsedAddress,
5149
+ network: network,
5150
+ publicKey,
5151
+ walletStateInit: stateInit
5152
+ },
5153
+ ...(tonProof ? [tonProof] : [])
5154
+ ],
5155
+ device: {
5156
+ appName: 'wallet_connect',
5157
+ appVersion: '',
5158
+ maxProtocolVersion: 2,
5159
+ features,
5160
+ platform: 'browser'
5161
+ }
5162
+ };
5163
+ logDebug('WalletConnect connect response:', {
5164
+ event: 'connect',
5165
+ payload,
5166
+ id: DEFAULT_EVENT_ID
5167
+ });
5168
+ this.emit({ event: 'connect', payload, traceId: options.traceId });
5169
+ yield this.storeConnection();
5170
+ });
5171
+ }
5172
+ buildFeatureList(methods) {
5173
+ const features = [];
5174
+ if (methods.includes('ton_sendMessage')) {
5175
+ features.push('SendTransaction', {
5176
+ name: 'SendTransaction',
5177
+ maxMessages: 4,
5178
+ extraCurrencySupported: false
5179
+ });
5180
+ }
5181
+ if (methods.includes('ton_signData')) {
5182
+ features.push({ name: 'SignData', types: ['text', 'binary', 'cell'] });
5183
+ }
5184
+ return features;
5185
+ }
5186
+ disconnectWithError(options) {
5187
+ return __awaiter(this, void 0, void 0, function* () {
5188
+ yield this.disconnect();
5189
+ const payload = {
5190
+ code: options.code,
5191
+ message: options.message
5192
+ };
5193
+ logDebug('WalletConnect connect response:', {
5194
+ event: 'connect_error',
5195
+ id: DEFAULT_EVENT_ID,
5196
+ payload
5197
+ });
5198
+ this.emit({
5199
+ event: 'connect_error',
5200
+ traceId: options.traceId,
5201
+ payload
5202
+ });
5203
+ });
5204
+ }
5205
+ clearAbortController(abortController) {
5206
+ if (this.abortController === abortController) {
5207
+ this.abortController = undefined;
5208
+ }
5209
+ }
5210
+ emit(event, listeners) {
5211
+ (listeners !== null && listeners !== void 0 ? listeners : this.listeners).forEach(listener => listener(event));
5212
+ }
5213
+ storeConnection() {
5214
+ return this.connectionStorage.storeConnection({
5215
+ type: 'wallet-connect'
5216
+ });
5217
+ }
5218
+ }
5219
+
4682
5220
  class TonConnect {
4683
5221
  /**
4684
5222
  * Returns available wallets list.
@@ -4781,10 +5319,13 @@ class TonConnect {
4781
5319
  var _a, _b, _c;
4782
5320
  // TODO: remove deprecated method
4783
5321
  const options = Object.assign({}, additionalOptions);
4784
- if (typeof requestOrOptions === 'object' && 'tonProof' in requestOrOptions) {
5322
+ if (typeof requestOrOptions === 'object' &&
5323
+ requestOrOptions !== null &&
5324
+ 'tonProof' in requestOrOptions) {
4785
5325
  options.request = requestOrOptions;
4786
5326
  }
4787
5327
  if (typeof requestOrOptions === 'object' &&
5328
+ requestOrOptions !== null &&
4788
5329
  ('openingDeadlineMS' in requestOrOptions ||
4789
5330
  'signal' in requestOrOptions ||
4790
5331
  'request' in requestOrOptions ||
@@ -4861,6 +5402,9 @@ class TonConnect {
4861
5402
  case 'injected':
4862
5403
  provider = yield InjectedProvider.fromStorage(this.dappSettings.storage, this.analytics);
4863
5404
  break;
5405
+ case 'wallet-connect':
5406
+ provider = yield WalletConnectProvider.fromStorage(this.dappSettings.storage);
5407
+ break;
4864
5408
  default:
4865
5409
  if (embeddedWallet) {
4866
5410
  provider = this.createProvider(embeddedWallet);
@@ -4870,7 +5414,8 @@ class TonConnect {
4870
5414
  }
4871
5415
  }
4872
5416
  }
4873
- catch (_d) {
5417
+ catch (err) {
5418
+ logDebug('Provider is not restored', err);
4874
5419
  this.tracker.trackConnectionRestoringError('Provider is not restored', traceId);
4875
5420
  yield this.bridgeConnectionStorage.removeConnection();
4876
5421
  provider === null || provider === void 0 ? void 0 : provider.closeConnection();
@@ -4922,7 +5467,7 @@ class TonConnect {
4922
5467
  }
4923
5468
  sendTransaction(transaction, optionsOrOnRequestSent) {
4924
5469
  return __awaiter(this, void 0, void 0, function* () {
4925
- var _a;
5470
+ var _a, _b, _c;
4926
5471
  // TODO: remove deprecated method
4927
5472
  const options = {};
4928
5473
  if (typeof optionsOrOnRequestSent === 'function') {
@@ -4960,6 +5505,14 @@ class TonConnect {
4960
5505
  const { validUntil, messages } = transaction, tx = __rest(transaction, ["validUntil", "messages"]);
4961
5506
  const from = transaction.from || this.account.address;
4962
5507
  const network = transaction.network || this.account.chain;
5508
+ if (((_b = this.wallet) === null || _b === void 0 ? void 0 : _b.account.chain) && network !== this.wallet.account.chain) {
5509
+ throw new WalletWrongNetworkError('Wallet connected to a wrong network', {
5510
+ cause: {
5511
+ expectedChainId: (_c = this.wallet) === null || _c === void 0 ? void 0 : _c.account.chain,
5512
+ actualChainId: network
5513
+ }
5514
+ });
5515
+ }
4963
5516
  const response = yield this.provider.sendRequest(sendTransactionParser.convertToRpcRequest(Object.assign(Object.assign({}, tx), { from,
4964
5517
  network, valid_until: validUntil, messages: messages.map((_a) => {
4965
5518
  var { extraCurrency, payload, stateInit } = _a, msg = __rest(_a, ["extraCurrency", "payload", "stateInit"]);
@@ -4980,7 +5533,7 @@ class TonConnect {
4980
5533
  }
4981
5534
  signData(data, options) {
4982
5535
  return __awaiter(this, void 0, void 0, function* () {
4983
- var _a;
5536
+ var _a, _b, _c;
4984
5537
  const abortController = createAbortController(options === null || options === void 0 ? void 0 : options.signal);
4985
5538
  if (abortController.signal.aborted) {
4986
5539
  throw new TonConnectError('data sending was aborted');
@@ -5002,6 +5555,14 @@ class TonConnect {
5002
5555
  this.tracker.trackDataSentForSignature(this.wallet, data, sessionInfo, traceId);
5003
5556
  const from = data.from || this.account.address;
5004
5557
  const network = data.network || this.account.chain;
5558
+ if (((_b = this.wallet) === null || _b === void 0 ? void 0 : _b.account.chain) && network !== this.wallet.account.chain) {
5559
+ throw new WalletWrongNetworkError('Wallet connected to a wrong network', {
5560
+ cause: {
5561
+ expectedChainId: (_c = this.wallet) === null || _c === void 0 ? void 0 : _c.account.chain,
5562
+ actualChainId: network
5563
+ }
5564
+ });
5565
+ }
5005
5566
  const response = yield this.provider.sendRequest(signDataParser.convertToRpcRequest(Object.assign(Object.assign(Object.assign({}, data), (data.type === 'cell' ? { cell: normalizeBase64(data.cell) } : {})), { from,
5006
5567
  network })), { onRequestSent: options === null || options === void 0 ? void 0 : options.onRequestSent, signal: abortController.signal, traceId });
5007
5568
  if (signDataParser.isError(response)) {
@@ -5013,6 +5574,17 @@ class TonConnect {
5013
5574
  return Object.assign(Object.assign({}, result), { traceId });
5014
5575
  });
5015
5576
  }
5577
+ /**
5578
+ * Set desired network for the connection. Can only be set before connecting.
5579
+ * If wallet connects with a different chain, the SDK will throw an error and abort connection.
5580
+ * @param network desired network id (e.g., '-239', '-3', or custom). Pass undefined to allow any network.
5581
+ */
5582
+ setConnectionNetwork(network) {
5583
+ if (this.connected) {
5584
+ throw new TonConnectError('Cannot change network while wallet is connected');
5585
+ }
5586
+ this.desiredChainId = network;
5587
+ }
5016
5588
  /**
5017
5589
  * Disconnect form thw connected wallet and drop current session.
5018
5590
  */
@@ -5048,7 +5620,7 @@ class TonConnect {
5048
5620
  }
5049
5621
  try {
5050
5622
  const connection = yield this.bridgeConnectionStorage.getConnection();
5051
- if (!connection || connection.type === 'injected') {
5623
+ if (!connection || connection.type !== 'http') {
5052
5624
  return null;
5053
5625
  }
5054
5626
  if ('sessionCrypto' in connection) {
@@ -5134,6 +5706,9 @@ class TonConnect {
5134
5706
  if (!Array.isArray(wallet) && isWalletConnectionSourceJS(wallet)) {
5135
5707
  provider = new InjectedProvider(this.dappSettings.storage, wallet.jsBridgeKey, this.analytics);
5136
5708
  }
5709
+ else if (!Array.isArray(wallet) && isWalletConnectionSourceWalletConnect(wallet)) {
5710
+ provider = new WalletConnectProvider(this.dappSettings.storage);
5711
+ }
5137
5712
  else {
5138
5713
  provider = new BridgeProvider(this.dappSettings.storage, wallet, this.analytics);
5139
5714
  }
@@ -5155,7 +5730,7 @@ class TonConnect {
5155
5730
  }
5156
5731
  }
5157
5732
  onWalletConnected(connectEvent, options) {
5158
- var _a;
5733
+ var _a, _b;
5159
5734
  const tonAccountItem = connectEvent.items.find(item => item.name === 'ton_addr');
5160
5735
  const tonProofItem = connectEvent.items.find(item => item.name === 'ton_proof');
5161
5736
  if (!tonAccountItem) {
@@ -5177,6 +5752,15 @@ class TonConnect {
5177
5752
  publicKey: tonAccountItem.publicKey
5178
5753
  }
5179
5754
  };
5755
+ if (this.desiredChainId && wallet.account.chain !== this.desiredChainId) {
5756
+ const expectedChainId = this.desiredChainId;
5757
+ const actualChainId = wallet.account.chain;
5758
+ (_b = this.provider) === null || _b === void 0 ? void 0 : _b.disconnect();
5759
+ this.onWalletConnectError(new WalletWrongNetworkError('Wallet connected to a wrong network', {
5760
+ cause: { expectedChainId, actualChainId }
5761
+ }));
5762
+ return;
5763
+ }
5180
5764
  if (tonProofItem) {
5181
5765
  const validationError = validateTonProofItemReply(tonProofItem);
5182
5766
  let tonProof = undefined;
@@ -5257,9 +5841,7 @@ class TonConnect {
5257
5841
  }
5258
5842
  createConnectRequest(request) {
5259
5843
  const items = [
5260
- {
5261
- name: 'ton_addr'
5262
- }
5844
+ Object.assign({ name: 'ton_addr' }, (this.desiredChainId ? { network: this.desiredChainId } : {}))
5263
5845
  ];
5264
5846
  if (request === null || request === void 0 ? void 0 : request.tonProof) {
5265
5847
  items.push({
@@ -5285,5 +5867,5 @@ TonConnect.isWalletInjected = (walletJSKey) => InjectedProvider.isWalletInjected
5285
5867
  */
5286
5868
  TonConnect.isInsideWalletBrowser = (walletJSKey) => InjectedProvider.isInsideWalletBrowser(walletJSKey);
5287
5869
 
5288
- export { BadRequestError, BrowserEventDispatcher, FetchWalletsError, LocalstorageNotFoundError, ParseHexError, TonConnect, TonConnectError, UUIDv7, UnknownAppError, UnknownError, UserRejectsError, WalletAlreadyConnectedError, WalletMissingRequiredFeaturesError, WalletNotConnectedError, WalletNotInjectedError, WalletNotSupportFeatureError, WalletsListManager, WrongAddressError, checkRequiredWalletFeatures, createConnectionCompletedEvent, createConnectionErrorEvent, createConnectionRestoringCompletedEvent, createConnectionRestoringErrorEvent, createConnectionRestoringStartedEvent, createConnectionStartedEvent, createDataSentForSignatureEvent, createDataSignedEvent, createDataSigningFailedEvent, createDisconnectionEvent, createRequestVersionEvent, createResponseVersionEvent, createSelectedWalletEvent, createTransactionSentForSignatureEvent, createTransactionSignedEvent, createTransactionSigningFailedEvent, createVersionInfo, createWalletModalOpenedEvent, decodeTelegramUrlParameters, TonConnect as default, enableQaMode, encodeTelegramUrlParameters, isConnectUrl, isQaModeEnabled, isTelegramUrl, isWalletInfoCurrentlyEmbedded, isWalletInfoCurrentlyInjected, isWalletInfoInjectable, isWalletInfoInjected, isWalletInfoRemote, toUserFriendlyAddress };
5870
+ export { BadRequestError, BrowserEventDispatcher, FetchWalletsError, LocalstorageNotFoundError, ParseHexError, TonConnect, TonConnectError, UUIDv7, UnknownAppError, UnknownError, UserRejectsError, WalletAlreadyConnectedError, WalletMissingRequiredFeaturesError, WalletNotConnectedError, WalletNotInjectedError, WalletNotSupportFeatureError, WalletWrongNetworkError, WalletsListManager, WrongAddressError, checkRequiredWalletFeatures, createConnectionCompletedEvent, createConnectionErrorEvent, createConnectionRestoringCompletedEvent, createConnectionRestoringErrorEvent, createConnectionRestoringStartedEvent, createConnectionStartedEvent, createDataSentForSignatureEvent, createDataSignedEvent, createDataSigningFailedEvent, createDisconnectionEvent, createRequestVersionEvent, createResponseVersionEvent, createSelectedWalletEvent, createTransactionSentForSignatureEvent, createTransactionSignedEvent, createTransactionSigningFailedEvent, createVersionInfo, createWalletModalOpenedEvent, decodeTelegramUrlParameters, TonConnect as default, enableQaMode, encodeTelegramUrlParameters, initializeWalletConnect, isConnectUrl, isQaModeEnabled, isTelegramUrl, isWalletConnectInitialized, isWalletInfoCurrentlyEmbedded, isWalletInfoCurrentlyInjected, isWalletInfoInjectable, isWalletInfoInjected, isWalletInfoRemote, toUserFriendlyAddress };
5289
5871
  //# sourceMappingURL=index.mjs.map