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

chore: generate presetNetwork file from server #5410

Draft
wants to merge 9 commits into
base: x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
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
146 changes: 146 additions & 0 deletions development/fetchNetworks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
const axios = require('axios');
const fs = require('fs');
const { exec } = require('child_process');

const API_URL = 'https://wallet.onekeytest.com/wallet/v1/network/list/all';
const OUTPUT_FILE = 'packages/shared/src/config/presetNetworks.ts';

function sanitizeShortcode(shortcode) {
return shortcode.replace(/[-_]/g, '');
}

function stringifyWithSingleQuotes(obj, space = 2) {
const json = JSON.stringify(obj, null, space);
return json.replace(/"([^"]+)":/g, "'$1':").replace(/"/g, "'");
}

async function fetchNetworks() {
try {
if (fs.existsSync(OUTPUT_FILE)) {
fs.unlinkSync(OUTPUT_FILE);
console.log(`Deleted old ${OUTPUT_FILE}`);
}

const response = await axios.get(API_URL);
const networks = response.data.data;

if (!Array.isArray(networks) || !networks.length) {
console.error('Networks is empty');
return;
}

console.log('====>>>networks: ', networks);

let fileContent = `/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable spellcheck/spell-checker */
import { memoFn } from '@onekeyhq/shared/src/utils/cacheUtils';
import type { IServerNetwork } from '@onekeyhq/shared/types';
import { ENetworkStatus } from '@onekeyhq/shared/types';

import platformEnv from '../platformEnv';

// dangerNetwork represents a virtual network
export const dangerAllNetworkRepresent: IServerNetwork = {
'chainId': '0',
'code': 'onekeyall',
'decimals': 0,
'id': 'onekeyall--0',
'impl': 'onekeyall',
'isTestnet': false,
'isAllNetworks': true,
'logoURI': 'https://uni.onekey-asset.com/static/logo/chain_selector_logo.png',
'name': 'All Networks',
'shortcode': 'onekeyall',
'shortname': 'onekeyall',
'symbol': 'ALL NETWORKS',
'feeMeta': {
'code': '',
'decimals': 0,
'symbol': '0',
},
'defaultEnabled': true,
'status': ENetworkStatus.LISTED,
};\n
`;

// Group networks by impl
const networkGroups = {};
networks.forEach((network) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getNetworkIdsMap 也可以在预生成好,减少运行时计算量

const { impl, shortcode } = network;
if (!shortcode) return;

if (!networkGroups[impl]) {
networkGroups[impl] = [];
}
networkGroups[impl].push(network);
});

const networkMap = new Map();
const networkDeclarations = [];

Object.keys(networkGroups)
.sort()
.forEach((impl) => {
if (networkDeclarations.length > 0) {
networkDeclarations.push('');
}
networkDeclarations.push(`// ${impl.toUpperCase()} networks`);

networkGroups[impl].forEach((network) => {
const { shortcode } = network;
if (!shortcode) return;

const sanitizedShortcode = sanitizeShortcode(shortcode);
if (network.status === 'LISTED') {
network.status = 'ENetworkStatus.LISTED';
} else {
network.status = 'ENetworkStatus.TRASH';
}

const networkString = stringifyWithSingleQuotes(network).replace(
/'(ENetworkStatus\.(LISTED|TRASH))'/g,
'$1',
);

const networkDeclaration = `const ${sanitizedShortcode}: IServerNetwork = ${networkString};`;

networkDeclarations.push(networkDeclaration);
networkMap.set(sanitizedShortcode, network);
});
});

fileContent += networkDeclarations.join('\n');

fileContent += `

const chainsOnlyEnabledInDev: IServerNetwork[] = [
// Add your dev-only chains here
];

export const presetNetworksMap = {
${Array.from(networkMap.keys()).join(',\n ')}
};

export const getPresetNetworks = memoFn((): IServerNetwork[] => [
dangerAllNetworkRepresent,
${Array.from(networkMap.keys()).join(',\n ')},
...(platformEnv.isDev ? chainsOnlyEnabledInDev : []),
]);
`;
fs.writeFileSync(OUTPUT_FILE, fileContent);
console.log(`${OUTPUT_FILE} has been generated successfully.`);

// Run ESLint fix command
exec(`npx eslint --fix ${OUTPUT_FILE}`, (error, stdout, stderr) => {
if (error) {
console.error(`Error running ESLint: ${error}`);
return;
}
console.log(`ESLint fix completed for ${OUTPUT_FILE}`);
});
} catch (error) {
console.error('Error fetching networks:', error.message);
}
}

fetchNetworks();
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"app:android:device": "yarn workspace @onekeyhq/mobile android:device",
"icon:build": "yarn workspace @onekeyhq/components icon:build",
"fetch:locale": "yarn workspace @onekeyhq/shared fetch:locale",
"fetch:networks": "node ./development/fetchNetworks.js",
"clean": "yarn workspaces foreach -A -p run clean && ./development/scripts/clean_workspace.sh",
"clean:cache": "yarn workspaces foreach -A run clean:build",
"_tsc": "node ./development/lint/ts",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ import {
useClipboard,
} from '@onekeyhq/components';
import { ETranslations } from '@onekeyhq/shared/src/locale';
import { openUrlExternal } from '@onekeyhq/shared/src/utils/openUrlUtils';

import backgroundApiProxy from '../../../background/instance/backgroundApiProxy';
import { NetworkAvatar } from '../../../components/NetworkAvatar';
import { usePromiseResult } from '../../../hooks/usePromiseResult';
import { openExplorerAddressUrl } from '../../../utils/explorerUtils';

export function MarketTokenAddress({
tokenName,
Expand Down Expand Up @@ -50,12 +50,8 @@ export function MarketTokenAddress({
},
);
const handleOpenUrl = useCallback(async () => {
if (network?.explorers[0].address) {
openUrlExternal(
network.explorers[0].address.replace('{address}', address),
);
}
}, [address, network?.explorers]);
void openExplorerAddressUrl({ networkId, address });
}, [networkId, address]);
const renderIcon = useCallback(() => {
if (uri) {
return (
Expand Down
Loading
Loading