@tronweb3/tronwallet-adapter-tokenpocket 1.0.9 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/umd/index.js CHANGED
@@ -363,82 +363,7 @@
363
363
  return eventemitter3.exports;
364
364
  }
365
365
 
366
- var hasRequiredAdapter$2;
367
-
368
- function requireAdapter$2 () {
369
- if (hasRequiredAdapter$2) return adapter$1;
370
- hasRequiredAdapter$2 = 1;
371
- var __importDefault = (adapter$1 && adapter$1.__importDefault) || function (mod) {
372
- return (mod && mod.__esModule) ? mod : { "default": mod };
373
- };
374
- Object.defineProperty(adapter$1, "__esModule", { value: true });
375
- adapter$1.Adapter = adapter$1.AdapterState = adapter$1.WalletReadyState = adapter$1.EventEmitter = void 0;
376
- const eventemitter3_1 = __importDefault(requireEventemitter3());
377
- adapter$1.EventEmitter = eventemitter3_1.default;
378
- /**
379
- * Wallet ready state.
380
- */
381
- var WalletReadyState;
382
- (function (WalletReadyState) {
383
- /**
384
- * Adapter will start to check if wallet exists after adapter instance is created.
385
- */
386
- WalletReadyState["Loading"] = "Loading";
387
- /**
388
- * When checking ends and wallet is not found, readyState will be NotFound.
389
- */
390
- WalletReadyState["NotFound"] = "NotFound";
391
- /**
392
- * When checking ends and wallet is found, readyState will be Found.
393
- */
394
- WalletReadyState["Found"] = "Found";
395
- })(WalletReadyState || (adapter$1.WalletReadyState = WalletReadyState = {}));
396
- /**
397
- * Adapter state
398
- */
399
- var AdapterState;
400
- (function (AdapterState) {
401
- /**
402
- * If adapter is checking the wallet, the state is Loading.
403
- */
404
- AdapterState["Loading"] = "Loading";
405
- /**
406
- * If wallet is not installed, the state is NotFound.
407
- */
408
- AdapterState["NotFound"] = "NotFound";
409
- /**
410
- * If wallet is installed but is not connected to current Dapp, the state is Disconnected.
411
- */
412
- AdapterState["Disconnect"] = "Disconnected";
413
- /**
414
- * Wallet is connected to current Dapp.
415
- */
416
- AdapterState["Connected"] = "Connected";
417
- })(AdapterState || (adapter$1.AdapterState = AdapterState = {}));
418
- class Adapter extends eventemitter3_1.default {
419
- get connected() {
420
- return this.state === AdapterState.Connected;
421
- }
422
- /**
423
- * Some wallets such as TronLink don't support disconnect() method.
424
- */
425
- disconnect() {
426
- console.info("The current adapter doesn't support disconnect by DApp.");
427
- return Promise.resolve();
428
- }
429
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
430
- multiSign(transaction, options = {}) {
431
- return Promise.reject("The current wallet doesn't support multiSign.");
432
- }
433
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
434
- switchChain(_chainId) {
435
- return Promise.reject("The current wallet doesn't support switch chain.");
436
- }
437
- }
438
- adapter$1.Adapter = Adapter;
439
-
440
- return adapter$1;
441
- }
366
+ var typedData = {};
442
367
 
443
368
  var errors = {};
444
369
 
@@ -448,7 +373,7 @@
448
373
  if (hasRequiredErrors) return errors;
449
374
  hasRequiredErrors = 1;
450
375
  Object.defineProperty(errors, "__esModule", { value: true });
451
- errors.WalletGetNetworkError = errors.WalletSwitchChainError = errors.WalletWindowClosedError = errors.WalletWalletLoadError = errors.WalletSignTransactionError = errors.WalletSignMessageError = errors.WalletDisconnectionError = errors.WalletConnectionError = errors.WalletDisconnectedError = errors.WalletNotSelectedError = errors.WalletNotFoundError = errors.WalletError = void 0;
376
+ errors.WalletSignTypedDataError = errors.WalletGetNetworkError = errors.WalletSwitchChainError = errors.WalletWindowClosedError = errors.WalletWalletLoadError = errors.WalletSignTransactionError = errors.WalletSignMessageError = errors.WalletDisconnectionError = errors.WalletConnectionError = errors.WalletDisconnectedError = errors.WalletNotSelectedError = errors.WalletNotFoundError = errors.WalletError = void 0;
452
377
  class WalletError extends Error {
453
378
  constructor(message, error) {
454
379
  super(message);
@@ -569,10 +494,66 @@
569
494
  }
570
495
  }
571
496
  errors.WalletGetNetworkError = WalletGetNetworkError;
497
+ /**
498
+ * Occurs when call `signTypedData()`.
499
+ */
500
+ class WalletSignTypedDataError extends WalletError {
501
+ constructor() {
502
+ super(...arguments);
503
+ this.name = 'WalletSignTypedDataError';
504
+ }
505
+ }
506
+ errors.WalletSignTypedDataError = WalletSignTypedDataError;
572
507
 
573
508
  return errors;
574
509
  }
575
510
 
511
+ var hasRequiredTypedData;
512
+
513
+ function requireTypedData () {
514
+ if (hasRequiredTypedData) return typedData;
515
+ hasRequiredTypedData = 1;
516
+ Object.defineProperty(typedData, "__esModule", { value: true });
517
+ typedData.normalizeAndValidateTypedData = normalizeAndValidateTypedData;
518
+ const errors_js_1 = requireErrors();
519
+ function isPlainObject(value) {
520
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
521
+ }
522
+ /**
523
+ * Validate a TypedData payload and return a normalized copy safe to pass to wallets.
524
+ *
525
+ * Current normalization: convert `domain.chainId` from string to number (some wallets,
526
+ * e.g. TronLink, require a numeric chainId).
527
+ *
528
+ * Throws {@link WalletSignTypedDataError} if the payload is not a valid TypedData object.
529
+ */
530
+ function normalizeAndValidateTypedData(typedData) {
531
+ if (!isPlainObject(typedData)) {
532
+ throw new errors_js_1.WalletSignTypedDataError('typedData must be an object.');
533
+ }
534
+ if (!isPlainObject(typedData.domain)) {
535
+ throw new errors_js_1.WalletSignTypedDataError('typedData.domain must be an object.');
536
+ }
537
+ if (!isPlainObject(typedData.types)) {
538
+ throw new errors_js_1.WalletSignTypedDataError('typedData.types must be an object.');
539
+ }
540
+ if (!isPlainObject(typedData.message)) {
541
+ throw new errors_js_1.WalletSignTypedDataError('typedData.message must be an object.');
542
+ }
543
+ const { chainId } = typedData.domain;
544
+ if (typeof chainId === 'string') {
545
+ const parsed = Number(chainId);
546
+ if (!Number.isFinite(parsed)) {
547
+ throw new errors_js_1.WalletSignTypedDataError(`Invalid domain.chainId: ${chainId}.`);
548
+ }
549
+ return Object.assign(Object.assign({}, typedData), { domain: Object.assign(Object.assign({}, typedData.domain), { chainId: parsed }) });
550
+ }
551
+ return typedData;
552
+ }
553
+
554
+ return typedData;
555
+ }
556
+
576
557
  var types$1 = {};
577
558
 
578
559
  var hasRequiredTypes$1;
@@ -581,7 +562,47 @@
581
562
  if (hasRequiredTypes$1) return types$1;
582
563
  hasRequiredTypes$1 = 1;
583
564
  Object.defineProperty(types$1, "__esModule", { value: true });
584
- types$1.TIP6963RequestProviderEventName = types$1.TIP6963AnnounceProviderEventName = types$1.ChainNetwork = types$1.NetworkType = void 0;
565
+ types$1.TIP6963RequestProviderEventName = types$1.TIP6963AnnounceProviderEventName = types$1.ChainNetwork = types$1.NetworkType = types$1.AdapterState = types$1.WalletReadyState = void 0;
566
+ /**
567
+ * Wallet ready state.
568
+ */
569
+ var WalletReadyState;
570
+ (function (WalletReadyState) {
571
+ /**
572
+ * Adapter will start to check if wallet exists after adapter instance is created.
573
+ */
574
+ WalletReadyState["Loading"] = "Loading";
575
+ /**
576
+ * When checking ends and wallet is not found, readyState will be NotFound.
577
+ */
578
+ WalletReadyState["NotFound"] = "NotFound";
579
+ /**
580
+ * When checking ends and wallet is found, readyState will be Found.
581
+ */
582
+ WalletReadyState["Found"] = "Found";
583
+ })(WalletReadyState || (types$1.WalletReadyState = WalletReadyState = {}));
584
+ /**
585
+ * Adapter state
586
+ */
587
+ var AdapterState;
588
+ (function (AdapterState) {
589
+ /**
590
+ * If adapter is checking the wallet, the state is Loading.
591
+ */
592
+ AdapterState["Loading"] = "Loading";
593
+ /**
594
+ * If wallet is not installed, the state is NotFound.
595
+ */
596
+ AdapterState["NotFound"] = "NotFound";
597
+ /**
598
+ * If wallet is installed but is not connected to current Dapp, the state is Disconnected.
599
+ */
600
+ AdapterState["Disconnect"] = "Disconnected";
601
+ /**
602
+ * Wallet is connected to current Dapp.
603
+ */
604
+ AdapterState["Connected"] = "Connected";
605
+ })(AdapterState || (types$1.AdapterState = AdapterState = {}));
585
606
  var NetworkType;
586
607
  (function (NetworkType) {
587
608
  NetworkType["Mainnet"] = "Mainnet";
@@ -604,6 +625,59 @@
604
625
  return types$1;
605
626
  }
606
627
 
628
+ var hasRequiredAdapter$2;
629
+
630
+ function requireAdapter$2 () {
631
+ if (hasRequiredAdapter$2) return adapter$1;
632
+ hasRequiredAdapter$2 = 1;
633
+ var __importDefault = (adapter$1 && adapter$1.__importDefault) || function (mod) {
634
+ return (mod && mod.__esModule) ? mod : { "default": mod };
635
+ };
636
+ Object.defineProperty(adapter$1, "__esModule", { value: true });
637
+ adapter$1.Adapter = adapter$1.EventEmitter = void 0;
638
+ const eventemitter3_1 = __importDefault(requireEventemitter3());
639
+ adapter$1.EventEmitter = eventemitter3_1.default;
640
+ const typedData_js_1 = requireTypedData();
641
+ const types_js_1 = requireTypes$1();
642
+ class Adapter extends eventemitter3_1.default {
643
+ get connected() {
644
+ return this.state === types_js_1.AdapterState.Connected;
645
+ }
646
+ /**
647
+ * Some wallets such as TronLink don't support disconnect() method.
648
+ */
649
+ disconnect() {
650
+ console.info("The current adapter doesn't support disconnect by DApp.");
651
+ return Promise.resolve();
652
+ }
653
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
654
+ multiSign(transaction, options = {}) {
655
+ return Promise.reject("The current wallet doesn't support multiSign.");
656
+ }
657
+ signTypedData(typedData) {
658
+ let normalized;
659
+ try {
660
+ normalized = (0, typedData_js_1.normalizeAndValidateTypedData)(typedData);
661
+ }
662
+ catch (error) {
663
+ return Promise.reject(error);
664
+ }
665
+ return this._signTypedData(normalized);
666
+ }
667
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
668
+ _signTypedData(_typedData) {
669
+ return Promise.reject("The current wallet doesn't support signTypedData.");
670
+ }
671
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
672
+ switchChain(_chainId) {
673
+ return Promise.reject("The current wallet doesn't support switch chain.");
674
+ }
675
+ }
676
+ adapter$1.Adapter = Adapter;
677
+
678
+ return adapter$1;
679
+ }
680
+
607
681
  var utils$2 = {};
608
682
 
609
683
  var hasRequiredUtils$2;
@@ -666,6 +740,306 @@
666
740
  return utils$2;
667
741
  }
668
742
 
743
+ var addonAdapter = {};
744
+
745
+ var security = {};
746
+
747
+ var hasRequiredSecurity;
748
+
749
+ function requireSecurity () {
750
+ if (hasRequiredSecurity) return security;
751
+ hasRequiredSecurity = 1;
752
+ (function (exports$1) {
753
+ var __awaiter = (security && security.__awaiter) || function (thisArg, _arguments, P, generator) {
754
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
755
+ return new (P || (P = Promise))(function (resolve, reject) {
756
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
757
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
758
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
759
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
760
+ });
761
+ };
762
+ Object.defineProperty(exports$1, "__esModule", { value: true });
763
+ exports$1.defaultSecurityOptions = void 0;
764
+ exports$1.clearCache = clearCache;
765
+ exports$1.fetchJsonWithCache = fetchJsonWithCache;
766
+ exports$1.defaultSecurityOptions = {
767
+ onRiskDetected: (result) => __awaiter(void 0, void 0, void 0, function* () {
768
+ console.log(`[WalletAdapter] Risk detected:`, result);
769
+ }),
770
+ configUrls: [],
771
+ enabled: false,
772
+ timeout: 2000,
773
+ retries: 0,
774
+ cacheTTL: 10 * 60 * 1000,
775
+ };
776
+ function isValidRisk(risk) {
777
+ return (!!risk &&
778
+ typeof risk === 'object' &&
779
+ typeof risk.title === 'string' &&
780
+ risk.title.length > 0 &&
781
+ (risk.noticeType === 1 || risk.noticeType === 2 || risk.noticeType === 3));
782
+ }
783
+ function sanitizeRisk(risk) {
784
+ const clean = { title: risk.title, noticeType: risk.noticeType };
785
+ if (typeof risk.ext === 'string')
786
+ clean.ext = risk.ext;
787
+ if (typeof risk.ios === 'string')
788
+ clean.ios = risk.ios;
789
+ if (typeof risk.and === 'string')
790
+ clean.and = risk.and;
791
+ return clean;
792
+ }
793
+ /**
794
+ * Defensively coerce an arbitrary remote payload into a well-formed RiskConfig.
795
+ *
796
+ * The config comes from a remote URL, so a bad release (or a tampered response)
797
+ * must never break the connect flow. Anything malformed is dropped with a
798
+ * warning rather than thrown: `wallets` must be a record whose values are
799
+ * arrays, and each risk must have a non-empty string `title` and a `noticeType`
800
+ * of 1/2/3. Invalid entries are discarded so downstream merging/consumption
801
+ * only ever sees clean `Risk[]`.
802
+ */
803
+ function normalizeRiskConfig(data) {
804
+ const source = data && typeof data === 'object' ? data : {};
805
+ const wallets = {};
806
+ if (source.wallets && typeof source.wallets === 'object') {
807
+ for (const [walletName, rawRisks] of Object.entries(source.wallets)) {
808
+ if (!Array.isArray(rawRisks)) {
809
+ console.warn(`[WalletAdapter] Ignoring malformed risks for "${walletName}": expected an array, got ${typeof rawRisks}.`);
810
+ continue;
811
+ }
812
+ const validRisks = [];
813
+ for (const risk of rawRisks) {
814
+ if (isValidRisk(risk)) {
815
+ validRisks.push(sanitizeRisk(risk));
816
+ }
817
+ else {
818
+ console.warn(`[WalletAdapter] Dropping malformed risk entry for "${walletName}":`, risk);
819
+ }
820
+ }
821
+ if (validRisks.length > 0) {
822
+ wallets[walletName] = validRisks;
823
+ }
824
+ }
825
+ }
826
+ return {
827
+ v: typeof source.v === 'string' ? source.v : '',
828
+ ts: typeof source.ts === 'number' ? source.ts : 0,
829
+ wallets,
830
+ };
831
+ }
832
+ const _jsonCache = {};
833
+ function clearCache() {
834
+ Object.keys(_jsonCache).forEach((key) => {
835
+ Reflect.deleteProperty(_jsonCache, key);
836
+ });
837
+ }
838
+ function fetchJsonWithCache(options) {
839
+ return __awaiter(this, void 0, void 0, function* () {
840
+ const { configUrls = exports$1.defaultSecurityOptions.configUrls, timeout = exports$1.defaultSecurityOptions.timeout, retries = exports$1.defaultSecurityOptions.retries, onConfigFallback, cacheTTL = exports$1.defaultSecurityOptions.cacheTTL, } = options;
841
+ const now = Date.now();
842
+ function fetchOneUrl(url) {
843
+ return __awaiter(this, void 0, void 0, function* () {
844
+ const cache = _jsonCache[url];
845
+ if (cache && now - cache.timestamp < cacheTTL) {
846
+ return cache.data;
847
+ }
848
+ function fetchWithTimeout() {
849
+ return __awaiter(this, void 0, void 0, function* () {
850
+ return new Promise((resolve, reject) => {
851
+ const controller = new AbortController();
852
+ const timer = setTimeout(() => controller.abort(), timeout);
853
+ fetch(url, { signal: controller.signal })
854
+ .then((resp) => {
855
+ clearTimeout(timer);
856
+ if (!resp.ok)
857
+ reject(new Error('Fetch failed with code: ' + resp.status));
858
+ else
859
+ resp.json().then((data) => resolve(normalizeRiskConfig(data)), reject);
860
+ })
861
+ .catch((err) => {
862
+ clearTimeout(timer);
863
+ reject(err);
864
+ });
865
+ });
866
+ });
867
+ }
868
+ for (let i = 0; i <= retries; i++) {
869
+ try {
870
+ const data = yield fetchWithTimeout();
871
+ _jsonCache[url] = { data, timestamp: Date.now() };
872
+ return data;
873
+ }
874
+ catch (e) {
875
+ console.warn(`[WalletAdapter] Fetch attempt ${i + 1} for ${url} failed:`, e);
876
+ // continue to next retry
877
+ }
878
+ }
879
+ // All retries failed — let the outer caller decide (onConfigFallback or safe empty config)
880
+ return null;
881
+ });
882
+ }
883
+ const results = yield Promise.all(configUrls.map(fetchOneUrl));
884
+ const configs = results.filter((r) => r !== null);
885
+ if (configs.length > 0) {
886
+ return configs.reduce((merged, config) => {
887
+ var _a;
888
+ if (config.ts > merged.ts) {
889
+ merged.v = config.v;
890
+ merged.ts = config.ts;
891
+ }
892
+ // Pass every risk from every source through to the DApp without
893
+ // deduplication. Conflict resolution (highest severity wins, source
894
+ // weighting, etc.) is the DApp's responsibility — the adapter just
895
+ // delivers the union.
896
+ for (const [wallet, risks] of Object.entries(config.wallets)) {
897
+ merged.wallets[wallet] = [...((_a = merged.wallets[wallet]) !== null && _a !== void 0 ? _a : []), ...risks];
898
+ }
899
+ return merged;
900
+ }, { v: '', ts: 0, wallets: {} });
901
+ }
902
+ // All URLs failed with no cache — call custom fallback or default to safe (allow connection)
903
+ if (onConfigFallback) {
904
+ return normalizeRiskConfig(yield onConfigFallback());
905
+ }
906
+ return { v: '', ts: 0, wallets: {} };
907
+ });
908
+ }
909
+
910
+ } (security));
911
+ return security;
912
+ }
913
+
914
+ var hasRequiredAddonAdapter;
915
+
916
+ function requireAddonAdapter () {
917
+ if (hasRequiredAddonAdapter) return addonAdapter;
918
+ hasRequiredAddonAdapter = 1;
919
+ var __awaiter = (addonAdapter && addonAdapter.__awaiter) || function (thisArg, _arguments, P, generator) {
920
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
921
+ return new (P || (P = Promise))(function (resolve, reject) {
922
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
923
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
924
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
925
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
926
+ });
927
+ };
928
+ Object.defineProperty(addonAdapter, "__esModule", { value: true });
929
+ addonAdapter.AddonAdapter = void 0;
930
+ const adapter_js_1 = requireAdapter$2();
931
+ const errors_js_1 = requireErrors();
932
+ const security_js_1 = requireSecurity();
933
+ const types_js_1 = requireTypes$1();
934
+ const utils_js_1 = requireUtils$2();
935
+ /**
936
+ * Class to provide security check for wallets.
937
+ */
938
+ class AddonAdapter extends adapter_js_1.Adapter {
939
+ constructor(params) {
940
+ super();
941
+ this.commonConfig = {
942
+ checkTimeout: 2 * 1000,
943
+ openAppWithDeeplink: true,
944
+ openUrlWhenWalletNotFound: true,
945
+ securityOptions: security_js_1.defaultSecurityOptions,
946
+ };
947
+ this._securityCheckCache = null;
948
+ this.commonConfig = Object.assign(Object.assign({}, this.commonConfig), params);
949
+ if (typeof this.commonConfig.checkTimeout !== 'number') {
950
+ throw new Error(`[WalletAdapter] config.checkTimeout should be a number`);
951
+ }
952
+ AddonAdapter._validateSecurityOptions(this.commonConfig.securityOptions);
953
+ }
954
+ static _validateSecurityOptions(securityOptions) {
955
+ const { enabled, configUrls } = securityOptions;
956
+ if (enabled && (!configUrls || configUrls.length === 0)) {
957
+ throw new Error(`[WalletAdapter] config.securityOptions.configUrls is required when securityOptions.enabled is true`);
958
+ }
959
+ }
960
+ /**
961
+ * Update the security options at runtime. The given options are merged into
962
+ * the existing config, validated, and the cached security check result is
963
+ * cleared so the next connect runs a fresh check with the new configuration.
964
+ */
965
+ updateSecurityOptions(securityOptions) {
966
+ const merged = Object.assign(Object.assign({}, this.commonConfig.securityOptions), securityOptions);
967
+ AddonAdapter._validateSecurityOptions(merged);
968
+ this.commonConfig.securityOptions = merged;
969
+ this._securityCheckCache = null;
970
+ }
971
+ /**
972
+ * Run the pre-connect pipeline (wallet discovery, deeplink/url fallback,
973
+ * security check).
974
+ *
975
+ * @returns `true` when the caller should continue with the actual connect
976
+ * flow, `false` when the adapter is already connected/connecting and the
977
+ * caller should bail out. Throws `WalletNotFoundError` when the wallet
978
+ * cannot be found.
979
+ */
980
+ _beforeConnect() {
981
+ return __awaiter(this, void 0, void 0, function* () {
982
+ if (this.connected || this.connecting)
983
+ return false;
984
+ yield this._checkWallet();
985
+ if (this.readyState === types_js_1.WalletReadyState.NotFound) {
986
+ if ((0, utils_js_1.isInBrowser)() &&
987
+ !this._openAppByDeepLinkIfNeed() &&
988
+ this.commonConfig.openUrlWhenWalletNotFound !== false) {
989
+ window.open(this.url, '_blank');
990
+ }
991
+ throw new errors_js_1.WalletNotFoundError();
992
+ }
993
+ yield this.checkSecurity();
994
+ return true;
995
+ });
996
+ }
997
+ /**
998
+ * Fetch remote config and do risk check.
999
+ * In-flight calls share the same promise (so `onRiskDetected` fires at most
1000
+ * once even on a slow network). After the promise settles, the result is
1001
+ * cached for SECURITY_CHECK_CACHE_TTL; the next call after that window
1002
+ * runs a fresh check.
1003
+ */
1004
+ checkSecurity() {
1005
+ return __awaiter(this, void 0, void 0, function* () {
1006
+ if (!this.commonConfig.securityOptions.enabled)
1007
+ return;
1008
+ const cache = this._securityCheckCache;
1009
+ if (cache &&
1010
+ (cache.settledAt === null || Date.now() - cache.settledAt < AddonAdapter.SECURITY_CHECK_CACHE_TTL)) {
1011
+ return cache.promise;
1012
+ }
1013
+ const promise = (() => __awaiter(this, void 0, void 0, function* () {
1014
+ const result = yield (0, security_js_1.fetchJsonWithCache)(this.commonConfig.securityOptions);
1015
+ const risks = result.wallets[this.name];
1016
+ if (risks && risks.length > 0) {
1017
+ const callback = this.commonConfig.securityOptions.onRiskDetected || security_js_1.defaultSecurityOptions.onRiskDetected;
1018
+ yield callback({ risks });
1019
+ }
1020
+ }))();
1021
+ const entry = { promise, settledAt: null };
1022
+ this._securityCheckCache = entry;
1023
+ // The `.finally` chain returns a new promise that mirrors `promise`'s rejection.
1024
+ // Attach a noop `.catch` to avoid an unhandled rejection on that chain — the
1025
+ // original `promise` is still surfaced to callers via the return below.
1026
+ promise
1027
+ .finally(() => {
1028
+ if (this._securityCheckCache === entry) {
1029
+ entry.settledAt = Date.now();
1030
+ }
1031
+ })
1032
+ .catch(() => { });
1033
+ return promise;
1034
+ });
1035
+ }
1036
+ }
1037
+ addonAdapter.AddonAdapter = AddonAdapter;
1038
+ AddonAdapter.SECURITY_CHECK_CACHE_TTL = 5 * 1000;
1039
+
1040
+ return addonAdapter;
1041
+ }
1042
+
669
1043
  var hasRequiredCjs$2;
670
1044
 
671
1045
  function requireCjs$2 () {
@@ -690,7 +1064,10 @@
690
1064
  __exportStar(requireAdapter$2(), exports$1);
691
1065
  __exportStar(requireErrors(), exports$1);
692
1066
  __exportStar(requireTypes$1(), exports$1);
1067
+ __exportStar(requireTypedData(), exports$1);
693
1068
  __exportStar(requireUtils$2(), exports$1);
1069
+ __exportStar(requireAddonAdapter(), exports$1);
1070
+ __exportStar(requireSecurity(), exports$1);
694
1071
 
695
1072
  } (cjs$1));
696
1073
  return cjs$1;
@@ -829,10 +1206,10 @@
829
1206
  });
830
1207
  }
831
1208
  exports$1.TronLinkAdapterName = 'TronLink';
832
- class TronLinkAdapter extends tronwallet_abstract_adapter_1.Adapter {
1209
+ class TronLinkAdapter extends tronwallet_abstract_adapter_1.AddonAdapter {
833
1210
  // record if first connect event has emitted or not
834
1211
  constructor(config = {}) {
835
- super();
1212
+ super(config);
836
1213
  this.name = exports$1.TronLinkAdapterName;
837
1214
  this.url = 'https://www.tronlink.org/';
838
1215
  this.icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF0AAABdCAYAAADHcWrDAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAUGVYSWZNTQAqAAAACAACARIAAwAAAAEAAQAAh2kABAAAAAEAAAAmAAAAAAADoAEAAwAAAAEAAQAAoAIABAAAAAEAAABdoAMABAAAAAEAAABdAAAAAMkTBfIAAAFZaVRYdFhNTDpjb20uYWRvYmUueG1wAAAAAAA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA2LjAuMCI+CiAgIDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+CiAgICAgIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICAgICAgICAgIHhtbG5zOnRpZmY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vdGlmZi8xLjAvIj4KICAgICAgICAgPHRpZmY6T3JpZW50YXRpb24+MTwvdGlmZjpPcmllbnRhdGlvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Chle4QcAABZhSURBVHgB7V0JlBTVuf6runtWllkA2QeYQQRBZHNFxZjw4jFqMEFxCWIS1yOaTeJ76nk5Lyc5CUZNfCoa0BgUxRh3QD2CJs8lELaIgOCw78sszN4z0131vu/W1NDTfbtneqa7Zx5v/nN6prrq1q2q77//ev9bbUgcNHjm/sya7PIiIxA43TCNUbYEcw3bsOLo4v98U9sW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tFpAd6N0+aKpF/rk7Zk5xA8G4rzAKyWLJ3/kXrPZTJf8efJysRueMXyxK5XcE5P9n17MBqQFGIjoiNUCPTJQkJSgwa4CI2Q7+WJmHTEvE7dqwS/x2kH/Pgn65oX22Qw6d5p1mfPwc46r+MuxnU18QL5F4x0kwXQ0Fq+QmjAC1QIJUjHkXTaYyFdh6ehweUN8oKu3uliVhhW8uWzJ+AOhfbYA/firZ1Y3NFqzwJ0PDS+TTp2rahhKc/4xtBzCvXlOHnCymO/2SgTRXeQLf3RTdzx2HKnn0EXGMa9Jwyn2CSMYuKHkxSl/C2/bAnQerHp5cgl+6niGHax7Tsitpl8KDz8xFd8Z9fGF93x5so4un9Rb5Uno6nWU2AdfH5KVHjnSObdZjmBNBZWxLoQGSkvYwS3A8IqSF6GyNRQBOtuULTmvsnTxxB9YVuB6VG1sxW9O4zc1wb24lZrminHsopzRH482lTccc6eszEpEWoDLbmhEdbEPk1p8U5NTxqF5AAxORyUbVWI1PNbQEJhW9uI5n2laql36zE5T6/IXJi7Nu3H1CsO0r4OmmY2M5CT8oGmmw3IMjURZsWh3h/3pGbas3OKXE5hJy4lMs8s1WESwbAMOejwdUoaIVaR/nt6JKK1GoVAQDEF61lG4+Ks2GPRgQbId3InZl7cxQBeWLJ70ZYzHUYdigs4WHPX4txA9L8qfs34UfM7J2B6NFVmDxLB6i92q0KkLtfcPhX0vSqq3H6geC/98RHg/VwL0MW8e/hjvVy/Xim34CVG+21h+ePawjAk4HDG1byFN4q+r/dQH74aaDGOtFvnw4wC+2BJzo8db/XnJc1Njr7EMua7DuJAdXXXTrq8fI2lpUyPvz8LSjjXLjCEXHIw8Ft8eu65sqmTkjok4K+AvNnyZH0Xsb+eO/wWrg46Do/7gYAAAAABJRU5ErkJggg==';
@@ -858,8 +1235,8 @@
858
1235
  }
859
1236
  };
860
1237
  this._checkPromise = null;
861
- this._updateWallet = () => {
862
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1238
+ this._updateWallet = () => __awaiter(this, void 0, void 0, function* () {
1239
+ var _a, _b, _c, _d, _e, _f, _g, _h;
863
1240
  this._supportNewTronProtocol = false;
864
1241
  let state = this.state;
865
1242
  let address = this.address;
@@ -875,9 +1252,23 @@
875
1252
  };
876
1253
  }
877
1254
  address = ((_c = (_b = this._wallet.tronWeb) === null || _b === void 0 ? void 0 : _b.defaultAddress) === null || _c === void 0 ? void 0 : _c.base58) || null;
878
- state = address ? tronwallet_abstract_adapter_1.AdapterState.Connected : tronwallet_abstract_adapter_1.AdapterState.Disconnect;
1255
+ if (address) {
1256
+ // Only run the security check once the wallet is actually connected.
1257
+ try {
1258
+ yield this.checkSecurity();
1259
+ }
1260
+ catch (_j) {
1261
+ this.setAddress(null);
1262
+ this.setState(tronwallet_abstract_adapter_1.AdapterState.Disconnect);
1263
+ return;
1264
+ }
1265
+ state = tronwallet_abstract_adapter_1.AdapterState.Connected;
1266
+ }
1267
+ else {
1268
+ state = tronwallet_abstract_adapter_1.AdapterState.Disconnect;
1269
+ }
879
1270
  }
880
- else if (window.tron && window.tron.isTronLink) {
1271
+ else if (this.isLegacyTronLinkProvider(window.tron)) {
881
1272
  this._supportNewTronProtocol = true;
882
1273
  this._wallet = window.tron;
883
1274
  this._listenTronEvent();
@@ -899,16 +1290,6 @@
899
1290
  address = ((_h = (_g = this._wallet.tronWeb) === null || _g === void 0 ? void 0 : _g.defaultAddress) === null || _h === void 0 ? void 0 : _h.base58) || null;
900
1291
  state = this._wallet.ready ? tronwallet_abstract_adapter_1.AdapterState.Connected : tronwallet_abstract_adapter_1.AdapterState.Disconnect;
901
1292
  }
902
- else if (window.tronWeb) {
903
- // fake tronLink
904
- this._wallet = {
905
- ready: window.tronWeb.ready,
906
- tronWeb: window.tronWeb,
907
- request: () => Promise.resolve(true),
908
- };
909
- address = ((_j = this._wallet.tronWeb.defaultAddress) === null || _j === void 0 ? void 0 : _j.base58) || null;
910
- state = this._wallet.ready ? tronwallet_abstract_adapter_1.AdapterState.Connected : tronwallet_abstract_adapter_1.AdapterState.Disconnect;
911
- }
912
1293
  else {
913
1294
  // no tronlink support
914
1295
  this._wallet = null;
@@ -921,26 +1302,40 @@
921
1302
  }
922
1303
  this.setAddress(address);
923
1304
  this.setState(state);
924
- };
1305
+ });
925
1306
  this.checkReadyInterval = null;
926
- const { checkTimeout = 30 * 1000, dappIcon = '', dappName = '', openUrlWhenWalletNotFound = true, openTronLinkAppOnMobile = true, openAppWithDeeplink = true, } = config;
1307
+ const { checkTimeout = 5 * 1000, dappIcon = '', dappName = '', openUrlWhenWalletNotFound = true, openTronLinkAppOnMobile = true, openAppWithDeeplink = true, } = config;
927
1308
  if (typeof checkTimeout !== 'number') {
928
1309
  throw new Error('[TronLinkAdapter] config.checkTimeout should be a number');
929
1310
  }
930
- this.config = {
931
- checkTimeout,
1311
+ this.config = Object.assign(Object.assign({}, this.commonConfig), { checkTimeout,
932
1312
  openTronLinkAppOnMobile,
933
1313
  openAppWithDeeplink,
934
1314
  openUrlWhenWalletNotFound,
935
1315
  dappIcon,
936
- dappName,
937
- };
1316
+ dappName });
938
1317
  this._connecting = false;
939
1318
  this._wallet = null;
940
1319
  this._address = null;
941
- if ((0, utils_js_1.supportTron)() || ((0, tronwallet_abstract_adapter_1.isInMobileBrowser)() && (window.tronLink || window.tronWeb))) {
1320
+ if (!(0, tronwallet_abstract_adapter_1.isInBrowser)()) {
1321
+ this._readyState = tronwallet_abstract_adapter_1.WalletReadyState.NotFound;
1322
+ this.setState(tronwallet_abstract_adapter_1.AdapterState.NotFound);
1323
+ return;
1324
+ }
1325
+ if (!(0, tronwallet_abstract_adapter_1.isInMobileBrowser)()) {
1326
+ this._checkWallet().then(() => {
1327
+ if (this.connected) {
1328
+ this.emit('connect', this.address || '');
1329
+ }
1330
+ });
1331
+ }
1332
+ else if ((0, utils_js_1.supportTron)() || ((0, tronwallet_abstract_adapter_1.isInMobileBrowser)() && (window.tronLink || window.tronWeb))) {
942
1333
  this._readyState = tronwallet_abstract_adapter_1.WalletReadyState.Found;
943
- this._updateWallet();
1334
+ this._updateWallet().then(() => {
1335
+ if (this.connected) {
1336
+ this.emit('connect', this.address || '');
1337
+ }
1338
+ });
944
1339
  }
945
1340
  else {
946
1341
  this._checkWallet().then(() => {
@@ -993,16 +1388,8 @@
993
1388
  return __awaiter(this, void 0, void 0, function* () {
994
1389
  var _a, _b;
995
1390
  try {
996
- this.checkIfOpenTronLink();
997
- if (this.connected || this.connecting)
1391
+ if (!(yield this._beforeConnect()))
998
1392
  return;
999
- yield this._checkWallet();
1000
- if (this.state === tronwallet_abstract_adapter_1.AdapterState.NotFound) {
1001
- if (this.config.openUrlWhenWalletNotFound !== false && (0, tronwallet_abstract_adapter_1.isInBrowser)()) {
1002
- window.open(this.url, '_blank');
1003
- }
1004
- throw new tronwallet_abstract_adapter_1.WalletNotFoundError();
1005
- }
1006
1393
  // lower version only support window.tronWeb, no window.tronLink
1007
1394
  if (!this._wallet)
1008
1395
  return;
@@ -1033,22 +1420,17 @@
1033
1420
  }
1034
1421
  else if (window.tronLink) {
1035
1422
  const wallet = this._wallet;
1036
- try {
1037
- const res = yield wallet.request({ method: 'tron_requestAccounts' });
1038
- if (!res) {
1039
- // 1. wallet is locked
1040
- // 2. tronlink is first installed and there is no wallet account
1041
- throw new tronwallet_abstract_adapter_1.WalletConnectionError('TronLink wallet is locked or no wallet account is avaliable.');
1042
- }
1043
- if (res.code === 4000) {
1044
- throw new tronwallet_abstract_adapter_1.WalletConnectionError('The same DApp has already initiated a request to connect to TronLink wallet, and the pop-up window has not been closed.');
1045
- }
1046
- if (res.code === 4001) {
1047
- throw new tronwallet_abstract_adapter_1.WalletConnectionError('The user rejected connection.');
1048
- }
1423
+ const res = yield wallet.request({ method: 'tron_requestAccounts' });
1424
+ if (!res) {
1425
+ // 1. wallet is locked
1426
+ // 2. tronlink is first installed and there is no wallet account
1427
+ throw new tronwallet_abstract_adapter_1.WalletConnectionError('TronLink wallet is locked or no wallet account is avaliable.');
1049
1428
  }
1050
- catch (error) {
1051
- throw new tronwallet_abstract_adapter_1.WalletConnectionError(error === null || error === void 0 ? void 0 : error.message, error);
1429
+ if (res.code === 4000) {
1430
+ throw new tronwallet_abstract_adapter_1.WalletConnectionError('The same DApp has already initiated a request to connect to TronLink wallet, and the pop-up window has not been closed.');
1431
+ }
1432
+ if (res.code === 4001) {
1433
+ throw new tronwallet_abstract_adapter_1.WalletConnectionError('The user rejected connection.');
1052
1434
  }
1053
1435
  const address = ((_a = wallet.tronWeb.defaultAddress) === null || _a === void 0 ? void 0 : _a.base58) || '';
1054
1436
  this.setAddress(address);
@@ -1066,8 +1448,9 @@
1066
1448
  this.connected && this.emit('connect', this.address || '');
1067
1449
  }
1068
1450
  catch (error) {
1069
- this.emit('error', error);
1070
- throw error;
1451
+ const err = error instanceof tronwallet_abstract_adapter_1.WalletError ? error : new tronwallet_abstract_adapter_1.WalletConnectionError(error === null || error === void 0 ? void 0 : error.message, error);
1452
+ this.emit('error', err);
1453
+ throw err;
1071
1454
  }
1072
1455
  finally {
1073
1456
  this._connecting = false;
@@ -1135,6 +1518,11 @@
1135
1518
  return this._checkAndSign((wallet) => __awaiter(this, void 0, void 0, function* () { return wallet.tronWeb.trx.signMessageV2(message); }), tronwallet_abstract_adapter_1.WalletSignMessageError);
1136
1519
  });
1137
1520
  }
1521
+ _signTypedData(typedData) {
1522
+ return __awaiter(this, void 0, void 0, function* () {
1523
+ return this._checkAndSign((wallet) => __awaiter(this, void 0, void 0, function* () { return wallet.tronWeb.trx._signTypedData(typedData.domain, typedData.types, typedData.message); }), tronwallet_abstract_adapter_1.WalletSignTypedDataError);
1524
+ });
1525
+ }
1138
1526
  /**
1139
1527
  * Switch to target chain. If current chain is the same as target chain, the call will success immediately.
1140
1528
  * Available chainIds:
@@ -1175,7 +1563,9 @@
1175
1563
  }
1176
1564
  checkAndGetWallet() {
1177
1565
  return __awaiter(this, void 0, void 0, function* () {
1178
- this.checkIfOpenTronLink();
1566
+ if (this._openAppByDeepLinkIfNeed()) {
1567
+ throw new tronwallet_abstract_adapter_1.WalletNotFoundError();
1568
+ }
1179
1569
  yield this._checkWallet();
1180
1570
  if (this.state !== tronwallet_abstract_adapter_1.AdapterState.Connected)
1181
1571
  throw new tronwallet_abstract_adapter_1.WalletDisconnectedError();
@@ -1185,14 +1575,12 @@
1185
1575
  return wallet;
1186
1576
  });
1187
1577
  }
1188
- checkIfOpenTronLink() {
1189
- const { dappName = '', dappIcon = '' } = this.config;
1190
- if (this.config.openTronLinkAppOnMobile === false || this.config.openAppWithDeeplink === false) {
1191
- return;
1192
- }
1193
- if ((0, utils_js_1.openTronLink)({ dappIcon, dappName })) {
1194
- throw new tronwallet_abstract_adapter_1.WalletNotFoundError();
1578
+ _openAppByDeepLinkIfNeed() {
1579
+ if (this.config.openAppWithDeeplink === false || this.config.openTronLinkAppOnMobile === false) {
1580
+ return false;
1195
1581
  }
1582
+ const { dappName = '', dappIcon = '' } = this.config;
1583
+ return (0, utils_js_1.openTronLink)({ dappIcon, dappName });
1196
1584
  }
1197
1585
  // following code is for TIP-1193
1198
1586
  _listenTronEvent() {
@@ -1208,6 +1596,12 @@
1208
1596
  (_a = wallet.removeListener) === null || _a === void 0 ? void 0 : _a.call(wallet, 'chainChanged', this._onChainChanged);
1209
1597
  (_b = wallet.removeListener) === null || _b === void 0 ? void 0 : _b.call(wallet, 'accountsChanged', this._onAccountsChanged);
1210
1598
  }
1599
+ isLegacyTronLinkProvider(provider) {
1600
+ return !!(provider === null || provider === void 0 ? void 0 : provider.isTronLink);
1601
+ }
1602
+ hasDesktopLegacyTronLinkProvider() {
1603
+ return this.isLegacyTronLinkProvider(window.tron) || !!window.tronLink;
1604
+ }
1211
1605
  /**
1212
1606
  * check if wallet exists by interval, the promise only resolve when wallet detected or timeout
1213
1607
  * @returns if wallet exists
@@ -1219,18 +1613,89 @@
1219
1613
  if (this._checkPromise) {
1220
1614
  return this._checkPromise;
1221
1615
  }
1616
+ if ((0, tronwallet_abstract_adapter_1.isInBrowser)() && !(0, tronwallet_abstract_adapter_1.isInMobileBrowser)()) {
1617
+ // Desktop: use TIP-6963 event-based discovery with fallback
1618
+ this._checkPromise = new Promise((resolve) => {
1619
+ let handled = false;
1620
+ let timer = null;
1621
+ let handler = null;
1622
+ const cleanupDesktopDetection = () => {
1623
+ if (timer) {
1624
+ clearTimeout(timer);
1625
+ timer = null;
1626
+ }
1627
+ if (typeof window !== 'undefined' && handler) {
1628
+ window.removeEventListener(tronwallet_abstract_adapter_1.TIP6963AnnounceProviderEventName, handler);
1629
+ }
1630
+ };
1631
+ const finishWithLegacyDetection = () => {
1632
+ if (handled) {
1633
+ return;
1634
+ }
1635
+ handled = true;
1636
+ cleanupDesktopDetection();
1637
+ if (typeof window === 'undefined') {
1638
+ resolve(false);
1639
+ return;
1640
+ }
1641
+ // Fallback to legacy detection
1642
+ this._updateWallet();
1643
+ const isSupport = this.state !== tronwallet_abstract_adapter_1.AdapterState.NotFound;
1644
+ this._readyState = isSupport ? tronwallet_abstract_adapter_1.WalletReadyState.Found : tronwallet_abstract_adapter_1.WalletReadyState.NotFound;
1645
+ this.emit('readyStateChanged', this._readyState);
1646
+ resolve(isSupport);
1647
+ };
1648
+ timer = setTimeout(finishWithLegacyDetection, this.config.checkTimeout);
1649
+ handler = (event) => __awaiter(this, void 0, void 0, function* () {
1650
+ var _a, _b;
1651
+ if (handled) {
1652
+ return;
1653
+ }
1654
+ const { info, provider } = event.detail;
1655
+ const isTronLinkProvider = info.name === 'TronLink';
1656
+ if (isTronLinkProvider) {
1657
+ handled = true;
1658
+ this._supportNewTronProtocol = true;
1659
+ this._wallet = provider;
1660
+ try {
1661
+ yield this.checkSecurity();
1662
+ }
1663
+ catch (_c) {
1664
+ this.setAddress(null);
1665
+ this.setState(tronwallet_abstract_adapter_1.AdapterState.Disconnect);
1666
+ this._readyState = tronwallet_abstract_adapter_1.WalletReadyState.Found;
1667
+ this.emit('readyStateChanged', this.readyState);
1668
+ resolve(true);
1669
+ return;
1670
+ }
1671
+ this._listenTronEvent();
1672
+ this._readyState = tronwallet_abstract_adapter_1.WalletReadyState.Found;
1673
+ const address = (((_a = this._wallet) === null || _a === void 0 ? void 0 : _a.tronWeb) && ((_b = this._wallet.tronWeb.defaultAddress) === null || _b === void 0 ? void 0 : _b.base58)) || null;
1674
+ const state = address ? tronwallet_abstract_adapter_1.AdapterState.Connected : tronwallet_abstract_adapter_1.AdapterState.Disconnect;
1675
+ this.setAddress(address);
1676
+ this.setState(state);
1677
+ this.emit('readyStateChanged', this.readyState);
1678
+ cleanupDesktopDetection();
1679
+ resolve(true);
1680
+ }
1681
+ });
1682
+ window.addEventListener(tronwallet_abstract_adapter_1.TIP6963AnnounceProviderEventName, handler);
1683
+ window.dispatchEvent(new Event(tronwallet_abstract_adapter_1.TIP6963RequestProviderEventName));
1684
+ });
1685
+ return this._checkPromise;
1686
+ }
1687
+ // Mobile: use legacy polling detection
1222
1688
  const interval = 100;
1223
- const checkTronTimes = Math.floor(2000 / interval);
1224
1689
  const maxTimes = Math.floor(this.config.checkTimeout / interval);
1225
1690
  let times = 0, timer;
1226
1691
  this._checkPromise = new Promise((resolve) => {
1227
1692
  const check = () => {
1228
1693
  times++;
1229
- const isSupport = times < checkTronTimes && !(0, tronwallet_abstract_adapter_1.isInMobileBrowser)() ? (0, utils_js_1.supportTron)() : (0, utils_js_1.supportTronLink)();
1694
+ this._updateWallet();
1695
+ const isSupport = !!((0, tronwallet_abstract_adapter_1.isInMobileBrowser)() && (window.tronLink || window.tronWeb));
1230
1696
  if (isSupport || times > maxTimes) {
1231
1697
  timer && clearInterval(timer);
1232
1698
  this._readyState = isSupport ? tronwallet_abstract_adapter_1.WalletReadyState.Found : tronwallet_abstract_adapter_1.WalletReadyState.NotFound;
1233
- this._updateWallet();
1234
1699
  this.emit('readyStateChanged', this.readyState);
1235
1700
  resolve(isSupport);
1236
1701
  }
@@ -1389,15 +1854,24 @@
1389
1854
  const utils_js_1 = requireUtils();
1390
1855
  const tronwallet_abstract_adapter_2 = /*@__PURE__*/ requireCjs$2();
1391
1856
  exports$1.TokenPocketAdapterName = 'TokenPocket';
1392
- class TokenPocketAdapter extends tronwallet_abstract_adapter_1.Adapter {
1857
+ class TokenPocketAdapter extends tronwallet_abstract_adapter_1.AddonAdapter {
1393
1858
  constructor(config = {}) {
1394
- super();
1859
+ super(config);
1395
1860
  this.name = exports$1.TokenPocketAdapterName;
1396
1861
  this.url = 'https://tokenpocket.pro/';
1397
1862
  this.icon = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGc+CjxwYXRoIGQ9Ik0xMDQxLjUyIDBILTI3VjEwMjRIMTA0MS41MlYwWiIgZmlsbD0iIzI5ODBGRSIvPgo8ZyBjbGlwLXBhdGg9InVybCgjY2xpcDBfNDA4XzIyNSkiPgo8cGF0aCBkPSJNNDA2Ljc5NiA0MzguNjQzSDQwNi45MjdDNDA2Ljc5NiA0MzcuODU3IDQwNi43OTYgNDM2Ljk0IDQwNi43OTYgNDM2LjE1NFY0MzguNjQzWiIgZmlsbD0iIzI5QUVGRiIvPgo8cGF0aCBkPSJNNjY3LjYwMiA0NjMuNTMzSDUyMy4yNDlWNzI0LjA3NkM1MjMuMjQ5IDczNi4zODkgNTMzLjIwNCA3NDYuMzQ1IDU0NS41MTcgNzQ2LjM0NUg2NDUuMzMzQzY1Ny42NDcgNzQ2LjM0NSA2NjcuNjAyIDczNi4zODkgNjY3LjYwMiA3MjQuMDc2VjQ2My41MzNaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNNDUzLjU2MyAyNzdINDQ4LjcxNkgxOTAuMjY5QzE3Ny45NTUgMjc3IDE2OCAyODYuOTU1IDE2OCAyOTkuMjY5VjM4OS42NTNDMTY4IDQwMS45NjcgMTc3Ljk1NSA0MTEuOTIyIDE5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WxsPSJ3aGl0ZSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTY4IDI3NykiLz4KPC9jbGlwUGF0aD4KPC9kZWZzPgo8L3N2Zz4K';
1398
1863
  this._readyState = (0, tronwallet_abstract_adapter_1.isInBrowser)() ? tronwallet_abstract_adapter_1.WalletReadyState.Loading : tronwallet_abstract_adapter_1.WalletReadyState.NotFound;
1399
1864
  this._state = tronwallet_abstract_adapter_1.AdapterState.Loading;
1865
+ /**
1866
+ * Whether the most recent security check passed. Gates the auto-connect
1867
+ * paths (e.g. `onAccountsChanged`) so a wallet that failed the security
1868
+ * check cannot silently connect when the extension emits account events.
1869
+ */
1870
+ this._securityPassed = false;
1400
1871
  this.onAccountsChanged = (accounts) => {
1872
+ // Do not auto-connect via account events when the security check has not passed.
1873
+ if (!this._securityPassed)
1874
+ return;
1401
1875
  const preAddr = this.address || '';
1402
1876
  const curAddr = (accounts === null || accounts === void 0 ? void 0 : accounts[0]) || '';
1403
1877
  if (!curAddr) {
@@ -1419,11 +1893,22 @@
1419
1893
  };
1420
1894
  this.checkReadyInterval = null;
1421
1895
  this._checkPromise = null;
1422
- this._updateWallet = () => {
1896
+ this._updateWallet = () => __awaiter(this, void 0, void 0, function* () {
1423
1897
  var _a, _b, _c, _d, _e;
1424
1898
  let state = this.state;
1425
1899
  let address = this.address;
1426
1900
  if ((0, utils_js_1.supportTokenPocket)()) {
1901
+ try {
1902
+ yield this.checkSecurity();
1903
+ this._securityPassed = true;
1904
+ }
1905
+ catch (_f) {
1906
+ this._securityPassed = false;
1907
+ this.stopListenTronEvent();
1908
+ this.setAddress(null);
1909
+ this.setState(tronwallet_abstract_adapter_1.AdapterState.Disconnect);
1910
+ return;
1911
+ }
1427
1912
  const tron = (_a = window.tokenpocket) === null || _a === void 0 ? void 0 : _a.tron;
1428
1913
  this._wallet = (0, tronwallet_abstract_adapter_1.isInMobileBrowser)()
1429
1914
  ? {
@@ -1449,22 +1934,18 @@
1449
1934
  }
1450
1935
  this.setAddress(address);
1451
1936
  this.setState(state);
1452
- };
1453
- const { checkTimeout = 2 * 1000, openUrlWhenWalletNotFound = true, openAppWithDeeplink = true } = config;
1454
- if (typeof checkTimeout !== 'number') {
1455
- throw new Error('[TokenPocketAdapter] config.checkTimeout should be a number');
1456
- }
1457
- this.config = {
1458
- checkTimeout,
1459
- openAppWithDeeplink,
1460
- openUrlWhenWalletNotFound,
1461
- };
1937
+ });
1938
+ this.config = Object.assign({}, this.commonConfig);
1462
1939
  this._connecting = false;
1463
1940
  this._wallet = null;
1464
1941
  this._address = null;
1465
1942
  if ((0, tronwallet_abstract_adapter_1.isInMobileBrowser)() && (0, utils_js_1.supportTokenPocket)()) {
1466
1943
  this._readyState = tronwallet_abstract_adapter_1.WalletReadyState.Found;
1467
- this._updateWallet();
1944
+ this._updateWallet().then(() => {
1945
+ if (this.connected) {
1946
+ this.emit('connect', this.address || '');
1947
+ }
1948
+ });
1468
1949
  }
1469
1950
  else {
1470
1951
  this._checkWallet().then(() => {
@@ -1515,42 +1996,26 @@
1515
1996
  connect() {
1516
1997
  return __awaiter(this, void 0, void 0, function* () {
1517
1998
  try {
1518
- this.checkIfOpenApp();
1519
- if (this.connected || this.connecting)
1999
+ if (!(yield this._beforeConnect()))
1520
2000
  return;
1521
- yield this._checkWallet();
1522
- if (this.readyState === tronwallet_abstract_adapter_1.WalletReadyState.NotFound) {
1523
- if (this.config.openUrlWhenWalletNotFound !== false && (0, tronwallet_abstract_adapter_1.isInBrowser)()) {
1524
- window.open(this.url, '_blank');
1525
- }
1526
- throw new tronwallet_abstract_adapter_1.WalletNotFoundError();
1527
- }
2001
+ this._securityPassed = true;
1528
2002
  if (!this._wallet)
1529
2003
  return;
1530
2004
  this._connecting = true;
1531
2005
  const wallet = this._wallet;
1532
- try {
1533
- const res = yield wallet.tron.request({ method: 'eth_requestAccounts' });
1534
- if (!(res === null || res === void 0 ? void 0 : res[0])) {
1535
- throw new tronwallet_abstract_adapter_1.WalletConnectionError('Request connect error.');
1536
- }
1537
- const address = res[0];
1538
- this.setAddress(address);
1539
- this.setState(tronwallet_abstract_adapter_1.AdapterState.Connected);
1540
- this.emit('connect', this.address || '');
1541
- }
1542
- catch (e) {
1543
- if (e instanceof tronwallet_abstract_adapter_1.WalletError) {
1544
- throw e;
1545
- }
1546
- else {
1547
- throw new tronwallet_abstract_adapter_1.WalletConnectionError(e === null || e === void 0 ? void 0 : e.message, e);
1548
- }
2006
+ const res = yield wallet.tron.request({ method: 'eth_requestAccounts' });
2007
+ if (!(res === null || res === void 0 ? void 0 : res[0])) {
2008
+ throw new tronwallet_abstract_adapter_1.WalletConnectionError('Request connect error.');
1549
2009
  }
2010
+ const address = res[0];
2011
+ this.setAddress(address);
2012
+ this.setState(tronwallet_abstract_adapter_1.AdapterState.Connected);
2013
+ this.emit('connect', this.address || '');
1550
2014
  }
1551
2015
  catch (error) {
1552
- this.emit('error', error);
1553
- throw error;
2016
+ const err = error instanceof tronwallet_abstract_adapter_1.WalletError ? error : new tronwallet_abstract_adapter_1.WalletConnectionError(error === null || error === void 0 ? void 0 : error.message, error);
2017
+ this.emit('error', err);
2018
+ throw err;
1554
2019
  }
1555
2020
  finally {
1556
2021
  this._connecting = false;
@@ -1562,6 +2027,7 @@
1562
2027
  if (this.state !== tronwallet_abstract_adapter_1.AdapterState.Connected) {
1563
2028
  return;
1564
2029
  }
2030
+ this._securityPassed = false;
1565
2031
  this.setAddress(null);
1566
2032
  this.setState(tronwallet_abstract_adapter_1.AdapterState.Disconnect);
1567
2033
  this.emit('disconnect');
@@ -1681,6 +2147,12 @@
1681
2147
  throw new tronwallet_abstract_adapter_1.WalletNotFoundError();
1682
2148
  }
1683
2149
  }
2150
+ _openAppByDeepLinkIfNeed() {
2151
+ if (this.config.openAppWithDeeplink === false) {
2152
+ return false;
2153
+ }
2154
+ return (0, utils_js_1.openTokenPocket)();
2155
+ }
1684
2156
  checkForWalletReady() {
1685
2157
  if (this.checkReadyInterval) {
1686
2158
  return;
@@ -1741,7 +2213,7 @@
1741
2213
  }
1742
2214
  this.emit('readyStateChanged', this._readyState);
1743
2215
  }, this.config.checkTimeout);
1744
- const handler = (event) => {
2216
+ const handler = (event) => __awaiter(this, void 0, void 0, function* () {
1745
2217
  var _a, _b, _c;
1746
2218
  const { info, provider } = event.detail;
1747
2219
  if (info.name === 'TokenPocket') {
@@ -1754,6 +2226,19 @@
1754
2226
  this._readyState = tronwallet_abstract_adapter_1.WalletReadyState.Found;
1755
2227
  const address = ((_c = this._wallet.tronWeb.defaultAddress) === null || _c === void 0 ? void 0 : _c.base58) || null;
1756
2228
  const state = address ? tronwallet_abstract_adapter_1.AdapterState.Connected : tronwallet_abstract_adapter_1.AdapterState.Disconnect;
2229
+ try {
2230
+ yield this.checkSecurity();
2231
+ this._securityPassed = true;
2232
+ }
2233
+ catch (_d) {
2234
+ this._securityPassed = false;
2235
+ this.stopListenTronEvent();
2236
+ this.setAddress(null);
2237
+ this.setState(tronwallet_abstract_adapter_1.AdapterState.Disconnect);
2238
+ clearTimeout(timer);
2239
+ resolve(true);
2240
+ return;
2241
+ }
1757
2242
  this.setState(state);
1758
2243
  this.setAddress(address);
1759
2244
  this.emit('readyStateChanged', this.readyState);
@@ -1764,7 +2249,7 @@
1764
2249
  this.checkForWalletReady();
1765
2250
  }
1766
2251
  }
1767
- };
2252
+ });
1768
2253
  window.addEventListener(tronwallet_abstract_adapter_2.TIP6963AnnounceProviderEventName, handler);
1769
2254
  window.dispatchEvent(new Event(tronwallet_abstract_adapter_2.TIP6963RequestProviderEventName));
1770
2255
  });