Create Wallet
Overview
Basic Wallet Creation
import { PrivateKey, HD, PublicKey } from '@bsv/sdk'
/**
* Basic Wallet Creator
*
* Simple wallet creation with key generation and address derivation
*/
class BasicWallet {
private privateKey: PrivateKey
private publicKey: PublicKey
private address: string
constructor(privateKey?: PrivateKey) {
if (privateKey) {
this.privateKey = privateKey
} else {
// Generate new random private key
this.privateKey = PrivateKey.fromRandom()
}
this.publicKey = this.privateKey.toPublicKey()
this.address = this.publicKey.toAddress()
}
/**
* Get wallet information
*/
getInfo(): WalletInfo {
return {
address: this.address,
publicKey: this.publicKey.toHex(),
privateKeyWIF: this.privateKey.toWif(),
privateKeyHex: this.privateKey.toHex()
}
}
/**
* Export wallet to JSON
*/
exportToJSON(): string {
return JSON.stringify({
address: this.address,
publicKey: this.publicKey.toHex(),
privateKey: this.privateKey.toWif()
}, null, 2)
}
/**
* Get private key for signing
*/
getPrivateKey(): PrivateKey {
return this.privateKey
}
/**
* Get address for receiving payments
*/
getAddress(): string {
return this.address
}
/**
* Create wallet from WIF
*/
static fromWIF(wif: string): BasicWallet {
try {
const privateKey = PrivateKey.fromWif(wif)
return new BasicWallet(privateKey)
} catch (error) {
throw new Error(`Failed to import wallet from WIF: ${error.message}`)
}
}
/**
* Create wallet from hex
*/
static fromHex(hex: string): BasicWallet {
try {
const privateKey = PrivateKey.fromHex(hex)
return new BasicWallet(privateKey)
} catch (error) {
throw new Error(`Failed to import wallet from hex: ${error.message}`)
}
}
/**
* Verify wallet integrity
*/
verify(): boolean {
try {
// Verify public key derives from private key
const derivedPublicKey = this.privateKey.toPublicKey()
const derivedAddress = derivedPublicKey.toAddress()
return (
derivedPublicKey.toHex() === this.publicKey.toHex() &&
derivedAddress === this.address
)
} catch (error) {
console.error('Wallet verification failed:', error.message)
return false
}
}
}
interface WalletInfo {
address: string
publicKey: string
privateKeyWIF: string
privateKeyHex: string
}
/**
* Usage Example
*/
async function basicWalletExample() {
console.log('=== Creating New Wallet ===')
// Create new wallet
const wallet = new BasicWallet()
const info = wallet.getInfo()
console.log('Address:', info.address)
console.log('Public Key:', info.publicKey)
console.log('Private Key (WIF):', info.privateKeyWIF)
// Verify wallet
const isValid = wallet.verify()
console.log('Wallet valid:', isValid)
// Export wallet
const json = wallet.exportToJSON()
console.log('Wallet JSON:', json)
// Import wallet from WIF
const importedWallet = BasicWallet.fromWIF(info.privateKeyWIF)
console.log('Imported address:', importedWallet.getAddress())
}HD Wallet with Mnemonic
Multi-Account Wallet Manager
Wallet Security and Encryption
Related Examples
See Also
Last updated
