Session keys
The user is guaranteed that the dapp can only execute transactions that comply to the policies of the session and until the session expires.
Creating a session key
Next you need to come up with the permissions you would like for your session. You also need to generate the session keypair you want to grant these rights to.
Generating a key pair
const generateKeyPair = () => {
const keyPair = ethers.Wallet.createRandom()
return {
address: keyPair.address,
pk: keyPair.privateKey,
}
}
This example session will allow the dapp to execute an example endpoint on an example contract without asking the user to approve the transaction again. After signing the session the dapp can execute all transactions listed in permissions
whenever it wants and as many times as it wants.
Creating a session parameters
const getPermissionParams = (tokenAddress: string): any => {
const ABI = ['function transfer(address to, uint amount)']
const iface = new ethers.utils.Interface(ABI)
const encodedData = iface.encodeFunctionData('transfer', [
'0x1234567890123456789012345678901234567890',
'10000000000',
])
const transferFunctionSignature = encodedData.slice(0, 10)
const permissionParams = {
whitelistDestination: tokenAddress,
whitelistMethods: [transferFunctionSignature],
tokenAmount: ethers.utils.parseEther('1000').toString(),
}
return permissionParams
}
Finally, the session parameters will define for how long a session key is valid for and if it's enabled.
Define validity for session
const getSessionParams = (): any => {
// todo: Remove hard coded session timestamp
const sessionParam = {
startTimestamp: '1665350119',
endTimestamp: '1665436509',
enable: true,
}
return sessionParam
}
We can then create the transaction:
Create a transaction using the session key
const permissionParams = getPermissionParams(usdcAddress)
const sessionParams = getSessionParams()
const keyPair = generateKeyPair()
const tx1 = {
to: config.sessionKeyModule.address,
data: iFaceSessionModule.encodeFunctionData('createSession', [
keyPair.address,
[permissionParams],
sessionParams,
]),
}
Using established sessions
With your signed session you can now use it with your dapp to do transactions without the user having to approve again.
Enabling the session plugin
Enabling the session keys plugin
const tx2 = {
to: _smartAccount.address,
data: iFace.encodeFunctionData('enableModule', [
config.sessionKeyModule.address,
]),
}