Social recovery is a security mechanism for smart accounts, also known as smart contract wallets (SCWs), that replaces the single point of failure inherent in a seed phrase. Instead of relying on one private key, a user designates a group of trusted individuals or devices—called guardians—who can collectively approve a wallet recovery request. This model, pioneered by projects like Vitalik Buterin's blog post on social recovery and implemented by wallets such as Safe (formerly Gnosis Safe) and Argent, shifts security from personal key management to social consensus, significantly reducing the risk of permanent fund loss.
How to Implement Social Recovery for Smart Accounts
Introduction to Social Recovery for Smart Accounts
A technical guide to implementing social recovery, a user-centric alternative to seed phrases for securing smart contract wallets.
The core mechanism involves deploying a smart account with a module that enforces a recovery policy. A common implementation uses a multi-signature scheme where a predefined threshold (e.g., 3 out of 5) of guardians must sign a recovery transaction to authorize a change of the account's signing key. This transaction typically calls a function like setOwner(address newOwner) on the wallet contract. The guardians' addresses are stored on-chain, often within the recovery module itself, and their signatures are verified via ecrecover or a signature aggregation contract like EIP-4337's Aggregator.
To implement a basic social recovery module, you start by defining the guardian set and threshold in your smart account's constructor or initializer. The recovery function should then check that the caller is authorized and that a sufficient number of valid guardian signatures are provided. Here's a simplified Solidity snippet illustrating the logic:
solidityfunction recoverAddress(address newOwner, bytes[] calldata guardianSigs) external { require(guardianSigs.length >= recoveryThreshold, "Insufficient guardians"); bytes32 hash = keccak256(abi.encodePacked(newOwner, nonce++)); address[] memory recoveredGuardians = new address[](guardianSigs.length); for (uint i = 0; i < guardianSigs.length; i++) { recoveredGuardians[i] = hash.recover(guardianSigs[i]); require(isGuardian[recoveredGuardians[i]], "Invalid guardian"); } owner = newOwner; }
Best practices for production systems involve several critical considerations. Guardian selection should include a mix of hardware devices (like Ledger or Trezor), trusted contacts, and potentially a delay-enabled institutional service as a last resort. To prevent griefing or denial-of-service attacks, implement a recovery time-lock (e.g., a 48-hour delay) that allows the current owner to cancel a malicious recovery attempt. Furthermore, consider using EIP-1271 for signature validation to support smart contract guardians, and store guardian sets in a separate, upgradeable module to allow for management without wallet redeployment.
Integrating social recovery within the EIP-4337 Account Abstraction standard is the current frontier. Bundlers can include recovery operations in UserOperations, and Paymasters can sponsor the gas fees for guardians, making the process seamless. Emerging solutions like Safe{Core} Account Abstraction Kit and ZeroDev's kernel provide SDKs and templates that abstract this complexity. When designing your system, audit the recovery flow for centralization risks—if all guardians are stored on a single backend, you've recreated a custodial solution. The goal is a resilient, user-owned security layer that balances accessibility with robust, decentralized oversight.
Prerequisites
Before implementing social recovery for smart accounts, ensure your development environment and foundational knowledge are ready.
To follow this guide, you need a basic understanding of Ethereum account abstraction and ERC-4337 EntryPoint architecture. Familiarity with smart account providers like Safe{Wallet}, ZeroDev, or Biconomy is beneficial, as they often provide the underlying account contracts. You should have Node.js (v18+) and npm/yarn installed, and be comfortable using a testnet like Sepolia or Goerli. Essential tools include a code editor (VS Code recommended), the Hardhat or Foundry framework for local development, and a wallet like MetaMask for testing.
Social recovery is a custodial alternative where a user's assets are secured by a smart contract wallet, and access is managed by a set of trusted 'guardians'. Unlike a seed phrase, recovery is initiated through a transaction signed by a predefined majority of these guardians. You must decide on the recovery parameters: the guardian set (e.g., 3 out of 5 multisig, other smart accounts, or dedicated services like Web3Auth), a security period (timelock delay), and the logic for adding/removing guardians. These choices directly impact security and usability.
You will need testnet ETH to deploy contracts and pay gas. For the implementation, we'll use the Safe{Wallet} as our smart account example, as its modular design allows for custom guard modules. Ensure you have the @safe-global/safe-core-sdk and ethers.js v6 libraries installed. This guide assumes you have a deployed Safe account (version 1.4.1+) on a testnet. If not, you can create one using the Safe{Wallet} dashboard. All code examples will be in JavaScript/TypeScript interacting with these libraries.
Key Concepts for Social Recovery
Social recovery is a critical security mechanism for smart accounts, allowing users to regain access through a network of trusted guardians instead of a single private key. This guide covers the core concepts and implementation steps.
Recovery Flow & Timelocks
A secure recovery process prevents unauthorized account takeover. The standard flow involves initiating a recovery request, gathering guardian approvals, and executing the account migration after a security delay.
- Initiation: The user (or a designated executor) submits a recovery request, proposing a new entry point or owner for the smart account.
- Approval Period: Guardians review and sign the request. This period should allow the original owner to notice and cancel a malicious attempt.
- Security Timelock: A mandatory waiting period (e.g., 24-72 hours) begins after the threshold is met. This is the final window for the original owner to cancel the recovery, providing a crucial defense against compromised guardians.
Security Considerations & Risks
While powerful, social recovery introduces new attack vectors that must be mitigated.
- Guardian Collusion: The primary risk. A majority of compromised guardians can initiate recovery. Mitigate by choosing non-correlated guardians.
- Front-running Recovery: A malicious actor could front-run the execution of a legitimate recovery. Using a commit-reveal scheme or a singleton, non-replaceable recovery hash can prevent this.
- Denial-of-Service: Guardians going offline can make recovery impossible. Use institutional guardians with high uptime guarantees for critical slots.
- Social Engineering: Attackers may target guardians directly. Educate guardians and consider using hardware-based signers or smart contract guardians with their own security rules.
Social Recovery Design Patterns
A guide to implementing decentralized recovery mechanisms for smart contract wallets, moving beyond seed phrase vulnerabilities.
Social recovery is a security model for smart accounts that replaces the single point of failure of a private key or seed phrase with a network of trusted entities, called guardians. Instead of one user holding absolute control, a predefined policy dictates that a subset of these guardians (e.g., 3 out of 5) must collectively approve a recovery operation. This pattern, pioneered by projects like Vitalik Buterin's Ethereum wallet design and implemented in ERC-4337 account abstraction, fundamentally shifts security from something you have (a key) to who you know and trust. Guardians can be other smart accounts (like a hardware wallet), trusted friends' addresses, institutional services like Coinbase's Delegated Recovery, or decentralized protocols.
The core smart contract logic involves two primary functions: a recovery initiation and a confirmation execution. A standard implementation includes a recovery module with a mapping of approved guardians and a threshold. When recovery is triggered, a new pending recovery request is created with a proposed new owner address. Guardians then submit signatures or transactions to confirmRecovery. Once the confirmation count meets the threshold, any user can call executeRecovery to finalize the owner change. It's critical to implement a time-lock or delay period (e.g., 24-48 hours) between initiation and execution to allow guardians to veto a malicious recovery attempt. Security audits for these contracts must focus on signature replay protection, threshold logic correctness, and guardian management functions.
For developers, implementing social recovery starts with defining the guardian set. A flexible design allows guardians to be added or removed by the current owner, often with a security delay. The EIP-4337 EntryPoint enables bundlers to pay for these recovery operations, allowing gasless experiences for guardians. A practical code snippet for a minimal recovery module might store guardians in an array and use EIP-712 typed signatures for off-chain approvals. Here's a simplified structure:
soliditymapping(address => bool) public isGuardian; address[] public guardians; uint256 public threshold; RecoveryRequest public pendingRequest; function initiateRecovery(address _newOwner) external onlyOwner { pendingRequest = RecoveryRequest(_newOwner, block.timestamp); } function confirmRecovery(bytes memory signature) external { require(isGuardian[msg.sender], "Not a guardian"); // Verify EIP-712 signature for pendingRequest.newOwner confirmedBy[msg.sender] = true; }
Several design patterns have emerged beyond basic multi-sig. Time-locked recovery adds a mandatory waiting period, as seen in Safe{Wallet}'s modules. Gradual recovery uses increasing thresholds over time (e.g., 1/5 quickly for emergencies, 3/5 for full control). Decentralized guardian networks, like Ethereum Name Service (ENS)'s integration with Lit Protocol, use distributed key generation to avoid centralized guardian points of failure. When designing your system, consider the trade-offs: more guardians and higher thresholds increase security but reduce convenience and speed. For mainstream adoption, integrating with existing web2 identity providers (via Sign-In with Ethereum) as guardians can lower onboarding friction while maintaining crypto-native security.
Best practices for a production social recovery system include using audited, standard implementations like Safe{Wallet} modules or OpenZeppelin's Governor pattern for governance. Always allow users to simulate recovery in a test environment. Provide clear, transparent UIs that show guardian status, pending requests, and time-lock counters. Monitor for unusual recovery initiation patterns. Ultimately, social recovery is not just a technical feature but a user experience paradigm that makes self-custody accessible and resilient, paving the way for the next billion users in web3.
Implementing Guardian Selection and Management
A practical guide to designing and coding a guardian-based recovery system for smart contract accounts, focusing on security and user experience.
Social recovery is a critical feature for non-custodial smart accounts, allowing a user to regain access if they lose their primary private key. Instead of a single seed phrase, control is distributed among a set of trusted guardians. These guardians can be other EOAs (Externally Owned Accounts), smart contracts, or even institutional services. The core mechanism involves a multi-signature scheme where a predefined threshold of guardians must approve a recovery request to reset the account's ownership. This model shifts security from a single point of failure to a social and configurable trust graph.
Selecting the right guardians is the first and most important step. A balanced approach mitigates risk. Consider a mix of: - Personal devices: A mobile wallet and a hardware wallet held by the user. - Trusted individuals: Family members or close friends with some technical understanding. - Institutional services: Dedicated custody services like Safe{Wallet} Guardians or WalletConnect's Cloud Backup. For maximum security, avoid concentration risk; using five guardians with a threshold of three is more resilient than three guardians with a threshold of two. Each guardian should be stored as an address within the account's smart contract logic.
The implementation involves two main smart contract functions: one to initiate recovery and another to confirm it. Below is a simplified Solidity example based on the ERC-4337 standard structure, showing core state variables and the recovery initiation logic.
soliditycontract SocialRecoveryAccount { address public owner; address[] public guardians; uint256 public threshold; uint256 public recoveryCooldown = 2 days; RecoveryRequest public activeRequest; struct RecoveryRequest { address newOwner; uint256 approvals; uint256 initiateTime; mapping(address => bool) hasApproved; } function initiateRecovery(address _newOwner) external { require(isGuardian[msg.sender], "Not a guardian"); require(activeRequest.newOwner == address(0), "Request active"); activeRequest.newOwner = _newOwner; activeRequest.initiateTime = block.timestamp; } }
Once a recovery is initiated, other guardians must submit their approvals. The confirmRecovery function checks the cooldown period, ensures the guardian hasn't already voted, and tallies approvals. If the threshold is met after the cooldown, the executeRecovery function can be called by anyone to finalize the ownership transfer. It's crucial to include a cooldown period (e.g., 48 hours) between initiation and execution. This gives the original owner a final window to cancel the request if it is malicious, serving as a vital security backstop.
Managing guardians over time is essential. Your contract should include functions for the owner to add or remove guardians and update the threshold, often requiring a transaction from the account itself. For better user experience, consider emitting clear events like RecoveryInitiated, GuardianAdded, and OwnershipTransferred. Always audit the final logic or use well-audited implementations from libraries like Safe{Core} AA SDK or ZeroDev's Kernel. Properly implemented, social recovery creates a user-owned safety net that is far more secure and usable than traditional seed phrase management.
How to Implement Social Recovery for Smart Accounts
A practical guide to implementing a social recovery mechanism for smart contract wallets, enabling users to regain access using a network of trusted guardians.
Social recovery is a critical security feature for smart accounts, allowing users to designate a set of trusted guardians—other EOAs or smart contracts—who can collectively approve a recovery operation. This mechanism mitigates the risk of permanent key loss, a major user experience hurdle in self-custody. Unlike traditional seed phrases, recovery is a social and procedural event, requiring a configurable threshold of guardians (e.g., 3 out of 5) to sign a recovery request. This tutorial outlines the core logic and Solidity implementation for this system.
The core contract requires several key state variables: a mapping of the account's guardians, a counter for recovery requests, and storage for pending requests. A recovery request should be a struct containing the proposed new owner address, a timestamp, and an array of guardian approvals. The primary functions are: initiateRecovery(address newOwner) to start the process, approveRecovery(uint256 requestId) for guardians to sign, executeRecovery(uint256 requestId) to finalize ownership transfer once the threshold is met, and cancelRecovery(uint256 requestId) for the original owner to abort. It's essential to include a time-lock period (e.g., 24-48 hours) on executed recoveries to give the original owner a final chance to cancel.
Here is a simplified code snippet for the approval logic. The contract must track which guardians have approved a specific request and prevent duplicate approvals.
soliditymapping(uint256 => mapping(address => bool)) public hasApproved; function approveRecovery(uint256 _requestId) external { RecoveryRequest storage request = recoveryRequests[_requestId]; require(isGuardian[msg.sender], "Not a guardian"); require(!hasApproved[_requestId][msg.sender], "Already approved"); require(request.newOwner != address(0), "Invalid request"); hasApproved[_requestId][msg.sender] = true; request.approvalCount++; emit RecoveryApproved(_requestId, msg.sender); }
The executeRecovery function would then check if request.approvalCount >= recoveryThreshold and the time-lock has passed before transferring ownership via owner = request.newOwner.
For production use, consider integrating with existing standards like ERC-4337 account abstraction. The recovery logic should be part of your account's validateUserOp function or a dedicated module. Key security considerations include: ensuring guardians can be added/removed only by the account owner (potentially with a delay), using a multi-sig or safe as a guardian for higher security, and implementing a guardian rotation policy to keep the set current. Avoid on-chain enumeration of guardians for large sets due to gas costs; use off-chain indexing instead.
Testing is paramount. Write comprehensive unit tests (using Foundry or Hardhat) for scenarios like: successful recovery with threshold met, failed execution without enough approvals, cancellation by the owner, and expiration of stale requests. Also test edge cases such as a guardian being removed mid-recovery. For real-world examples, study the recovery mechanisms in Safe{Wallet} (via Safe Modules) and Argent Wallet, which pioneered this model on Ethereum. Their publicly audited code provides excellent reference material for robust implementation patterns.
Finally, the user experience for guardians must be smooth. Provide clear interfaces for them to view pending requests and sign approvals, which could be simple Ethereum signatures (eth_signTypedData_v4) verified by the contract. The entire flow—from a user losing access, to guardians being notified, to signing, and finally to account recovery—should be designed to minimize friction while maximizing security. This transforms smart accounts from a technical novelty into a practical, user-owned alternative to centralized custody.
Security Considerations and Attack Vectors
Comparison of security trade-offs and potential attack vectors for different social recovery guardian configurations.
| Attack Vector / Consideration | On-Chain Guardians (e.g., Safe{Wallet}) | Off-Chain Guardians (e.g., ERC-4337) | Hybrid Approach (e.g., Soul Wallet) |
|---|---|---|---|
Guardian Sybil Attack | High Risk Guardian addresses can be cheaply created | Medium Risk Requires Sybil-resistant off-chain identity | Medium Risk Depends on off-chain component |
Transaction Front-Running | High Risk Recovery request is public on-chain | Low Risk Recovery approval can be private | Medium Risk On-chain request step is exposed |
Guardian Collusion Threshold | Configurable (e.g., 3-of-5) | Configurable (e.g., 3-of-5) | Configurable (e.g., 3-of-5) |
Recovery Latency | ~1-5 blocks Depends on network congestion | < 1 sec Uses off-chain signatures | ~1-5 blocks Final step requires on-chain tx |
Implementation Complexity | Low Uses existing multisig logic | High Requires secure off-chain infrastructure | Medium Combines on-chain and off-chain systems |
Guardian Key Compromise | High Impact Private key loss enables direct attack | Medium Impact Compromised signer can be rotated off-chain | Medium Impact Depends on which component is compromised |
Cost per Recovery | $50-200 Gas for multiple guardian txs | $10-30 Gas for single bundled tx | $30-100 Gas costs for on-chain finalization |
Integrating Recovery into User Onboarding
A practical guide to implementing social recovery for smart accounts, ensuring users can regain access without relying on a single seed phrase.
Social recovery is a critical security mechanism for smart accounts, allowing a user to designate trusted guardians—other wallets or entities—who can collectively authorize a wallet recovery. Unlike traditional externally owned accounts (EOAs) secured by a single, easily-lost private key, smart accounts enable programmable logic for key management. This shifts the security model from something you have (a seed phrase) to who you know (a network of trusted contacts or devices). Integrating this during onboarding is essential for user adoption, as it directly addresses the major pain point of permanent fund loss.
To implement social recovery, you first need to choose a smart account standard that supports it, such as ERC-4337 (Account Abstraction) or a specific SDK like Safe{Wallet} (formerly Gnosis Safe). The core logic involves deploying a smart contract wallet with a function that allows a new signing key to be set, but only after a predefined threshold of guardian signatures is provided. For example, a user might set up a 2-of-3 recovery scheme where any two of their three designated guardians must approve a recovery request. This logic is embedded in the wallet's validateUserOp function or a dedicated recovery module.
Here is a simplified conceptual example of a recovery function in a smart contract:
solidityfunction initiateRecovery(address newOwner, bytes[] calldata guardianSignatures) external { require(guardianSignatures.length >= recoveryThreshold, "Insufficient guardians"); // Verify each signature is from an approved guardian for (uint i = 0; i < guardianSignatures.length; i++) { address signer = recoverSigner(newOwner, guardianSignatures[i]); require(isGuardian[signer], "Invalid guardian"); } owner = newOwner; // Execute the key rotation }
In practice, you would use libraries like OpenZeppelin's ECDSA for signature verification and implement a time-delay or challenge period to prevent malicious recovery attempts.
The user onboarding flow must seamlessly incorporate guardian setup. After a user creates their account, prompt them to add recovery contacts. Best practices include: - Allowing guardians to be other smart accounts, EOAs, or institutional signers like WalletConnect or Web3Auth nodes. - Storing guardian addresses off-chain (e.g., in your app's backend) until the user confirms them to save gas. - Providing clear educational UI explaining the recovery process and the responsibilities of guardians. Tools like Safe{Core} SDK and ZeroDev Kernel provide abstracted APIs to manage these flows without writing low-level contract code.
Consider the security trade-offs. A lower guardian threshold (e.g., 1-of-2) is more convenient but less secure against collusion. A higher threshold (e.g., 3-of-5) is more secure but harder to execute. Introduce a recovery delay period (e.g., 48 hours) where the user can cancel a pending recovery, adding a critical safety net. For maximum accessibility, consider integrating with social login guardians via services like Web3Auth, which can use a user's Google or Discord account as a recovery factor, blending Web2 and Web3 security models.
Finally, test your implementation thoroughly. Use testnets like Sepolia or Polygon Amoy to simulate recovery scenarios. Monitor events like RecoveryInitiated and RecoveryCompleted. Provide users with a clear, step-by-step recovery path in your documentation and support channels. By making social recovery a default, opt-out part of onboarding, you significantly reduce barrier to entry and custodial risk, paving the way for mainstream smart account adoption.
Implementation Resources and Tools
Practical resources for implementing social recovery in smart accounts using production-grade tooling. These cards focus on concrete architectures, audited modules, and real-world account abstraction flows.
Guardian Management Patterns
Guardian selection and lifecycle management are the core security surface of social recovery. Poor guardian design is a common cause of wallet compromise.
Recommended patterns:
- Use heterogeneous guardians: EOAs, hardware wallets, and smart contracts
- Avoid guardians controlled by the same seed phrase or custody provider
- Require majority or supermajority thresholds (e.g. 3-of-5, 4-of-7)
- Add guardian rotation functions with cooldowns
- Enforce recovery delays to allow user intervention if a recovery is malicious
Advanced implementations include social graph guardians, DAO-controlled guardians, or institutional signers using MPC. Guardian logic should be simple, auditable, and isolated from upgrade logic to reduce attack surface.
Frequently Asked Questions
Common technical questions and solutions for implementing social recovery in smart accounts, focusing on ERC-4337, ERC-6900, and practical developer concerns.
Social recovery is a mechanism that allows a smart account to be recovered by a predefined group of trusted entities (guardians) rather than a single private key or seed phrase. It fundamentally shifts security from key management to social consensus.
Key Differences:
- Seed Phrases: A single, static 12-24 word mnemonic. Loss or compromise results in permanent, irreversible loss of funds.
- Social Recovery: Uses a multi-signature-like scheme where a threshold (e.g., 3 out of 5) of guardians must approve a recovery operation to designate a new signing key for the account. This happens via a recovery transaction executed on-chain.
Protocols like ERC-4337 enable this by allowing smart accounts to execute arbitrary logic, including calling a recovery module. ERC-6900 (Modular Account) standardizes this further by defining clear interfaces for plug-in modules, including recovery.
Conclusion and Next Steps
You have now explored the core concepts and practical steps for implementing social recovery for smart accounts. This guide covered the architectural patterns, security considerations, and a concrete example using ERC-4337 and the ZeroDev SDK.
Social recovery transforms wallet security by shifting the burden from a single private key to a trusted social graph. The key components you've implemented include a modular smart account (like those from ZeroDev, Biconomy, or Safe), a guardian management module to add/remove recovery signers, and a recovery execution flow that uses a multi-signature scheme. This setup ensures that losing a device or seed phrase is no longer a catastrophic event, as a predefined majority of your guardians can collectively authorize a wallet recovery.
For production deployment, several critical steps remain. First, thoroughly test the recovery flow on a testnet, simulating various failure scenarios like guardian unavailability or malicious actors. Second, carefully select and onboard guardians, ensuring they understand their responsibility and have secure signing setups themselves (using hardware wallets or dedicated mobile apps). Third, consider implementing recovery delay periods and security notifications to give the original owner a window to cancel any unauthorized recovery attempts, adding a crucial layer of protection.
The ecosystem for account abstraction and recovery is rapidly evolving. To stay current, monitor developments in ERC-4337 bundler infrastructure and paymaster services for gas sponsorship. Explore advanced patterns like hierarchical recovery (assigning different weights to guardians) or time-locked recovery for high-value accounts. Continue your learning by reviewing the official ERC-4337 documentation and experimenting with other SDKs like Safe{Core} AA SDK or Alchemy's Account Kit.