SDK
grantSession
Grant a scoped session key for a wallet. The admin signer authorizes the session onchain; from that point forward the session can act on the wallet within its permissions, enforced onchain.
import { createClient, BNB, signerFromPrivateKey } from "@altananetwork/sdk";
const client = createClient({ chains: [BNB] });
const admin = signerFromPrivateKey("0x...");
const wallet = await client.createWallet({ signer: admin });
const session = await client.grantSession({
wallet,
signer: admin,
permissions: {
calls: [{ to: "0xUniswapRouter..." }],
spend: [{
limit: 50n * 10n ** 18n, // 50 USDT. Note: 18 decimals on BNB Chain.
period: "day",
token: "0xUSDT...",
}],
},
expiry: Math.floor(Date.now() / 1000) + 7 * 24 * 60 * 60, // 7 days
});
console.log(session.transactionHash);
// Hand `session` to whichever process runs the agent.grantSession authorizes the session on one chain: the one you name with chainId, or the client's default chain. It resolves once the wallet's account on that chain has authorized the key, with the transaction in transactionHash, and throws when the account did not authorize it.
To authorize the same session on several chains in one call, pass chainIds:
const session = await client.grantSession({
wallet,
signer: admin,
permissions,
expiry,
chainIds: [56, 42220],
});
if (session.status !== "granted") {
console.error(session.legs.filter((leg) => leg.status === "FAILED"));
}A grant on several chains does not throw for a chain that failed. status is granted only when every chain went through, and legs says how each one went.
Registering the session key
The session's public key is written to Keystore via the Controller, batched into the same userOp — controlled by the register flag, on by default. Registration is what makes the key's authority provable to anyone:
- Third parties can verify it on-chain — other agents, counterparties, dashboards, and compliance tools can check the key's authority, expiry, and revocation state (
getKeys/isValidKey, or the MCPverify_authorizationtool) without trusting you or Altana. Reads are free and unlimited. - Keys are discoverable — a wallet's keys can be enumerated from chain for recovery and auditing.
- Grants and revokes leave an on-chain trail — timestamped, monotonic revocation.
- (Ethereum) one registration extends across chains via
ensureKeyCached.
To skip registration (and its one-time fee), pass register: false. The session works the same, but Keystore readers like verify_authorization won't see it. Register it later at any time:
await client.registerSessionKey({ wallet, signer: admin, session });Parameters
client.grantSession(opts: ClientGrantSessionOptions): Promise<GrantSessionResult>;
type ClientGrantSessionOptions = {
wallet: Wallet;
signer: Signer; // the wallet's admin signer
permissions: SessionPermissions;
/** Unix epoch seconds. Most apps use Date.now()/1000 + N. */
expiry: number;
/** Bring your own session signer, or omit to let the SDK generate one. */
sessionSigner?: Signer;
/** Register the key in Keystore (default true). */
register?: boolean;
/**
* L2s only: prove the Keystore entry into each L2 cache (default true). The proof runs on
* after grantSession returns; "await" waits for it; false skips it.
*/
populateCache?: boolean | "await";
/** Progress, per chain where it applies. */
onStatus?: (status: "registry-write" | "registry-write-pending" | "registry-write-failed"
| "account-authorization" | "cache-sync" | "done",
detail?: { chainId: number; step?: "root" | "session"; reason?: string }) => void;
/**
* The token(s) the session may pay relay fees in, one address or a list.
* Each gets a daily spend cap added to the session (default one whole
* token; see feeSpendLimit), and the grant itself pays its fee with the
* first one the wallet holds. Omitted, the relay charges whichever
* accepted token the wallet holds.
*/
feeToken?: Address | readonly Address[];
/** The cap added for each fee token, in its smallest unit. Default one whole token per day. */
feeSpendLimit?: bigint;
/** The chain to grant on. Defaults to the client's default chain. */
chainId?: number;
/** Grant on several chains in one call. Use it instead of chainId. */
chainIds?: number[];
};Pass chainId or chainIds, not both.
A session pays relay fees only out of its spend caps: with no feeToken on an
execute, the SDK charges the capped token the relay accepts that the wallet
holds the most of. Pass feeToken here (one address or a list) so a session can pay
from a stablecoin the wallet holds (on Celo: USDC, USDT); the
returned Session.permissions carries the added caps, and execute must be
called with that session, not with the permissions you passed in. A token the
relay does not accept on any of the chains granted on is refused.
See Sessions for the full permission shape reference.
Returns
type GrantSessionResult = Session & {
keyId: Hex; // the key's id in the Keystore
keyHash: Hex; // the key's hash on the account
transactionHash?: Hex; // the account authorization, on a one-chain grant
status: "granted" | "failed";
legs: SessionLeg[]; // one per step per chain; see revokeSession for the shape
registration: Promise<SessionLeg[]>; // the registry legs once the Keystore write is in
cacheSync: Promise<SessionLeg[]>; // the cache legs once their proofs are in
};
type Session = {
walletAddress: Address;
signer: Signer; // session key. Agent signs with this.
publicKey: Hex;
permissions: SessionPermissions;
expiry: number;
};GrantSessionResult is a Session, so it goes anywhere a Session goes: execute, revokeSession, registerSessionKey, signOrder.
transactionHash is the transaction in which the account authorized the key, on a grant to one chain. A grant with chainIds has one per chain, on the account legs.
status is either granted or failed. It is granted only when every leg confirmed or had nothing to do; any failed leg makes it failed, and legs says which chain and which step. Each leg carries its own transactionHash, which is the receipt to record for the registration fee. Granting again with the same sessionSigner is safe: a key already valid in the Keystore is not written or charged twice.
On a grant to one chain, the account leg decides whether the call throws. When it did not confirm, the error is the one the relay or the chain raised, with its cause intact, or Session grant did not confirm: status=<STATUS> (relay code <N>) when the relay answered with a status other than confirmed. On an L2 the Keystore write and the cache proof run after the account has authorized the key, so a session returned with status: "failed" is live on the account: legs, registration and cacheSync say which later step is left, and granting again with the same sessionSigner finishes it.
What lands onchain
For every chain you grant on, the SDK runs up to three legs:
- Account. The session authorized on the wallet's smart account on that chain, through its relay, the fee paid in an accepted token the wallet holds there (or the
feeTokenyou name). The chains run in parallel. On an L2 this goes first and waits for nothing, so the session is usable as soon as the call returns. - Registry. One Keystore write per Keystore chain:
registerKey(session), preceded byinitialRegisterKey(admin)on the wallet's first write, skipped when the key is already valid there. On a chain with its own Keystore (BNB, Ethereum, Celo) it rides in that chain's account leg, in the same userOp, so the registration and the authorization land atomically. For an L2 it is a separate write on the L1, through the L1 relay, started once the account has authorized the key: its leg readsPENDINGwhen the call returns, andregistrationresolves with it. The relay pays that write, registration fee and relay fee, from the wallet's balance on the L2 being granted on; ETH the wallet holds on the Keystore chain is not used. The leg carriesfundedFromChainIdandsourceTransactionHash. Two L2s behind the same L1 share one write. - Cache. On an L2, the proof of the Keystore entry into its KeyStoreCache, as a wallet call through the same relay (see
syncSessionToCache). It follows the Keystore write. Skipped withregister: falseorpopulateCache: false.
On an L2, grantSession does not make the user wait for the Keystore write or the proof: it returns as soon as the account authorization is confirmed, which is when the session is usable (nothing in execute reads the Keystore or the cache). The Keystore write confirms shortly after. The proof can only be built once the L2 has anchored the L1 block of that write, which takes 15 to 30 minutes. The registry and cache legs read PENDING meanwhile, and registration and cacheSync resolve with the finished legs. Neither rejects; a step that fails is a FAILED leg there. If your process exits first, the session still works, and granting again with the same sessionSigner finishes what is left (syncSessionToCache submits a proof on its own). Pass populateCache: "await" to return only once every proof is in.
The payment for a Keystore write is held on the L2 before the relay carries the write to the L1. If the relay is slow there, the SDK does not give up while that payment is held: it reports registry-write-pending once, keeps waiting for up to 65 minutes, and then goes on with the session key and the proof. The relay either completes the write or returns the payment. If your process stopped in the meantime, registerSessionKey registers what is missing and proves it into the cache.
What it costs
client.quoteGrantSession takes the same options and returns one line per leg plus the payers' balances, without signing or sending anything. On BNB, Ethereum and Celo the registration is part of the account line: its value is the registration fee, twice on a wallet's first grant. On an L2 the registry line is paid from the L2, carries fundedFromChainId and is charged to the wallet's balance on that chain, not on the Keystore chain. A balance's needed is the fee plus the registration fee, not the registration fee alone, and it is stated in the token the relay priced that leg in (see revokeSession). A cache proof needs a Keystore entry to prove: after the first grant the quote proves one of the wallet's existing keys, which costs the same; on a first grant there is none yet, so those lines come back deferred (priced once the registry write lands) and complete is false.
Persisting a session
A Session embeds the session's private key and bigint spend limits, so never JSON.stringify it — that throws on the bigints, and when it doesn't, it writes the secret into your storage while dropping the signing capability. The supported pattern splits the two halves:
import { generatePrivateKey } from "viem/accounts";
import { signerFromPrivateKey, serializeSession, deserializeSession } from "@altananetwork/sdk";
// Grant: bring your own key, and store it where you keep secrets.
const sessionKey = generatePrivateKey();
await secrets.save("agent-1.key", sessionKey); // keychain, KMS, env — yours
const session = await client.grantSession({
wallet, signer: admin,
sessionSigner: signerFromPrivateKey(sessionKey),
permissions, expiry,
});
await db.save("agent-1.session", serializeSession(session)); // JSON-safe, contains NO secret
// Restore — any process, any time:
const restored = deserializeSession(
await db.load("agent-1.session"),
signerFromPrivateKey(await secrets.load("agent-1.key")),
);serializeSession keeps walletAddress, publicKey, permissions (spend limits as decimal strings), and expiry — the values that must match the grant at execute time. deserializeSession restores the bigints and refuses a key that doesn't match the session's registered publicKey, so a mixed-up key fails loudly at restore instead of opaquely at execute.
If you omit sessionSigner, the SDK generates a key that exists only in the current process's memory and warns on the console: lose it (a crash, the script ending) and the on-chain authorization it backs is permanently unusable — revoke-and-regrant is the only exit.
Notes
- Persist both halves: the serialized session (above) and the key, separately. An agent needs
permissions + expiryto execute, not just the key. permissions.callsomitted = unrestricted. Always set bothcallsandspendunless you specifically want an open-scope session.- This is the call that costs the user money. It pays a one-time Keystore registration fee, and on a wallet's very first admin action it pays that fee twice, because
initialRegisterKeyfor the admin is prepended into the same userOp. Record the legs'transactionHashif you show users a history of what they were charged for. Passregister: falseto skip the registration fee entirely.