@subwallet/extension-base 1.0.13-0 → 1.1.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 (67) hide show
  1. package/background/KoniTypes.d.ts +37 -0
  2. package/background/KoniTypes.js +8 -1
  3. package/background/handlers/Extension.js +17 -2
  4. package/background/types.d.ts +6 -1
  5. package/cjs/background/KoniTypes.js +10 -2
  6. package/cjs/background/handlers/Extension.js +22 -6
  7. package/cjs/constants/index.js +7 -1
  8. package/cjs/defaults.js +1 -1
  9. package/cjs/koni/api/dotsama/balance.js +5 -0
  10. package/cjs/koni/api/dotsama/transfer.js +6 -0
  11. package/cjs/koni/background/cron.js +12 -1
  12. package/cjs/koni/background/handlers/Extension.js +324 -147
  13. package/cjs/koni/background/handlers/State.js +222 -50
  14. package/cjs/koni/background/subscription.js +3 -0
  15. package/cjs/packageInfo.js +1 -1
  16. package/cjs/services/chain-service/constants.js +10 -4
  17. package/cjs/services/chain-service/handler/SubstrateApi.js +2 -1
  18. package/cjs/services/chain-service/handler/SubstrateChainHandler.js +3 -1
  19. package/cjs/services/chain-service/handler/manta/MantaPrivateHandler.js +147 -0
  20. package/cjs/services/chain-service/index.js +54 -5
  21. package/cjs/services/chain-service/utils.js +6 -1
  22. package/cjs/services/event-service/types.js +3 -1
  23. package/cjs/services/storage-service/DatabaseService.js +31 -1
  24. package/cjs/services/storage-service/databases/index.js +3 -0
  25. package/cjs/services/storage-service/db-stores/MantaPay.js +40 -0
  26. package/cjs/utils/index.js +12 -0
  27. package/cjs/utils/lazy.js +52 -0
  28. package/constants/index.d.ts +2 -0
  29. package/constants/index.js +2 -0
  30. package/defaults.d.ts +1 -1
  31. package/defaults.js +1 -1
  32. package/koni/api/dotsama/balance.js +6 -1
  33. package/koni/api/dotsama/transfer.js +7 -1
  34. package/koni/background/cron.d.ts +1 -0
  35. package/koni/background/cron.js +13 -2
  36. package/koni/background/handlers/Extension.d.ts +5 -0
  37. package/koni/background/handlers/Extension.js +186 -11
  38. package/koni/background/handlers/State.d.ts +15 -3
  39. package/koni/background/handlers/State.js +224 -49
  40. package/koni/background/subscription.js +3 -0
  41. package/package.json +22 -5
  42. package/packageInfo.js +1 -1
  43. package/services/chain-service/constants.d.ts +3 -0
  44. package/services/chain-service/constants.js +5 -2
  45. package/services/chain-service/handler/SubstrateApi.d.ts +1 -1
  46. package/services/chain-service/handler/SubstrateApi.js +2 -1
  47. package/services/chain-service/handler/SubstrateChainHandler.d.ts +1 -1
  48. package/services/chain-service/handler/SubstrateChainHandler.js +3 -1
  49. package/services/chain-service/handler/manta/MantaPrivateHandler.d.ts +30 -0
  50. package/services/chain-service/handler/manta/MantaPrivateHandler.js +140 -0
  51. package/services/chain-service/handler/types.d.ts +2 -0
  52. package/services/chain-service/index.d.ts +7 -3
  53. package/services/chain-service/index.js +56 -7
  54. package/services/chain-service/utils.d.ts +1 -0
  55. package/services/chain-service/utils.js +5 -1
  56. package/services/event-service/types.d.ts +3 -0
  57. package/services/event-service/types.js +3 -1
  58. package/services/storage-service/DatabaseService.d.ts +10 -1
  59. package/services/storage-service/DatabaseService.js +31 -1
  60. package/services/storage-service/databases/index.d.ts +2 -0
  61. package/services/storage-service/databases/index.js +3 -0
  62. package/services/storage-service/db-stores/MantaPay.d.ts +9 -0
  63. package/services/storage-service/db-stores/MantaPay.js +32 -0
  64. package/utils/index.d.ts +1 -0
  65. package/utils/index.js +2 -1
  66. package/utils/lazy.d.ts +2 -0
  67. package/utils/lazy.js +43 -0
@@ -0,0 +1,140 @@
1
+ // Copyright 2019-2022 @subwallet/extension-base authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { BaseWallet, MantaPayWallet } from 'manta-extension-sdk';
5
+ import { Subject } from 'rxjs';
6
+ export class MantaPrivateHandler {
7
+ _privateWallet = undefined;
8
+ syncStateSubject = new Subject();
9
+ constructor(dbService) {
10
+ this.dbService = dbService;
11
+ this.syncState = {
12
+ isSyncing: false,
13
+ progress: 0
14
+ };
15
+ this.syncStateSubject.next(this.syncState);
16
+ }
17
+ setCurrentAddress(address) {
18
+ this.currentAddress = address;
19
+ }
20
+ getSyncState() {
21
+ return this.syncState;
22
+ }
23
+ get privateWallet() {
24
+ return this._privateWallet;
25
+ }
26
+ subscribeSyncState() {
27
+ return this.syncStateSubject;
28
+ }
29
+ async updateMantaPayConfig(address, chain, changes) {
30
+ await this.dbService.updateMantaPayData(`config_${chain}_${address}`, changes);
31
+ }
32
+ async saveMantaPayConfig(config) {
33
+ await this.dbService.setMantaPayData({
34
+ key: `config_${config.chain}_${config.address}`,
35
+ ...config
36
+ });
37
+ }
38
+ async getMantaPayConfig(address, chain) {
39
+ return this.dbService.getMantaPayData(`config_${chain}_${address}`);
40
+ }
41
+ async getMantaPayFirstConfig(chain) {
42
+ return this.dbService.getMantaPayFirstConfig(chain);
43
+ }
44
+ async deleteMantaPayConfig(address, chain) {
45
+ return this.dbService.deleteMantaPayConfig(`config_${chain}_${address}`);
46
+ }
47
+ async saveMantaAuthContext(context) {
48
+ await this.dbService.setMantaPayData({
49
+ key: `authContext_${context.chain}_${context.address}`,
50
+ ...context
51
+ });
52
+ }
53
+ async getMantaAuthContext(address, chain) {
54
+ return this.dbService.getMantaPayData(`authContext_${chain}_${address}`);
55
+ }
56
+ async deleteMantaAuthContext(address, chain) {
57
+ return this.dbService.deleteMantaPayConfig(`authContext_${chain}_${address}`);
58
+ }
59
+ async saveLedgerState(palletName, network, data) {
60
+ try {
61
+ const suffix = this.currentAddress ? `_${this.currentAddress}` : '';
62
+ await this.dbService.setMantaPayData({
63
+ key: `storage_state_${palletName}_${network}${suffix}`,
64
+ ...data
65
+ });
66
+ } catch (e) {
67
+ console.error('manta-pay', e);
68
+ return false;
69
+ }
70
+ return true;
71
+ }
72
+ async getLedgerState(palletName, network) {
73
+ let result;
74
+ try {
75
+ const suffix = this.currentAddress ? `_${this.currentAddress}` : '';
76
+
77
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
78
+ result = await this.dbService.getMantaPayData(`storage_state_${palletName}_${network}${suffix}`);
79
+ } catch (e) {
80
+ console.error(e);
81
+ }
82
+
83
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
84
+ return result || null;
85
+ }
86
+ async initMantaPay(providerUrl, network) {
87
+ const networkParam = network.charAt(0).toUpperCase() + network.slice(1); // Manta || Calamari || Dolphin
88
+
89
+ const baseWallet = await BaseWallet.init({
90
+ apiEndpoint: providerUrl,
91
+ loggingEnabled: false,
92
+ provingFilePath: './manta-pay/proving',
93
+ parametersFilePath: './manta-pay/parameters',
94
+ saveStorageStateToLocal: this.saveLedgerState.bind(this),
95
+ getStorageStateFromLocal: this.getLedgerState.bind(this)
96
+ });
97
+ this._privateWallet = MantaPayWallet.init(networkParam, baseWallet);
98
+ return this._privateWallet.api;
99
+ }
100
+ async getCurrentLedgerState() {
101
+ var _this$_privateWallet;
102
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
103
+ const ledgerState = await this.getLedgerState('mantaPay', 'Calamari');
104
+ if (!ledgerState) {
105
+ return 0;
106
+ }
107
+
108
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment
109
+ return await ((_this$_privateWallet = this._privateWallet) === null || _this$_privateWallet === void 0 ? void 0 : _this$_privateWallet.getLedgerCurrentCount(ledgerState.checkpoint));
110
+ }
111
+ setSyncState(data) {
112
+ this.syncState = data;
113
+ this.syncStateSubject.next(this.syncState);
114
+ }
115
+ async subscribeSyncProgress() {
116
+ var _this$_privateWallet2;
117
+ const ledgerTotalCount = await ((_this$_privateWallet2 = this._privateWallet) === null || _this$_privateWallet2 === void 0 ? void 0 : _this$_privateWallet2.getLedgerTotalCount());
118
+ const interval = setInterval(() => {
119
+ this.getCurrentLedgerState().then(currentCount => {
120
+ const progress = Math.floor(currentCount / ledgerTotalCount * 100);
121
+ if (progress === 100) {
122
+ this.syncState = {
123
+ isSyncing: false,
124
+ progress
125
+ };
126
+ clearInterval(interval);
127
+ } else {
128
+ this.syncState = {
129
+ isSyncing: true,
130
+ progress
131
+ };
132
+ }
133
+ this.syncStateSubject.next(this.syncState);
134
+ }).catch(console.error);
135
+ }, 1000);
136
+ return () => {
137
+ interval && clearInterval(interval);
138
+ };
139
+ }
140
+ }
@@ -1,4 +1,5 @@
1
1
  import { MetadataItem } from '@subwallet/extension-base/background/KoniTypes';
2
+ import { ApiPromise } from '@polkadot/api';
2
3
  export interface _EvmChainSpec {
3
4
  evmChainId: number;
4
5
  name: string;
@@ -19,6 +20,7 @@ export interface _ApiOptions {
19
20
  providerName?: string;
20
21
  metadata?: MetadataItem;
21
22
  onUpdateStatus?: (isConnected: boolean) => void;
23
+ externalApiPromise?: ApiPromise;
22
24
  }
23
25
  export declare enum _CHAIN_VALIDATION_ERROR {
24
26
  INVALID_INFO_TYPE = "invalidInfoType",
@@ -1,6 +1,6 @@
1
1
  import { _AssetRef, _AssetType, _ChainAsset, _ChainInfo, _MultiChainAsset } from '@subwallet/chain-list/types';
2
2
  import { AssetSetting, ValidateNetworkResponse } from '@subwallet/extension-base/background/KoniTypes';
3
- import { SubstrateApi } from '@subwallet/extension-base/services/chain-service/handler/SubstrateApi';
3
+ import { MantaPrivateHandler } from '@subwallet/extension-base/services/chain-service/handler/manta/MantaPrivateHandler';
4
4
  import { _ChainConnectionStatus, _ChainState, _NetworkUpsertParams, _ValidateCustomAssetRequest, _ValidateCustomAssetResponse } from '@subwallet/extension-base/services/chain-service/types';
5
5
  import { EventService } from '@subwallet/extension-base/services/event-service';
6
6
  import { IMetadataItem } from '@subwallet/extension-base/services/storage-service/databases';
@@ -13,6 +13,8 @@ export declare class ChainService {
13
13
  private lockChainInfoMap;
14
14
  private substrateChainHandler;
15
15
  private evmChainHandler;
16
+ private mantaChainHandler;
17
+ get mantaPay(): MantaPrivateHandler;
16
18
  private chainInfoMapSubject;
17
19
  private chainStateMapSubject;
18
20
  private assetRegistrySubject;
@@ -25,8 +27,8 @@ export declare class ChainService {
25
27
  getXcmRefMap(): Record<string, _AssetRef>;
26
28
  getEvmApi(slug: string): import("./handler/EvmApi").EvmApi;
27
29
  getEvmApiMap(): Record<string, import("./handler/EvmApi").EvmApi>;
28
- getSubstrateApiMap(): Record<string, SubstrateApi>;
29
- getSubstrateApi(slug: string): SubstrateApi;
30
+ getSubstrateApiMap(): Record<string, import("./handler/SubstrateApi").SubstrateApi>;
31
+ getSubstrateApi(slug: string): import("./handler/SubstrateApi").SubstrateApi;
30
32
  getChainCurrentProviderByKey(slug: string): {
31
33
  endpoint: string;
32
34
  providerName: string;
@@ -54,6 +56,7 @@ export declare class ChainService {
54
56
  getChainInfoByKey(key: string): _ChainInfo;
55
57
  getActiveChainInfos(): Record<string, _ChainInfo>;
56
58
  getAssetBySlug(slug: string): _ChainAsset;
59
+ getMantaZkAssets(chain: string): Record<string, _ChainAsset>;
57
60
  getFungibleTokensByChain(chainSlug: string, checkActive?: boolean): Record<string, _ChainAsset>;
58
61
  getXcmEqualAssetByChain(destinationChainSlug: string, originTokenSlug: string): _ChainAsset | undefined;
59
62
  getAssetByChainAndType(chainSlug: string, assetTypes: _AssetType[]): Record<string, _ChainAsset>;
@@ -96,6 +99,7 @@ export declare class ChainService {
96
99
  checkAndUpdateStatusMapForChain(chainSlug: string): void;
97
100
  initAssetSettings(): Promise<void>;
98
101
  setAssetSettings(assetSettings: Record<string, AssetSetting>, emitEvent?: boolean): void;
102
+ setMantaZkAssetSettings(visible: boolean): void;
99
103
  getStoreAssetSettings(): Promise<Record<string, AssetSetting>>;
100
104
  getAssetSettings(): Promise<Record<string, AssetSetting>>;
101
105
  updateAssetSetting(assetSlug: string, assetSetting: AssetSetting, autoEnableNativeToken?: boolean): Promise<boolean | undefined>;
@@ -3,12 +3,13 @@
3
3
 
4
4
  import { AssetLogoMap, AssetRefMap, ChainAssetMap, ChainInfoMap, ChainLogoMap, MultiChainAssetMap } from '@subwallet/chain-list';
5
5
  import { _AssetRefPath, _AssetType, _ChainStatus, _SubstrateChainType } from '@subwallet/chain-list/types';
6
- import { _ASSET_LOGO_MAP_SRC, _ASSET_REF_SRC, _CHAIN_ASSET_SRC, _CHAIN_INFO_SRC, _CHAIN_LOGO_MAP_SRC, _DEFAULT_ACTIVE_CHAINS, _MULTI_CHAIN_ASSET_SRC } from '@subwallet/extension-base/services/chain-service/constants';
6
+ import { _ASSET_LOGO_MAP_SRC, _ASSET_REF_SRC, _CHAIN_ASSET_SRC, _CHAIN_INFO_SRC, _CHAIN_LOGO_MAP_SRC, _DEFAULT_ACTIVE_CHAINS, _MANTA_ZK_CHAIN_GROUP, _MULTI_CHAIN_ASSET_SRC, _ZK_ASSET_PREFIX } from '@subwallet/extension-base/services/chain-service/constants';
7
7
  import { EvmChainHandler } from '@subwallet/extension-base/services/chain-service/handler/EvmChainHandler';
8
+ import { MantaPrivateHandler } from '@subwallet/extension-base/services/chain-service/handler/manta/MantaPrivateHandler';
8
9
  import { SubstrateChainHandler } from '@subwallet/extension-base/services/chain-service/handler/SubstrateChainHandler';
9
10
  import { _CHAIN_VALIDATION_ERROR } from '@subwallet/extension-base/services/chain-service/handler/types';
10
11
  import { _ChainConnectionStatus, _CUSTOM_PREFIX, _NFT_CONTRACT_STANDARDS, _SMART_CONTRACT_STANDARDS } from '@subwallet/extension-base/services/chain-service/types';
11
- import { _isAssetFungibleToken, _isChainEnabled, _isCustomAsset, _isCustomChain, _isEqualContractAddress, _isEqualSmartContractAsset, _isPureEvmChain, _isPureSubstrateChain, _parseAssetRefKey } from '@subwallet/extension-base/services/chain-service/utils';
12
+ import { _isAssetFungibleToken, _isChainEnabled, _isCustomAsset, _isCustomChain, _isEqualContractAddress, _isEqualSmartContractAsset, _isMantaZkAsset, _isPureEvmChain, _isPureSubstrateChain, _parseAssetRefKey } from '@subwallet/extension-base/services/chain-service/utils';
12
13
  import AssetSettingStore from '@subwallet/extension-base/stores/AssetSetting';
13
14
  import { BehaviorSubject, Subject } from 'rxjs';
14
15
  import Web3 from 'web3';
@@ -22,6 +23,10 @@ export class ChainService {
22
23
  };
23
24
  lockChainInfoMap = false; // prevent unwanted changes (edit, enable, disable) to chainInfoMap
24
25
 
26
+ get mantaPay() {
27
+ return this.mantaChainHandler;
28
+ }
29
+
25
30
  // TODO: consider BehaviorSubject
26
31
  chainInfoMapSubject = new Subject();
27
32
  chainStateMapSubject = new Subject();
@@ -35,6 +40,10 @@ export class ChainService {
35
40
  constructor(dbService, eventService) {
36
41
  this.dbService = dbService;
37
42
  this.eventService = eventService;
43
+ this.substrateChainHandler = new SubstrateChainHandler();
44
+ this.evmChainHandler = new EvmChainHandler();
45
+ this.mantaChainHandler = new MantaPrivateHandler(dbService);
46
+ this.chainInfoMapSubject.next(this.dataMap.chainInfoMap);
38
47
  this.chainStateMapSubject.next(this.dataMap.chainStateMap);
39
48
  this.chainInfoMapSubject.next(this.dataMap.chainInfoMap);
40
49
  this.assetRegistrySubject.next(this.dataMap.assetRegistry);
@@ -212,6 +221,15 @@ export class ChainService {
212
221
  getAssetBySlug(slug) {
213
222
  return this.getAssetRegistry()[slug];
214
223
  }
224
+ getMantaZkAssets(chain) {
225
+ const result = {};
226
+ Object.values(this.getAssetRegistry()).forEach(chainAsset => {
227
+ if (chainAsset.originChain === chain && _isAssetFungibleToken(chainAsset) && chainAsset.symbol.startsWith(_ZK_ASSET_PREFIX)) {
228
+ result[chainAsset.slug] = chainAsset;
229
+ }
230
+ });
231
+ return result;
232
+ }
215
233
  getFungibleTokensByChain(chainSlug, checkActive = false) {
216
234
  const result = {};
217
235
  const assetSettings = this.assetSettingSubject.value;
@@ -399,11 +417,21 @@ export class ChainService {
399
417
  }
400
418
  };
401
419
  if (chainInfo.substrateInfo !== null && chainInfo.substrateInfo !== undefined) {
402
- const chainApi = await this.substrateChainHandler.initApi(chainInfo.slug, endpoint, {
403
- providerName,
404
- onUpdateStatus
405
- });
406
- this.substrateChainHandler.setSubstrateApi(chainInfo.slug, chainApi);
420
+ if (_MANTA_ZK_CHAIN_GROUP.includes(chainInfo.slug)) {
421
+ const apiPromise = await this.mantaChainHandler.initMantaPay(endpoint, chainInfo.slug);
422
+ const chainApi = await this.substrateChainHandler.initApi(chainInfo.slug, endpoint, {
423
+ providerName,
424
+ externalApiPromise: apiPromise,
425
+ onUpdateStatus
426
+ });
427
+ this.substrateChainHandler.setSubstrateApi(chainInfo.slug, chainApi);
428
+ } else {
429
+ const chainApi = await this.substrateChainHandler.initApi(chainInfo.slug, endpoint, {
430
+ providerName,
431
+ onUpdateStatus
432
+ });
433
+ this.substrateChainHandler.setSubstrateApi(chainInfo.slug, chainApi);
434
+ }
407
435
  }
408
436
  if (chainInfo.evmInfo !== null && chainInfo.evmInfo !== undefined) {
409
437
  const chainApi = await this.evmChainHandler.initApi(chainInfo.slug, endpoint, {
@@ -1161,6 +1189,27 @@ export class ChainService {
1161
1189
  });
1162
1190
  this.store.set('AssetSetting', assetSettings);
1163
1191
  }
1192
+ setMantaZkAssetSettings(visible) {
1193
+ const zkAssetSettings = {};
1194
+ Object.values(this.dataMap.assetRegistry).forEach(asset => {
1195
+ if (_isMantaZkAsset(asset)) {
1196
+ zkAssetSettings[asset.slug] = {
1197
+ visible
1198
+ };
1199
+ }
1200
+ });
1201
+ this.store.get('AssetSetting', storedAssetSettings => {
1202
+ const newAssetSettings = {
1203
+ ...storedAssetSettings,
1204
+ ...zkAssetSettings
1205
+ };
1206
+ this.store.set('AssetSetting', newAssetSettings);
1207
+ this.assetSettingSubject.next(newAssetSettings);
1208
+ Object.keys(zkAssetSettings).forEach(slug => {
1209
+ this.eventService.emit('asset.updateState', slug);
1210
+ });
1211
+ });
1212
+ }
1164
1213
  async getStoreAssetSettings() {
1165
1214
  return new Promise(resolve => {
1166
1215
  this.store.get('AssetSetting', resolve);
@@ -65,3 +65,4 @@ export declare function _isCustomProvider(providerKey: string): boolean;
65
65
  export declare function _generateCustomProviderKey(index: number): string;
66
66
  export declare const findChainInfoByHalfGenesisHash: (chainMap: Record<string, _ChainInfo>, halfGenesisHash?: string) => _ChainInfo | null;
67
67
  export declare const findChainInfoByChainId: (chainMap: Record<string, _ChainInfo>, chainId?: number) => _ChainInfo | null;
68
+ export declare function _isMantaZkAsset(chainAsset: _ChainAsset): boolean;
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
4
  import { _AssetRefPath, _AssetType, _SubstrateChainType } from '@subwallet/chain-list/types';
5
+ import { _MANTA_ZK_CHAIN_GROUP, _ZK_ASSET_PREFIX } from '@subwallet/extension-base/services/chain-service/constants';
5
6
  import { _CUSTOM_PREFIX, _SMART_CONTRACT_STANDARDS } from '@subwallet/extension-base/services/chain-service/types';
6
7
  import { isEthereumAddress } from '@polkadot/util-crypto';
7
8
  export function _isCustomChain(slug) {
@@ -354,4 +355,7 @@ export const findChainInfoByChainId = (chainMap, chainId) => {
354
355
  }
355
356
  }
356
357
  return null;
357
- };
358
+ };
359
+ export function _isMantaZkAsset(chainAsset) {
360
+ return _MANTA_ZK_CHAIN_GROUP.includes(chainAsset.originChain) && chainAsset.symbol.startsWith(_ZK_ASSET_PREFIX);
361
+ }
@@ -20,6 +20,9 @@ export interface EventRegistry {
20
20
  'transaction.failed': [SWTransaction | undefined];
21
21
  'transaction.submitStaking': [string];
22
22
  'transaction.transferNft': [SWTransaction | undefined];
23
+ 'mantaPay.initSync': [string | undefined];
24
+ 'mantaPay.submitTransaction': [SWTransaction | undefined];
25
+ 'mantaPay.enable': [string];
23
26
  }
24
27
  export declare type EventType = keyof EventRegistry;
25
28
  export declare const COMMON_RELOAD_EVENTS: EventType[];
@@ -1,4 +1,6 @@
1
1
  // Copyright 2019-2022 @subwallet/extension-base
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- export const COMMON_RELOAD_EVENTS = ['account.updateCurrent', 'asset.updateState', 'account.add', 'chain.updateState', 'account.remove', 'chain.add'];
4
+ export const COMMON_RELOAD_EVENTS = ['account.updateCurrent', 'asset.updateState', 'account.add', 'chain.updateState', 'account.remove', 'chain.add', 'mantaPay.initSync',
5
+ // TODO: re-check this
6
+ 'mantaPay.enable'];
@@ -1,9 +1,10 @@
1
1
  import { _ChainAsset } from '@subwallet/chain-list/types';
2
- import { BalanceItem, ChainStakingMetadata, CrowdloanItem, NftCollection, NftItem, NominatorMetadata, PriceJson, StakingItem, StakingType, TransactionHistoryItem } from '@subwallet/extension-base/background/KoniTypes';
2
+ import { BalanceItem, ChainStakingMetadata, CrowdloanItem, MantaPayConfig, NftCollection, NftItem, NominatorMetadata, PriceJson, StakingItem, StakingType, TransactionHistoryItem } from '@subwallet/extension-base/background/KoniTypes';
3
3
  import { EventService } from '@subwallet/extension-base/services/event-service';
4
4
  import { IBalance, IChain, INft } from '@subwallet/extension-base/services/storage-service/databases';
5
5
  import { AssetStore, BalanceStore, ChainStore, CrowdloanStore, MetadataStore, MigrationStore, NftCollectionStore, NftStore, PriceStore, StakingStore, TransactionStore } from '@subwallet/extension-base/services/storage-service/db-stores';
6
6
  import ChainStakingMetadataStore from '@subwallet/extension-base/services/storage-service/db-stores/ChainStakingMetadata';
7
+ import MantaPayStore from '@subwallet/extension-base/services/storage-service/db-stores/MantaPay';
7
8
  import NominatorMetadataStore from '@subwallet/extension-base/services/storage-service/db-stores/NominatorMetadata';
8
9
  import { HistoryQuery } from '@subwallet/extension-base/services/storage-service/db-stores/Transaction';
9
10
  import { Subscription } from 'dexie';
@@ -24,6 +25,7 @@ export default class DatabaseService {
24
25
  asset: AssetStore;
25
26
  chainStakingMetadata: ChainStakingMetadataStore;
26
27
  nominatorMetadata: NominatorMetadataStore;
28
+ mantaPay: MantaPayStore;
27
29
  };
28
30
  private logger;
29
31
  private nftSubscription;
@@ -67,4 +69,11 @@ export default class DatabaseService {
67
69
  updateNominatorMetadata(item: NominatorMetadata): Promise<unknown>;
68
70
  getNominatorMetadata(): Promise<NominatorMetadata[]>;
69
71
  resetWallet(resetAll: boolean): Promise<void>;
72
+ setMantaPayData(data: any): Promise<void>;
73
+ updateMantaPayData(key: string, data: Record<string, any>): Promise<void>;
74
+ getMantaPayData(key: string): Promise<any>;
75
+ deleteMantaPayConfig(key: string): Promise<number>;
76
+ subscribeMantaPayConfig(chain: string, callback: (data: MantaPayConfig[]) => void): void;
77
+ getMantaPayConfig(chain: string): Promise<any[]>;
78
+ getMantaPayFirstConfig(chain: string): Promise<any>;
70
79
  }
@@ -5,6 +5,7 @@ import { APIItemState, StakingType } from '@subwallet/extension-base/background/
5
5
  import KoniDatabase from '@subwallet/extension-base/services/storage-service/databases';
6
6
  import { AssetStore, BalanceStore, ChainStore, CrowdloanStore, MetadataStore, MigrationStore, NftCollectionStore, NftStore, PriceStore, StakingStore, TransactionStore } from '@subwallet/extension-base/services/storage-service/db-stores';
7
7
  import ChainStakingMetadataStore from '@subwallet/extension-base/services/storage-service/db-stores/ChainStakingMetadata';
8
+ import MantaPayStore from '@subwallet/extension-base/services/storage-service/db-stores/MantaPay';
8
9
  import NominatorMetadataStore from '@subwallet/extension-base/services/storage-service/db-stores/NominatorMetadata';
9
10
  import { reformatAddress } from '@subwallet/extension-base/utils';
10
11
  import { logger as createLogger } from '@polkadot/util';
@@ -32,7 +33,8 @@ export default class DatabaseService {
32
33
  asset: new AssetStore(this._db.asset),
33
34
  // staking
34
35
  chainStakingMetadata: new ChainStakingMetadataStore(this._db.chainStakingMetadata),
35
- nominatorMetadata: new NominatorMetadataStore(this._db.nominatorMetadata)
36
+ nominatorMetadata: new NominatorMetadataStore(this._db.nominatorMetadata),
37
+ mantaPay: new MantaPayStore(this._db.mantaPay)
36
38
  };
37
39
  }
38
40
  async updatePriceStore(priceData) {
@@ -229,4 +231,32 @@ export default class DatabaseService {
229
231
  });
230
232
  });
231
233
  }
234
+ async setMantaPayData(data) {
235
+ await this._db.mantaPay.put(data); // just override if exist
236
+ }
237
+
238
+ async updateMantaPayData(key, data) {
239
+ await this._db.mantaPay.update(key, data); // just override if exist
240
+ }
241
+
242
+ async getMantaPayData(key) {
243
+ return this._db.mantaPay.get({
244
+ key
245
+ });
246
+ }
247
+ async deleteMantaPayConfig(key) {
248
+ return this.stores.mantaPay.deleteRecord(key);
249
+ }
250
+ subscribeMantaPayConfig(chain, callback) {
251
+ this.stores.mantaPay.subscribeMantaPayConfig(chain).subscribe({
252
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
253
+ next: data => callback && callback(data)
254
+ });
255
+ }
256
+ async getMantaPayConfig(chain) {
257
+ return this.stores.mantaPay.getConfig(chain);
258
+ }
259
+ async getMantaPayFirstConfig(chain) {
260
+ return this.stores.mantaPay.getFirstConfig(chain);
261
+ }
232
262
  }
@@ -28,6 +28,7 @@ export interface IMigration {
28
28
  }
29
29
  export interface IMetadataItem extends MetadataItem, DefaultChainDoc {
30
30
  }
31
+ export declare type IMantaPayLedger = any;
31
32
  export default class KoniDatabase extends Dexie {
32
33
  price: Table<PriceJson, object>;
33
34
  balances: Table<IBalance, object>;
@@ -42,6 +43,7 @@ export default class KoniDatabase extends Dexie {
42
43
  asset: Table<_ChainAsset, object>;
43
44
  chainStakingMetadata: Table<ChainStakingMetadata, object>;
44
45
  nominatorMetadata: Table<NominatorMetadata, object>;
46
+ mantaPay: Table<IMantaPayLedger, object>;
45
47
  private schemaVersion;
46
48
  constructor(name?: string, schemaVersion?: number);
47
49
  private conditionalVersion;
@@ -27,6 +27,9 @@ export default class KoniDatabase extends Dexie {
27
27
  this.conditionalVersion(2, {
28
28
  metadata: 'genesisHash, chain'
29
29
  });
30
+ this.conditionalVersion(3, {
31
+ mantaPay: 'key, chain'
32
+ });
30
33
  }
31
34
  conditionalVersion(version, schema, upgrade) {
32
35
  if (this.schemaVersion != null && this.schemaVersion < version) {
@@ -0,0 +1,9 @@
1
+ import { IMantaPayLedger } from '@subwallet/extension-base/services/storage-service/databases';
2
+ import BaseStore from '@subwallet/extension-base/services/storage-service/db-stores/BaseStore';
3
+ export default class MantaPayStore extends BaseStore<IMantaPayLedger> {
4
+ getAll(): Promise<any[]>;
5
+ subscribeMantaPayConfig(chain: string): import("dexie").Observable<any[]>;
6
+ getConfig(chain: string): import("dexie").PromiseExtended<any[]>;
7
+ getFirstConfig(chain: string): import("dexie").PromiseExtended<any>;
8
+ deleteRecord(key: string): import("dexie").PromiseExtended<number>;
9
+ }
@@ -0,0 +1,32 @@
1
+ // Copyright 2019-2022 @subwallet/extension-base authors & contributors
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import BaseStore from '@subwallet/extension-base/services/storage-service/db-stores/BaseStore';
5
+ import { liveQuery } from 'dexie';
6
+ export default class MantaPayStore extends BaseStore {
7
+ async getAll() {
8
+ return this.table.toArray();
9
+ }
10
+ subscribeMantaPayConfig(chain) {
11
+ return liveQuery(
12
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-return
13
+ () => this.table.where({
14
+ chain
15
+ }).filter(data => (data === null || data === void 0 ? void 0 : data.key) && (data === null || data === void 0 ? void 0 : data.key.startsWith('config'))).toArray());
16
+ }
17
+ getConfig(chain) {
18
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-return
19
+ return this.table.where({
20
+ chain
21
+ }).filter(data => (data === null || data === void 0 ? void 0 : data.key) && (data === null || data === void 0 ? void 0 : data.key.startsWith('config'))).toArray();
22
+ }
23
+ getFirstConfig(chain) {
24
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-return
25
+ return this.table.where({
26
+ chain
27
+ }).filter(data => (data === null || data === void 0 ? void 0 : data.key) && (data === null || data === void 0 ? void 0 : data.key.startsWith('config'))).first();
28
+ }
29
+ deleteRecord(key) {
30
+ return this.table.where('key').equals(key).delete();
31
+ }
32
+ }
package/utils/index.d.ts CHANGED
@@ -40,3 +40,4 @@ export declare function waitTimeout(ms: number): Promise<void>;
40
40
  export declare const stripUrl: (url: string) => string;
41
41
  export * from './array';
42
42
  export * from './environment';
43
+ export * from './lazy';
package/utils/index.js CHANGED
@@ -285,4 +285,5 @@ export const stripUrl = url => {
285
285
  return parts[2];
286
286
  };
287
287
  export * from "./array.js";
288
- export * from "./environment.js";
288
+ export * from "./environment.js";
289
+ export * from "./lazy.js";
@@ -0,0 +1,2 @@
1
+ export declare function removeLazy(key: string): void;
2
+ export declare function addLazy(key: string, callback: () => void, lazyTime?: number, maxLazyTime?: number): void;
package/utils/lazy.js ADDED
@@ -0,0 +1,43 @@
1
+ // Copyright 2019-2022 @subwallet/extension-base
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ const lazyMap = {};
5
+ export function removeLazy(key) {
6
+ if (lazyMap[key]) {
7
+ clearTimeout(lazyMap[key].timeout);
8
+ delete lazyMap[key];
9
+ }
10
+ }
11
+
12
+ // Add or update new lazy thread
13
+ export function addLazy(key, callback, lazyTime = 300, maxLazyTime = 3000) {
14
+ const existed = lazyMap[key];
15
+ const now = new Date().getTime();
16
+ if (existed) {
17
+ clearTimeout(existed.timeout);
18
+ lazyMap[key] = {
19
+ ...existed,
20
+ callback
21
+ };
22
+
23
+ // Fire callback if last fire is too long
24
+ if (now - existed.lastFire >= maxLazyTime) {
25
+ callback();
26
+ lazyMap[key].lastFire = now;
27
+ } else {
28
+ lazyMap[key].timeout = setTimeout(() => {
29
+ // This will be fire in the last call of lazy thread
30
+ callback();
31
+ lazyMap[key].lastFire = new Date().getTime();
32
+ removeLazy(key);
33
+ }, lazyTime);
34
+ }
35
+ } else {
36
+ // Fire callback immediately in the first time
37
+ callback();
38
+ lazyMap[key] = {
39
+ callback,
40
+ lastFire: now
41
+ };
42
+ }
43
+ }