For AI agents: a documentation index is available at /llms.txt. A markdown version of this page is available at the same URL with .md appended (or via Accept: text/markdown).
Skip to main content

Delegation API reference

The following API methods are related to creating and managing delegations.

createCaveatBuilder​

Builds an array of caveatsCaveat A restriction attached to a delegation that limits how delegated authority can be used..

Parameters​

NameTypeRequiredDescription
environmentSmartAccountsEnvironmentYesEnvironment to resolve the smart contracts for the current chain.
configCaveatBuilderConfigNoConfiguration for CoreCaveatBuilder.

Example​

import { createCaveatBuilder } from '@metamask/smart-accounts-kit/utils'
import { getSmartAccountsEnvironment } from '@metamask/smart-accounts-kit'
import { sepolia } from 'viem/chains'

const environment = getSmartAccountsEnvironment(sepolia.id)
const caveatBuilder = createCaveatBuilder(environment)

Allow empty caveats​

To create an empty caveat collection, set the CaveatBuilderConfig.allowInsecureUnrestrictedDelegation to true.

example.ts
import { createCaveatBuilder } from '@metamask/smart-accounts-kit/utils'
import { getSmartAccountsEnvironment } from '@metamask/smart-accounts-kit'
import { sepolia } from 'viem/chains'

const environment = getSmartAccountsEnvironment(sepolia.id)
const caveatBuilder = createCaveatBuilder(environment, {
allowInsecureUnrestrictedDelegation: true,
})

createDelegation​

Creates a delegation with a specific delegateDelegate account The account that receives delegated authority and can redeem a delegation under its constraints..

Parameters​

NameTypeRequiredDescription
fromHexYesThe address that is granting the delegation.
toHexYesThe address to which the delegation is being granted.
scopeScopeConfigYesThe scope of the delegation that defines the initial authority. See delegation scopes for the full list of scope types and their parameters.
environmentSmartAccountsEnvironmentYesThe environment used by the toolkit to define contract addresses for interacting with the Delegation FrameworkDelegation Framework A set of audited smart contracts that handle smart account creation, the delegation lifecycle, and caveat enforcement. contracts.
caveatsCaveatsNoCaveats that further refine the authority granted by the scope. See caveats reference for the full list of caveat types and their parameters.
parentDelegationDelegation | HexNoThe parent delegation or its corresponding hex to create a delegation chain. Mutually exclusive with parentPermissionContext.
parentPermissionContextPermissionContextNoParent chain as Hex or as decoded Delegation values (leaf first). Mutually exclusive with parentDelegation.
saltHexNoThe salt for generating the delegation hash. This helps prevent hash collisions when creating identical delegations.

Example​

import {
createDelegation,
getSmartAccountsEnvironment,
ScopeType,
} from '@metamask/smart-accounts-kit'
import { sepolia } from 'viem/chains'
import { parseEther } from 'viem'

const delegation = createDelegation({
// Address that is granting the delegation
from: '0x7E48cA6b7fe6F3d57fdd0448B03b839958416fC1',
// Address to which the delegation is being granted
to: '0x2B2dBd1D5fbeB77C4613B66e9F35dBfE12cB0488',
// Alternatively you can use environment property of MetaMask smart account.
environment: getSmartAccountsEnvironment(sepolia.id),
scope: {
type: ScopeType.NativeTokenTransferAmount,
// 0.001 ETH in wei format.
maxAmount: parseEther('0.001'),
},
})

createOpenDelegation​

Creates an open delegationOpen delegation A delegation that leaves the delegate unspecified, allowing any account to redeem it. that can be redeemed by any delegate.

Parameters​

NameTypeRequiredDescription
fromHexYesThe address that is granting the delegation.
scopeScopeConfigConditionalDefines the delegation authority. See delegation scopes for supported types and parameters. Required for a root open delegation. Optional when either parentDelegation or parentPermissionContext is set; if omitted, authority is inherited from the parent chain.
environmentSmartAccountsEnvironmentYesThe environment used by the toolkit to define contract addresses for interacting with the Delegation FrameworkDelegation Framework A set of audited smart contracts that handle smart account creation, the delegation lifecycle, and caveat enforcement. contracts.
caveatsCaveatsNoCaveats that further refine the authority granted by the scope. See caveats reference for the full list of caveat types and their parameters.
parentDelegationDelegation | HexNoThe parent delegation or its corresponding hex to create a delegation chain. Mutually exclusive with parentPermissionContext.
parentPermissionContextPermissionContextNoParent chain as Hex or as decoded Delegation values (leaf first). Mutually exclusive with parentDelegation.
saltHexNoThe salt for generating the delegation hash. This helps prevent hash collisions when creating identical delegations.

Example​

import {
createOpenDelegation,
getSmartAccountsEnvironment,
ScopeType,
} from '@metamask/smart-accounts-kit'
import { sepolia } from 'viem/chains'
import { parseEther } from 'viem'

const delegation = createOpenDelegation({
// Address that is granting the delegation
from: '0x7E48cA6b7fe6F3d57fdd0448B03b839958416fC1',
// Alternatively you can use environment property of MetaMask smart account.
environment: getSmartAccountsEnvironment(sepolia.id),
scope: {
type: ScopeType.NativeTokenTransferAmount,
// 0.001 ETH in wei format.
maxAmount: parseEther('0.001'),
},
})

createExecution​

Creates an ExecutionStruct instance.

Parameters​

NameTypeRequiredDescription
targetAddressNoAddress of the contract or recipient that the call is directed to.
valuebigintNoValue of native tokens to send along with the call in wei.
callDataHexNoEncoded function data or payload to be executed on the target address.

Example​

import { createExecution } from '@metamask/smart-accounts-kit'
import { parseEther } from 'viem'

// Creates an ExecutionStruct to transfer 0.01 ETH to
// 0xe3C818389583fDD5cAC32f548140fE26BcEaE907 address.
const execution = createExecution({
target: '0xe3C818389583fDD5cAC32f548140fE26BcEaE907',
// 0.01 ETH in wei
value: parseEther('0.01'),
callData: '0x',
})

decodeDelegations​

Decodes an ABI-encoded hex string to an array of delegations.

Use decodeDelegations when working with a permission context that contains a delegation chain, such as the context property returned by requestExecutionPermissions response.

Parameters​

NameTypeRequiredDescription
encodedHexYesThe ABI encoded hex string to decode.

Example​

import { decodeDelegations } from '@metamask/smart-accounts-kit/utils'

const delegations = decodeDelegations('0x7f0db33d..c06aeeac')

decodeDelegation​

Decodes an ABI-encoded hex string to a single delegation.

Use decodeDelegation when you have a single encoded delegation rather than an encoded delegation chain.

Parameters​

NameTypeRequiredDescription
encodedHexYesThe ABI-encoded hex string to decode.

Example​

import { decodeDelegation } from '@metamask/smart-accounts-kit/utils'

const delegation = decodeDelegation('0x7f0db33d..c06aeeac')

decodeCaveat​

Decodes a caveat's encoded terms.

Throws an error if the caveat enforcer is not a known enforcer in SmartAccountsEnvironment.

Parameters​

NameTypeRequiredDescription
caveatCaveatYesThe caveatCaveat A restriction attached to a delegation that limits how delegated authority can be used. object containing an enforcer address and ABI-encoded terms.
environmentSmartAccountsEnvironmentYesEnvironment to resolve the caveat enforcerCaveat enforcer A smart contract that enforces delegation rules by validating caveat conditions during redemption hooks. addresses.

Example​

import { decodeCaveat } from '@metamask/smart-accounts-kit/utils'
import { delegation } from './config.ts'

const environment = delegation.environment

// Decode the first caveat from the delegation.
const decodedCaveat = decodeCaveat({
caveat: delegation.caveats[0],
environment,
})

// Output:
// {
// type: 'erc20TransferAmount',
// tokenAddress: '0x1c7D...7238',
// maxAmount: 10000000n,
// }

decodeRevertData​

Decodes raw ABI-encoded revert data into a DecodedRevertReason.

Tries standard Solidity errors, and known Delegation FrameworkDelegation Framework A set of audited smart contracts that handle smart account creation, the delegation lifecycle, and caveat enforcement. ABIs, then falls back to decoding printable ASCII bytes.

Returns undefined if the data could not be decoded.

Parameters​

NameTypeRequiredDescription
rawDataHexYesThe raw ABI-encoded revert data.

Example​

import { decodeRevertData } from '@metamask/smart-accounts-kit/utils'

const decoded = decodeRevertData('0x08c379a0...')

decodeRevertReason​

Extracts revert data from an error object and decodes it using decodeRevertData. Use this when you catch an error from any Delegation FrameworkDelegation Framework A set of audited smart contracts that handle smart account creation, the delegation lifecycle, and caveat enforcement. interaction and want to decode the revert reason.

Returns undefined if no revert data is found in the error.

Parameters​

NameTypeRequiredDescription
errorunknownYesThe error object to extract and decode revert data from.

Example​

This example assumes you have a delegation signed by the delegatorDelegator account The account that creates and signs a delegation to grant limited authority to another account..

import { ExecutionMode } from '@metamask/smart-accounts-kit'
import { DelegationManager } from '@metamask/smart-accounts-kit/contracts'
import { decodeRevertReason } from '@metamask/smart-accounts-kit/utils'

try {
await DelegationManager.execute.redeemDelegations({
delegations: [[signedDelegation]],
modes: [ExecutionMode.SingleDefault],
executions: [[execution]],
})
} catch (error) {
const decoded = decodeRevertReason(error)
if (decoded) {
console.log(decoded.message)
}
}

deploySmartAccountsEnvironment​

Deploys the Delegation FrameworkDelegation Framework A set of audited smart contracts that handle smart account creation, the delegation lifecycle, and caveat enforcement. contracts to an EVM chain.

Parameters​

NameTypeRequiredDescription
walletClientWalletClientYesViem Wallet Client to deploy the contracts.
publicClientPublicClientYesViem Public Client to interact with the given chain.
chainChainYesViem Chain where you wish to deploy the Delegation Framework contracts.
deployedContracts{ [contract: string]: Hex }NoAllows overriding specific contract addresses when calling the function. For example, if certain contracts have already been deployed on the target chain, their addresses can be provided directly to the function.

Example​

import { deploySmartAccountsEnvironment } from '@metamask/smart-accounts-kit/utils'
import { walletClient, publicClient } from './config.ts'
import { sepolia as chain } from 'viem/chains'

const environment = await deploySmartAccountsEnvironment(walletClient, publicClient, chain)

Inject deployed contracts​

Once the contracts are deployed, you can use them to override the delegator environment using overrideDeployedEnvironment.

example.ts
import { walletClient, publicClient } from './config.ts'
import { sepolia as chain } from 'viem/chains'
import { SmartAccountsEnvironment } from '@metamask/smart-accounts-kit'
import {
overrideDeployedEnvironment,
deploySmartAccountsEnvironment,
} from '@metamask/smart-accounts-kit/utils'

const environment: SmartAccountsEnvironment = await deploySmartAccountsEnvironment(
walletClient,
publicClient,
chain
)

overrideDeployedEnvironment(chain.id, '1.3.0', environment)

disableDelegation​

Encodes the calldata for disabling a delegation.

Parameters​

NameTypeRequiredDescription
delegationDelegationYesThe delegation to be disabled.

Example​

import { DelegationManager } from '@metamask/smart-accounts-kit/contracts'
import { delegation } from './delegation.ts'

const disableDelegationData = DelegationManager.encode.disableDelegation({
delegation,
})

enableDelegation​

Encodes the calldata to enable a disabled delegation.

Parameters​

NameTypeRequiredDescription
delegationDelegationYesThe delegation to be enabled.

Example​

import { DelegationManager } from '@metamask/smart-accounts-kit/contracts'

const enableDelegationData = DelegationManager.encode.enableDelegation({
delegation, // Already disabled delegation.
})

encodeDelegations​

Encodes an array of delegations to an ABI-encoded hex string.

The delegations must be ordered from leaf to root delegation, with each delegation's authority referencing the hash of the next entry in the array.

Parameters​

NameTypeRequiredDescription
delegationsDelegation[]YesThe delegation chain to encode, ordered from leaf to root delegation.

Example​

import { encodeDelegations } from '@metamask/smart-accounts-kit/utils'
import { delegation } from './delegation.ts'

const encodedDelegations = encodeDelegations([delegation])

encodeDelegation​

Encodes a single delegation to an ABI-encoded hex string.

Parameters​

NameTypeRequiredDescription
delegationDelegationYesThe delegation to be encoded.

Example​

import { encodeDelegation } from '@metamask/smart-accounts-kit/utils'
import { delegation } from './delegation.ts'

const encodedDelegation = encodeDelegation(delegation)

hashDelegation​

Returns the delegation hash.

Parameters​

NameTypeRequiredDescription
inputDelegationYesThe delegation object to hash.

Example​

import { hashDelegation } from '@metamask/smart-accounts-kit/utils'
import { delegation } from './config.ts'

const delegationHash = hashDelegation(delegation)

getSmartAccountsEnvironment​

Resolves the SmartAccountsEnvironment for a chain.

Parameters​

NameTypeRequiredDescription
chainIdnumberYesThe chain ID of the network for which the SmartAccountsEnvironment should be resolved.
versionSupportedVersionNoSpecifies the version of the Delegation FrameworkDelegation Framework A set of audited smart contracts that handle smart account creation, the delegation lifecycle, and caveat enforcement. contracts to use. If omitted, the latest supported version will be used by default.

Example​

import { getSmartAccountsEnvironment } from '@metamask/smart-accounts-kit'
import { sepolia } from 'viem/chains'

const environment = getSmartAccountsEnvironment(sepolia.id)

generateSalt​

Generates a random 32-byte hex salt for creating delegations. This helps prevent hash collisions when creating identical delegations.

Example​

import { generateSalt } from '@metamask/smart-accounts-kit/utils'

const salt = generateSalt()

overrideDeployedEnvironment​

Overrides or adds the SmartAccountsEnvironment for a chain and supported version.

Parameters​

NameTypeRequiredDescription
chainIdnumberYesThe chain ID of the network for which the SmartAccountsEnvironment should be overridden.
versionSupportedVersionYesThe version of the Delegation FrameworkDelegation Framework A set of audited smart contracts that handle smart account creation, the delegation lifecycle, and caveat enforcement. contracts to override for the specified chain.
environmentSmartAccountsEnvironmentYesThe environment containing contract addresses to override for the given chain and version.

Example​

import { environment } from './environment.ts'
import { overrideDeployedEnvironment } from '@metamask/smart-accounts-kit/utils'
import { sepolia } from 'viem/chains'

overrideDeployedEnvironment(sepolia.id, '1.3.0', environment)

redeemDelegations​

Encodes calldata for redeeming delegations. This method supports batch redemption, allowing multiple delegations to be processed within a single transaction.

Each inner delegation array must be ordered from leaf to root delegation, with each delegation's authority referencing the hash of the next entry in the array.

Parameters​

NameTypeRequiredDescription
delegationsDelegation[][]YesA nested collection representing chains of delegations. Each inner collection contains a chain of delegations to be redeemed, ordered from leaf to root delegation.
modesExecutionMode[]YesA collection specifying the execution mode for each corresponding delegation chain.
executionsExecutionStruct[][]YesA nested collection where each inner collection contains a list of ExecutionStruct objects associated with a specific delegation chain.

Example​

This example assumes you have a delegation signed by the delegatorDelegator account The account that creates and signs a delegation to grant limited authority to another account..

import { createExecution, ExecutionMode } from '@metamask/smart-accounts-kit'
import { DelegationManager } from '@metamask/smart-accounts-kit/contracts'
import { zeroAddress } from 'viem'

const data = DelegationManager.encode.redeemDelegations({
delegations: [[signedDelegation]],
modes: [ExecutionMode.SingleDefault],
executions: [[execution]],
})

signDelegation​

Signs the delegation and returns the delegation signature.

Parameters​

NameTypeRequiredDescription
privateKeyHexYesThe private key to use for signing the delegation.
delegationOmit<Delegation, "signature">YesThe unsigned delegation object to sign.
chainIdnumberYesThe chain ID on which the delegation manager is deployed.
delegationManager0x${string}YesThe address of the Delegation Manager.
namestringNoThe name of the domain of the Delegation Manager. The default is DelegationManager.
versionstringNoThe version of the domain of the Delegation Manager. The default is 1.
allowInsecureUnrestrictedDelegationbooleanNoWhether to allow insecure unrestricted delegation with no caveatsCaveat A restriction attached to a delegation that limits how delegated authority can be used.. The default is false.

Example​

import { signDelegation } from '@metamask/smart-accounts-kit'
import { privateKey, delegation, delegationManager } from './config.ts'
import { sepolia } from 'viem/chains'

const signature = signDelegation({
privateKey,
delegation,
chainId: sepolia.id,
delegationManager,
})

toDelegationStruct​

Converts a Delegation object to a DelegationStruct object.

Use when you need to pass a delegation directly to a Delegation FrameworkDelegation Framework A set of audited smart contracts that handle smart account creation, the delegation lifecycle, and caveat enforcement. contract call or other onchain interaction that expects the struct form.

Parameters​

NameTypeRequiredDescription
delegationDelegationYesThe delegation to convert.

Example​

import { toDelegationStruct } from '@metamask/smart-accounts-kit/utils'
import { delegation } from './delegation.ts'

const delegationStruct = toDelegationStruct(delegation)