Skip to content

Commit 902f9fc

Browse files
authored
Names an account with last 4 of address if no name exists (#301)
1 parent 2c14153 commit 902f9fc

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

main/api/manager.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { RpcClient } from "@ironfish/sdk";
2+
import log from "electron-log";
23

34
import { getExternalChainHead } from "./accounts/utils/getExternalChainHead";
45
import { Ironfish } from "./ironfish/Ironfish";
@@ -46,6 +47,58 @@ export class Manager {
4647
return hoursSinceLastBlock > 24 * 7 * 2;
4748
};
4849

50+
private async handleUnnamedAccounts(
51+
rpcClient: RpcClient,
52+
accountsResponse: { content: { accounts: string[] } },
53+
) {
54+
// Create a set of existing account names and find unnamed accounts in one pass
55+
const existingNames = new Set<string>();
56+
const unnamedAccounts = accountsResponse.content.accounts.filter(
57+
(account) => {
58+
existingNames.add(account);
59+
if (account.trim()) {
60+
return false;
61+
}
62+
return true;
63+
},
64+
);
65+
66+
// Handle each unnamed account sequentially
67+
for (const account of unnamedAccounts) {
68+
const publicKey = await rpcClient.wallet.getAccountPublicKey({
69+
account,
70+
});
71+
const accountAddress = publicKey.content.publicKey;
72+
let newName = `account-${accountAddress.slice(0, 4)}`;
73+
try {
74+
const MAX_ATTEMPTS = 5;
75+
let attempts = 0;
76+
while (existingNames.has(newName) && attempts < MAX_ATTEMPTS) {
77+
const randomString = `-${Math.floor(Math.random() * 100000)
78+
.toString()
79+
.padStart(5, "0")}`;
80+
newName = `${newName}${randomString}`;
81+
attempts++;
82+
}
83+
84+
if (attempts === MAX_ATTEMPTS && existingNames.has(newName)) {
85+
const errorMsg =
86+
"Could not generate unique account name after maximum attempts";
87+
log.error(errorMsg);
88+
throw new Error(errorMsg);
89+
}
90+
91+
existingNames.add(newName); // Add the new name to the set
92+
await rpcClient.wallet.renameAccount({
93+
account,
94+
newName,
95+
});
96+
} catch (error) {
97+
log.error(`Failed to rename account ${accountAddress}: ${error}`);
98+
}
99+
}
100+
}
101+
49102
async getInitialState(): Promise<InitialState> {
50103
const ironfish = await this.getIronfish();
51104

@@ -62,6 +115,9 @@ export class Manager {
62115

63116
const accountsResponse = await rpcClient.wallet.getAccounts();
64117

118+
// Pass accountsResponse to handleUnnamedAccounts
119+
await this.handleUnnamedAccounts(rpcClient, accountsResponse);
120+
65121
if (accountsResponse.content.accounts.length === 0) {
66122
return "onboarding";
67123
}

0 commit comments

Comments
 (0)