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