What are Session Keys? The Complete Guide to Building Invisible Blockchain Experiences with Account Abstraction
Introduction
Session keys are an important feature for building seamless onchain apps. They improve user experience by allowing smooth interactions with apps and games without needing constant confirmations. These keys provide temporary access to a user's account with specific permissions. This is especially useful in situations where user experience is crucial, like gaming or automated transactions. For example, a user can let an app execute transactions on their behalf, reducing interruptions during gameplay or other activities.
Additionally, session keys reduce the risk of exposing the main private key, which enhances security. If a session key is compromised, the attacker cannot access the user's main account and funds. This security feature is essential for maintaining user trust in blockchain applications.
Session keys can autonomously sign transactions for users while being limited to specific timeframes and values. This allows users to grant dApps permission to send pre-approved transactions without needing confirmation each time, opening up many use cases for dApps.
What Are Session Keys?
Session keys are additional authorized signers that let users interact with blockchain applications without repeatedly using their primary key. These keys operate through ERC-4337 infrastructure, including bundlers and EntryPoint, to execute transactions on an account's behalf under certain restrictions. This capability is crucial for applications needing frequent user interactions, such as games and decentralized finance (DeFi) platforms.
For instance, a user can allow an app to execute specific transactions on their behalf using a session key, significantly reducing interruptions during gameplay or automated processes like reward claims and liquidity management. The session key's permissions can be tailored to the application's needs while maintaining overall account security.
Functionality and Permissions
The strength of session keys lies in their ability to limit actions based on predefined permissions. Developers can specify various parameters, including time ranges, access control lists, and spending limits for both ERC-20 tokens and native tokens. This ensures that users maintain control over their assets while enjoying a smooth experience.
For example, a session key can be set to allow an app to spend a certain amount of tokens within a specific timeframe, automating transactions without compromising security. This feature not only enhances user experience but also opens up new payment models, such as subscriptions and recurring payments.
Security Considerations
While session keys simplify interactions, they also introduce important security considerations. Even if a session key is compromised, the main account remains secure, as the session key operates within its defined limits.
This minimizes the exposure of the primary private key, which is crucial for maintaining user security.
Account Abstraction: Transforming crypto UX.
Account Abstraction makes it possible to deploy session keys in your web3 app or game.
Account Abstraction enables the creation of smart contract wallets, which are independent smart contracts that can initiate and execute transactions with enhanced flexibility and programmability. Any custom operation that can be defined in the form of smart contract code can be implemented in these wallets.
The operation of smart contract wallets, or account abstracted wallets, is fairly simple. Instead of sending regular transactions as traditional wallets do, smart contract wallets use UserOperations, which represent actions to be conducted on behalf of the user.
A UserOperation contains multiple fields that describe the type of transaction, the token, gas limit and price for various steps of the transaction, the signature to validate the transaction, and other metadata.
Every time a smart account sends a UserOperation, it goes into the common waiting area for all UserOperations called the alt mempool.
These requests are then bundled by bundlers, who are similar to nodes verifying regular transactions. They even use the same logic as mining or validator nodes to prioritize transactions where they can extract the most value.
The bundled UserOperations are sent through a single whitelisted “Entry Point,” where every individual UserOperation is verified and executed by calling different functions.
As UserOperations can include any type of logic, it allows users to implement various customizations to how they want to manage their accounts and the funds in them.
Implementing Session Keys in Web3 apps to build a seamless UX.
To enable Session Keys in your web3 app, simply add Account Abstraction to your thirdweb Connect sign-in module.
- Deploy an Account Factory smart contract on the network of your choice:
- Add Account Abstraction to the
ConnectButton
with In-App Wallet
import { ConnectButton } from "thirdweb/react";
const accountAbstraction = {
chain: chain,
factoryAddress: "<contract_address>",
sponsorGas: true,
}
export const AALogin = () => {
return (
<ConnectButton
client={client}
chain={chain}
accountAbstraction={accountAbstraction}
connectButton={{
label: "AA Login"
}}
/>
)
};
In this example, we will use Smart Wallets (Account Abstraction) and the use of a paymaster to sponsor the gas fees needed for the user.
This means that a user can sign-in with an email or social login and instantly start using our app and interacting with the blockchain without needing to fund their wallet.
- Create a session key using the
addSessionKey
extension. Using the smart contract deployed for our Smart Wallet we can set permissions to asessionKeyAddress
const account = useActiveAccount();
const smartAccount = getContract({
client: client,
chain: <chain>,
address: account?.address as string,
});
const createSessionKey = async () => {
if (!account) return;
try {
const tx = addSessionKey({
contract: smartAccount,
account: account,
sessionKeyAddress: "<address>",
permissions: {
approvedTargets: "*",
nativeTokenLimitPerTransaction: 0.1,
permissionStartTimestamp: new Date(),
permissionEndTimestamp: new Date(Date.now() + <set_date>),
}
});
await sendAndConfirmTransaction({
account: account,
transaction: tx,
});
} catch (error) {
console.error(error);
}
};
- View the signers on a Smart Wallet by calling the
getAllSigners
function. Easily do this with theuseReadContract
hook andgetAllSigners
extension.
const smartAccount = getContract({
client: client,
chain: <chain>,
address: account?.address as string,
});
const { data: activeSigners } = useReadContract(
getAllActiveSigners,
{
contract: smartAccount,
}
);
- Remove signers and their permissions with the
removeSessionKey
extension.
const revokeSessionKey = async (signer: string) => {
if (!account) return;
try {
const tx = removeSessionKey({
contract: smartAccount,
account: account,
sessionKeyAddress: signer,
});
await sendAndConfirmTransaction({
account: account,
transaction: tx,
});
} catch (error) {
console.error(error);
}
};
Now, you can add, view, and remove session keys from your Smart Wallets. Permissions and limitation to what a session key can execute on behalf of your Smart Wallet are set when creating the session key. This includes permissions like spending limit, whitelisted contracts, and time period which the session key has permission.
Real-world Use Cases and Success Stories
Session keys are making it possible to build web3 apps with near perfect User Experience – making it possible to onboard non-crypto native users.
Cityverse Tycoon, a monopoly-style mobile game developed by OwnPlay, has taken the mobile gaming world by storm, amassing over 200k+ iOS downloads in the USA alone.
The experience is built using a combination of thirdweb's In-App wallets, which let users sign-in with their email, Google or Apple accounts, and Account Abstraction, which provides session keys for the users to complete onchain actions without signing transactions.
Conclusion: Embracing Session Keys to level up web3 UX
Embracing session keys represents a significant leap forward in the usability and functionality of blockchain applications. These temporary cryptographic keys allow users to interact with apps without needing constant confirmations using their primary keys. This innovation not only enhances user experience but also minimizes the exposure of sensitive information, making blockchain interactions more secure and seamless.
By simplifying the authentication process and enhancing user experience, session keys pave the way for more intuitive interactions with decentralized technologies. Developers looking to enhance their blockchain applications should consider integrating session keys to create seamless and secure user experiences.