SDK
ensureKeyCached
A session you granted on Ethereum via grantSession is registered in the Keystore on L1. For another chain to honor that session, the registry state has to be mirrored to an L2 cache on that chain. ensureKeyCached does that.
This page is about the Ethereum → Base path specifically. Sessions granted on BNB Smart Chain, the SDK default, live in that chain's standalone Keystore and do not use this flow. On an L2 execution network, grantSession and revokeSession submit the proof into the L2 cache themselves; syncSessionToCache below runs it on its own.
It's idempotent: if the L2 cache already has the key, it returns immediately. Otherwise it waits for the L2 to anchor past the relevant L1 block, then submits a storage proof.
The proof is built at the L1 block the L2 anchors, which can be a hundred blocks behind the L1's head, so l1Client must point at an RPC that serves eth_getProof that far back. syncSessionToCache picks one for you from the registry network's proofRpcUrls.
Call it yourself before the first action on an L2; execute does not call it for you. Base is a verification target only: it hosts a cache and no relay, so BASE cannot be passed to createClient.
import { ensureKeyCached, ETHEREUM, BASE } from "@altananetwork/sdk";
import { createPublicClient, createWalletClient, http } from "viem";
import { mainnet, base } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";
const l1Client = createPublicClient({ chain: mainnet, transport: http(ETHEREUM.publicRpcUrl) });
const l2Client = createPublicClient({ chain: base, transport: http(BASE.publicRpcUrl) });
// The L2 wallet client pays L2 gas to submit the proof. This can be ANY
// account with L2 native ETH — your own EOA, a backend relayer, a per-user
// funded address, etc. The proof is permissionless; no privilege is granted.
const l2WalletClient = createWalletClient({
account: privateKeyToAccount(relayerKey),
chain: base,
transport: http(BASE.publicRpcUrl),
});
await ensureKeyCached({
l1Client,
l2Client,
l2WalletClient,
l1KeyStore: ETHEREUM.keyStore,
l2Cache: BASE.keyStoreCache,
user: session.walletAddress,
publicKey: session.publicKey,
onStatus: (status) => {
// "cache-hit" | "waiting-for-anchor" | "submitting-proof" | "done"
console.log(status);
},
});
// Session is now valid on Base. Subsequent agent actions are instant.What it does
- Reads
isValidKey(user, keyId)on the L2 cache. Iftrue, returns immediately (cache-hit). - Otherwise polls the L2's
L1Blockpredeploy until it points to an L1 block that contains the registration (waiting-for-anchor). Base anchors ~1–3 min behind L1. - Fetches an
eth_getProofagainst L1 for the packed Key storage slot, RLP-encodes the L1 block header, and submitspopulateKey(...)to the L2 cache (submitting-proof). - Reads the cache back and resolves with the populated
CachedKey(done).
The first cross-chain action on a given chain pays this cost once. After the cache is populated, the L2 reads it locally without further L1 round-trips.
Who pays L2 gas
The submitter of populateKey pays. The op is permissionless on the contract, so anyone can land a valid proof, but someone has to send the L2 tx. Practically:
- A relayer EOA you control. Simplest in v0. Fund a single address on each L2 and have your backend submit proofs on demand.
- The user themselves, if they already hold L2 native ETH. Pass their
WalletClient. - A future bundler-batched flow that includes
populateKeyas the first call of the L2 userOp. Not wired intoexecuteyet.
There's no on-protocol relayer. The cache contract is just a verifier.
Parameters
function ensureKeyCached(args: EnsureKeyCachedArgs): Promise<CachedKey>;
type EnsureKeyCachedArgs = {
/** Public client on the L1 chain (Ethereum). Used for eth_getProof + block lookup. */
l1Client: PublicClient;
/** Public client on the L2 chain. Used for L1Block read + receipt wait. */
l2Client: PublicClient;
/** Wallet client on the L2 chain — the relayer that pays L2 gas. */
l2WalletClient: WalletClient;
/** L1 Keystore address. From ETHEREUM.keyStore. */
l1KeyStore: Address;
/** L2 cache address. From BASE.keyStoreCache. */
l2Cache: Address;
/** Wallet whose key is being mirrored — the smart account that registered on L1. */
user: Address;
/** SEC1-encoded public key bytes for the session being mirrored. */
publicKey: Hex;
/** Progress callback for the four lifecycle states. */
onStatus?: (status: EnsureKeyCachedStatus) => void;
/** Poll cadence while waiting for L2 to anchor. Default 3s. */
anchorPollIntervalMs?: number;
/** Max wait for the L1 anchor. Default 30 minutes. */
anchorTimeoutMs?: number;
};
type EnsureKeyCachedStatus =
| "cache-hit"
| "waiting-for-anchor"
| "submitting-proof"
| "done";Returns
type CachedKey = {
publicKey: Hex;
revoked: boolean;
expiry: number; // unix seconds, 0 = never expires
isRoot: boolean;
sourceBlockHash: Hex;
sourceBlockNumber: bigint;
};The sourceBlockHash / sourceBlockNumber fields record which L1 block the cache state was proven against, useful for monitoring how stale the L2 view is.
syncSessionToCache
On an L2 execution network the SDK submits proofs itself: grantSession proves the new Keystore entry into the L2 cache as its third step, and revokeSession proves the revocation. Both report the outcome in result.cache. client.syncSessionToCache is the same operation on its own, for a grant made with populateCache: false or for refreshing an entry:
const synced = await client.syncSessionToCache({
wallet,
signer: admin, // the proof is a wallet call the admin signs
session, // or the session's public key
afterL1Block: 11_668_483n, // optional: wait until the L2 anchors this L1 block or later
maxAttempts: 3, // anchors to try when a proof misses its window (default 3)
onStatus: (s, { attempt, l1BlockNumber }) => console.log(s, attempt, l1BlockNumber),
});
synced.status; // "CONFIRMED" | "FAILED" | "PENDING", plus callsId / transactionHash
synced.cachedKey; // the cache entry after the proof
synced.l1BlockNumber; // the L1 block the proof was built againstDifferences from ensureKeyCached:
- No relayer EOA. The proof is executed as a wallet call through the L2's relay and paid in the L2's native token by the wallet.
- Always submits. It never returns early on a cache hit, so it propagates revocations too.
- Follows the anchor. The cache accepts a proof for the L1 block the L2 anchors at inclusion time. When the anchor moves between building and inclusion, the call rebuilds against the new anchor, up to
maxAttempts.
The exported building blocks it uses are readL1Anchor, waitForL1Anchor, buildPopulateKeyCall and computeKeyPackedSlot, for integrations that submit the proof some other way.
Related helpers
ensureKeyCached is the function most apps want. The lower-level helpers are also exported for cases where you want explicit control:
// Always submit a fresh proof regardless of cache state. Use to propagate a
// revocation you just landed on L1 without waiting for the next cache miss.
syncKeyToL2(args): Promise<{ txHash: Hex; cachedKey: CachedKey }>;
// Pure read against the L2 cache. Returns zeroed struct if not yet populated.
readCachedKey(l2Client, l2Cache, user, keyId): Promise<CachedKey>;
// Pure read: cache has the key AND it's not revoked AND not expired.
// Equivalent to KeyStoreCache.isValidKey(user, keyId).
isCachedKeyValid(l2Client, l2Cache, user, keyId): Promise<boolean>;
// The L1 block the L2 currently anchors (hash + number), from L1Block.
readL1Anchor(l2Client): Promise<L1Anchor>;
// Poll until the L2 anchors targetL1Block or later.
waitForL1Anchor({ l1Client, l2Client, targetL1Block, pollIntervalMs?, timeoutMs? }): Promise<L1Anchor>;
// The populateKey call (to, data, value) proving (user, publicKey) at the
// anchored block: RLP header, account proof, storage proof. Send it from
// any funded account, or as a wallet call.
buildPopulateKeyCall({ l1Client, l2Client, l1KeyStore, l2Cache, user, publicKey, anchor? }): Promise<PopulateKeyCall>;
// The KeyStore storage slot a proof covers (mirrors KeyStoreCacheOPStack.keyPackedSlot).
computeKeyPackedSlot(user, keyId): Hex;Notes
- L1 Keystore is the source of truth. The L2 cache is only as fresh as the last proof submitted. Revocations on L1 do not propagate automatically; until someone submits a post-revocation proof, the L2 cache still reports the key as valid. Call
syncKeyToL2right afterrevokeSessionto push the revocation through. Do not expectensureKeyCachedto handle it: it returns early whenever the cache reports the key as valid, which is precisely the stale state left behind by a revocation, so it will never submit the proof that would correct it. - Monotonic revoke is enforced cache-side too. Once the cache observes
revoked=true, it cannot be flipped back to live by a later proof: even one against an older L1 block. This prevents replay attacks during the L1→L2 anchor window. - The cache is permissionless. Any address can submit a proof for any
(user, publicKey)pair. There is no admin and no relayer registry. - One cache per chain. For Base, use
BASE.keyStoreCache; for an L2 execution network,keyStoreCacheOf(network). See the Chains table.