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/discover both legacy and new keys #2795

Merged
merged 2 commits into from
Jan 16, 2025
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
16 changes: 16 additions & 0 deletions packages/apps/dev-wallet/src/App/layout-full.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Stack } from '@kadena/kode-ui';
import { FC } from 'react';
import { Outlet } from 'react-router-dom';
import { LayoutFullContainerStyle } from './layout-mini.css';

export const LayoutFull: FC = () => {
return (
<>
<Stack className={LayoutFullContainerStyle}>
<Outlet />
</Stack>

<div id="modalportal"></div>
</>
);
};
14 changes: 14 additions & 0 deletions packages/apps/dev-wallet/src/App/layout-mini.css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,17 @@ export const containerStyle = style([
height: '100dvh',
},
]);

export const LayoutFullContainerStyle = style([
atoms({
padding: 'sm',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}),
{
margin: '0 auto',
textAlign: 'center',
height: '100dvh',
},
]);
8 changes: 4 additions & 4 deletions packages/apps/dev-wallet/src/App/routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import { HomePage } from '../pages/home/home-page';
import { SelectProfile } from '../pages/select-profile/select-profile';
import { UnlockProfile } from '../pages/unlock-profile/unlock-profile';
import { getScriptType } from '../utils/window';
import { LayoutFull } from './layout-full';
import { LayoutMini } from './layout-mini';
import { Layout } from './Layout/Layout';
import { useGlobalState } from './providers/globalState';
Expand Down Expand Up @@ -142,12 +143,11 @@ export const Routes: FC = () => {
path="/settings/keep-password-policy"
element={<KeepPasswordPolicy />}
/>
<Route
path="/account-discovery/:keySourceId"
element={<AccountDiscovery />}
/>
</Route>
</Route>
<Route element={<LayoutFull />}>
<Route path="/account-discovery" element={<AccountDiscovery />} />
</Route>
<Route element={<LayoutMini />}>
<Route path="/settings/reveal-phrase" element={<RevealPhrase />} />
<Route
Expand Down
2 changes: 1 addition & 1 deletion packages/apps/dev-wallet/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const config = {
colorList,
defaultAccentColor: colorList[0],
DB: {
DB_VERSION: 44,
DB_VERSION: 45,
DB_NAME: 'dev-wallet',
},
ACCOUNTS: {
Expand Down
158 changes: 75 additions & 83 deletions packages/apps/dev-wallet/src/modules/account/account.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import { IRetrievedAccount } from './IRetrievedAccount';

export type IWalletDiscoveredAccount = {
chainId: ChainId;
networkUUID: UUID;
result:
| undefined
| {
Expand Down Expand Up @@ -129,7 +130,7 @@ export const accountDiscovery = (
)(
(emit) =>
async (
network: INetwork,
networks: INetwork[],
keySource: IKeySource,
profileId: string,
numberOfKeys = 20,
Expand All @@ -140,7 +141,6 @@ export const accountDiscovery = (
}
const keySourceService = await keySourceManager.get(keySource.source);
const accounts: IAccount[] = [];
const keysets: IKeySet[] = [];
const usedKeys: IKeyItem[] = [];
const saveCallbacks: Array<() => Promise<void>> = [];
for (let i = 0; i < numberOfKeys; i++) {
Expand All @@ -150,95 +150,87 @@ export const accountDiscovery = (
}
await emit('key-retrieved')(key);
const principal = `k:${key.publicKey}`;
const chainResult = await discoverAccount(
principal,
network.networkId,
undefined,
contract,
)
.on('chain-result', async (data) => {
await emit('chain-result')({
chainId: data.chainId,
result: data.result
? {
...data.result,
guard: data.result.details.guard
? {
...data.result.details.guard,
principal: data.result.principal,
}
: undefined,
}
: undefined,
for (const network of networks) {
const chainResult = await discoverAccount(
principal,
network.networkId,
undefined,
contract,
)
.on('chain-result', async (data) => {
await emit('chain-result')({
chainId: data.chainId,
networkUUID: network.uuid,
result: data.result
? {
...data.result,
guard: data.result.details.guard
? {
...data.result.details.guard,
principal: data.result.principal,
}
: undefined,
balance: data.result.details.balance,
}
: undefined,
});
})
.execute()
.catch((error) => {
console.log('DISCOVERY_ERROR', error);
return [];
});
})
.execute();

if (chainResult.filter(({ result }) => Boolean(result)).length > 0) {
const availableKeyset = await accountRepository.getKeysetByPrincipal(
principal,
profileId,
);
usedKeys.push(key);
const keyset: IKeySet = availableKeyset || {
uuid: crypto.randomUUID(),
principal,
profileId,
guard: {
keys: [key.publicKey],
pred: 'keys-all',
},
alias: '',
};
if (!availableKeyset) {
keysets.push(keyset);
if (chainResult.filter(({ result }) => Boolean(result)).length > 0) {
usedKeys.push(key);
const account: IAccount = {
uuid: crypto.randomUUID(),
profileId,
networkUUID: network.uuid,
contract,
guard: {
keys: [key.publicKey],
pred: 'keys-all',
principal,
},
address: `k:${key.publicKey}`,
chains: chainResult
.filter(({ result }) => Boolean(result))
.map(({ chainId, result }) => ({
chainId: chainId!,
balance:
new PactNumber(result!.details.balance).toDecimal() ||
'0.0',
})),
overallBalance: chainResult.reduce(
(acc, { result }) =>
result && result.details.balance
? new PactNumber(result.details.balance)
.plus(acc)
.toDecimal()
: acc,
'0',
),
};
accounts.push(account);
saveCallbacks.push(async () => {
if (!keySource.keys.find((k) => k.publicKey === key.publicKey)) {
await keySourceService.createKey(
keySource.uuid,
key.index as number,
);
}
await accountRepository.addAccount(account);
});
}
const account: IAccount = {
uuid: crypto.randomUUID(),
profileId,
networkUUID: network.uuid,
contract,
keysetId: keyset.uuid,
guard: {
keys: [key.publicKey],
pred: 'keys-all',
principal,
},
address: `k:${key.publicKey}`,
chains: chainResult
.filter(({ result }) => Boolean(result))
.map(({ chainId, result }) => ({
chainId: chainId!,
balance:
new PactNumber(result!.details.balance).toDecimal() || '0.0',
})),
overallBalance: chainResult.reduce(
(acc, { result }) =>
result && result.details.balance
? new PactNumber(result.details.balance).plus(acc).toDecimal()
: acc,
'0',
),
};
accounts.push(account);
saveCallbacks.push(async () => {
if (!keySource.keys.find((k) => k.publicKey === key.publicKey)) {
await keySourceService.createKey(
keySource.uuid,
key.index as number,
);
}
if (!availableKeyset) {
await accountRepository.addKeyset(keyset);
}
await accountRepository.addAccount(account);
});
}
}

await emit('query-done')(accounts);

await Promise.all(saveCallbacks.map((cb) => cb().catch(console.error)));
for (const cb of saveCallbacks) {
await cb().catch(console.error);
}

keySourceService.clearCache();
await emit('accounts-saved')(accounts);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,15 @@ export const CommunicationProvider: FC<PropsWithChildren> = ({ children }) => {
return () => {
handlers.forEach((unsubscribe) => unsubscribe());
};
}, [navigate, requests, isUnlocked]);
}, [
navigate,
requests,
isUnlocked,
accounts,
profile,
networks,
activeNetwork,
]);

return (
<communicationContext.Provider value={requests}>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// check the change log for more details
import { INetwork } from '@/modules/network/network.repository';
import { getAllItems, putItem } from '../indexeddb';

const changeLog = ['Enable mainnet by default'];

export async function migrateFrom44to45(
db: IDBDatabase,
transaction: IDBTransaction,
) {
console.log('change log:');
changeLog.forEach((log, index) => console.log(index, log));
const allNetworks = await getAllItems(db, transaction)<INetwork>('network');
const update = putItem(db, transaction);
const mainnet = allNetworks.find(
(network) => network.networkId === 'mainnet01',
);
if (mainnet?.disabled) {
await update<INetwork>('network', {
...mainnet,
disabled: false,
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { migrateFrom40to41 } from './migrateFrom40to41';
import { migrateFrom41to42 } from './migrateFrom41to42';
import { migrateFrom42to43 } from './migrateFrom42to43';
import { migrateFrom43to44 } from './migrateFrom43to44';
import { migrateFrom44to45 } from './migrateFrom44to45';

const { DB_NAME, DB_VERSION } = config.DB;

Expand All @@ -19,6 +20,7 @@ const migrationMap = {
41: migrateFrom41to42,
42: migrateFrom42to43,
43: migrateFrom43to44,
44: migrateFrom44to45,
};

export async function migration(result: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,29 +36,68 @@ export interface IWebAuthn {
}>;
}

export type KeySourceType = IHDBIP44 | IHDChainweaver | IWebAuthn;
export type KeySourceType = (IHDBIP44 | IHDChainweaver | IWebAuthn) & {
isDefault?: boolean;
};

export interface HDWalletRepository {
getKeySource: (id: string) => Promise<KeySourceType>;
getKeySources: (profileId: string) => Promise<KeySourceType[]>;
addKeySource: (profile: KeySourceType) => Promise<void>;
updateKeySource: (profile: KeySourceType) => Promise<void>;
patchKeySource: (id: string, patch: Partial<KeySourceType>) => Promise<void>;
setAsDefault: (id: string, profileId: string) => Promise<void>;
}

const createKeySourceRepository = ({
getOne,
add,
update,
getAll,
}: IDBService): HDWalletRepository => {
const getKeySource = async (id: string): Promise<KeySourceType> => {
return getOne('keySource', id);
};
const getKeySources = async (profileId: string): Promise<KeySourceType[]> => {
return getAll('keySource', profileId, 'profileId');
};
const addKeySource = async (keySource: KeySourceType): Promise<void> => {
return add('keySource', keySource);
};
const updateKeySource = async (keySource: KeySourceType): Promise<void> => {
return update('keySource', keySource);
};
const patchKeySource = async (
id: string,
patch: Partial<KeySourceType>,
): Promise<void> => {
const keySource = await getOne('keySource', id);
if (!keySource) return;
return update('keySource', { ...keySource, ...patch });
};
const setAsDefault = async (id: string, profileId: string): Promise<void> => {
const keySources: KeySourceType[] = await getAll(
'keySource',
profileId,
'profileId',
);
if (!keySources || !keySources.length) return;
await Promise.all(
keySources
.filter((ks) => ks.uuid !== id)
.map((ks) => update('keySource', { ...ks, isDefault: false })),
);
const keySource: KeySourceType = await getOne('keySource', id);
return update('keySource', { ...keySource, isDefault: true });
};

return {
getKeySource: async (id: string): Promise<KeySourceType> => {
return getOne('keySource', id);
},
addKeySource: async (keySource: KeySourceType): Promise<void> => {
return add('keySource', keySource);
},
updateKeySource: async (keySource: KeySourceType): Promise<void> => {
return update('keySource', keySource);
},
getKeySource,
getKeySources,
addKeySource,
updateKeySource,
patchKeySource,
setAsDefault,
};
};

Expand Down
Loading
Loading