@subwallet/extension-base 1.0.1 → 1.0.2-1

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.
Files changed (169) hide show
  1. package/background/KoniTypes.d.ts +10 -3
  2. package/background/KoniTypes.js +6 -0
  3. package/cjs/background/KoniTypes.js +8 -1
  4. package/cjs/constants/index.js +6 -3
  5. package/cjs/koni/api/dotsama/balance.js +11 -0
  6. package/cjs/koni/api/staking/bonding/amplitude.js +6 -2
  7. package/cjs/koni/api/staking/bonding/astar.js +40 -243
  8. package/cjs/koni/api/staking/bonding/index.js +4 -4
  9. package/cjs/koni/api/staking/bonding/paraChain.js +16 -10
  10. package/cjs/koni/api/staking/bonding/relayChain.js +62 -7
  11. package/cjs/koni/api/staking/bonding/utils.js +29 -3
  12. package/cjs/koni/api/xcm/index.js +0 -111
  13. package/cjs/koni/api/xcm/polkadotXcm.js +1 -1
  14. package/cjs/koni/api/xcm/xTokens.js +2 -4
  15. package/cjs/koni/background/cron.js +61 -62
  16. package/cjs/koni/background/handlers/Extension.js +143 -149
  17. package/cjs/koni/background/handlers/State.js +129 -91
  18. package/cjs/koni/background/handlers/Tabs.js +40 -38
  19. package/cjs/koni/background/subscription.js +48 -43
  20. package/cjs/packageInfo.js +1 -1
  21. package/cjs/page/index.js +5 -0
  22. package/cjs/services/chain-service/constants.js +1 -11
  23. package/cjs/services/chain-service/index.js +39 -5
  24. package/cjs/services/chain-service/utils.js +4 -0
  25. package/cjs/services/event-service/index.js +71 -0
  26. package/cjs/services/event-service/types.js +1 -0
  27. package/cjs/services/history-service/index.js +36 -17
  28. package/cjs/services/history-service/subsquid-multi-chain-history.js +7 -2
  29. package/cjs/services/keyring-service/index.js +101 -0
  30. package/cjs/services/migration-service/index.js +13 -10
  31. package/cjs/{koni/migration/scripts/RemoveWrongCrowdloan.js → services/migration-service/scripts/AutoEnableChainsTokens.js} +11 -6
  32. package/cjs/services/migration-service/scripts/MigrateNetworkSettings.js +39 -19
  33. package/cjs/services/migration-service/scripts/MigrateSettings.js +31 -0
  34. package/cjs/services/migration-service/scripts/MigrateTransactionHistory.js +72 -0
  35. package/cjs/services/migration-service/scripts/index.js +13 -4
  36. package/cjs/services/price-service/coingecko.js +16 -3
  37. package/cjs/services/price-service/index.js +15 -17
  38. package/cjs/services/request-service/constants.js +8 -2
  39. package/cjs/services/request-service/handler/AuthRequestHandler.js +39 -12
  40. package/cjs/services/request-service/index.js +3 -0
  41. package/cjs/services/storage-service/DatabaseService.js +1 -1
  42. package/cjs/services/storage-service/databases/index.js +1 -1
  43. package/cjs/services/storage-service/db-stores/BaseStoreWithAddressAndChain.js +2 -8
  44. package/cjs/services/storage-service/db-stores/Nft.js +4 -1
  45. package/cjs/services/storage-service/db-stores/Transaction.js +10 -7
  46. package/cjs/services/subscan-service/index.js +107 -0
  47. package/cjs/services/subscan-service/subscan-chain-map.js +74 -0
  48. package/cjs/services/subscan-service/types.js +1 -0
  49. package/cjs/services/transaction-service/index.js +45 -10
  50. package/cjs/services/transaction-service/utils.js +4 -6
  51. package/cjs/utils/address.js +9 -1
  52. package/cjs/utils/index.js +24 -13
  53. package/constants/index.d.ts +1 -0
  54. package/constants/index.js +1 -0
  55. package/koni/api/dotsama/balance.js +11 -0
  56. package/koni/api/staking/bonding/amplitude.d.ts +1 -1
  57. package/koni/api/staking/bonding/amplitude.js +8 -4
  58. package/koni/api/staking/bonding/astar.d.ts +2 -11
  59. package/koni/api/staking/bonding/astar.js +35 -229
  60. package/koni/api/staking/bonding/index.d.ts +1 -1
  61. package/koni/api/staking/bonding/index.js +4 -4
  62. package/koni/api/staking/bonding/paraChain.d.ts +1 -1
  63. package/koni/api/staking/bonding/paraChain.js +17 -11
  64. package/koni/api/staking/bonding/relayChain.d.ts +1 -1
  65. package/koni/api/staking/bonding/relayChain.js +63 -8
  66. package/koni/api/staking/bonding/utils.d.ts +13 -1
  67. package/koni/api/staking/bonding/utils.js +27 -3
  68. package/koni/api/xcm/index.js +1 -112
  69. package/koni/api/xcm/polkadotXcm.js +1 -1
  70. package/koni/api/xcm/xTokens.js +3 -5
  71. package/koni/background/cron.js +60 -60
  72. package/koni/background/handlers/Extension.js +71 -76
  73. package/koni/background/handlers/State.d.ts +16 -14
  74. package/koni/background/handlers/State.js +126 -91
  75. package/koni/background/handlers/Tabs.js +22 -19
  76. package/koni/background/subscription.d.ts +1 -1
  77. package/koni/background/subscription.js +49 -44
  78. package/package.json +56 -16
  79. package/packageInfo.js +1 -1
  80. package/page/index.d.ts +2 -0
  81. package/page/index.js +4 -0
  82. package/services/chain-service/constants.d.ts +0 -1
  83. package/services/chain-service/constants.js +0 -9
  84. package/services/chain-service/index.d.ts +6 -4
  85. package/services/chain-service/index.js +39 -7
  86. package/services/chain-service/utils.d.ts +1 -0
  87. package/services/chain-service/utils.js +3 -0
  88. package/services/event-service/index.d.ts +22 -0
  89. package/services/event-service/index.js +59 -0
  90. package/services/event-service/types.d.ts +32 -0
  91. package/services/event-service/types.js +1 -0
  92. package/services/history-service/index.d.ts +5 -3
  93. package/services/history-service/index.js +36 -17
  94. package/services/history-service/subsquid-multi-chain-history.js +7 -2
  95. package/services/keyring-service/index.d.ts +19 -0
  96. package/services/keyring-service/index.js +93 -0
  97. package/services/migration-service/index.js +11 -9
  98. package/services/migration-service/scripts/AutoEnableChainsTokens.d.ts +4 -0
  99. package/services/migration-service/scripts/AutoEnableChainsTokens.js +13 -0
  100. package/services/migration-service/scripts/MigrateNetworkSettings.js +37 -18
  101. package/services/migration-service/scripts/MigrateSettings.d.ts +4 -0
  102. package/services/migration-service/scripts/MigrateSettings.js +23 -0
  103. package/services/migration-service/scripts/MigrateTransactionHistory.d.ts +4 -0
  104. package/services/migration-service/scripts/MigrateTransactionHistory.js +64 -0
  105. package/services/migration-service/scripts/index.d.ts +1 -0
  106. package/services/migration-service/scripts/index.js +10 -3
  107. package/services/price-service/coingecko.js +16 -3
  108. package/services/price-service/index.d.ts +5 -3
  109. package/services/price-service/index.js +15 -17
  110. package/services/request-service/constants.d.ts +1 -0
  111. package/services/request-service/constants.js +6 -1
  112. package/services/request-service/handler/AuthRequestHandler.d.ts +8 -1
  113. package/services/request-service/handler/AuthRequestHandler.js +40 -13
  114. package/services/request-service/index.d.ts +7 -1
  115. package/services/request-service/index.js +3 -0
  116. package/services/storage-service/DatabaseService.js +1 -1
  117. package/services/storage-service/databases/index.js +1 -1
  118. package/services/storage-service/db-stores/BaseStoreWithAddressAndChain.d.ts +1 -1
  119. package/services/storage-service/db-stores/BaseStoreWithAddressAndChain.js +2 -8
  120. package/services/storage-service/db-stores/Nft.d.ts +2 -1
  121. package/services/storage-service/db-stores/Nft.js +4 -1
  122. package/services/storage-service/db-stores/Transaction.js +10 -7
  123. package/services/subscan-service/index.d.ts +20 -0
  124. package/services/subscan-service/index.js +99 -0
  125. package/services/subscan-service/subscan-chain-map.d.ts +5 -0
  126. package/services/subscan-service/subscan-chain-map.js +63 -0
  127. package/services/subscan-service/types.d.ts +27 -0
  128. package/services/subscan-service/types.js +1 -0
  129. package/services/transaction-service/event-parser/index.d.ts +2 -2
  130. package/services/transaction-service/index.d.ts +4 -2
  131. package/services/transaction-service/index.js +45 -10
  132. package/services/transaction-service/utils.js +5 -6
  133. package/utils/address.d.ts +1 -0
  134. package/utils/address.js +9 -2
  135. package/utils/index.d.ts +1 -0
  136. package/utils/index.js +21 -12
  137. package/cjs/background/errors/EvmRpcError.js +0 -21
  138. package/cjs/background/errors/SubWalletProviderError.js +0 -17
  139. package/cjs/constants/ethereum.js +0 -19
  140. package/cjs/errors/SubWalletProviderError.js +0 -17
  141. package/cjs/koni/api/xcm/astar.js +0 -160
  142. package/cjs/koni/api/xcm/moonbeamXcm.js +0 -80
  143. package/cjs/koni/api/xcm/statemintXcm.js +0 -197
  144. package/cjs/koni/api/xcm/substrateXcm.js +0 -213
  145. package/cjs/koni/migration/Base.js +0 -20
  146. package/cjs/koni/migration/index.js +0 -45
  147. package/cjs/koni/migration/scripts/ChangeRouteToHome.js +0 -22
  148. package/cjs/koni/migration/scripts/ClearOldStorage.js +0 -24
  149. package/cjs/koni/migration/scripts/RemoveWrongTransactionHistoriesFromStore.js +0 -36
  150. package/cjs/koni/migration/scripts/ResetTransactionHistoryEventIdx.js +0 -21
  151. package/cjs/koni/migration/scripts/index.js +0 -22
  152. package/cjs/koni/page/index.js +0 -16
  153. package/cjs/services/asset-service/index.js +0 -91
  154. package/cjs/services/storage-service/db-stores/ExtraDelegationInfo.js +0 -17
  155. package/cjs/stores/Balance.js +0 -18
  156. package/cjs/stores/Crowdloan.js +0 -18
  157. package/cjs/stores/CustomEvmToken.js +0 -18
  158. package/cjs/stores/NetworkMap.js +0 -18
  159. package/cjs/stores/Nft.js +0 -18
  160. package/cjs/stores/NftCollection.js +0 -18
  161. package/cjs/stores/Price.js +0 -18
  162. package/cjs/stores/Staking.js +0 -18
  163. package/cjs/stores/StakingReward.js +0 -18
  164. package/cjs/utils/eth/parseTransactionData.js +0 -284
  165. package/koni/page/index.d.ts +0 -2
  166. package/koni/page/index.js +0 -9
  167. /package/cjs/{koni/page → page}/SubWalleEvmProvider.js +0 -0
  168. /package/{koni/page → page}/SubWalleEvmProvider.d.ts +0 -0
  169. /package/{koni/page → page}/SubWalleEvmProvider.js +0 -0
@@ -108,10 +108,15 @@ export function parseSubsquidTransactionData(address, type, historyItem, chainIn
108
108
  to = autoFormatAddress(parsedArgs.to);
109
109
  from = autoFormatAddress(parsedArgs.from);
110
110
  extrinsicHash = parsedArgs.transactionHash;
111
- amount = transaction.value;
111
+ amount = transaction.value || '0';
112
112
  fee = (parseInt(transaction.gasPrice) * parseInt(transaction.gasLimit)).toString();
113
113
  signature = generateSignature(transaction.signature);
114
114
  success = extrinsic.success;
115
+
116
+ // Special fix for moonbeam
117
+ if ((historyItem.chainId === 'moonbeam' || historyItem.chainId === 'moonriver') && typeof amount === 'object') {
118
+ amount = amount[0];
119
+ }
115
120
  break;
116
121
  }
117
122
 
@@ -156,7 +161,7 @@ export function parseSubsquidTransactionData(address, type, historyItem, chainIn
156
161
  }
157
162
  return {
158
163
  address,
159
- origin: MULTI_CHAIN_URL,
164
+ origin: 'subsquid',
160
165
  time: toTimestamp(historyItem.timestamp),
161
166
  chainType,
162
167
  from,
@@ -0,0 +1,19 @@
1
+ import { CurrentAccountInfo, KeyringState } from '@subwallet/extension-base/background/KoniTypes';
2
+ import { EventService } from '@subwallet/extension-base/services/event-service';
3
+ import { SubjectInfo } from '@subwallet/ui-keyring/observable/types';
4
+ import { BehaviorSubject } from 'rxjs';
5
+ export declare class KeyringService {
6
+ private readonly currentAccountStore;
7
+ readonly currentAccountSubject: BehaviorSubject<CurrentAccountInfo>;
8
+ readonly accountsSubject: BehaviorSubject<SubjectInfo>;
9
+ private beforeAccount;
10
+ readonly keyringStateSubject: BehaviorSubject<KeyringState>;
11
+ private eventService;
12
+ constructor(eventService: EventService);
13
+ private subscribeAccounts;
14
+ get keyringState(): KeyringState;
15
+ updateKeyringState(isReady?: boolean): void;
16
+ get accounts(): SubjectInfo;
17
+ get currentAccount(): CurrentAccountInfo;
18
+ setCurrentAccount(currentAccountData: CurrentAccountInfo): void;
19
+ }
@@ -0,0 +1,93 @@
1
+ // Copyright 2019-2022 @subwallet/extension-base
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { CurrentAccountStore } from '@subwallet/extension-base/stores';
5
+ import { keyring } from '@subwallet/ui-keyring';
6
+ import { BehaviorSubject } from 'rxjs';
7
+ export class KeyringService {
8
+ currentAccountStore = new CurrentAccountStore();
9
+ currentAccountSubject = new BehaviorSubject({
10
+ address: '',
11
+ currentGenesisHash: null
12
+ });
13
+ accountsSubject = keyring.accounts.subject;
14
+ beforeAccount = keyring.accounts.subject.value;
15
+ keyringStateSubject = new BehaviorSubject({
16
+ isReady: false,
17
+ hasMasterPassword: false,
18
+ isLocked: false
19
+ });
20
+ constructor(eventService) {
21
+ this.eventService = eventService;
22
+ this.currentAccountStore.get('CurrentAccountInfo', rs => {
23
+ this.currentAccountSubject.next(rs);
24
+ });
25
+ this.subscribeAccounts().catch(console.error);
26
+ }
27
+ async subscribeAccounts() {
28
+ // Wait until account ready
29
+ await new Promise(resolve => {
30
+ const onReady = () => {
31
+ this.eventService.off('account.ready', onReady);
32
+ resolve(true);
33
+ };
34
+ this.eventService.on('account.ready', onReady);
35
+ });
36
+ this.beforeAccount = {
37
+ ...this.accountsSubject.value
38
+ };
39
+ this.accountsSubject.subscribe(subjectInfo => {
40
+ // Check if accounts changed
41
+ const beforeAddresses = Object.keys(this.beforeAccount);
42
+ const afterAddresses = Object.keys(subjectInfo);
43
+ if (beforeAddresses.length > afterAddresses.length) {
44
+ const removedAddresses = beforeAddresses.filter(address => !afterAddresses.includes(address));
45
+
46
+ // Remove account
47
+ removedAddresses.forEach(address => {
48
+ console.log('account.remove', address);
49
+ this.eventService.emit('account.remove', address);
50
+ });
51
+ } else if (beforeAddresses.length < afterAddresses.length) {
52
+ const addedAddresses = afterAddresses.filter(address => !beforeAddresses.includes(address));
53
+
54
+ // Add account
55
+ addedAddresses.forEach(address => {
56
+ console.log('account.add', address);
57
+ this.eventService.emit('account.add', address);
58
+ });
59
+ } else {
60
+ // Handle case update later
61
+ }
62
+ this.beforeAccount = {
63
+ ...subjectInfo
64
+ };
65
+ });
66
+ }
67
+ get keyringState() {
68
+ return this.keyringStateSubject.value;
69
+ }
70
+ updateKeyringState(isReady = true) {
71
+ var _keyring$keyring, _keyring$keyring2;
72
+ if (!this.keyringState.isReady && isReady) {
73
+ this.eventService.emit('keyring.ready', true);
74
+ this.eventService.emit('account.ready', true);
75
+ }
76
+ this.keyringStateSubject.next({
77
+ hasMasterPassword: !!((_keyring$keyring = keyring.keyring) !== null && _keyring$keyring !== void 0 && _keyring$keyring.hasMasterPassword),
78
+ isLocked: !!((_keyring$keyring2 = keyring.keyring) !== null && _keyring$keyring2 !== void 0 && _keyring$keyring2.isLocked),
79
+ isReady: isReady
80
+ });
81
+ }
82
+ get accounts() {
83
+ return this.accountsSubject.value;
84
+ }
85
+ get currentAccount() {
86
+ return this.currentAccountSubject.value;
87
+ }
88
+ setCurrentAccount(currentAccountData) {
89
+ this.currentAccountSubject.next(currentAccountData);
90
+ this.eventService.emit('account.updateCurrent', currentAccountData);
91
+ this.currentAccountStore.set('CurrentAccountInfo', currentAccountData);
92
+ }
93
+ }
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
4
  import { logger as createLogger } from '@polkadot/util';
5
- import MigrationScripts from "./scripts/index.js";
5
+ import MigrationScripts, { EVERYTIME } from "./scripts/index.js";
6
6
  export default class MigrationService {
7
7
  constructor(state) {
8
8
  this.state = state;
@@ -14,23 +14,25 @@ export default class MigrationService {
14
14
  try {
15
15
  for (let i = 0; i < keys.length; i++) {
16
16
  const JobClass = MigrationScripts[keys[i]];
17
+ const key = keys[i];
18
+ const name = JobClass.name;
17
19
  const check = await this.state.dbService.stores.migration.table.where({
18
- name: JobClass.name,
19
- key: keys[i]
20
+ name,
21
+ key
20
22
  }).first();
21
- if (!check) {
22
- const job = new JobClass(this.state);
23
+ if (!check || key.startsWith(EVERYTIME)) {
23
24
  this.logger.log('Running script: ', JobClass.name);
25
+ const job = new JobClass(this.state);
24
26
  await job.run();
25
27
  await this.state.dbService.stores.migration.table.put({
26
- key: keys[i],
27
- name: JobClass.name,
28
- timestamp: +new Date()
28
+ key,
29
+ name,
30
+ timestamp: new Date().getTime()
29
31
  });
30
32
  }
31
33
  }
32
34
  } catch (error) {
33
- this.logger.warn('Migration error: ', error);
35
+ this.logger.error('Migration error: ', error);
34
36
  }
35
37
  this.logger.log('Migration done.');
36
38
  }
@@ -0,0 +1,4 @@
1
+ import BaseMigrationJob from '@subwallet/extension-base/services/migration-service/Base';
2
+ export default class AutoEnableChainsTokens extends BaseMigrationJob {
3
+ run(): Promise<void>;
4
+ }
@@ -0,0 +1,13 @@
1
+ // Copyright 2019-2022 @subwallet/extension-koni authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import BaseMigrationJob from '@subwallet/extension-base/services/migration-service/Base';
5
+ import { keyring } from '@subwallet/ui-keyring';
6
+ export default class AutoEnableChainsTokens extends BaseMigrationJob {
7
+ async run() {
8
+ const accounts = keyring.getAccounts();
9
+ await this.state.autoEnableChains(accounts.map(({
10
+ address
11
+ }) => address));
12
+ }
13
+ }
@@ -1,30 +1,49 @@
1
1
  // Copyright 2019-2022 @subwallet/extension-koni authors & contributors
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
+ import { _AssetType } from '@subwallet/chain-list/types';
4
5
  import BaseMigrationJob from '@subwallet/extension-base/services/migration-service/Base';
5
6
  export default class MigrateNetworkSettings extends BaseMigrationJob {
6
7
  async run() {
7
8
  const state = this.state;
8
- return new Promise((resolve, reject) => {
9
- chrome.storage.local.get('NetworkMap', function (items) {
10
- if (items && items.NetworkMap) {
11
- const networkMap = items.NetworkMap;
12
- const enableList = [];
13
- const stateMap = state.getChainStateMap();
14
- Object.entries(networkMap).forEach(([slug, chain]) => {
15
- if (chain.active) {
16
- const currentState = stateMap[slug];
9
+ const items = await new Promise(resolve => {
10
+ chrome.storage.local.get('NetworkMap', items => {
11
+ resolve(items);
12
+ });
13
+ });
14
+ const oldNetworkMap = items.NetworkMap;
15
+ const enableList = [];
16
+ const stateMap = state.getChainStateMap();
17
+ if (!oldNetworkMap) {
18
+ return;
19
+ }
20
+ Object.entries(oldNetworkMap).forEach(([slug, chain]) => {
21
+ if (chain.active) {
22
+ const currentState = stateMap[slug];
23
+
24
+ // Ensure chain in the list and is not active
25
+ currentState && enableList.push(slug);
26
+ }
27
+ });
28
+ if (enableList.length > 0) {
29
+ state.chainService.enableChains(enableList);
17
30
 
18
- // Ensure chain in the list and is not active
19
- currentState && !currentState.active && enableList.push(slug);
20
- }
21
- });
22
- if (enableList.length > 0) {
23
- state.chainService.enableChains(enableList);
24
- }
31
+ // Enable native token of these chains
32
+ const currentAssetSettings = await state.chainService.getAssetSettings();
33
+ const assetInfoMap = state.chainService.getAssetRegistry();
34
+ Object.entries(assetInfoMap).forEach(([slug, assetInfo]) => {
35
+ const assetSetting = currentAssetSettings[slug] || {};
36
+
37
+ // Enable native token of these chains
38
+ if (assetInfo.name && assetInfo.assetType === _AssetType.NATIVE && enableList.includes(assetInfo.originChain) && !assetSetting.visible) {
39
+ currentAssetSettings[slug] = {
40
+ visible: true
41
+ };
25
42
  }
26
- resolve();
27
43
  });
28
- });
44
+ state.chainService.setAssetSettings({
45
+ ...currentAssetSettings
46
+ });
47
+ }
29
48
  }
30
49
  }
@@ -0,0 +1,4 @@
1
+ import BaseMigrationJob from '@subwallet/extension-base/services/migration-service/Base';
2
+ export default class MigrateSettings extends BaseMigrationJob {
3
+ run(): Promise<void>;
4
+ }
@@ -0,0 +1,23 @@
1
+ // Copyright 2019-2022 @subwallet/extension-koni authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import BaseMigrationJob from '@subwallet/extension-base/services/migration-service/Base';
5
+ import uiSettings from '@polkadot/ui-settings';
6
+ export default class MigrateSettings extends BaseMigrationJob {
7
+ async run() {
8
+ try {
9
+ return new Promise(resolve => {
10
+ this.state.settingService.getSettings(currentSettings => {
11
+ const isAccessCamera = uiSettings.camera === 'on';
12
+ this.state.settingService.setSettings({
13
+ ...currentSettings,
14
+ camera: isAccessCamera
15
+ });
16
+ resolve();
17
+ });
18
+ });
19
+ } catch (e) {
20
+ console.error(e);
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,4 @@
1
+ import BaseMigrationJob from '@subwallet/extension-base/services/migration-service/Base';
2
+ export default class MigrateTransactionHistory extends BaseMigrationJob {
3
+ run(): Promise<void>;
4
+ }
@@ -0,0 +1,64 @@
1
+ // Copyright 2019-2022 @subwallet/extension-koni authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { ChainType, ExtrinsicStatus, ExtrinsicType, TransactionDirection } from '@subwallet/extension-base/background/KoniTypes';
5
+ import { _getChainNativeTokenBasicInfo } from '@subwallet/extension-base/services/chain-service/utils';
6
+ import BaseMigrationJob from '@subwallet/extension-base/services/migration-service/Base';
7
+ import Dexie from 'dexie';
8
+ import { isEthereumAddress } from '@polkadot/util-crypto';
9
+ export default class MigrateTransactionHistory extends BaseMigrationJob {
10
+ async run() {
11
+ const state = this.state;
12
+ const chainInfoMap = state.getChainInfoMap();
13
+ const assetList = Object.values(state.getAssetRegistry());
14
+ try {
15
+ const db = new Dexie('SubWalletDB');
16
+ const dexieDB = await db.open();
17
+ const transactionTable = dexieDB.table('transactions');
18
+ const oldTransactionData = await transactionTable.toArray();
19
+ const newTransactionItems = [];
20
+ oldTransactionData.forEach(item => {
21
+ const chainInfo = chainInfoMap[item.networkKey];
22
+ if (!chainInfo) {
23
+ return;
24
+ }
25
+ const direction = item.action === 'send' ? TransactionDirection.SEND : TransactionDirection.RECEIVED;
26
+ const extrinsicType = item.changeSymbol === item.feeSymbol ? ExtrinsicType.TRANSFER_BALANCE : ExtrinsicType.TRANSFER_TOKEN;
27
+ const nativeAsset = _getChainNativeTokenBasicInfo(chainInfo);
28
+ const transferAsset = assetList.find(a => a.originChain === item.networkKey && a.symbol === item.changeSymbol) || nativeAsset;
29
+ const newItem = {
30
+ chain: item.networkKey,
31
+ origin: 'migration',
32
+ type: extrinsicType,
33
+ address: item.address,
34
+ extrinsicHash: item.extrinsicHash,
35
+ time: item.time,
36
+ status: item.isSuccess ? ExtrinsicStatus.SUCCESS : ExtrinsicStatus.FAIL,
37
+ from: direction === TransactionDirection.SEND ? item.address : '',
38
+ to: direction === TransactionDirection.RECEIVED ? item.address : '',
39
+ amount: {
40
+ value: item.change,
41
+ decimals: transferAsset.decimals || 18,
42
+ symbol: transferAsset.symbol
43
+ },
44
+ fee: {
45
+ value: item.fee,
46
+ decimals: nativeAsset.decimals,
47
+ symbol: nativeAsset.symbol
48
+ },
49
+ direction: direction,
50
+ chainType: isEthereumAddress(item.address) ? ChainType.EVM : ChainType.SUBSTRATE,
51
+ chainName: chainInfo.name,
52
+ blockNumber: 0,
53
+ blockHash: '',
54
+ data: '',
55
+ signature: ''
56
+ };
57
+ newTransactionItems.push(newItem);
58
+ });
59
+ await state.historyService.addHistoryItems(newTransactionItems);
60
+ } catch (e) {
61
+ this.logger.error(e);
62
+ }
63
+ }
64
+ }
@@ -1,3 +1,4 @@
1
1
  import BaseMigrationJob from '../Base';
2
+ export declare const EVERYTIME = "__everytime__";
2
3
  declare const _default: Record<string, typeof BaseMigrationJob>;
3
4
  export default _default;
@@ -1,10 +1,17 @@
1
1
  // Copyright 2019-2022 @subwallet/extension-koni authors & contributors
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
+ import AutoEnableChainsTokens from '@subwallet/extension-base/services/migration-service/scripts/AutoEnableChainsTokens';
4
5
  import MigrateImportedToken from '@subwallet/extension-base/services/migration-service/scripts/MigrateImportedToken';
5
6
  import MigrateNetworkSettings from '@subwallet/extension-base/services/migration-service/scripts/MigrateNetworkSettings';
7
+ import MigrateSettings from '@subwallet/extension-base/services/migration-service/scripts/MigrateSettings';
8
+ import MigrateTransactionHistory from '@subwallet/extension-base/services/migration-service/scripts/MigrateTransactionHistory';
9
+ export const EVERYTIME = '__everytime__';
6
10
  export default {
7
- '1.0.1-1': MigrateNetworkSettings,
8
- '1.0.1-2': MigrateImportedToken
9
- // '1.0.1-0': ClearOldStorage
11
+ '1.0.1-11': MigrateNetworkSettings,
12
+ '1.0.1-20': MigrateImportedToken,
13
+ '1.0.1-30': MigrateTransactionHistory,
14
+ '1.0.1-40': AutoEnableChainsTokens,
15
+ '1.0.1-50': MigrateSettings
16
+ // [`${EVERYTIME}-1`]: AutoEnableChainsTokens
10
17
  };
@@ -2,15 +2,28 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
4
  import axios from 'axios';
5
+ let useBackupApi = false;
5
6
  export const getTokenPrice = async (priceIds, currency = 'usd') => {
6
7
  try {
8
+ var _res;
7
9
  const idStr = Array.from(priceIds).join(',');
8
- // const res = await axios.get(`https://api.coingecko.com/api/v3/coins/markets?vs_currency=${currency}&per_page=250&ids=${idStr}`);
9
- const res = await axios.get(`https://chain-data.subwallet.app/api/price/get?ids=${idStr}`);
10
+ let res;
11
+ if (!useBackupApi) {
12
+ try {
13
+ res = await axios.get(`https://api.coingecko.com/api/v3/coins/markets?vs_currency=${currency}&per_page=250&ids=${idStr}`);
14
+ } catch (err) {
15
+ useBackupApi = true;
16
+ }
17
+ }
18
+ if (useBackupApi || ((_res = res) === null || _res === void 0 ? void 0 : _res.status) !== 200) {
19
+ console.log('Use backup api for price');
20
+ useBackupApi = true;
21
+ res = await axios.get(`https://chain-data.subwallet.app/api/price/get?ids=${idStr}`);
22
+ }
10
23
  if (res.status !== 200) {
11
24
  console.warn('Failed to get token price');
12
25
  }
13
- const responseData = res.data;
26
+ const responseData = res.data || [];
14
27
  const priceMap = {};
15
28
  const price24hMap = {};
16
29
  responseData.forEach(val => {
@@ -1,14 +1,16 @@
1
- import { PriceJson, ServiceInfo } from '@subwallet/extension-base/background/KoniTypes';
1
+ import { PriceJson } from '@subwallet/extension-base/background/KoniTypes';
2
2
  import { ChainService } from '@subwallet/extension-base/services/chain-service';
3
+ import { EventService } from '@subwallet/extension-base/services/event-service';
3
4
  import DatabaseService from '@subwallet/extension-base/services/storage-service/DatabaseService';
4
- import { BehaviorSubject, Subject } from 'rxjs';
5
+ import { BehaviorSubject } from 'rxjs';
5
6
  export declare class PriceService {
6
7
  private dbService;
8
+ private eventService;
7
9
  private chainService;
8
10
  private priceSubject;
9
11
  private refreshTimeout;
10
12
  private priceIds;
11
- constructor(serviceInfoSubject: Subject<ServiceInfo>, dbService: DatabaseService, chainService: ChainService);
13
+ constructor(dbService: DatabaseService, eventService: EventService, chainService: ChainService);
12
14
  getPrice(): Promise<PriceJson>;
13
15
  getPriceSubject(): BehaviorSubject<PriceJson>;
14
16
  getPriceIds(): Set<string>;
@@ -13,27 +13,27 @@ const DEFAULT_PRICE_SUBJECT = {
13
13
  export class PriceService {
14
14
  priceSubject = new BehaviorSubject(DEFAULT_PRICE_SUBJECT);
15
15
  priceIds = new Set();
16
- constructor(serviceInfoSubject, dbService, chainService) {
16
+ constructor(dbService, eventService, chainService) {
17
17
  this.dbService = dbService;
18
+ this.eventService = eventService;
18
19
  this.chainService = chainService;
19
20
 
20
21
  // Fetch data from storage
21
22
  this.getPrice().catch(console.error);
23
+ const eventHandler = () => {
24
+ const newPriceIds = this.getPriceIds();
22
25
 
23
- // Add some delay to avoid fetching many times when start extension background
24
- // Subscribe service info to update price list
25
- setTimeout(() => {
26
+ // Compare two set newPriceIds and this.priceIds
27
+ if (newPriceIds.size !== this.priceIds.size || !Array.from(newPriceIds).every(v => this.priceIds.has(v))) {
28
+ this.priceIds = newPriceIds;
29
+ this.refreshPriceData(this.priceIds);
30
+ }
31
+ };
32
+ this.eventService.waitAssetReady.then(() => {
26
33
  this.refreshPriceData();
27
- serviceInfoSubject.subscribe(serviceInfo => {
28
- const newPriceIds = this.getPriceIds();
29
-
30
- // Compare two set newPriceIds and this.priceIds
31
- if (newPriceIds.size !== this.priceIds.size || !Array.from(newPriceIds).every(v => this.priceIds.has(v))) {
32
- this.priceIds = newPriceIds;
33
- this.refreshPriceData(this.priceIds);
34
- }
35
- });
36
- }, 3000);
34
+ this.eventService.on('asset.enable', eventHandler);
35
+ this.eventService.on('asset.update', eventHandler);
36
+ }).catch(console.error);
37
37
  }
38
38
  async getPrice() {
39
39
  const isReady = this.priceSubject.value.ready;
@@ -63,9 +63,7 @@ export class PriceService {
63
63
  });
64
64
  this.dbService.updatePriceStore(rs).catch(console.error);
65
65
  console.log('Get Token Price From CoinGecko');
66
- }).catch(e => {
67
- // Pass
68
- });
66
+ }).catch(console.error);
69
67
  this.refreshTimeout = setTimeout(this.refreshPriceData.bind(this), CRON_REFRESH_PRICE_INTERVAL);
70
68
  }
71
69
  }
@@ -1 +1,2 @@
1
1
  export declare const EXTENSION_REQUEST_URL = "extension";
2
+ export declare const PREDEFINED_CHAIN_DAPP_CHAIN_MAP: Record<string, string[]>;
@@ -1,4 +1,9 @@
1
1
  // Copyright 2019-2022 @subwallet/extension-base authors & contributors
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- export const EXTENSION_REQUEST_URL = 'extension';
4
+ export const EXTENSION_REQUEST_URL = 'extension';
5
+ export const PREDEFINED_CHAIN_DAPP_CHAIN_MAP = {
6
+ 'portal.astar.network': ['astar', 'astarEvm'],
7
+ 'apps.moonbeam.network': ['moonbeam', 'moonriver'],
8
+ 'app.stellaswap.com': ['moonbeam']
9
+ };
@@ -1,5 +1,6 @@
1
+ import { _ChainInfo } from '@subwallet/chain-list/types';
1
2
  import { AuthRequestV2 } from '@subwallet/extension-base/background/KoniTypes';
2
- import { AuthorizeRequest, RequestAuthorizeTab } from '@subwallet/extension-base/background/types';
3
+ import { AccountAuthType, AuthorizeRequest, RequestAuthorizeTab } from '@subwallet/extension-base/background/types';
3
4
  import { ChainService } from '@subwallet/extension-base/services/chain-service';
4
5
  import RequestService from '@subwallet/extension-base/services/request-service';
5
6
  import { AuthUrls } from '@subwallet/extension-base/services/request-service/types';
@@ -20,6 +21,12 @@ export default class AuthRequestHandler {
20
21
  setAuthorize(data: AuthUrls, callback?: () => void): void;
21
22
  getAuthorize(update: (value: AuthUrls) => void): void;
22
23
  getAuthList(): Promise<AuthUrls>;
24
+ getDAppChainInfo(options: {
25
+ accessType: AccountAuthType;
26
+ autoActive?: boolean;
27
+ defaultChain?: string;
28
+ url?: string;
29
+ }): _ChainInfo | undefined;
23
30
  private authCompleteV2;
24
31
  authorizeUrlV2(url: string, request: RequestAuthorizeTab): Promise<boolean>;
25
32
  getAuthRequestV2(id: string): AuthRequestV2;
@@ -1,8 +1,10 @@
1
1
  // Copyright 2019-2022 @subwallet/extension-base authors & contributors
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import { _isChainEnabled, _isChainEvmCompatible } from '@subwallet/extension-base/services/chain-service/utils';
4
+ import { _isChainEvmCompatible } from '@subwallet/extension-base/services/chain-service/utils';
5
+ import { PREDEFINED_CHAIN_DAPP_CHAIN_MAP } from '@subwallet/extension-base/services/request-service/constants';
5
6
  import AuthorizeStore from '@subwallet/extension-base/stores/Authorize';
7
+ import { getDomainFromUrl } from '@subwallet/extension-base/utils';
6
8
  import { getId } from '@subwallet/extension-base/utils/getId';
7
9
  import { accounts } from '@subwallet/ui-keyring/observable/accounts';
8
10
  import { BehaviorSubject, Subject } from 'rxjs';
@@ -78,9 +80,39 @@ export default class AuthRequestHandler {
78
80
  });
79
81
  });
80
82
  }
81
- authCompleteV2 = (id, resolve, reject) => {
83
+ getDAppChainInfo(options) {
84
+ const chainInfoMaps = this.#chainService.getChainInfoMap();
85
+ const chainStateMap = this.#chainService.getChainStateMap();
86
+ let defaultChain = options.defaultChain;
87
+ const needEnableChains = [];
88
+ if (options.url) {
89
+ const domain = getDomainFromUrl(options.url);
90
+ const predefinedSupportChains = PREDEFINED_CHAIN_DAPP_CHAIN_MAP[domain];
91
+ if (predefinedSupportChains) {
92
+ defaultChain = predefinedSupportChains[0];
93
+ options.autoActive && needEnableChains.push(...predefinedSupportChains);
94
+ }
95
+ }
96
+ let chainInfo;
97
+ if (['both', 'evm'].includes(options.accessType)) {
98
+ const evmChains = Object.values(chainInfoMaps).filter(_isChainEvmCompatible);
99
+ chainInfo = (defaultChain ? chainInfoMaps[defaultChain] : evmChains.find(chain => {
100
+ var _chainStateMap$chain$;
101
+ return (_chainStateMap$chain$ = chainStateMap[chain.slug]) === null || _chainStateMap$chain$ === void 0 ? void 0 : _chainStateMap$chain$.active;
102
+ })) || evmChains[0];
103
+ if (options.autoActive) {
104
+ if (!needEnableChains.includes(chainInfo.slug)) {
105
+ needEnableChains.push(chainInfo.slug);
106
+ }
107
+ }
108
+ }
109
+ needEnableChains.length > 0 && this.#chainService.enableChains(needEnableChains);
110
+ return chainInfo;
111
+ }
112
+ authCompleteV2 = (id, url, resolve, reject) => {
82
113
  const isAllowedMap = this.getAddressList();
83
114
  const complete = (result, cb, accounts) => {
115
+ var _this$getDAppChainInf;
84
116
  const isAllowed = result === true;
85
117
  let isCancelled = false;
86
118
  if (!isAllowed && typeof result === 'object' && result.message === 'Cancelled') {
@@ -113,16 +145,11 @@ export default class AuthRequestHandler {
113
145
  isAllowedMap[acc] = true;
114
146
  });
115
147
  }
116
- let defaultEvmNetworkKey;
117
- if (accountAuthType === 'both' || accountAuthType === 'evm') {
118
- const defaultChain = Object.values(this.#chainService.getChainInfoMap()).find(chainInfo => {
119
- const chainState = this.#chainService.getChainStateByKey(chainInfo.slug);
120
- return _isChainEvmCompatible(chainInfo) && _isChainEnabled(chainState);
121
- });
122
- if (defaultChain) {
123
- defaultEvmNetworkKey = defaultChain.slug;
124
- }
125
- }
148
+ const defaultEvmNetworkKey = (_this$getDAppChainInf = this.getDAppChainInfo({
149
+ accessType: accountAuthType,
150
+ url,
151
+ autoActive: !isCancelled && isAllowed
152
+ })) === null || _this$getDAppChainInf === void 0 ? void 0 : _this$getDAppChainInf.slug;
126
153
  this.getAuthorize(value => {
127
154
  let authorizeList = {};
128
155
  if (value) {
@@ -209,7 +236,7 @@ export default class AuthRequestHandler {
209
236
  return new Promise((resolve, reject) => {
210
237
  const id = getId();
211
238
  this.#authRequestsV2[id] = {
212
- ...this.authCompleteV2(id, resolve, reject),
239
+ ...this.authCompleteV2(id, url, resolve, reject),
213
240
  id,
214
241
  idStr,
215
242
  request,
@@ -1,5 +1,5 @@
1
1
  import { AuthRequestV2, ConfirmationDefinitions, ConfirmationsQueue, ConfirmationsQueueItemOptions, ConfirmationType, RequestConfirmationComplete } from '@subwallet/extension-base/background/KoniTypes';
2
- import { AccountJson, AuthorizeRequest, MetadataRequest, RequestAuthorizeTab, RequestSign, ResponseSigning, SigningRequest } from '@subwallet/extension-base/background/types';
2
+ import { AccountAuthType, AccountJson, AuthorizeRequest, MetadataRequest, RequestAuthorizeTab, RequestSign, ResponseSigning, SigningRequest } from '@subwallet/extension-base/background/types';
3
3
  import { ChainService } from '@subwallet/extension-base/services/chain-service';
4
4
  import { AuthUrls, MetaRequest } from '@subwallet/extension-base/services/request-service/types';
5
5
  import SettingService from '@subwallet/extension-base/services/setting-service/SettingService';
@@ -29,6 +29,12 @@ export default class RequestService {
29
29
  getAuthList(): Promise<AuthUrls>;
30
30
  authorizeUrlV2(url: string, request: RequestAuthorizeTab): Promise<boolean>;
31
31
  getAuthRequestV2(id: string): AuthRequestV2;
32
+ getDAppChainInfo(options: {
33
+ accessType: AccountAuthType;
34
+ autoActive?: boolean;
35
+ defaultChain?: string;
36
+ url?: string;
37
+ }): import("@subwallet/chain-list/types")._ChainInfo | undefined;
32
38
  get subscribeEvmChainChange(): Subject<AuthUrls>;
33
39
  get subscribeAuthorizeUrlSubject(): Subject<AuthUrls>;
34
40
  ensureUrlAuthorizedV2(url: string): Promise<boolean>;