p-sdk-wallet
Version:
A comprehensive wallet SDK for React Native (pwc), supporting multi-chain and multi-account features.
494 lines (493 loc) • 21.9 kB
TypeScript
import { type EncryptedData } from './crypto/EncryptionService';
import { type ChainId } from './config/chains';
import { Recipient, MultiTransferResult } from './types/multiTransfer';
import { NFTDetailExtended, NFTOptions } from './types/nft';
export interface Account {
address: string;
type: 'HD' | 'Simple' | 'Solana';
name: string;
}
export interface TransactionResponse {
hash: string;
from: string;
to: string;
blockNumber?: number;
}
export interface Token {
address: string;
name: string;
symbol: string;
decimals: number;
totalSupply?: string;
}
export interface VaultConfig {
rpcUrls?: Record<string, string>;
explorerUrls?: Record<string, string>;
gasConfig?: Partial<typeof import('./config/gas').GAS_CONFIG>;
networkGasConfig?: Record<string, Partial<{
maxFeePerGas: bigint;
maxPriorityFeePerGas: bigint;
}>>;
defaultChainId?: ChainId;
supportedChains?: ChainId[];
features?: {
enableEIP1559?: boolean;
enableBatchProcessing?: boolean;
enableGasEstimation?: boolean;
};
}
export declare class Vault {
private keyrings;
private chainId;
private config?;
private static exportAttempts;
private static readonly MAX_EXPORT_ATTEMPTS;
private static readonly EXPORT_COOLDOWN_MS;
/**
* Creates a new Vault instance with the specified keyrings.
* @param keyrings - Array of keyrings to initialize the vault with. Defaults to empty array.
*/
private constructor();
/**
* Creates a new Vault with a fresh mnemonic.
* @param password - The password used to encrypt the vault data
* @param chainType - The type of blockchain to support ('evm' for Ethereum-compatible chains or 'solana' for Solana). Defaults to 'evm'
* @returns Promise resolving to an object containing the created vault instance and its encrypted data
* @throws Error if mnemonic generation or keyring initialization fails
*/
static createNew(password: string, chainType?: 'evm' | 'solana', config?: VaultConfig): Promise<{
vault: Vault;
encryptedVault: EncryptedData;
}>;
/**
* Creates a new Vault from an existing mnemonic phrase.
* @param mnemonic - The existing mnemonic phrase (12, 15, 18, 21, or 24 words)
* @param password - The password used to encrypt the vault data
* @param chainType - The type of blockchain to support ('evm' for Ethereum-compatible chains or 'solana' for Solana). Defaults to 'evm'
* @returns Promise resolving to an object containing the created vault instance and its encrypted data
* @throws Error if mnemonic is invalid or keyring initialization fails
*/
static createFromMnemonic(mnemonic: string, password: string, chainType?: 'evm' | 'solana', config?: VaultConfig): Promise<{
vault: Vault;
encryptedVault: EncryptedData;
}>;
/**
* Loads a Vault from its encrypted state using the provided password.
* @param password - The password used to decrypt the vault data
* @param encryptedVault - The encrypted vault data to decrypt and load
* @returns Promise resolving to the loaded Vault instance
* @throws Error if password is incorrect or decryption fails
*/
static load(password: string, encryptedVault: EncryptedData, config?: VaultConfig): Promise<Vault>;
/**
* Adds a new account derived from the HD keyring using BIP-44 derivation.
* @returns Promise resolving to the newly created account information
* @throws Error if no HD keyring is available in the vault
*/
addNewHDAccount(): Promise<Account>;
/**
* Adds a new Solana account derived from the Solana keyring.
* @returns Promise resolving to the newly created Solana account information
* @throws Error if no Solana keyring is available in the vault
*/
addNewSolanaAccount(): Promise<Account>;
/**
* Imports an account from a private key and adds it to the vault.
* @param privateKey - The private key to import (hex string without '0x' prefix for EVM, base58 for Solana)
* @returns Promise resolving to the imported account information
* @throws Error if the private key is already managed by an HD keyring or if import fails
*/
importAccount(privateKey: string): Promise<Account>;
/**
* Returns a list of all accounts managed by the vault across all keyrings.
* @returns Array of Account objects representing all accounts in the vault
*/
getAccounts(): Account[];
/**
* Exports the mnemonic phrase from the vault for backup purposes.
* Requires password verification and includes rate limiting for security.
* @param password - The vault password to verify before exporting
* @returns Promise resolving to the mnemonic phrase as a string
* @throws Error if password is incorrect, no mnemonic exists, or rate limit exceeded
*/
exportMnemonic(password: string): Promise<string>;
/**
* Gets a unique identifier for this vault used for rate limiting purposes.
* @returns String identifier based on the first account address
*/
private getVaultId;
/**
* Encrypts the entire vault's state using the provided password.
* @param password - The password to use for encryption
* @returns Promise resolving to the encrypted vault data
* @throws Error if encryption fails
*/
encrypt(password: string): Promise<EncryptedData>;
/**
* Retrieves the private key for a specific address from the appropriate keyring.
* @param address - The account address to get the private key for
* @returns Promise resolving to the private key as a string
* @throws Error if the address is not found in any keyring
*/
getPrivateKeyFor(address: string): Promise<string>;
/**
* Gets the token balance for a specific account and token contract.
* @param accountAddress - The account address to check balance for
* @param tokenAddress - The contract address of the token
* @param chainId - The ID of the blockchain where the token is deployed
* @returns Promise resolving to the token balance as a bigint
* @throws Error if account or token not found, or chain service fails
*/
getTokenBalance(accountAddress: string, tokenAddress: string, chainId: ChainId): Promise<bigint>;
/**
* Sends tokens from a specific account to another address.
* @param fromAddress - The sender's account address
* @param to - The recipient's address
* @param amount - The amount of tokens to send as a string
* @param tokenAddress - The contract address of the token to send
* @param chainId - The ID of the blockchain for the transaction
* @returns Promise resolving to the transaction response with hash and details
* @throws Error if insufficient balance, invalid addresses, or transaction fails
*/
sendToken(fromAddress: string, to: string, amount: string, tokenAddress: string, chainId: ChainId): Promise<TransactionResponse>;
/**
* Generates a vanity HD wallet with a specific address prefix.
* Uses default configuration from VANITY_WALLET_CONFIG for optimal settings.
* The prefix defaults to 'aaa' as configured in VANITY_WALLET_CONFIG.DEFAULT_PREFIX.
*
* @param password - The password to encrypt the generated vault
* @param onProgress - Optional callback function for progress updates (attempts count and current address)
* @returns Promise resolving to an object containing the generated vault, encrypted vault, number of attempts, and the found address
* @throws Error if generation fails or max attempts exceeded
*
* @example
* ```typescript
* // Simple usage - will use default prefix 'aaa'
* const result = await Vault.generateVanityHDWallet("mypassword");
*
* // With progress callback
* const result = await Vault.generateVanityHDWallet(
* "mypassword",
* (attempts, address) => console.log(`Attempt ${attempts}: ${address}`)
* );
* ```
*/
static generateVanityHDWallet(password: string, onProgress?: (attempts: number, currentAddress: string) => void): Promise<{
vault: Vault;
encryptedVault: EncryptedData;
attempts: number;
foundAddress: string;
}>;
/**
* Generates a vanity HD wallet optimized for mobile devices.
* Uses mobile-optimized settings for faster completion and better UX.
*
* @param password - The password to encrypt the generated vault
* @param onProgress - Optional callback function for progress updates (attempts count and current address)
* @param options - Optional configuration options for mobile optimization
* @returns Promise resolving to an object containing the generated vault, encrypted vault, number of attempts, and the found address
* @throws Error if generation fails, max attempts exceeded, or timeout reached
*
* @example
* ```typescript
* // Simple mobile-optimized usage
* const result = await Vault.generateVanityHDWalletMobile("mypassword");
*
* // With custom options
* const result = await Vault.generateVanityHDWalletMobile(
* "mypassword",
* (attempts, address) => console.log(`Attempt ${attempts}: ${address}`),
* { prefix: 'ab', maxAttempts: 10000 }
* );
* ```
*/
static generateVanityHDWalletMobile(password: string, onProgress?: (attempts: number, currentAddress: string) => void, options?: {
prefix?: string;
maxAttempts?: number;
caseSensitive?: boolean;
timeout?: number;
}): Promise<{
vault: Vault;
encryptedVault: EncryptedData;
attempts: number;
foundAddress: string;
}>;
/**
* Ultra-optimized vanity wallet generation for maximum performance.
* Bypasses heavy HDKeyring initialization and uses direct cryptographic operations.
* Similar to web-based vanity generators for maximum speed.
*
* @param password - The password to encrypt the generated vault
* @param onProgress - Optional callback function for progress updates
* @param options - Configuration options for ultra-optimized generation
* @returns Promise resolving to generated vault data
*/
static generateVanityHDWalletUltra(password: string, onProgress?: (attempts: number, currentAddress: string) => void, options?: {
prefix?: string;
maxAttempts?: number;
caseSensitive?: boolean;
timeout?: number;
batchSize?: number;
}): Promise<{
vault: Vault;
encryptedVault: EncryptedData;
attempts: number;
foundAddress: string;
}>;
/**
* Transfers native tokens to multiple recipients in a single operation.
* Uses batch processing for optimal performance and provides progress tracking.
*
* @param fromAddress - The sender's account address
* @param recipients - Array of recipients with addresses and amounts
* @param chainId - The ID of the blockchain for the transaction
* @param onProgress - Optional callback for progress updates (completed, total, txHash)
* @returns Promise resolving to the multi-transfer result with success/failure details
* @throws Error if validation fails, insufficient balance, or transfer fails
*
* @example
* ```typescript
* const recipients = [
* { address: '0x123...', amount: '0.1' },
* { address: '0x456...', amount: '0.2' },
* { address: '0x789...', amount: '0.05' }
* ];
*
* const result = await vault.multiTransferNativeTokens(
* '0xmyAddress',
* recipients,
* '1', // Ethereum
* (completed, total, txHash) => console.log(`Completed ${completed}/${total}: ${txHash}`)
* );
*
* console.log(`Success: ${result.successfulCount}, Failed: ${result.failedCount}`);
* ```
*/
multiTransferNativeTokens(fromAddress: string, recipients: Recipient[], chainId: ChainId, onProgress?: (completed: number, total: number, txHash: string) => void): Promise<MultiTransferResult>;
/**
* Transfers ERC-20/SPL tokens to multiple recipients in a single operation.
* Uses batch processing for optimal performance and provides progress tracking.
*
* @param fromAddress - The sender's account address
* @param tokenAddress - The contract address of the token to send
* @param recipients - Array of recipients with addresses and amounts
* @param chainId - The ID of the blockchain for the transaction
* @param onProgress - Optional callback for progress updates (completed, total, txHash)
* @returns Promise resolving to the multi-transfer result with success/failure details
* @throws Error if validation fails, insufficient balance, or transfer fails
*
* @example
* ```typescript
* const recipients = [
* { address: '0x1111...', amount: '100' },
* { address: '0x456...', amount: '200' },
* { address: '0x789...', amount: '50' }
* ];
*
* const result = await vault.multiTransferTokens(
* '0xmyAddress',
* '0xtokenContract',
* recipients,
* '1', // Ethereum
* (completed, total, txHash) => console.log(`Completed ${completed}/${total}: ${txHash}`)
* );
*
* console.log(`Success: ${result.successfulCount}, Failed: ${result.failedCount}`);
* ```
*/
multiTransferTokens(fromAddress: string, tokenAddress: string, recipients: Recipient[], chainId: ChainId, onProgress?: (completed: number, total: number, txHash: string) => void): Promise<MultiTransferResult>;
/**
* Estimates gas cost for a native token transfer.
* Useful for displaying gas costs to users before sending transactions.
*
* @param fromAddress - The sender's account address
* @param to - The recipient's address
* @param amount - The amount to send as a string (e.g., "0.1")
* @param chainId - The ID of the blockchain for the transaction
* @returns Promise resolving to the estimated gas cost as a bigint
* @throws Error if estimation fails or addresses are invalid
*
* @example
* ```typescript
* const gasEstimate = await vault.estimateNativeTransferGas(
* '0x1234...',
* '0x5678...',
* '0.01', // 0.01 ETH
* '1' // Ethereum
* );
*
* console.log('Estimated gas:', gasEstimate.toString());
* console.log('Estimated cost (in ETH):', ethers.formatEther(gasEstimate * gasPrice));
* ```
*/
estimateNativeTransferGas(fromAddress: string, to: string, amount: string, chainId: ChainId): Promise<bigint>;
/**
* Estimates gas cost for an ERC-20/SPL token transfer.
* Useful for displaying gas costs to users before sending token transactions.
*
* @param fromAddress - The sender's account address
* @param tokenAddress - The contract address of the token
* @param to - The recipient's address
* @param amount - The amount of tokens to send as a string
* @param chainId - The ID of the blockchain for the transaction
* @returns Promise resolving to the estimated gas cost as a bigint
* @throws Error if estimation fails, token contract is invalid, or addresses are invalid
*
* @example
* ```typescript
* const gasEstimate = await vault.estimateTokenTransferGas(
* '0x1234...',
* '0xA0b86a33E6441b8c4C8C8C8C8C8C8C8C8C8C8C8C', // USDC
* '0x5678...',
* '100', // 100 USDC
* '1' // Ethereum
* );
*
* console.log('Estimated gas for token transfer:', gasEstimate.toString());
* ```
*/
estimateTokenTransferGas(fromAddress: string, tokenAddress: string, to: string, amount: string, chainId: ChainId): Promise<bigint>;
/**
* Estimates gas cost for multi-transfer operations.
* Useful for displaying total gas costs before executing batch transfers.
*
* @param fromAddress - The sender's account address
* @param recipients - Array of recipients with addresses and amounts
* @param chainId - The ID of the blockchain for the transaction
* @param isNative - Whether estimating for native tokens (true) or ERC-20/SPL tokens (false)
* @param tokenAddress - Token contract address (required if isNative is false)
* @returns Promise resolving to the estimated total gas cost as a bigint
* @throws Error if estimation fails or parameters are invalid
*
* @example
* ```typescript
* const recipients = [
* { address: '0x1111...', amount: '0.01' },
* { address: '0x2222...', amount: '0.02' },
* { address: '0x3333...', amount: '0.005' }
* ];
*
* // Estimate for native token multi-transfer
* const nativeGasEstimate = await vault.estimateMultiTransferGas(
* '0x1234...',
* recipients,
* '1', // Ethereum
* true // Native tokens
* );
*
* // Estimate for token multi-transfer
* const tokenGasEstimate = await vault.estimateMultiTransferGas(
* '0x1234...',
* recipients,
* '1', // Ethereum
* false, // ERC-20 tokens
* '0xA0b86a33E6441b8c4C8C8C8C8C8C8C8C8C8C8C8C' // USDC
* );
*
* console.log('Native multi-transfer gas:', nativeGasEstimate.toString());
* console.log('Token multi-transfer gas:', tokenGasEstimate.toString());
* ```
*/
estimateMultiTransferGas(fromAddress: string, recipients: Recipient[], chainId: ChainId, isNative?: boolean, tokenAddress?: string): Promise<bigint>;
/**
* Gets all NFTs owned by an address across multiple collections.
* Pure blockchain implementation - reads from smart contracts.
*
* @param address - Wallet address to check
* @param contractAddresses - Array of NFT contract addresses to check
* @param options - NFT query options
* @returns Promise resolving to array of NFT details
* @throws Error if any contract query fails
*
* @example
* ```typescript
* const collections = [
* '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D', // BAYC
* '0x60E4d786628Fea6478F785A6d7e704777c86a7c6' // MAYC
* ];
*
* const nfts = await vault.getOwnedNFTs(
* '0x1234...', // Wallet address
* collections,
* { includeMetadata: true }
* );
*
* console.log(`Found ${nfts.length} owned NFTs`);
* nfts.forEach(nft => {
* console.log(`${nft.name} from ${nft.contractAddress}`);
* });
* ```
*/
getOwnedNFTs(address: string, contractAddresses: string[], options?: NFTOptions): Promise<NFTDetailExtended[]>;
/**
* Transfers an NFT from one address to another.
* Pure blockchain implementation using smart contract calls.
*
* @param fromAddress - Sender's address
* @param toAddress - Recipient's address
* @param contractAddress - NFT contract address
* @param tokenId - Token ID to transfer
* @returns Promise resolving to transaction response
* @throws Error if transfer fails, insufficient permissions, or NFT not owned
*
* @example
* ```typescript
* const result = await vault.transferNFT(
* '0x1234...', // From address
* '0x5678...', // To address
* '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D', // BAYC contract
* '1234' // Token ID
* );
*
* console.log('Transfer successful:', result.hash);
* ```
*/
transferNFT(fromAddress: string, toAddress: string, contractAddress: string, tokenId: string): Promise<TransactionResponse>;
/**
* Imports wallet from QR code data.
* @param qrString - QR code string to parse
* @param password - Password to decrypt the mnemonic
* @returns Promise resolving to imported account information
* @throws Error if QR data is invalid or import fails
*
* @example
* ```typescript
* // Import wallet from scanned QR code
* const accounts = await vault.importFromQR(qrString, 'my-password');
* console.log('Imported accounts:', accounts);
* ```
*/
importFromQR(qrString: string, password: string): Promise<Account[]>;
/**
* Processes transaction from QR code data.
* @param qrString - QR code string to parse
* @param fromAddress - Sender's address
* @returns Promise resolving to transaction response
* @throws Error if QR data is invalid or transaction fails
*
* @example
* ```typescript
* // Process transaction from scanned QR code
* const result = await vault.processTransactionFromQR(qrString, '0x1234...');
* console.log('Transaction hash:', result.hash);
* ```
*/
processTransactionFromQR(qrString: string, fromAddress: string): Promise<TransactionResponse>;
/**
* Sends native tokens (ETH, BNB, MATIC, etc.) from a specific account to another address.
* @param fromAddress - The sender's account address
* @param to - The recipient's address
* @param amount - The amount to send as a string (e.g., "0.1")
* @param chainId - The ID of the blockchain for the transaction
* @returns Promise resolving to the transaction response
* @throws Error if insufficient balance, invalid addresses, or transaction fails
*
* @example
* ```typescript
* // Send 0.1 ETH on Ethereum mainnet
* const tx = await vault.sendNativeToken(from, to, '0.1', '1');
* console.log('Transaction hash:', tx.hash);
* ```
*/
sendNativeToken(fromAddress: string, to: string, amount: string, chainId: ChainId): Promise<TransactionResponse>;
}