MetaMask 智能账户套件:Web3 与 ERC-4337 开发 - Openclaw Skills
作者:互联网
2026-04-03
什么是 MetaMask 智能账户套件 (Smart Accounts Kit)?
MetaMask 智能账户套件是一款强大的开发工具集,旨在简化利用账户抽象(Account Abstraction)创建去中心化应用程序(dApps)的过程。作为 Openclaw Skills 库的一部分,该技能使开发者能够实现复杂的 Web3 功能,如 Gas 抽象(支付主节点 Paymasters)、基于通行密钥(Passkey)的身份验证和多重签名安全。它弥合了传统钱包交互与可编程智能账户之间的差距,为发送用户操作(User Operations)和管理混合型(Hybrid)及无状态(Stateless7702)账户实现提供了流线型接口。
除了账户管理,该套件还提供对委托框架(ERC-7710)和高级权限(ERC-7715)的原生支持。这允许创建细粒度、限时且受范围限制的权限,从而在不影响安全性的情况下实现会话密钥和自动化交易。通过与 Viem 和 MetaMask Flask 集成,它为 Openclaw Skills 生态系统内的开发者提供了一个前沿环境,用于构建高性能、用户友好的区块链应用程序。
下载入口:https://github.com/openclaw/skills/tree/main/skills/ayushbherwani1998/metamask-smart-accounts-kit
安装与下载
1. ClawHub CLI
从源直接安装技能的最快方式。
npx clawhub@latest install metamask-smart-accounts-kit
2. 手动安装
将技能文件夹复制到以下位置之一
全局模式~/.openclaw/skills/
工作区
/skills/
优先级:工作区 > 本地 > 内置
3. 提示词安装
将此提示词复制到 OpenClaw 即可自动安装。
请帮我使用 Clawhub 安装 metamask-smart-accounts-kit。如果尚未安装 Clawhub,请先安装(npm i -g clawhub)。
MetaMask 智能账户套件 (Smart Accounts Kit) 应用场景
- 实现无 Gas 交易流,由 dApp 通过支付主节点(Paymaster)代付用户 Gas 费。
- 为 Web3 游戏设置会话密钥,允许流畅的游戏体验,无需频繁的钱包弹窗提示。
- 使用自定义阈值和多个签署者创建复杂的多签账户结构。
- 利用混合实现和通行密钥为区块链账户启用生物识别身份验证。
- 通过高级权限范围实现定期代币转账或流支付的自动化。
- 账户初始化:通过指定实现方式(Hybrid、Multisig 或 Stateless7702)和签署者,使用
toMetaMaskSmartAccount创建智能账户。 - 委托设置:定义授权范围(例如
erc20TransferAmount),并附加特定的限制条件(Caveats),如timestamp或limitedCalls,以限制受托人的权力。 - 签名与存储:使用智能账户的权限为委托生成签名,以授权受托人的行为。
- 兑现委托:受托人通过对调用数据(calldata)进行编码,并将其作为用户操作(User Operation)通过捆绑器(Bundler)或直接通过 EOA 提交,来执行授权操作。
MetaMask 智能账户套件 (Smart Accounts Kit) 配置指南
使用 npm 安装核心库:
npm install @metamask/smart-accounts-kit@0.3.0
对于创建自定义限制执行器的开发者,安装委托框架合约:
forge install metamask/delegation-framework@v1.3.0
MetaMask 智能账户套件 (Smart Accounts Kit) 数据架构与分类体系
该套件围绕核心 ERC 标准和智能合约部署组织其操作。下表总结了主要的数学组件:
| 组件 | 描述 |
|---|---|
| 实现 (Implementation) | 定义账户逻辑:Hybrid (EOA+Passkey)、Multisig 或 Stateless7702 |
| 入口点 (EntryPoint) | 用于处理 ERC-4337 用户操作的单例合约 (0x000...032) |
| 委托管理器 (DelegationManager) | 用于创建和兑现 ERC-7710 委托的核心合约 (0xdb9...dB3) |
| 限制执行器 (Caveat Enforcers) | 验证限制条件的逻辑单元,如 allowedMethods、valueLte 和 timestamp |
| 执行模式 (Execution Modes) | 定义调用的处理方式:SingleDefault、SingleTry、BatchDefault 或 BatchTry |
name: smart-accounts-kit
description: Web3 development using MetaMask Smart Accounts Kit. Use when the user wants to build dApps with ERC-4337 smart accounts, send user operations, batch transactions, configure signers (EOA, passkey, multisig), implement gas abstraction with paymasters, create delegations, or request advanced permissions (ERC-7715). Supports Viem integration, multiple signer types (Dynamic, Web3Auth, Wagmi), gasless transactions, and the Delegation Framework.
metadata: {"openclaw":{"emoji":"??","homepage":"https://docs.metamask.io/smart-accounts-kit"}}
Quick Reference
This skill file provides quick access to the MetaMask Smart Accounts Kit v0.3.0. For detailed information, refer to the specific reference files.
?? Detailed References:
- Smart Accounts Reference - Account creation, implementations, signers
- Delegations Reference - Delegation lifecycle, scopes, caveats
- Advanced Permissions Reference - ERC-7715 permissions via MetaMask
Package Installation
npm install @metamask/smart-accounts-kit@0.3.0
For custom caveat enforcers:
forge install metamask/delegation-framework@v1.3.0
Core Concepts Summary
1. Smart Accounts (ERC-4337)
Three implementation types:
- Hybrid (
Implementation.Hybrid) - EOA + passkey signers - Multisig (
Implementation.MultiSig) - Multiple signers with threshold - Stateless7702 (
Implementation.Stateless7702) - EIP-7702 upgraded EOA
2. Delegation Framework (ERC-7710)
Grant permissions from delegator to delegate:
- Scopes - Initial authority (spending limits, function calls)
- Caveats - Restrictions enforced by smart contracts
- Types - Root, open root, redelegation, open redelegation
- Lifecycle - Create → Sign → Store → Redeem
3. Advanced Permissions (ERC-7715)
Request permissions via MetaMask extension:
- Human-readable UI confirmations
- ERC-20 and native token permissions
- Requires MetaMask Flask 13.5.0+
- User must have smart account
Quick Code Examples
Create Smart Account
import { Implementation, toMetaMaskSmartAccount } from '@metamask/smart-accounts-kit'
import { privateKeyToAccount } from 'viem/accounts'
const account = privateKeyToAccount('0x...')
const smartAccount = await toMetaMaskSmartAccount({
client: publicClient,
implementation: Implementation.Hybrid,
deployParams: [account.address, [], [], []],
deploySalt: '0x',
signer: { account },
})
Create Delegation
import { createDelegation } from '@metamask/smart-accounts-kit'
import { parseUnits } from 'viem'
const delegation = createDelegation({
to: delegateAddress,
from: delegatorSmartAccount.address,
environment: delegatorSmartAccount.environment,
scope: {
type: 'erc20TransferAmount',
tokenAddress: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238',
maxAmount: parseUnits('10', 6),
},
caveats: [
{ type: 'timestamp', afterThreshold: now, beforeThreshold: expiry },
{ type: 'limitedCalls', limit: 5 },
],
})
Sign Delegation
const signature = await smartAccount.signDelegation({ delegation })
const signedDelegation = { ...delegation, signature }
Redeem Delegation
import { createExecution, ExecutionMode } from '@metamask/smart-accounts-kit'
import { DelegationManager } from '@metamask/smart-accounts-kit/contracts'
import { encodeFunctionData, erc20Abi } from 'viem'
const callData = encodeFunctionData({
abi: erc20Abi,
args: [recipient, parseUnits('1', 6)],
functionName: 'transfer',
})
const execution = createExecution({ target: tokenAddress, callData })
const redeemCalldata = DelegationManager.encode.redeemDelegations({
delegations: [[signedDelegation]],
modes: [ExecutionMode.SingleDefault],
executions: [[execution]],
})
// Via smart account
const userOpHash = await bundlerClient.sendUserOperation({
account: delegateSmartAccount,
calls: [{ to: delegateSmartAccount.address, data: redeemCalldata }],
})
// Via EOA
const txHash = await delegateWalletClient.sendTransaction({
to: environment.DelegationManager,
data: redeemCalldata,
})
Request Advanced Permissions
import { erc7715ProviderActions } from '@metamask/smart-accounts-kit/actions'
const walletClient = createWalletClient({
transport: custom(window.ethereum),
}).extend(erc7715ProviderActions())
const grantedPermissions = await walletClient.requestExecutionPermissions([
{
chainId: chain.id,
expiry: now + 604800,
signer: {
type: 'account',
data: { address: sessionAccount.address },
},
permission: {
type: 'erc20-token-periodic',
data: {
tokenAddress,
periodAmount: parseUnits('10', 6),
periodDuration: 86400,
justification: 'Transfer 10 USDC daily',
},
},
isAdjustmentAllowed: true,
},
])
Redeem Advanced Permissions
// Smart account
import { erc7710BundlerActions } from '@metamask/smart-accounts-kit/actions'
const bundlerClient = createBundlerClient({
client: publicClient,
transport: http(bundlerUrl),
}).extend(erc7710BundlerActions())
const permissionsContext = grantedPermissions[0].context
const delegationManager = grantedPermissions[0].signerMeta.delegationManager
const userOpHash = await bundlerClient.sendUserOperationWithDelegation({
publicClient,
account: sessionAccount,
calls: [
{
to: tokenAddress,
data: calldata,
permissionsContext,
delegationManager,
},
],
})
// EOA
import { erc7710WalletActions } from '@metamask/smart-accounts-kit/actions'
const walletClient = createWalletClient({
account: sessionAccount,
chain,
transport: http(),
}).extend(erc7710WalletActions())
const txHash = await walletClient.sendTransactionWithDelegation({
to: tokenAddress,
data: calldata,
permissionsContext,
delegationManager,
})
Key API Methods
Smart Accounts
toMetaMaskSmartAccount()- Create smart accountaggregateSignature()- Combine multisig signaturessignDelegation()- Sign delegationsignUserOperation()- Sign user operationsignMessage()/signTypedData()- Standard signing
Delegations
createDelegation()- Create delegation with delegatecreateOpenDelegation()- Create open delegationcreateCaveatBuilder()- Build caveats arraycreateExecution()- Create execution structredeemDelegations()- Encode redemption calldatasignDelegation()- Sign with private keygetSmartAccountsEnvironment()- Resolve environmentdeploySmartAccountsEnvironment()- Deploy contractsoverrideDeployedEnvironment()- Override environment
Advanced Permissions
erc7715ProviderActions()- Wallet client extension for requestingrequestExecutionPermissions()- Request permissionserc7710BundlerActions()- Bundler client extensionsendUserOperationWithDelegation()- Redeem with smart accounterc7710WalletActions()- Wallet client extensionsendTransactionWithDelegation()- Redeem with EOA
Supported ERC-7715 Permission Types
ERC-20 Token Permissions
| Permission Type | Description |
|---|---|
erc20-token-periodic |
Per-period limit that resets at each period |
erc20-token-streaming |
Linear streaming with amountPerSecond rate |
Native Token Permissions
| Permission Type | Description |
|---|---|
native-token-periodic |
Per-period ETH limit that resets |
native-token-streaming |
Linear ETH streaming with amountPerSecond rate |
Common Delegation Scopes
Spending Limits
| Scope | Description |
|---|---|
erc20TransferAmount |
Fixed ERC-20 limit |
erc20PeriodTransfer |
Per-period ERC-20 limit |
erc20Streaming |
Linear streaming ERC-20 |
nativeTokenTransferAmount |
Fixed native token limit |
nativeTokenPeriodTransfer |
Per-period native token limit |
nativeTokenStreaming |
Linear streaming native |
erc721Transfer |
ERC-721 (NFT) transfer |
Function Calls
| Scope | Description |
|---|---|
functionCall |
Specific methods/addresses allowed |
ownershipTransfer |
Ownership transfers only |
Common Caveat Enforcers
Target & Method
allowedTargets- Limit callable addressesallowedMethods- Limit callable methodsallowedCalldata- Validate specific calldataexactCalldata/exactCalldataBatch- Exact calldata matchexactExecution/exactExecutionBatch- Exact execution match
Value & Token
valueLte- Limit native token valueerc20TransferAmount- Limit ERC-20 amounterc20BalanceChange- Validate ERC-20 balance changeerc721Transfer/erc721BalanceChange- ERC-721 restrictionserc1155BalanceChange- ERC-1155 validation
Time & Frequency
timestamp- Valid time range (seconds)blockNumber- Valid block rangelimitedCalls- Limit redemption counterc20PeriodTransfer/erc20Streaming- Time-based ERC-20nativeTokenPeriodTransfer/nativeTokenStreaming- Time-based native
Security & State
redeemer- Limit redemption to specific addressesid- One-time delegation with IDnonce- Bulk revocation via noncedeployed- Auto-deploy contractownershipTransfer- Ownership transfer onlynativeTokenPayment- Require paymentnativeBalanceChange- Validate native balancemultiTokenPeriod- Multi-token period limits
Execution Modes
| Mode | Chains | Processing | On Failure |
|---|---|---|---|
SingleDefault |
One | Sequential | Revert |
SingleTry |
One | Sequential | Continue |
BatchDefault |
Multiple | Interleaved | Revert |
BatchTry |
Multiple | Interleaved | Continue |
Contract Addresses (v1.3.0)
Core
| Contract | Address |
|---|---|
| EntryPoint | 0x0000000071727De22E5E9d8BAf0edAc6f37da032 |
| SimpleFactory | 0x69Aa2f9fe1572F1B640E1bbc512f5c3a734fc77c |
| DelegationManager | 0xdb9B1e94B5b69Df7e401DDbedE43491141047dB3 |
| MultiSigDeleGatorImpl | 0x56a9EdB16a0105eb5a4C54f4C062e2868844f3A7 |
| HybridDeleGatorImpl | 0x48dBe696A4D990079e039489bA2053B36E8FFEC4 |
Critical Rules
Always Required
- Always use caveats - Never create unrestricted delegations
- Deploy delegator first - Account must be deployed before redeeming
- Check smart account status - ERC-7715 requires user has smart account
Behavior
- Caveats are cumulative - In delegation chains, restrictions stack
- Function call default - v0.3.0 defaults to NO native token (use
valueLte) - Batch mode caveat - No compatible caveat enforcers available
Requirements
- ERC-7715 requirements - MetaMask Flask 13.5.0+, smart account
- Multisig threshold - Need at least threshold signers
- 7702 upgrade - Stateless7702 requires EIP-7702 upgrade first
Common Patterns
Pattern 1: ERC-20 with Time Limit
const delegation = createDelegation({
to: delegate,
from: delegator,
environment,
scope: {
type: 'erc20TransferAmount',
tokenAddress,
maxAmount: parseUnits('100', 6),
},
caveats: [
{ type: 'timestamp', afterThreshold: now, beforeThreshold: expiry },
{ type: 'limitedCalls', limit: 10 },
{ type: 'redeemer', redeemers: [delegate] },
],
})
Pattern 2: Function Call with Value
const delegation = createDelegation({
to: delegate,
from: delegator,
environment,
scope: {
type: 'functionCall',
targets: [contractAddress],
selectors: ['transfer(address,uint256)'],
valueLte: { maxValue: parseEther('0.1') },
},
caveats: [{ type: 'allowedMethods', selectors: ['transfer(address,uint256)'] }],
})
Pattern 3: Periodic Native Token
const delegation = createDelegation({
to: delegate,
from: delegator,
environment,
scope: {
type: 'nativeTokenPeriodTransfer',
periodAmount: parseEther('0.01'),
periodDuration: 86400,
startDate: now,
},
})
Pattern 4: Redelegation Chain
// Alice → Bob (100 USDC)
const aliceToBob = createDelegation({
to: bob,
from: alice,
environment,
scope: { type: 'erc20TransferAmount', tokenAddress, maxAmount: parseUnits('100', 6) },
})
// Bob → Carol (50 USDC, subset of authority)
const bobToCarol = createDelegation({
to: carol,
from: bob,
environment,
scope: { type: 'erc20TransferAmount', tokenAddress, maxAmount: parseUnits('50', 6) },
parentDelegation: aliceToBob,
caveats: [{ type: 'timestamp', afterThreshold: now, beforeThreshold: expiry }],
})
Troubleshooting Quick Fixes
| Issue | Solution |
|---|---|
| Account not deployed | Use bundlerClient.sendUserOperation() to deploy |
| Invalid signature | Verify chain ID, delegation manager, signer permissions |
| Caveat enforcer reverted | Check caveat parameters match execution, verify order |
| Redemption failed | Check delegator balance, calldata validity, target contracts |
| ERC-7715 not working | Upgrade to Flask 13.5.0+, ensure user has smart account |
| Permission denied | Handle gracefully, provide manual fallback |
| Threshold not met | Add more signers for multisig |
| 7702 not working | Confirm EOA upgraded via EIP-7702 first |
Resources
- NPM:
@metamask/smart-accounts-kit - Contracts:
metamask/delegation-framework@v1.3.0 - ERC Standards: ERC-4337, ERC-7710, ERC-7715, ERC-7579
- MetaMask Flask: https://metamask.io/flask
Version Info
- Toolkit: 0.3.0
- Delegation Framework: 1.3.0
- Breaking Change: Function call scope defaults to no native token transfer
For detailed documentation, see the reference files in the /references directory.
相关推荐
专题
+ 收藏
+ 收藏
+ 收藏
+ 收藏
+ 收藏
+ 收藏
最新数据
相关文章
阿里云大模型服务平台百炼新人免费额度如何申请?申请与使用免费额度教程及常见问题解答
办公 AI 工具 OpenClaw 部署 Windows 系统一站式教程
Qwen3.6 正式发布!阿里云百炼同步开启“AI大模型节省计划”超值优惠
【新手零难度操作 】OpenClaw 2.6.4 安装误区规避与快速使用指南(包含最新版安装包)
OpenClaw 2.6.4 可视化部署 打造个人 AI 数字员工(包含最新版安装包)
【小白友好!】OpenClaw 2.6.4 本地 AI 智能体快速搭建教程(内有安装包)
零基础部署 OpenClaw v2.6.2,Windows 系统完整教程
【适合新手的】零基础部署 OpenClaw 自动化工具教程
开发者们的第一台自主进化的“爱马仕”来了
极简部署 OpenClaw 2.6.2 本地 AI 智能体快速启用(含最新版安装包)
AI精选
