- Fix all TypeScript compilation errors (40+ fixes) - Add missing type definitions (TransactionRequest, SafeInfo) - Fix TransactionRequestStatus vs TransactionStatus confusion - Fix import paths and provider type issues - Fix test file errors and mock providers - Implement comprehensive security features - AES-GCM encryption with PBKDF2 key derivation - Input validation and sanitization - Rate limiting and nonce management - Replay attack prevention - Access control and authorization - Add comprehensive test suite - Integration tests for transaction flow - Security validation tests - Wallet management tests - Encryption and rate limiter tests - E2E tests with Playwright - Add extensive documentation - 12 numbered guides (setup, development, API, security, etc.) - Security documentation and audit reports - Code review and testing reports - Project organization documentation - Update dependencies - Update axios to latest version (security fix) - Update React types to v18 - Fix peer dependency warnings - Add development tooling - CI/CD workflows (GitHub Actions) - Pre-commit hooks (Husky) - Linting and formatting (Prettier, ESLint) - Security audit workflow - Performance benchmarking - Reorganize project structure - Move reports to docs/reports/ - Clean up root directory - Organize documentation - Add new features - Smart wallet management (Gnosis Safe, ERC4337) - Transaction execution and approval workflows - Balance management and token support - Error boundary and monitoring (Sentry) - Fix WalletConnect configuration - Handle missing projectId gracefully - Add environment variable template
12 KiB
API Reference
Complete API documentation for the Impersonator Smart Wallet system.
Table of Contents
Context APIs
SmartWalletContext
Manages smart wallet configuration and state.
Hook
const {
smartWallets,
activeWallet,
balance,
isLoadingBalance,
provider,
connectToWallet,
createWallet,
deleteWallet,
addOwner,
removeOwner,
updateThreshold,
refreshBalance,
setProvider,
} = useSmartWallet();
Methods
connectToWallet(address, networkId, type)
Connect to an existing smart wallet.
Parameters:
address: string- Wallet addressnetworkId: number- Network IDtype: SmartWalletType- Wallet type (GNOSIS_SAFE | ERC4337)
Returns: Promise<SmartWalletConfig | null>
Example:
const wallet = await connectToWallet(
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
1,
SmartWalletType.GNOSIS_SAFE
);
createWallet(config)
Create a new wallet configuration.
Parameters:
config: { type, address, networkId, owners, threshold }
Returns: Promise<SmartWalletConfig>
addOwner(walletId, owner, callerAddress?)
Add an owner to a wallet.
Parameters:
walletId: string- Wallet IDowner: OwnerInfo- Owner informationcallerAddress?: string- Address of caller (for authorization)
Returns: Promise<void>
removeOwner(walletId, ownerAddress, callerAddress?)
Remove an owner from a wallet.
Parameters:
walletId: string- Wallet IDownerAddress: string- Owner address to removecallerAddress?: string- Address of caller (for authorization)
Returns: Promise<void>
updateThreshold(walletId, threshold, callerAddress?)
Update the threshold for a wallet.
Parameters:
walletId: string- Wallet IDthreshold: number- New thresholdcallerAddress?: string- Address of caller (for authorization)
Returns: Promise<void>
TransactionContext
Manages transaction lifecycle and approvals.
Hook
const {
transactions,
pendingTransactions,
createTransaction,
approveTransaction,
rejectTransaction,
executeTransaction,
estimateGas,
defaultExecutionMethod,
setDefaultExecutionMethod,
} = useTransaction();
Methods
createTransaction(tx)
Create a new transaction request.
Parameters:
tx: Omit<TransactionRequest, "id" | "status" | "createdAt">
Returns: Promise<TransactionRequest>
Example:
const tx = await createTransaction({
from: "0x...",
to: "0x...",
value: "1000000000000000000",
data: "0x",
method: TransactionExecutionMethod.DIRECT_ONCHAIN,
});
approveTransaction(transactionId, approver)
Approve a transaction.
Parameters:
transactionId: string- Transaction IDapprover: string- Approver address
Returns: Promise<void>
executeTransaction(transactionId)
Execute an approved transaction.
Parameters:
transactionId: string- Transaction ID
Returns: Promise<string | null> - Transaction hash
estimateGas(tx)
Estimate gas for a transaction.
Parameters:
tx: Partial<TransactionRequest>
Returns: Promise<GasEstimate | null>
SafeInjectContext
Manages iframe communication and Safe App SDK integration.
Hook
const {
address,
appUrl,
rpcUrl,
provider,
latestTransaction,
setAddress,
setAppUrl,
setRpcUrl,
sendMessageToIFrame,
iframeRef,
} = useSafeInject();
Security Utilities
Address Validation
validateAddress(address)
Validates an Ethereum address with checksum verification.
Parameters:
address: string- Address to validate
Returns:
{
valid: boolean;
error?: string;
checksummed?: string;
}
Example:
const result = validateAddress("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb");
if (result.valid) {
const checksummed = result.checksummed!;
}
isContractAddress(address, provider)
Checks if an address is a contract.
Parameters:
address: string- Address to checkprovider: Provider- Ethereum provider
Returns: Promise<boolean>
Transaction Validation
validateTransactionRequest(tx)
Validates a complete transaction request.
Parameters:
tx: { from?, to?, value?, data? }
Returns:
{
valid: boolean;
errors: string[];
}
validateTransactionData(data)
Validates transaction data field.
Parameters:
data: string- Transaction data (hex string)
Returns:
{
valid: boolean;
error?: string;
}
validateTransactionValue(value)
Validates transaction value.
Parameters:
value: string- Transaction value (hex string)
Returns:
{
valid: boolean;
error?: string;
parsed?: BigNumber;
}
validateGasLimit(gasLimit, maxGas?)
Validates gas limit.
Parameters:
gasLimit: string- Gas limitmaxGas?: string- Maximum gas (default: 10M)
Returns:
{
valid: boolean;
error?: string;
}
Network Validation
validateNetworkId(networkId)
Validates network ID.
Parameters:
networkId: number- Network ID
Returns:
{
valid: boolean;
error?: string;
}
Rate Limiting
RateLimiter
Rate limiter class for preventing DoS attacks.
Constructor:
new RateLimiter(maxRequests?, windowMs?)
Parameters:
maxRequests?: number- Max requests per window (default: 10)windowMs?: number- Time window in ms (default: 60000)
Methods:
checkLimit(key: string): boolean- Check if request is allowedreset(key: string): void- Reset limit for key
Example:
const limiter = new RateLimiter(10, 60000);
if (limiter.checkLimit(userAddress)) {
// Process request
}
Nonce Management
NonceManager
Manages transaction nonces to prevent conflicts.
Constructor:
new NonceManager(provider: Provider)
Methods:
getNextNonce(address: string): Promise<number>- Get next noncerefreshNonce(address: string): Promise<number>- Refresh from chain
Example:
const nonceManager = new NonceManager(provider);
const nonce = await nonceManager.getNextNonce(address);
Encryption Utilities
SecureStorage
Secure storage wrapper with encryption.
Constructor:
new SecureStorage()
Methods:
setItem(key: string, value: string): Promise<void>- Store encrypted valuegetItem(key: string): Promise<string | null>- Retrieve and decrypt valueremoveItem(key: string): void- Remove item
Example:
const storage = new SecureStorage();
await storage.setItem("wallets", JSON.stringify(wallets));
const data = await storage.getItem("wallets");
Encryption Functions
encryptData(data, key)
Encrypt data using AES-GCM.
Parameters:
data: string- Data to encryptkey: string- Encryption key
Returns: Promise<string> - Encrypted data (base64)
decryptData(encrypted, key)
Decrypt data.
Parameters:
encrypted: string- Encrypted data (base64)key: string- Encryption key
Returns: Promise<string> - Decrypted data
generateEncryptionKey()
Generate encryption key from session.
Returns: string - Encryption key
Helper Functions
Gnosis Safe Helpers
getSafeInfo(safeAddress, provider)
Get Safe contract information.
Parameters:
safeAddress: string- Safe addressprovider: Provider- Ethereum provider
Returns: Promise<SafeInfo | null>
connectToSafe(safeAddress, networkId, provider)
Connect to an existing Safe.
Parameters:
safeAddress: string- Safe addressnetworkId: number- Network IDprovider: Provider- Ethereum provider
Returns: Promise<SmartWalletConfig | null>
deploySafe(owners, threshold, provider, signer)
Deploy a new Safe.
Parameters:
owners: string[]- Owner addressesthreshold: number- Thresholdprovider: Provider- Ethereum providersigner: Signer- Signer for deployment
Returns: Promise<string | null> - Deployed Safe address
Transaction Execution
executeDirectTransaction(tx, provider, signer)
Execute transaction directly on-chain.
Parameters:
tx: TransactionRequest- Transaction requestprovider: Provider- Ethereum providersigner: Signer- Transaction signer
Returns: Promise<string> - Transaction hash
executeRelayerTransaction(tx, relayerUrl, apiKey?)
Execute transaction via relayer.
Parameters:
tx: TransactionRequest- Transaction requestrelayerUrl: string- Relayer URLapiKey?: string- Optional API key
Returns: Promise<string> - Transaction hash
simulateTransaction(tx, provider, from)
Simulate transaction execution.
Parameters:
tx: TransactionRequest- Transaction requestprovider: Provider- Ethereum providerfrom: string- From address
Returns:
Promise<{
success: boolean;
gasUsed: string;
error?: string;
}>
Balance Helpers
getNativeBalance(address, provider)
Get native token balance.
Parameters:
address: string- Wallet addressprovider: Provider- Ethereum provider
Returns: Promise<string> - Balance (wei)
getTokenBalance(tokenAddress, walletAddress, provider)
Get ERC20 token balance.
Parameters:
tokenAddress: string- Token contract addresswalletAddress: string- Wallet addressprovider: Provider- Ethereum provider
Returns: Promise<TokenBalance | null>
getWalletBalance(address, provider, tokens?)
Get complete wallet balance.
Parameters:
address: string- Wallet addressprovider: Provider- Ethereum providertokens?: string[]- Optional token addresses
Returns: Promise<WalletBalance>
Monitoring Service
Monitoring
Centralized logging and error tracking service.
Methods:
debug(message, context?)- Log debug messageinfo(message, context?)- Log info messagewarn(message, context?)- Log warningerror(message, error?, context?)- Log errortrackSecurityEvent(event, details)- Track security eventtrackRateLimit(key)- Track rate limit hittrackTransaction(event, txId, details?)- Track transaction event
Example:
import { monitoring } from "@/utils/monitoring";
monitoring.info("Transaction created", { txId: "0x..." });
monitoring.error("Transaction failed", error, { txId: "0x..." });
Constants
Security Constants
SECURITY = {
DEFAULT_RATE_LIMIT_REQUESTS: 10,
DEFAULT_RATE_LIMIT_WINDOW_MS: 60000,
MESSAGE_REPLAY_WINDOW_MS: 1000,
TRANSACTION_EXPIRATION_MS: 3600000,
MAX_TRANSACTION_DATA_LENGTH: 10000,
MAX_TRANSACTION_VALUE_ETH: 1000000,
MIN_GAS_LIMIT: 21000,
MAX_GAS_LIMIT: 10000000,
// ... more constants
}
Network Constants
NETWORKS = {
SUPPORTED_NETWORK_IDS: [1, 5, 137, ...],
MAINNET: 1,
POLYGON: 137,
// ... more networks
}
Storage Keys
STORAGE_KEYS = {
SMART_WALLETS: "impersonator_smart_wallets",
ACTIVE_WALLET: "impersonator_active_wallet",
TRANSACTIONS: "impersonator_transactions",
// ... more keys
}
Type Definitions
See types.ts for complete type definitions including:
SmartWalletConfigTransactionRequestSafeInfoWalletBalanceTransactionStatus- And more...