Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Issue-3960] Improve token enabling #3975

Open
wants to merge 47 commits into
base: subwallet-dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
70dacfe
[Update] - Update message in case perform Liquid staking have XCM
tunghp2002 Oct 23, 2024
695376b
Merge branch 'subwallet-dev' into koni/dev/issue-3745
tunghp2002 Nov 22, 2024
d5550e3
[Add] Extension - Handle negative number
tunghp2002 Nov 27, 2024
f406414
[Issue-3920] Show well-known tokens on top
PDTnhah Dec 18, 2024
14e192a
[Issue-3920] fix lint
PDTnhah Dec 18, 2024
7cc18f5
[Issue-3920] fix lint
PDTnhah Dec 18, 2024
6bd8c6d
Merge branch 'subwallet-dev' into koni/dev/issue-3745
tunghp2002 Dec 19, 2024
d0fa8c0
[Update] Fix acala liquid staking screen
tunghp2002 Dec 19, 2024
5c8e40f
Merge branch 'subwallet-dev' into koni/dev/issue-3920
PDTnhah Dec 19, 2024
7a273ef
[Issue-3920] Show well-known tokens on top
PDTnhah Dec 19, 2024
1746742
[Issue-3920] Refactor code
PDTnhah Dec 19, 2024
142010c
[Update] Add number for alt token
tunghp2002 Dec 25, 2024
22e1de5
[Update] Refactor code by use util
tunghp2002 Dec 25, 2024
dc320da
For test
tunghp2002 Dec 30, 2024
c7ca8e5
[Update] Fix logic earning and xcm
tunghp2002 Dec 31, 2024
320d586
[Fixed] Fixed missing amount display
tunghp2002 Dec 31, 2024
b15d055
Merge branch 'subwallet-dev' into koni/dev/issue-3920
PDTnhah Dec 31, 2024
dc29965
[Update] Change content
tunghp2002 Dec 31, 2024
fcafddc
[Issue-3920] Show well-known tokens on top
PDTnhah Dec 31, 2024
4629d9b
[Fix] Sum
tunghp2002 Jan 2, 2025
b660a02
[Hot fix] Format popup message
tunghp2002 Jan 2, 2025
907d602
Merge branch 'refs/heads/subwallet-dev' into koni/dev/issue-3960_v2
dungnguyen-art Jan 3, 2025
6083b5f
Merge branch 'subwallet-dev' into koni/dev/issue-3920
PDTnhah Jan 4, 2025
3a9322e
[Issue-3920] Refactor code
PDTnhah Jan 6, 2025
29edf3e
[Issue-3920] Rename interface & variables
PDTnhah Jan 6, 2025
68420cf
[Issue-3920] Fix lint
PDTnhah Jan 6, 2025
e8393da
[Issue-3960] Add support for enabling chain with popular tokens (1)
dungnguyen-art Jan 7, 2025
56d143e
[Issue-3960] Add support for enabling chain with popular tokens (2)
dungnguyen-art Jan 7, 2025
15d0b17
[Issue-3920] Refactor code related to priority tokens
lw-cdm Jan 7, 2025
2741ac5
Merge remote-tracking branch 'refs/remotes/origin/koni/dev/issue-3920…
dungnguyen-art Jan 7, 2025
93d7267
[Issue-3960] Create migration job to disable zero-balance tokens
dungnguyen-art Jan 7, 2025
9920a24
[Issue-3960] Refactor name variable, function, message
dungnguyen-art Jan 7, 2025
d0c7734
[Issue-3960] Update logic filter tokenList
dungnguyen-art Jan 8, 2025
ad2bc79
[Issue-3960] Update enabled token when network is turned on
dungnguyen-art Jan 8, 2025
fd15c4d
[Issue-3960] Only disable token have zero balance
dungnguyen-art Jan 8, 2025
15b57a5
[Issue-3960] Update enable native token when turn on token
dungnguyen-art Jan 8, 2025
c705900
Merge branch 'subwallet-dev' into koni/dev/issue-3745
tunghp2002 Jan 10, 2025
a1232c6
Merge branch 'subwallet-dev' into koni/dev/issue-3745
tunghp2002 Jan 10, 2025
153b100
Merge pull request #3800 from Koniverse/koni/dev/issue-3745
saltict Jan 10, 2025
04f64bc
Merge pull request #3959 from Koniverse/koni/dev/issue-3958
saltict Jan 16, 2025
82c50da
[Issue-3920] Refactor code for sorting token
PDTnhah Jan 16, 2025
477d9d0
Merge branch 'subwallet-dev' into koni/dev/issue-3920
PDTnhah Jan 16, 2025
acb25fc
[Issue-3920] fix lint
PDTnhah Jan 16, 2025
28e5e0b
[Issue-3920] Refactor code for sorting token
PDTnhah Jan 17, 2025
75aec1b
[Issue-3920] Refactor code for sorting token
PDTnhah Jan 17, 2025
df59347
Merge remote-tracking branch 'refs/remotes/origin/koni/dev/issue-3920…
dungnguyen-art Jan 20, 2025
2f3214f
[Issue-3960] Update the code to align with the structured data of pri…
dungnguyen-art Jan 20, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/extension-base/src/background/KoniTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,13 +232,13 @@
externalUrl?: string;
rarity?: string;
description?: string;
properties?: Record<any, any> | null;

Check warning on line 235 in packages/extension-base/src/background/KoniTypes.ts

View workflow job for this annotation

GitHub Actions / Build Development Preview

Unexpected any. Specify a different type

Check warning on line 235 in packages/extension-base/src/background/KoniTypes.ts

View workflow job for this annotation

GitHub Actions / Build Development Preview

Unexpected any. Specify a different type
}

interface NftItemExtraInfo {
type?: _AssetType.ERC721 | _AssetType.PSP34 | RMRK_VER; // for sending
rmrk_ver?: RMRK_VER;
onChainOption?: any; // for sending PSP-34 tokens, should be done better

Check warning on line 241 in packages/extension-base/src/background/KoniTypes.ts

View workflow job for this annotation

GitHub Actions / Build Development Preview

Unexpected any. Specify a different type
assetHubType?: AssetHubNftType // for sending assetHub nft. There're 2 types nft
}

Expand Down Expand Up @@ -543,7 +543,7 @@
[ExtrinsicType.STAKING_COMPOUNDING]: RequestTuringStakeCompound,
[ExtrinsicType.STAKING_CANCEL_COMPOUNDING]: RequestTuringCancelStakeCompound,
[ExtrinsicType.STAKING_CANCEL_UNSTAKE]: RequestStakeCancelWithdrawal,
[ExtrinsicType.STAKING_POOL_WITHDRAW]: any,

Check warning on line 546 in packages/extension-base/src/background/KoniTypes.ts

View workflow job for this annotation

GitHub Actions / Build Development Preview

Unexpected any. Specify a different type

// Yield
[ExtrinsicType.JOIN_YIELD_POOL]: RequestYieldStepSubmit,
Expand Down Expand Up @@ -574,9 +574,9 @@
[ExtrinsicType.CLAIM_BRIDGE]: RequestClaimBridge

[ExtrinsicType.EVM_EXECUTE]: TransactionConfig,
[ExtrinsicType.CROWDLOAN]: any,

Check warning on line 577 in packages/extension-base/src/background/KoniTypes.ts

View workflow job for this annotation

GitHub Actions / Build Development Preview

Unexpected any. Specify a different type
[ExtrinsicType.SWAP]: SwapTxData
[ExtrinsicType.UNKNOWN]: any

Check warning on line 579 in packages/extension-base/src/background/KoniTypes.ts

View workflow job for this annotation

GitHub Actions / Build Development Preview

Unexpected any. Specify a different type
}

export enum ExtrinsicStatus {
Expand Down Expand Up @@ -675,7 +675,7 @@
// : T extends ExtrinsicType.MINT_VDOT
// ? Pick<SubmitBifrostLiquidStaking, 'rewardTokenSlug' | 'estimatedAmountReceived'>
// : undefined;
export interface TransactionHistoryItem<ET extends ExtrinsicType = ExtrinsicType.TRANSFER_BALANCE> {

Check warning on line 678 in packages/extension-base/src/background/KoniTypes.ts

View workflow job for this annotation

GitHub Actions / Build Development Preview

'ET' is defined but never used
origin?: 'app' | 'migration' | 'subsquid' | 'subscan', // 'app' or history source
callhash?: string,
signature?: string,
Expand All @@ -700,7 +700,7 @@
tip?: AmountData,
fee?: AmountData,
explorerUrl?: string,
additionalInfo?: any,

Check warning on line 703 in packages/extension-base/src/background/KoniTypes.ts

View workflow job for this annotation

GitHub Actions / Build Development Preview

Unexpected any. Specify a different type
startBlock?: number,
nonce?: number,
addressPrefix?: number
Expand Down Expand Up @@ -932,12 +932,12 @@
recipientAddress: string,

nftItemName?: string, // Use for confirmation view only
params: Record<string, any>,

Check warning on line 935 in packages/extension-base/src/background/KoniTypes.ts

View workflow job for this annotation

GitHub Actions / Build Development Preview

Unexpected any. Specify a different type
nftItem: NftItem
}

export interface EvmNftTransaction extends ValidateTransactionResponse {
tx: Record<string, any> | null;

Check warning on line 940 in packages/extension-base/src/background/KoniTypes.ts

View workflow job for this annotation

GitHub Actions / Build Development Preview

Unexpected any. Specify a different type
}

export interface ValidateNetworkResponse {
Expand Down Expand Up @@ -1709,6 +1709,13 @@
};
}

// Popular tokens

export interface TokenPriorityDetails {
priorityTokens: Record<string, number>,
groupPriority: number
}

/// WalletConnect

// Connect
Expand Down Expand Up @@ -1923,6 +1930,7 @@
'pri(chainService.upsertChain)': [_NetworkUpsertParams, boolean];
'pri(chainService.enableChains)': [EnableMultiChainParams, boolean];
'pri(chainService.enableChain)': [EnableChainParams, boolean];
'pri(chainService.enableChainWithPriorityAssets)': [EnableChainParams, boolean];
'pri(chainService.reconnectChain)': [string, boolean];
'pri(chainService.disableChains)': [string[], boolean];
'pri(chainService.disableChain)': [string, boolean];
Expand Down Expand Up @@ -2297,6 +2305,11 @@

/* Ledger */
'pri(ledger.generic.allow)': [null, string[], string[]];
/* Ledger */

/* Popular tokens */
'pri(tokens.subscribePriority)': [null, Record<string, TokenPriorityDetails>, Record<string, TokenPriorityDetails>];
/* Popular tokens */
}

export interface ApplicationMetadataType {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { _AssetRef, _AssetType, _ChainAsset, _ChainInfo, _MultiChainAsset } from
import { TransactionError } from '@subwallet/extension-base/background/errors/TransactionError';
import { withErrorLog } from '@subwallet/extension-base/background/handlers/helpers';
import { createSubscription } from '@subwallet/extension-base/background/handlers/subscriptions';
import { AccountExternalError, AddressBookInfo, AmountData, AmountDataWithId, AssetSetting, AssetSettingUpdateReq, BondingOptionParams, BrowserConfirmationType, CampaignBanner, CampaignData, CampaignDataType, ChainType, CronReloadRequest, CrowdloanJson, ExternalRequestPromiseStatus, ExtrinsicType, KeyringState, MantaPayEnableMessage, MantaPayEnableParams, MantaPayEnableResponse, MantaPaySyncState, MetadataItem, NftCollection, NftJson, NftTransactionRequest, NftTransactionResponse, PriceJson, RequestAccountCreateExternalV2, RequestAccountCreateHardwareMultiple, RequestAccountCreateHardwareV2, RequestAccountCreateWithSecretKey, RequestAccountExportPrivateKey, RequestAddInjectedAccounts, RequestApproveConnectWalletSession, RequestApproveWalletConnectNotSupport, RequestAuthorization, RequestAuthorizationBlock, RequestAuthorizationPerAccount, RequestAuthorizationPerSite, RequestAuthorizeApproveV2, RequestBondingSubmit, RequestCameraSettings, RequestCampaignBannerComplete, RequestChangeEnableChainPatrol, RequestChangeLanguage, RequestChangeMasterPassword, RequestChangePriceCurrency, RequestChangeShowBalance, RequestChangeShowZeroBalance, RequestChangeTimeAutoLock, RequestConfirmationComplete, RequestConfirmationCompleteTon, RequestConnectWalletConnect, RequestCrowdloanContributions, RequestDeleteContactAccount, RequestDisconnectWalletConnectSession, RequestEditContactAccount, RequestFindRawMetadata, RequestForgetSite, RequestFreeBalance, RequestGetTransaction, RequestKeyringExportMnemonic, RequestMaxTransferable, RequestMigratePassword, RequestParseEvmContractInput, RequestParseTransactionSubstrate, RequestPassPhishingPage, RequestQrParseRLP, RequestQrSignEvm, RequestQrSignSubstrate, RequestRejectConnectWalletSession, RequestRejectExternalRequest, RequestRejectWalletConnectNotSupport, RequestRemoveInjectedAccounts, RequestResetWallet, RequestResolveExternalRequest, RequestSaveAppConfig, RequestSaveBrowserConfig, RequestSaveOSConfig, RequestSaveRecentAccount, RequestSettingsType, RequestSigningApprovePasswordV2, RequestStakePoolingBonding, RequestStakePoolingUnbonding, RequestSubscribeHistory, RequestSubstrateNftSubmitTransaction, RequestTuringCancelStakeCompound, RequestTuringStakeCompound, RequestUnbondingSubmit, RequestUnlockKeyring, RequestUnlockType, ResolveAddressToDomainRequest, ResolveDomainRequest, ResponseAccountCreateWithSecretKey, ResponseAccountExportPrivateKey, ResponseChangeMasterPassword, ResponseFindRawMetadata, ResponseKeyringExportMnemonic, ResponseMigratePassword, ResponseNftImport, ResponseParseEvmContractInput, ResponseParseTransactionSubstrate, ResponseQrParseRLP, ResponseQrSignEvm, ResponseQrSignSubstrate, ResponseRejectExternalRequest, ResponseResetWallet, ResponseResolveExternalRequest, ResponseSubscribeHistory, ResponseUnlockKeyring, ShowCampaignPopupRequest, StakingJson, StakingRewardJson, StakingType, SufficientMetadata, ThemeNames, TransactionHistoryItem, TransactionResponse, ValidateNetworkRequest, ValidateNetworkResponse, ValidatorInfo } from '@subwallet/extension-base/background/KoniTypes';
import { AccountExternalError, AddressBookInfo, AmountData, AmountDataWithId, AssetSetting, AssetSettingUpdateReq, BondingOptionParams, BrowserConfirmationType, CampaignBanner, CampaignData, CampaignDataType, ChainType, CronReloadRequest, CrowdloanJson, ExternalRequestPromiseStatus, ExtrinsicType, KeyringState, MantaPayEnableMessage, MantaPayEnableParams, MantaPayEnableResponse, MantaPaySyncState, MetadataItem, NftCollection, NftJson, NftTransactionRequest, NftTransactionResponse, PriceJson, RequestAccountCreateExternalV2, RequestAccountCreateHardwareMultiple, RequestAccountCreateHardwareV2, RequestAccountCreateWithSecretKey, RequestAccountExportPrivateKey, RequestAddInjectedAccounts, RequestApproveConnectWalletSession, RequestApproveWalletConnectNotSupport, RequestAuthorization, RequestAuthorizationBlock, RequestAuthorizationPerAccount, RequestAuthorizationPerSite, RequestAuthorizeApproveV2, RequestBondingSubmit, RequestCameraSettings, RequestCampaignBannerComplete, RequestChangeEnableChainPatrol, RequestChangeLanguage, RequestChangeMasterPassword, RequestChangePriceCurrency, RequestChangeShowBalance, RequestChangeShowZeroBalance, RequestChangeTimeAutoLock, RequestConfirmationComplete, RequestConfirmationCompleteTon, RequestConnectWalletConnect, RequestCrowdloanContributions, RequestDeleteContactAccount, RequestDisconnectWalletConnectSession, RequestEditContactAccount, RequestFindRawMetadata, RequestForgetSite, RequestFreeBalance, RequestGetTransaction, RequestKeyringExportMnemonic, RequestMaxTransferable, RequestMigratePassword, RequestParseEvmContractInput, RequestParseTransactionSubstrate, RequestPassPhishingPage, RequestQrParseRLP, RequestQrSignEvm, RequestQrSignSubstrate, RequestRejectConnectWalletSession, RequestRejectExternalRequest, RequestRejectWalletConnectNotSupport, RequestRemoveInjectedAccounts, RequestResetWallet, RequestResolveExternalRequest, RequestSaveAppConfig, RequestSaveBrowserConfig, RequestSaveOSConfig, RequestSaveRecentAccount, RequestSettingsType, RequestSigningApprovePasswordV2, RequestStakePoolingBonding, RequestStakePoolingUnbonding, RequestSubscribeHistory, RequestSubstrateNftSubmitTransaction, RequestTuringCancelStakeCompound, RequestTuringStakeCompound, RequestUnbondingSubmit, RequestUnlockKeyring, RequestUnlockType, ResolveAddressToDomainRequest, ResolveDomainRequest, ResponseAccountCreateWithSecretKey, ResponseAccountExportPrivateKey, ResponseChangeMasterPassword, ResponseFindRawMetadata, ResponseKeyringExportMnemonic, ResponseMigratePassword, ResponseNftImport, ResponseParseEvmContractInput, ResponseParseTransactionSubstrate, ResponseQrParseRLP, ResponseQrSignEvm, ResponseQrSignSubstrate, ResponseRejectExternalRequest, ResponseResetWallet, ResponseResolveExternalRequest, ResponseSubscribeHistory, ResponseUnlockKeyring, ShowCampaignPopupRequest, StakingJson, StakingRewardJson, StakingType, SufficientMetadata, ThemeNames, TokenPriorityDetails, TransactionHistoryItem, TransactionResponse, ValidateNetworkRequest, ValidateNetworkResponse, ValidatorInfo } from '@subwallet/extension-base/background/KoniTypes';
import { AccountAuthType, AuthorizeRequest, MessageTypes, MetadataRequest, RequestAccountExport, RequestAuthorizeCancel, RequestAuthorizeReject, RequestCurrentAccountAddress, RequestMetadataApprove, RequestMetadataReject, RequestSigningApproveSignature, RequestSigningCancel, RequestTypes, ResponseAccountExport, ResponseAuthorizeList, ResponseType, SigningRequest, WindowOpenParams } from '@subwallet/extension-base/background/types';
import { TransactionWarning } from '@subwallet/extension-base/background/warnings/TransactionWarning';
import { ALL_ACCOUNT_KEY, LATEST_SESSION, XCM_FEE_RATIO } from '@subwallet/extension-base/constants';
Expand Down Expand Up @@ -1615,6 +1615,10 @@ export default class KoniExtension {
return await this.#koniState.enableChain(chainSlug, enableTokens);
}

private async enableChainWithPriorityAssets ({ chainSlug, enableTokens }: EnableChainParams): Promise<boolean> {
return await this.#koniState.enableChainWithPriorityAssets(chainSlug, enableTokens);
}

private async reconnectChain (chainSlug: string): Promise<boolean> {
return this.#koniState.chainService.reconnectChain(chainSlug);
}
Expand Down Expand Up @@ -3946,6 +3950,24 @@ export default class KoniExtension {

/* Ledger */

/* Popular tokens */

private subscribePriorityTokens (id: string, port: chrome.runtime.Port): Record<string, TokenPriorityDetails> {
const cb = createSubscription<'pri(tokens.subscribePriority)'>(id, port);

const subscription = this.#koniState.chainService.observable.priorityTokens.subscribe(cb);

this.createUnsubscriptionHandle(id, subscription.unsubscribe);

port.onDisconnect.addListener((): void => {
this.cancelSubscription(id);
});

return this.#koniState.chainService.value.priorityTokens;
}

/* Popular tokens */

// --------------------------------------------------------------
// eslint-disable-next-line @typescript-eslint/require-await
public async handle<TMessageType extends MessageTypes> (id: string, type: TMessageType, request: RequestTypes[TMessageType], port: chrome.runtime.Port): Promise<ResponseType<TMessageType>> {
Expand Down Expand Up @@ -4243,6 +4265,8 @@ export default class KoniExtension {
return this.getSupportedSmartContractTypes();
case 'pri(chainService.enableChain)':
return await this.enableChain(request as EnableChainParams);
case 'pri(chainService.enableChainWithPriorityAssets)':
return await this.enableChainWithPriorityAssets(request as EnableChainParams);
case 'pri(chainService.reconnectChain)':
return await this.reconnectChain(request as string);
case 'pri(chainService.disableChain)':
Expand Down Expand Up @@ -4556,6 +4580,12 @@ export default class KoniExtension {
case 'pri(ledger.generic.allow)':
return this.subscribeLedgerGenericAllowChains(id, port);
/* Ledger */

/* Priority tokens */
case 'pri(tokens.subscribePriority)':
return this.subscribePriorityTokens(id, port);
/* Priority tokens */

// Default
default:
throw new Error(`Unable to handle message of type ${type}`);
Expand Down
10 changes: 9 additions & 1 deletion packages/extension-base/src/koni/background/handlers/State.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ export default class KoniState {

if (authUrls[shortenUrl]) {
if (chainInfo && !_isChainEnabled(chainState)) {
await this.enableChain(networkKey);
await this.enableChainWithPriorityAssets(networkKey);
}

authUrls[shortenUrl].currentEvmNetworkKey = networkKey;
Expand Down Expand Up @@ -895,6 +895,14 @@ export default class KoniState {
return this.chainService.enableChain(chainSlug);
}

public async enableChainWithPriorityAssets (chainSlug: string, enableTokens = true): Promise<boolean> {
if (enableTokens) {
await this.chainService.updatePriorityAssetsByChain(chainSlug, true);
}

return this.chainService.enableChain(chainSlug);
}

public resetDefaultChains () {
const defaultChains = this.getDefaultNetworkKeys();

Expand Down
59 changes: 58 additions & 1 deletion packages/extension-base/src/services/chain-service/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import { AssetLogoMap, AssetRefMap, ChainAssetMap, ChainInfoMap, ChainLogoMap, MultiChainAssetMap } from '@subwallet/chain-list';
import { _AssetRef, _AssetRefPath, _AssetType, _ChainAsset, _ChainInfo, _ChainStatus, _EvmInfo, _MultiChainAsset, _SubstrateChainType, _SubstrateInfo, _TonInfo } from '@subwallet/chain-list/types';
import { AssetSetting, ValidateNetworkResponse } from '@subwallet/extension-base/background/KoniTypes';
import { AssetSetting, TokenPriorityDetails, ValidateNetworkResponse } from '@subwallet/extension-base/background/KoniTypes';
import { _DEFAULT_ACTIVE_CHAINS, _ZK_ASSET_PREFIX, LATEST_CHAIN_DATA_FETCHING_INTERVAL } from '@subwallet/extension-base/services/chain-service/constants';
import { EvmChainHandler } from '@subwallet/extension-base/services/chain-service/handler/EvmChainHandler';
import { MantaPrivateHandler } from '@subwallet/extension-base/services/chain-service/handler/manta/MantaPrivateHandler';
Expand Down Expand Up @@ -92,6 +92,7 @@ export class ChainService {
private assetLogoMapSubject = new BehaviorSubject<Record<string, string>>(AssetLogoMap);
private chainLogoMapSubject = new BehaviorSubject<Record<string, string>>(ChainLogoMap);
private ledgerGenericAllowChainsSubject = new BehaviorSubject<string[]>([]);
private priorityTokensSubject = new BehaviorSubject<Record<string, TokenPriorityDetails>>({});

// Todo: Update to new store indexed DB
private store: AssetSettingStore = new AssetSettingStore();
Expand Down Expand Up @@ -123,20 +124,28 @@ export class ChainService {

public get value () {
const ledgerGenericAllowChains = this.ledgerGenericAllowChainsSubject;
const priorityTokens = this.priorityTokensSubject;

return {
get ledgerGenericAllowChains () {
return ledgerGenericAllowChains.value;
},
get priorityTokens () {
return priorityTokens.value;
}
};
}

public get observable () {
const ledgerGenericAllowChains = this.ledgerGenericAllowChainsSubject;
const priorityTokens = this.priorityTokensSubject;

return {
get ledgerGenericAllowChains () {
return ledgerGenericAllowChains.asObservable();
},
get priorityTokens () {
return priorityTokens.asObservable();
}
};
}
Expand Down Expand Up @@ -767,6 +776,11 @@ export class ChainService {
this.logger.log('Finished updating latest ledger generic allow chains');
}

handleLatestPriorityTokens (latestPriorityTokens: Record<string, TokenPriorityDetails>) {
this.priorityTokensSubject.next(latestPriorityTokens);
this.logger.log('Finished updating latest popular tokens');
}

handleLatestData () {
this.fetchLatestChainData().then((latestChainInfo) => {
this.lockChainInfoMap = true; // do not need to check current lockChainInfoMap because all remains action is fast enough and don't affect this feature.
Expand All @@ -786,6 +800,12 @@ export class ChainService {
this.handleLatestLedgerGenericAllowChains(latestledgerGenericAllowChains);
})
.catch(console.error);

this.fetchLatestPriorityTokens()
.then((latestPriorityTokens) => {
this.handleLatestPriorityTokens(latestPriorityTokens);
})
.catch(console.error);
}

private async initApis () {
Expand Down Expand Up @@ -1088,6 +1108,10 @@ export class ChainService {
return await fetchStaticData<string[]>('chains/ledger-generic-allow-chains') || [];
}

private async fetchLatestPriorityTokens () {
return await fetchStaticData<Record<string, TokenPriorityDetails>>('chain-assets/priority-tokens') || [];
}

private async initChains () {
const storedChainSettings = await this.dbService.getAllChainStore();
const defaultChainInfoMap = filterChainInfoMap(ChainInfoMap, ignoredList);
Expand Down Expand Up @@ -2003,6 +2027,39 @@ export class ChainService {
this.setAssetSettings(assetSettings);
}

public async updatePriorityAssetsByChain (chainSlug: string, visible: boolean) {
const currentAssetSettings = await this.getAssetSettings();
const assetsByChain = this.getFungibleTokensByChain(chainSlug);
const priorityTokensMap = this.priorityTokensSubject.value || {};

const priorityTokensList = Object.values(priorityTokensMap).flatMap((tokenData) =>
Object.keys(tokenData.priorityTokens)
);

let priorityTokenFound = false;

for (const asset of Object.values(assetsByChain)) {
if (visible) {
const isPriorityToken = priorityTokensList.includes(asset.slug);

if (isPriorityToken) {
currentAssetSettings[asset.slug] = { visible: true };
priorityTokenFound = true;
}
} else {
currentAssetSettings[asset.slug] = { visible: false };
}
}

if (!priorityTokenFound && visible) {
S2kael marked this conversation as resolved.
Show resolved Hide resolved
const nativeTokenInfo = this.getNativeTokenInfo(chainSlug);

currentAssetSettings[nativeTokenInfo.slug] = { visible: true };
}

this.setAssetSettings(currentAssetSettings);
}

public subscribeAssetSettings () {
return this.assetSettingSubject;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export class AccountLedgerHandler extends AccountBaseHandler {

if (Object.keys(slugMap).length) {
for (const chainSlug of Object.keys(slugMap)) {
this.state.enableChain(chainSlug);
this.state.enableChainWithPriorityAssets(chainSlug);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,10 @@ export class AccountState {
this.koniState.enableChain(slug, true).catch(console.error);
}

public enableChainWithPriorityAssets (slug: string) {
this.koniState.enableChainWithPriorityAssets(slug, true).catch(console.error);
}

/* Others */

/* Reset wallet */
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright 2019-2022 @subwallet/extension-koni authors & contributors
// SPDX-License-Identifier: Apache-2.0

import { TokenPriorityDetails } from '@subwallet/extension-base/background/KoniTypes';
import { _isNativeToken } from '@subwallet/extension-base/services/chain-service/utils';
import BaseMigrationJob from '@subwallet/extension-base/services/migration-service/Base';
import { fetchStaticData } from '@subwallet/extension-base/utils';

// Usage:
// 1. Disable tokens with a balance of 0, except for the native token and priorityToken.

export default class DisableZeroBalanceTokens extends BaseMigrationJob {
public override async run (): Promise<void> {
const state = this.state;

try {
const rawBalanceMap = await state.dbService.getStoredBalance();
const tokensList = await state.chainService.getAssetSettings();

const balanceNonZero = rawBalanceMap.filter((item) => {
return (BigInt(item.free) + BigInt(item.locked) > 0);
});

const priorityTokensMap = await fetchStaticData<Record<string, TokenPriorityDetails>>('chain-assets/priority-tokens') || [];
const priorityTokensList = Object.values(priorityTokensMap).flatMap((tokenData) =>
Object.keys(tokenData.priorityTokens)
);
// Extract the slugs of tokens with balance > 0
const allowedSlugs = new Set(balanceNonZero.map((item) => item.tokenSlug));
dungnguyen-art marked this conversation as resolved.
Show resolved Hide resolved
const updatedSettings = { ...tokensList };
dungnguyen-art marked this conversation as resolved.
Show resolved Hide resolved

Object.keys(tokensList).forEach((slug) => {
dungnguyen-art marked this conversation as resolved.
Show resolved Hide resolved
const originAsset = state.chainService.getAssetBySlug(slug);

// Check if it is a native token
const isNativeToken = originAsset && _isNativeToken(originAsset);

// Check if it is a popular token
const isPopularToken = priorityTokensList.includes(slug);

if (!isNativeToken && !isPopularToken && !allowedSlugs.has(slug)) {
updatedSettings[slug] = {
visible: false
};
}
});

state.chainService.setAssetSettings(updatedSettings);
} catch (error) {
console.error(error);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ export default abstract class EnableChain extends BaseMigrationJob {
public override async run (): Promise<void> {
const state = this.state;

await state.enableChain(this.slug, true);
await state.enableChainWithPriorityAssets(this.slug, true);
}
}
Loading
Loading