11 KiB
Web Crypto API to Blockchain Integration
This document describes the implementation of linking Web Crypto API (ECDSA P-256) accounts with Ethereum-compatible wallets (MetaMask, Gnosis Safe) to enable blockchain transaction execution.
Overview
The integration uses a minimal proxy contract pattern where:
- Each user deploys a lightweight proxy contract that stores their Web Crypto P-256 public key
- Users sign transaction authorization messages with their Web Crypto API private key (P-256)
- The proxy contract verifies the P-256 signature and executes the transaction
- Transactions can be submitted either:
- Through wallet (MetaMask/Gnosis Safe) - User pays gas fees
- Through relayer (Gasless) - Relayer service pays gas fees on behalf of users
Architecture
Core Components
-
Web Crypto API Signing (
src/lib/auth/cryptoBlockchain.ts)- EIP-712 structured data signing
- Transaction authorization message creation
- Signature formatting for blockchain
-
Ethereum Integration (
src/lib/blockchain/ethereum.ts)- Wallet connection (MetaMask, etc.)
- Transaction building and submission
- Chain management
-
Account Linking (
src/lib/auth/blockchainLinking.ts)- Links Web Crypto accounts with Ethereum addresses
- Stores linked account mappings
- Verifies ownership of both keys
-
Wallet Integration (
src/lib/blockchain/walletIntegration.ts)- Proxy contract deployment
- Public key coordinate extraction
- Factory contract interaction
-
Relayer Service (
src/lib/blockchain/relayer.ts&worker/blockchainRelayer.ts)- Gasless transaction submission
- Relayer configuration management
- Cloudflare Worker relayer implementation
- Signature verification before submission
-
Smart Contracts (
contracts/)WebCryptoProxy.sol- Minimal proxy contract for each userWebCryptoProxyFactory.sol- Factory for deploying proxies
-
UI Components
BlockchainLink.tsx- Link Web Crypto account with walletWalletStatus.tsx- Display connection statusTransactionBuilder.tsx- Build and authorize transactions (with gasless option)
-
Context (
src/context/BlockchainContext.tsx)- React context for blockchain state management
- Wallet connection state
- Linked account management
Technical Details
Challenge: P-256 vs secp256k1
- Web Crypto API: Uses ECDSA P-256 (NIST curve)
- Ethereum: Uses secp256k1 (different curve)
- Solution: Proxy contract verifies P-256 signatures on-chain
Transaction Flow
Standard Flow (User Pays Gas)
- User initiates transaction in the application
- Application builds EIP-712 structured authorization message
- Web Crypto API signs message with P-256 private key
- Application constructs proxy contract call with signature
- MetaMask/Gnosis Safe prompts user to submit transaction
- Wallet submits transaction to proxy contract
- Proxy contract verifies P-256 signature
- If valid, proxy contract executes the transaction
- User pays gas fees
Gasless Flow (Relayer Pays Gas)
- User initiates transaction in the application
- Application builds EIP-712 structured authorization message
- Web Crypto API signs message with P-256 private key
- User selects "Use gasless transaction" option
- Application submits signed transaction to relayer service
- Relayer verifies signature and transaction validity
- Relayer submits transaction to proxy contract (pays gas)
- Proxy contract verifies P-256 signature
- If valid, proxy contract executes the transaction
- User pays no gas fees
EIP-712 Message Format
{
types: {
EIP712Domain: [...],
Transaction: [
{ name: 'to', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'data', type: 'bytes' },
{ name: 'nonce', type: 'uint256' },
{ name: 'deadline', type: 'uint256' }
]
},
domain: {
name: 'WebCryptoProxy',
version: '1',
chainId: number,
verifyingContract: string
},
message: {
to: string,
value: string,
data: string,
nonce: number,
deadline: number
}
}
Proxy Contract Structure
The minimal proxy contract (WebCryptoProxy.sol):
- Stores P-256 public key (X and Y coordinates)
- Verifies P-256 signatures
- Executes transactions when signature is valid
- Implements replay protection via nonces
- Enforces transaction deadlines
Note: The P-256 signature verification in the contract is currently a placeholder. You'll need to implement or import a P-256 verification library. Options include:
- Use a precompile (if available on your chain)
- Import a P-256 verification library (e.g., from OpenZeppelin)
- Use an external verification contract
Setup
Dependencies
npm install viem @noble/curves
Smart Contract Deployment
- Deploy
WebCryptoProxyFactory.solto your target chain - Update factory address in
walletIntegration.ts - Users deploy their proxy contracts via the factory
Integration
- Wrap your app with
BlockchainProvider:
import { BlockchainProvider } from './context/BlockchainContext';
function App() {
return (
<BlockchainProvider>
{/* Your app */}
</BlockchainProvider>
);
}
- Use the blockchain context:
import { useBlockchain } from './context/BlockchainContext';
function MyComponent() {
const { wallet, connect, linkWebCryptoAccount } = useBlockchain();
// ...
}
Usage
Linking Accounts
- User logs in with Web Crypto API
- User connects their Ethereum wallet (MetaMask, etc.)
- User links accounts via
BlockchainLinkcomponent - System stores the mapping between Web Crypto and Ethereum accounts
Building Transactions
Standard Transaction (User Pays Gas)
- User fills out transaction details in
TransactionBuilder - Application creates EIP-712 authorization message
- Web Crypto API signs the message
- Application builds proxy contract call
- Wallet prompts user to submit transaction
- Transaction executes through proxy contract
- User pays gas fees
Gasless Transaction (Relayer Pays Gas)
- User fills out transaction details in
TransactionBuilder - User checks "Use gasless transaction" checkbox
- Application creates EIP-712 authorization message
- Web Crypto API signs the message
- Application submits to relayer service
- Relayer verifies and submits transaction
- Transaction executes through proxy contract
- Relayer pays gas fees (user pays nothing)
Note: Gasless transactions require a relayer service to be deployed and configured. See Gasless Transactions Setup for details.
Gasless Transactions
The system supports gasless transactions through a relayer service. This allows users to execute blockchain transactions without paying gas fees.
How It Works
- User signs transaction with Web Crypto API
- Relayer receives signed transaction request
- Relayer verifies signature and transaction validity
- Relayer submits transaction to blockchain (pays gas)
- Transaction executes through proxy contract
Setup
See Gasless Transactions Setup for complete setup instructions, including:
- Deploying the relayer worker
- Configuring relayer URLs
- Funding the relayer wallet
- Security considerations
Usage
Users can enable gasless transactions by checking the "Use gasless transaction" checkbox in the TransactionBuilder component. The system automatically falls back to wallet-based transactions if the relayer is unavailable.
Security Considerations
- Private Key Storage: Web Crypto private keys should use secure storage (IndexedDB, Web Crypto API key storage)
- Signature Verification: P-256 verification must be properly implemented in the smart contract
- Replay Protection: Nonces prevent transaction replay attacks
- Deadline Enforcement: Transactions expire after deadline
- Gas Limits: Set reasonable gas limits for executed transactions
- Relayer Security: Relayer private key must be stored securely (Cloudflare Workers secrets)
- Relayer Rate Limiting: Implement rate limiting to prevent abuse of gasless transactions
- Relayer Monitoring: Monitor relayer wallet balance and transaction costs
Limitations & TODO
Current Limitations
- P-256 Verification: The smart contract's P-256 signature verification is not yet implemented
- Private Key Storage: Currently uses simplified storage - needs secure key management
- Nonce Management: Nonces are currently timestamp-based - should use contract state
- Proxy Deployment: Factory address needs to be configured per chain
TODO
- Implement P-256 signature verification in smart contract
- Add secure private key storage using Web Crypto API key storage
- Implement proper nonce management from contract state
- Add support for multiple chains
- Add transaction history tracking
- Add error handling and retry logic
- Add support for Gnosis Safe multi-sig wallets
- Add gas estimation and optimization
- Add transaction status monitoring
- Implement gasless transactions via relayer service
- Add relayer rate limiting and abuse prevention
- Implement paymaster contract integration (alternative to relayer)
- Add relayer health monitoring and automatic failover
File Structure
src/
├── lib/
│ ├── auth/
│ │ ├── cryptoBlockchain.ts # Blockchain signing utilities
│ │ └── blockchainLinking.ts # Account linking service
│ └── blockchain/
│ ├── ethereum.ts # Ethereum integration
│ ├── walletIntegration.ts # Wallet integration
│ ├── relayer.ts # Gasless transaction relayer client
│ └── index.ts # Exports
├── components/
│ ├── auth/
│ │ └── BlockchainLink.tsx # Link account UI
│ └── blockchain/
│ ├── WalletStatus.tsx # Status display
│ └── TransactionBuilder.tsx # Transaction builder (with gasless option)
├── context/
│ └── BlockchainContext.tsx # Blockchain state context
worker/
└── blockchainRelayer.ts # Cloudflare Worker relayer service
contracts/
├── WebCryptoProxy.sol # Minimal proxy contract
└── WebCryptoProxyFactory.sol # Factory contract
Related Documentation
- Gasless Transactions Setup - Complete guide for setting up and using gasless transactions
- Blockchain Implementation Summary - Implementation details and status
References
- Web Crypto API
- EIP-712: Typed Structured Data Hashing and Signing
- Viem Documentation
- Ethereum Cryptography
- ERC-4337: Account Abstraction - Alternative approach for gasless transactions