import {
generateKeyPair,
getKeypair,
getCryptoKeyAccount,
createBaseAccountSDK
} from '@base-org/account';
class AccountManager {
private sdk: any;
constructor() {
this.sdk = createBaseAccountSDK({
appName: 'My App',
appLogoUrl: 'https://example.com/logo.png',
appChainIds: [8453], // Base mainnet
});
}
// Initialize account management
async initialize() {
const account = await this.getCurrentAccount();
if (!account) {
console.log('No account found, user needs to connect');
return null;
}
return account;
}
// Get current account or prompt connection
async getCurrentAccount() {
const cryptoAccount = await getCryptoKeyAccount();
return cryptoAccount?.account || null;
}
// Get or generate key pair for advanced operations
async getKeyPair() {
let keyPair = await getKeypair();
if (!keyPair) {
console.log('Generating new key pair...');
keyPair = await generateKeyPair();
}
return keyPair;
}
// Example: Use account for Sub Account creation
async createSubAccount() {
const account = await this.getCurrentAccount();
const keyPair = await this.getKeyPair();
if (!account || !keyPair) {
throw new Error('Account and key pair required');
}
// Use the SDK to create sub account
const subAccount = await this.sdk.subAccount.create({
type: 'create',
keys: [{
type: 'webauthn-p256',
publicKey: keyPair.publicKey,
}],
});
return subAccount;
}
// Get account address for transactions
getAccountAddress(): string | null {
// This would be called after initialization
const account = this.getCurrentAccount();
return account?.address || null;
}
}
// Usage
const accountManager = new AccountManager();
// Initialize and get account
const account = await accountManager.initialize();
if (account) {
console.log('User is connected:', account.address);
// Create sub account if needed
const subAccount = await accountManager.createSubAccount();
console.log('Sub account created:', subAccount.address);
} else {
console.log('User needs to connect their account');
}