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

✨ feat: support to switch to dev mode #164

Merged
merged 1 commit into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions apps/wallet/src/i18n/locales/cnt.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@
"page_settings_title": "設置",
"page_settings_security": "安全性",
"page_settings_changePassword": "更改錢包密碼",
"page_settings_developerMode": "開發者模式",
"page_settings_devModeField": "啟用內部測試網",
"page_settings_account": "帳戶",
"page_settings_linkMore": "連結更多",
"page_account_title": "連結更多",
Expand Down
2 changes: 2 additions & 0 deletions apps/wallet/src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@
"page_settings_title": "Settings",
"page_settings_security": "Security",
"page_settings_changePassword": "Change wallet password",
"page_settings_developerMode": "Developer Mode",
"page_settings_devModeField": "Enable internal testnet",
"page_settings_account": "Account",
"page_settings_linkMore": "Link more",

Expand Down
2 changes: 2 additions & 0 deletions apps/wallet/src/i18n/locales/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@
"page_settings_title": "設定",
"page_settings_security": "セキュリティ",
"page_settings_changePassword": "ウォレットパスワードの変更",
"page_settings_developerMode": "開発者モード",
"page_settings_devModeField": "内部テストネットを有効化",
"page_settings_account": "アカウント",
"page_settings_linkMore": "さらにリンク",
"page_account_title": "さらにリンク",
Expand Down
2 changes: 2 additions & 0 deletions apps/wallet/src/i18n/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@
"page_settings_title": "Настройки",
"page_settings_security": "Безопасность",
"page_settings_changePassword": "Изменить пароль кошелька",
"page_settings_developerMode": "Режим разработчика",
"page_settings_devModeField": "Активировать внутреннюю тестовую сеть",
"page_settings_account": "Аккаунт",
"page_settings_linkMore": "Подключить больше",
"page_account_title": "Подключить больше",
Expand Down
2 changes: 1 addition & 1 deletion apps/wallet/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ html, body, #root {
.btn-primary {
@apply text-base-content;
}
.btn-sm:not(.btn-square,.btn-circle) {
.btn-sm:not(.btn-square,.btn-circle,.btn-link) {
@apply h-10;
}
.btn-ex3-primary {
Expand Down
35 changes: 28 additions & 7 deletions apps/wallet/src/pages/settings/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import AuthenticatorLogo from "../../components/AuthenticatorLogo";
import { AuthenticatorType } from "@delandlabs/hibit-id-sdk";
import hibitIdSession from "../../stores/session";
import PageHeader from "../../components/PageHeader";
import SvgGo from '../../assets/right-arrow.svg?react'

const SettingsPage: FC = observer(() => {
const navigate = useNavigate()
Expand All @@ -21,12 +22,12 @@ const SettingsPage: FC = observer(() => {
<p className="label-text text-neutral text-sm font-bold">
{t('page_settings_account')}
</p>
<div className="mt-4 flex justify-between items-center">
<div className="mt-2 flex justify-between items-center">
<div className="flex items-center gap-2 text-xs">
<AuthenticatorLogo type={AuthenticatorType.Telegram} className="size-6" />
<span>{userName}</span>
</div>
<button className="btn btn-link btn-xs no-underline p-0" onClick={() => {
<button className="btn btn-link btn-sm no-underline p-0" onClick={() => {
navigate('/account-manage')
}}>
{t('page_settings_linkMore')}
Expand All @@ -38,11 +39,31 @@ const SettingsPage: FC = observer(() => {
<p className="label-text text-neutral text-sm font-bold">
{t('page_settings_security')}
</p>
<button className="btn btn-link btn-xs mt-4 no-underline p-0" onClick={() => {
navigate('/change-password')
}}>
{t('page_settings_changePassword')}
</button>
<label className="mt-2 flex justify-between items-center">
<button className="btn btn-link btn-sm !h-5 !min-h-5 no-underline p-0" onClick={() => {
navigate('/change-password')
}}>
{t('page_settings_changePassword')}
</button>
<SvgGo className="size-5" />
</label>
</div>

<div className="mt-6">
<p className="label-text text-neutral text-sm font-bold">
{t('page_settings_developerMode')}
</p>
<label className="mt-2 flex justify-between items-center">
<span className="text-sm">{t('page_settings_devModeField')}</span>
<input
type="checkbox"
className="toggle toggle-primary toggle-sm rounded-full"
checked={hibitIdSession.config.devMode}
onChange={(e) => {
hibitIdSession.setDevMode(e.target.checked)
}}
/>
</label>
</div>
</div>
)
Expand Down
39 changes: 27 additions & 12 deletions apps/wallet/src/stores/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,29 @@ import { HibitEnv, RuntimeEnv } from "../utils/basicEnums";
import rpcManager from "./rpc";
import { WalletAccount } from "@delandlabs/hibit-id-sdk";
import { Oidc } from '../utils/oidc/lib/oidc-spa-4.11.1/src';
import { MnemonicManager, UpdateMnemonicAsync } from '../apis/services/auth';
import { MnemonicManager } from '../apis/services/auth';
import { HibitIDError, HibitIDErrorCode } from "../utils/error-code";
import { GetMnemonicResult, UpdateMnemonicInput } from "../apis/models";
import { GetMnemonicResult } from "../apis/models";
import { AES, enc, MD5 } from "crypto-js";
import { HIBIT_ENV } from "../utils/env";
import { getChainByChainId, getSupportedChains } from "../utils/chain";
import { getChainByChainId, getDevModeSwitchChain, getSupportedChains } from "../utils/chain";

const SESSION_CONFIG_KEY = 'hibit-id-config'
const PASSWORD_STORAGE_KEY = 'hibit-id-p'

interface SessionConfig {
lastChainId: string
devMode: boolean
}

export class HibitIdSession {
public walletPool: ChainWalletPool | null = null
public auth: Oidc.Tokens | null = null
public chainInfo: ChainInfo
public config: SessionConfig = {
lastChainId: '',
devMode: false
}

private _mnemonic: GetMnemonicResult | null = null
private _password: string | null = null
Expand All @@ -37,16 +42,17 @@ export class HibitIdSession {
let initialChainInfo = IS_TELEGRAM_MINI_APP
? HIBIT_ENV === HibitEnv.PROD ? Ton : TonTestnet
: HIBIT_ENV === HibitEnv.PROD ? Ethereum : EthereumSepolia
const config = localStorage.getItem(SESSION_CONFIG_KEY)
if (config) {
const { lastChainId } = JSON.parse(config) as SessionConfig
const chainId = ChainId.fromString(lastChainId)
const chainInfo = getChainByChainId(chainId)
const configString = localStorage.getItem(SESSION_CONFIG_KEY)
if (configString) {
const config = JSON.parse(configString) as SessionConfig
this.config = config
const chainId = ChainId.fromString(config.lastChainId)
const chainInfo = getChainByChainId(chainId, config.devMode)
if (chainInfo) {
initialChainInfo = chainInfo
}
}
const supportedChains = getSupportedChains()
const supportedChains = getSupportedChains(this.config.devMode)
if (!supportedChains.find((c) => c.chainId.equals(initialChainInfo.chainId))) {
initialChainInfo = supportedChains[0]
}
Expand Down Expand Up @@ -96,9 +102,18 @@ export class HibitIdSession {

public setChainInfo = (chainInfo: ChainInfo) => {
this.chainInfo = chainInfo
localStorage.setItem(SESSION_CONFIG_KEY, JSON.stringify({
lastChainId: chainInfo.chainId.toString(),
} as SessionConfig))
this.config.lastChainId = chainInfo.chainId.toString()
localStorage.setItem(SESSION_CONFIG_KEY, JSON.stringify(this.config))
}

public setDevMode = (devMode: boolean) => {
if (this.config.devMode === devMode) return
this.config.devMode = devMode
localStorage.setItem(SESSION_CONFIG_KEY, JSON.stringify(this.config))
setTimeout(() => {
const newChain = getDevModeSwitchChain(!devMode, this.chainInfo.chainId)
this.switchChain(newChain)
})
}

public getValidAddress = async () => {
Expand Down
5 changes: 0 additions & 5 deletions apps/wallet/src/utils/basicEnums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,6 @@ export enum RuntimeEnv {
SDK = 'sdk',
}

export enum BlockNetwork {
Mainnet = 'mainnet',
Testnet = 'testnet'
}

/**
* ex3 key signature schema
*/
Expand Down
4 changes: 2 additions & 2 deletions apps/wallet/src/utils/chain/chain-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const Ethereum: ChainInfo = {
nativeAssetDecimals: 18,
supportedSignaturesSchemas: [WalletSignatureSchema.EvmEcdsa],
explorer: 'https://etherscan.io',
rpcUrls: ['https://endpoints.omniatech.io/v1/eth/mainnet/public']
rpcUrls: ['https://ethereum.blockpi.network/v1/rpc/public']
};
export const EthereumSepolia: ChainInfo = {
chainId: new ChainId(Chain.Ethereum, ChainNetwork.EvmSepoliaNet),
Expand All @@ -24,7 +24,7 @@ export const EthereumSepolia: ChainInfo = {
nativeAssetDecimals: 18,
supportedSignaturesSchemas: [WalletSignatureSchema.EvmEcdsa],
explorer: 'https://sepolia.etherscan.io',
rpcUrls: ['https://rpc-sepolia.rockx.com']
rpcUrls: ['https://ethereum-sepolia.blockpi.network/v1/rpc/public ']
};

export const EthereumBsc: ChainInfo = {
Expand Down
22 changes: 13 additions & 9 deletions apps/wallet/src/utils/chain/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { BlockNetwork } from '../basicEnums';
import { Chain, ChainId } from '../basicTypes';
import { Ethereum, EthereumAvalanche, EthereumAvalancheFuji, EthereumBase, EthereumBaseSepolia, EthereumBsc, EthereumBscTestnet, EthereumScroll, EthereumScrollSepolia, EthereumSepolia, EthereumBitlayer, EthereumBitlayerTestnet, Ton, TonTestnet } from './chain-list';
import { ChainInfo } from '../basicTypes';
import { BLOCK_NETWORK } from '../env';
import { RUNTIME_SUPPORTED_CHAIN_IDS } from '../runtime';
import hibitIdSession from '../../stores/session';

// TODO: should update when we support more chains
const SupportedChainsForMainnet = [
Expand Down Expand Up @@ -31,17 +30,14 @@ const SupportedChainsForTestnet = [
// TronNile,
];

export function getChainByChainId(chainId: ChainId | null): ChainInfo | null {
export function getChainByChainId(chainId: ChainId | null, devMode?: boolean): ChainInfo | null {
if (!chainId) return null;
const chains = getSupportedChains();
const chains = getSupportedChains(devMode);
return chains.find(c => c.chainId.equals(chainId)) ?? null;
}

export function getSupportedChains(chainTypes?: Chain[]): ChainInfo[] {
let supported =
BLOCK_NETWORK === BlockNetwork.Mainnet
? SupportedChainsForMainnet
: SupportedChainsForTestnet;
export function getSupportedChains(devMode?: boolean, chainTypes?: Chain[]): ChainInfo[] {
let supported = (devMode ?? hibitIdSession.config.devMode) ? SupportedChainsForTestnet : SupportedChainsForMainnet;
if (RUNTIME_SUPPORTED_CHAIN_IDS.length > 0) {
supported = supported.filter(
c => RUNTIME_SUPPORTED_CHAIN_IDS.find((id) => id.equals(c.chainId))
Expand All @@ -51,3 +47,11 @@ export function getSupportedChains(chainTypes?: Chain[]): ChainInfo[] {
c => !chainTypes || !!chainTypes.find(type => type.equals(c.chainId.type))
);
}

export function getDevModeSwitchChain(isCurrentDevMode: boolean, chainId: ChainId): ChainInfo {
const [currentList, mappingList] = isCurrentDevMode
? [SupportedChainsForTestnet, SupportedChainsForMainnet]
: [SupportedChainsForMainnet, SupportedChainsForTestnet];
const index = currentList.findIndex(c => c.chainId.equals(chainId));
return index < 0 ? mappingList[0] : mappingList[index];
}
3 changes: 1 addition & 2 deletions apps/wallet/src/utils/env.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BlockNetwork, HibitEnv } from "./basicEnums";
import { HibitEnv } from "./basicEnums";

let env: HibitEnv = HibitEnv.DEV
switch (import.meta.env.VITE_APP_ENV.toLowerCase()) {
Expand All @@ -12,4 +12,3 @@ switch (import.meta.env.VITE_APP_ENV.toLowerCase()) {
}
}
export const HIBIT_ENV = env
export const BLOCK_NETWORK = HIBIT_ENV === HibitEnv.PROD? BlockNetwork.Mainnet : BlockNetwork.Testnet
2 changes: 1 addition & 1 deletion packages/sdk/.env
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
VITE_HIBIT_ID_PROD_URL=https://id.hibit.app
VITE_HIBIT_ID_TEST_URL=https://idtestnet.hibit.app
VITE_HIBIT_ID_DEV_URL=https://localhost:5176
VITE_HIBIT_ID_DEV_URL=https://127.0.0.1:5176
VITE_RELEASE_VERSION=1.0.0
1 change: 0 additions & 1 deletion packages/sdk/src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export const RPC_SERVICE_NAME = 'hibit-id-rpc'
export const IFRAME_CONTAINER_ID = 'hibit-id-app'
export const CONTROLLER_CONTAINER_ID = 'hibit-id-controller'
export const SDK_AUTH_PARAM_KEY = 'a'
2 changes: 1 addition & 1 deletion packages/sdk/src/lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export { HibitIdWallet } from './wallet'
export { getSupportedAuthParties } from './utils'
export { RPC_SERVICE_NAME, SDK_AUTH_PARAM_KEY } from './constants'
export { RPC_SERVICE_NAME } from './constants'
export { ClientExposeRPCMethod, HibitIdExposeRPCMethod, AuthenticatorType, HibitIdAssetType, HibitIdChainId, HibitIdErrorCode } from './enums'
export { BridgePromise } from './types'
export type {
Expand Down
Loading