-
Notifications
You must be signed in to change notification settings - Fork 560
[SDK] EIP-7702 Session Keys #7432
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
4386865
[SDK] EIP-7702 Session Keys
0xFirekeeper 25a575b
fix lint
0xFirekeeper 0e4baef
Create chatty-chairs-mate.md
0xFirekeeper 283c799
duration check
0xFirekeeper 2ba6041
exports
0xFirekeeper e31ed6b
address review
0xFirekeeper 7595cc8
export enums, update test to use them
0xFirekeeper 79835e0
fix lint
0xFirekeeper e392604
wts crlf
0xFirekeeper File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
"thirdweb": patch | ||
--- | ||
|
||
Introduces Session Keys to EIP-7702-powered In-App Wallets via a new createSessionKey extension |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
181 changes: 181 additions & 0 deletions
181
packages/thirdweb/src/extensions/erc7702/account/createSessionKey.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,181 @@ | ||
import type { BaseTransactionOptions } from "../../../transaction/types.js"; | ||
import { randomBytesHex } from "../../../utils/random.js"; | ||
import type { Account } from "../../../wallets/interfaces/wallet.js"; | ||
import { | ||
createSessionWithSig, | ||
isCreateSessionWithSigSupported, | ||
} from "../__generated__/MinimalAccount/write/createSessionWithSig.js"; | ||
import { | ||
type CallSpecInput, | ||
CallSpecRequest, | ||
ConstraintRequest, | ||
SessionSpecRequest, | ||
type TransferSpecInput, | ||
TransferSpecRequest, | ||
UsageLimitRequest, | ||
} from "./types.js"; | ||
|
||
/** | ||
* @extension ERC7702 | ||
*/ | ||
export type CreateSessionKeyOptions = { | ||
/** | ||
* The admin account that will perform the operation. | ||
*/ | ||
account: Account; | ||
/** | ||
* The address to add as a session key. | ||
*/ | ||
sessionKeyAddress: string; | ||
/** | ||
* How long the session key should be valid for, in seconds. | ||
*/ | ||
durationInSeconds: number; | ||
/** | ||
* Whether to grant full execution permissions to the session key. | ||
*/ | ||
grantFullPermissions?: boolean; | ||
/** | ||
* Smart contract interaction policies to apply to the session key, ignored if grantFullPermissions is true. | ||
*/ | ||
callPolicies?: CallSpecInput[]; | ||
/** | ||
* Value transfer policies to apply to the session key, ignored if grantFullPermissions is true. | ||
*/ | ||
transferPolicies?: TransferSpecInput[]; | ||
}; | ||
|
||
/** | ||
* Creates session key permissions for a specified address. | ||
* @param options - The options for the createSessionKey function. | ||
* @param {Contract} options.contract - The EIP-7702 smart EOA contract to create the session key from | ||
* @returns The transaction object to be sent. | ||
* @example | ||
* ```ts | ||
* import { createSessionKey } from 'thirdweb/extensions/7702'; | ||
* import { sendTransaction } from 'thirdweb'; | ||
* | ||
* const transaction = createSessionKey({ | ||
* account: account, | ||
* contract: accountContract, | ||
* sessionKeyAddress: TEST_ACCOUNT_A.address, | ||
* durationInSeconds: 86400, // 1 day | ||
* grantFullPermissions: true | ||
*}) | ||
* | ||
* await sendTransaction({ transaction, account }); | ||
* ``` | ||
* @extension ERC7702 | ||
*/ | ||
export function createSessionKey( | ||
options: BaseTransactionOptions<CreateSessionKeyOptions>, | ||
) { | ||
const { | ||
contract, | ||
account, | ||
sessionKeyAddress, | ||
durationInSeconds, | ||
grantFullPermissions, | ||
callPolicies, | ||
transferPolicies, | ||
} = options; | ||
|
||
if (durationInSeconds <= 0) { | ||
throw new Error("durationInSeconds must be positive"); | ||
} | ||
|
||
return createSessionWithSig({ | ||
async asyncParams() { | ||
const req = { | ||
callPolicies: (callPolicies || []).map((policy) => ({ | ||
constraints: (policy.constraints || []).map((constraint) => ({ | ||
condition: Number(constraint.condition), | ||
index: constraint.index || BigInt(0), | ||
limit: constraint.limit | ||
? { | ||
limit: constraint.limit.limit, | ||
limitType: Number(constraint.limit.limitType), | ||
period: constraint.limit.period, | ||
} | ||
: { | ||
limit: BigInt(0), | ||
limitType: 0, | ||
period: BigInt(0), | ||
}, | ||
refValue: constraint.refValue || "0x", | ||
0xFirekeeper marked this conversation as resolved.
Show resolved
Hide resolved
|
||
})), | ||
maxValuePerUse: policy.maxValuePerUse || BigInt(0), | ||
selector: policy.selector, | ||
target: policy.target, | ||
valueLimit: policy.valueLimit | ||
? { | ||
limit: policy.valueLimit.limit, | ||
limitType: Number(policy.valueLimit.limitType), | ||
period: policy.valueLimit.period, | ||
} | ||
: { | ||
limit: BigInt(0), | ||
limitType: 0, | ||
period: BigInt(0), | ||
}, | ||
})), | ||
expiresAt: BigInt(Math.floor(Date.now() / 1000) + durationInSeconds), | ||
isWildcard: grantFullPermissions ?? true, | ||
signer: sessionKeyAddress, | ||
transferPolicies: (transferPolicies || []).map((policy) => ({ | ||
maxValuePerUse: policy.maxValuePerUse || BigInt(0), | ||
target: policy.target, | ||
valueLimit: policy.valueLimit | ||
? { | ||
limit: policy.valueLimit.limit, | ||
limitType: Number(policy.valueLimit.limitType), | ||
period: policy.valueLimit.period, | ||
} | ||
: { | ||
limit: BigInt(0), | ||
limitType: 0, | ||
period: BigInt(0), | ||
}, | ||
})), | ||
uid: await randomBytesHex(), | ||
}; | ||
|
||
const signature = await account.signTypedData({ | ||
domain: { | ||
chainId: contract.chain.id, | ||
name: "MinimalAccount", | ||
verifyingContract: contract.address, | ||
version: "1", | ||
}, | ||
message: req, | ||
primaryType: "SessionSpec", | ||
types: { | ||
CallSpec: CallSpecRequest, | ||
Constraint: ConstraintRequest, | ||
SessionSpec: SessionSpecRequest, | ||
TransferSpec: TransferSpecRequest, | ||
UsageLimit: UsageLimitRequest, | ||
}, | ||
}); | ||
|
||
return { sessionSpec: req, signature }; | ||
}, | ||
contract, | ||
}); | ||
} | ||
|
||
/** | ||
* Checks if the `isCreateSessionKeySupported` method is supported by the given contract. | ||
* @param availableSelectors An array of 4byte function selectors of the contract. You can get this in various ways, such as using "whatsabi" or if you have the ABI of the contract available you can use it to generate the selectors. | ||
* @returns A boolean indicating if the `isAddSessionKeySupported` method is supported. | ||
* @extension ERC7702 | ||
* @example | ||
* ```ts | ||
* import { isCreateSessionKeySupported } from "thirdweb/extensions/erc7702"; | ||
* | ||
* const supported = isCreateSessionKeySupported(["0x..."]); | ||
* ``` | ||
*/ | ||
export function isCreateSessionKeySupported(availableSelectors: string[]) { | ||
return isCreateSessionWithSigSupported(availableSelectors); | ||
} | ||
132 changes: 132 additions & 0 deletions
132
packages/thirdweb/src/extensions/erc7702/account/sessionkey.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
import { defineChain } from "src/chains/utils.js"; | ||
import { prepareTransaction } from "src/transaction/prepare-transaction.js"; | ||
import { inAppWallet } from "src/wallets/in-app/web/in-app.js"; | ||
import type { Account } from "src/wallets/interfaces/wallet.js"; | ||
import { beforeAll, describe, expect, it } from "vitest"; | ||
import { TEST_CLIENT } from "../../../../test/src/test-clients.js"; | ||
import { TEST_ACCOUNT_A } from "../../../../test/src/test-wallets.js"; | ||
import { ZERO_ADDRESS } from "../../../constants/addresses.js"; | ||
import { | ||
getContract, | ||
type ThirdwebContract, | ||
} from "../../../contract/contract.js"; | ||
import { parseEventLogs } from "../../../event/actions/parse-logs.js"; | ||
import { sendAndConfirmTransaction } from "../../../transaction/actions/send-and-confirm-transaction.js"; | ||
import { sessionCreatedEvent } from "../__generated__/MinimalAccount/events/SessionCreated.js"; | ||
import { createSessionKey } from "./createSessionKey.js"; | ||
import { Condition, LimitType } from "./types.js"; | ||
|
||
describe.runIf(process.env.TW_SECRET_KEY)( | ||
"Session Key Behavior", | ||
{ | ||
retry: 0, | ||
timeout: 240_000, | ||
}, | ||
() => { | ||
const chainId = 11155111; | ||
let account: Account; | ||
let accountContract: ThirdwebContract; | ||
|
||
beforeAll(async () => { | ||
// Create 7702 Smart EOA | ||
const wallet = inAppWallet({ | ||
executionMode: { | ||
mode: "EIP7702", | ||
sponsorGas: true, | ||
}, | ||
}); | ||
account = await wallet.connect({ | ||
chain: defineChain(chainId), | ||
client: TEST_CLIENT, | ||
strategy: "guest", | ||
}); | ||
|
||
// Send a null tx to trigger deploy/upgrade | ||
await sendAndConfirmTransaction({ | ||
account: account, | ||
transaction: prepareTransaction({ | ||
chain: defineChain(chainId), | ||
client: TEST_CLIENT, | ||
to: account.address, | ||
value: 0n, | ||
}), | ||
}); | ||
|
||
// Will auto resolve abi since it's deployed | ||
accountContract = getContract({ | ||
address: account.address, | ||
chain: defineChain(chainId), | ||
client: TEST_CLIENT, | ||
}); | ||
}, 120_000); | ||
|
||
it("should allow adding adminlike session keys", async () => { | ||
const receipt = await sendAndConfirmTransaction({ | ||
account: account, | ||
transaction: createSessionKey({ | ||
account: account, | ||
contract: accountContract, | ||
durationInSeconds: 86400, | ||
grantFullPermissions: true, // 1 day | ||
sessionKeyAddress: TEST_ACCOUNT_A.address, | ||
}), | ||
}); | ||
const logs = parseEventLogs({ | ||
events: [sessionCreatedEvent()], | ||
logs: receipt.logs, | ||
}); | ||
expect(logs[0]?.args.signer).toBe(TEST_ACCOUNT_A.address); | ||
}); | ||
|
||
it("should allow adding granular session keys", async () => { | ||
const receipt = await sendAndConfirmTransaction({ | ||
account: account, | ||
transaction: createSessionKey({ | ||
account: account, | ||
callPolicies: [ | ||
{ | ||
constraints: [ | ||
{ | ||
condition: Condition.Unconstrained, | ||
index: 0n, | ||
refValue: | ||
"0x0000000000000000000000000000000000000000000000000000000000000000", | ||
}, | ||
], | ||
maxValuePerUse: 0n, | ||
selector: "0x00000000", | ||
target: ZERO_ADDRESS, | ||
valueLimit: { | ||
limit: 0n, | ||
limitType: LimitType.Unlimited, | ||
period: 0n, | ||
}, | ||
}, | ||
], | ||
contract: accountContract, | ||
durationInSeconds: 86400, // 1 day | ||
grantFullPermissions: false, | ||
sessionKeyAddress: TEST_ACCOUNT_A.address, | ||
transferPolicies: [ | ||
{ | ||
maxValuePerUse: 0n, | ||
target: ZERO_ADDRESS, | ||
valueLimit: { | ||
limit: 0n, | ||
limitType: 0, | ||
period: 0n, | ||
}, | ||
}, | ||
], | ||
}), | ||
}); | ||
const logs = parseEventLogs({ | ||
events: [sessionCreatedEvent()], | ||
logs: receipt.logs, | ||
}); | ||
expect(logs[0]?.args.signer).toBe(TEST_ACCOUNT_A.address); | ||
expect(logs[0]?.args.sessionSpec.callPolicies).toHaveLength(1); | ||
expect(logs[0]?.args.sessionSpec.transferPolicies).toHaveLength(1); | ||
}); | ||
}, | ||
); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.