# wallet-intent

Builds, signs and sends transactions for MOSS accounts without the wallet: from your server, a script or an agent.
A MOSS account is an EIP-7702 smart account, and its transactions are intents that the relay submits. Use it to act
for a user who has granted your key permissions, to run your own accounts, and to verify MOSS signatures.
See [Executing on Your Server](https://moss.megaeth.com/developers/concepts/permissions#executing-on-your-server).

```bash title="pnpm"
pnpm add @megaeth-labs/wallet-intent viem
```

```bash title="npm"
npm install @megaeth-labs/wallet-intent viem
```

```bash title="yarn"
yarn add @megaeth-labs/wallet-intent viem
```

Most functions take a viem `Client`. For sending, point it at the relay; for reading and verifying, any MegaETH RPC
works. `Address`, `Hex`, `Call` and `Client` in the types below are viem's.

```ts title="Setup"
import { createClient, createPublicClient, http } from 'viem';
import { megaethTestnet } from 'viem/chains';

// Sends intents. Mainnet's relay is https://mainnet.megaeth.com/relay, with the megaeth chain.
export const relay = createClient({
    chain: megaethTestnet,
    transport: http('https://carrot.megaeth.com/relay'),
});

// Reads the chain and verifies signatures.
export const publicClient = createPublicClient({ chain: megaethTestnet, transport: http() });
```

## Accounts and Keys

### `Account.from`

Creates an account from its address, and optionally the keys you hold for it.

```ts title="Types"
Account.from: (parameters: string | { address: Hex; keys?: readonly Key[] }) => Account;

type Account = {
    address: Hex;
    keys?: readonly Key[];
    source: 'porto' | 'privateKey';
    sign?: (parameters: { hash: Hex }) => Promise<Hex>; // Only on privateKey accounts
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Account } from '@megaeth-labs/wallet-intent';

const user = Account.from('0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0');
```

### `Account.fromPrivateKey`

Creates an account from a secp256k1 private key, signing as the account's own root key.

```ts title="Types"
Account.fromPrivateKey: (privateKey: Hex, options?: { keys?: readonly Key[] }) => Account;

type Account = {
    address: Hex;
    keys?: readonly Key[];
    source: 'porto' | 'privateKey';
    sign?: (parameters: { hash: Hex }) => Promise<Hex>; // Only on privateKey accounts
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Account } from '@megaeth-labs/wallet-intent';

const treasury = Account.fromPrivateKey(process.env.TREASURY_PRIVATE_KEY as `0x${string}`);
```

### `Key.fromSecp256k1`

Creates a secp256k1 key from a private key, a public key or an address. A key with a private key can sign.
See [Executing on Your Server](https://moss.megaeth.com/developers/methods/calling-contracts/grant-permissions#executing-on-your-server).

```ts title="Types"
Key.fromSecp256k1: (parameters: FromSecp256k1Parameters) => Secp256k1Key;

type FromSecp256k1Parameters = {
    role?: 'admin' | 'session';
    expiry?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
} & ({ address: Hex } | { publicKey: Hex } | { privateKey: Hex });

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const serverKey = Key.fromSecp256k1({
    privateKey: process.env.SERVER_PRIVATE_KEY as `0x${string}`,
});
```

### `Key.fromP256`

Creates a P256 key from a private key.

```ts title="Types"
Key.fromP256: (parameters: FromP256Parameters) => P256Key;

type FromP256Parameters = {
    privateKey: Hex;
    role?: 'admin' | 'session';
    expiry?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type P256Key = BaseKey<'p256', () => Hex>;

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};

type AddressKey = BaseKey<'address', undefined>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const sessionKey = Key.fromP256({
    privateKey: process.env.SESSION_PRIVATE_KEY as `0x${string}`,
    role: 'session',
});
```

### `Key.createSecp256k1`

Creates a secp256k1 key with a new random private key.

```ts title="Types"
Key.createSecp256k1: (parameters?: CreateParameters) => Secp256k1Key;

type CreateParameters = {
    role?: 'admin' | 'session';
    expiry?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const key = Key.createSecp256k1({ role: 'session', expiry: Math.floor(Date.now() / 1000) + 60 * 60 });
```

### `Key.createP256`

Creates a P256 key with a new random private key.

```ts title="Types"
Key.createP256: (parameters?: CreateParameters) => P256Key;

type CreateParameters = {
    role?: 'admin' | 'session';
    expiry?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type P256Key = BaseKey<'p256', () => Hex>;

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};

type AddressKey = BaseKey<'address', undefined>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const key = Key.createP256({ role: 'session' });
```

### `Key.fromWebAuthnP256`

Creates a passkey from a WebAuthn credential. Signing with it asks the user's authenticator.

```ts title="Types"
Key.fromWebAuthnP256: (parameters: FromWebAuthnP256Parameters) => WebAuthnKey;

type FromWebAuthnP256Parameters = {
    credential: Pick<P256Credential, 'id' | 'publicKey'>; // From ox's WebAuthnP256
    rpId?: string;
    chainId?: number;
    expiry?: number;
    id?: Hex;
    permissions?: Permissions;
    role?: 'admin' | 'session';
    feeToken?: FeeToken | null;
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';
import { WebAuthnP256 } from 'ox';

const credential = await WebAuthnP256.createCredential({ name: 'Example' });
const passkey = Key.fromWebAuthnP256({ credential, role: 'admin' });
```

### `Key.fromHeadlessWebAuthnP256`

Creates a WebAuthn key from a raw P256 private key, which signs without an authenticator. For servers and tests.

```ts title="Types"
Key.fromHeadlessWebAuthnP256: (parameters: FromHeadlessWebAuthnP256Parameters) => WebAuthnKey;

type FromHeadlessWebAuthnP256Parameters = {
    privateKey: Hex;
    chainId?: number;
    expiry?: number;
    permissions?: Permissions;
    role?: 'admin' | 'session';
    feeToken?: FeeToken | null;
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const key = Key.fromHeadlessWebAuthnP256({
    privateKey: process.env.WEBAUTHN_PRIVATE_KEY as `0x${string}`,
});
```

### `Key.createHeadlessWebAuthnP256`

Creates a headless WebAuthn key with a new random private key.

```ts title="Types"
Key.createHeadlessWebAuthnP256: (parameters?: CreateParameters) => WebAuthnKey;

type CreateParameters = {
    role?: 'admin' | 'session';
    expiry?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const key = Key.createHeadlessWebAuthnP256();
```

### `Key.from`

Creates a key of any type from its parameters. Use it for an `address` key, which lets another account act for this
one.
See [Sub Accounts](https://moss.megaeth.com/developers/concepts/sub-accounts).

```ts title="Types"
Key.from: (key: FromValue, options?: { chainId?: number }) => Key;

type FromValue = {
    type: 'address' | 'p256' | 'secp256k1' | 'webauthn-p256';
    publicKey: Hex;
    privateKey?: Key['privateKey'];
    role?: 'admin' | 'session';
    expiry?: number;
    id?: Hex;
    prehash?: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const mainAccount = Key.from({
    type: 'address',
    publicKey: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0',
    role: 'admin',
});
```

### `getKeys`

Returns the keys authorized on an account, read from the relay.
See [Get Permissions](https://moss.megaeth.com/developers/methods/calling-contracts/get-permissions).

```ts title="Types"
getKeys: (client: Client, input: GetKeysInput) => Promise<readonly Key[]>;

type GetKeysInput = {
    account: Account | Address;
    chainIds?: readonly number[];
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type Account = {
    address: Hex;
    keys?: readonly Key[];
    source: 'porto' | 'privateKey';
    sign?: (parameters: { hash: Hex }) => Promise<Hex>; // Only on privateKey accounts
};

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { getKeys } from '@megaeth-labs/wallet-intent';

const keys = await getKeys(relay, { account: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0' });
```

## Sending

### `sendCalls`

Builds, signs and sends an intent, and resolves with the receipt once it is on chain. Pass `merchantUrl` to have a
sponsor pay the fee.
See [Executing on Your Server](https://moss.megaeth.com/developers/concepts/permissions#executing-on-your-server),
[Sponsoring Gas](https://moss.megaeth.com/developers/concepts/sponsoring-gas) and [wallet-merchant](https://moss.megaeth.com/developers/packages/wallet-merchant).

```ts title="Types"
sendCalls: (client: Client, input: SendCallsInput) => Promise<SendCallsResult>;

type SendCallsInput = {
    account: Account;
    key?: Key; // Defaults to the account's root key
    externalAdminKey?: Key; // Signs for an `address` key
    webAuthn?: { getFn?: WebAuthnP256.sign.Options['getFn'] }; // How a passkey signs, from ox
    merchantUrl?: string; // A sponsor to pay the fee
    payer?: Address; // Defaults to the account itself
    payerKey?: Key; // A key on `payer` that authorizes the fee
    calls?: readonly Call[];
    authorizeKeys?: readonly Key[];
    revokeKeys?: readonly Pick<Key, 'publicKey' | 'type'>[];
    feeToken?: Address; // address(0) for native
    paymentMaxAmount?: bigint;
    paymentGasBudget?: bigint; // Defaults to ESTIMATED_GAS_BUDGET
    paymentPerGas?: bigint;
    authorization?: UpgradeAccount; // From upgradeAccount, for an account that isn't upgraded yet
};

type SendCallsResult = SendCallsReceipt & {
    delegated?: boolean; // true when this intent upgraded the account
};

type Account = {
    address: Hex;
    keys?: readonly Key[];
    source: 'porto' | 'privateKey';
    sign?: (parameters: { hash: Hex }) => Promise<Hex>; // Only on privateKey accounts
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type UpgradeAccount = {
    authorization: SignedAuthorization;
    encodedPreCall: Hex;
};

type SendCallsReceipt = {
    transactionHash: Hex;
    blockHash: Hex;
    blockNumber: Hex;
    status: Hex | string; // '0x1' when it succeeded
    gasUsed: Hex;
    logs: SendCallsReceiptLog[];
    chainId?: Hex | number;
    type?: Hex;
    cumulativeGasUsed?: Hex;
    logsBloom?: Hex;
    transactionIndex?: Hex;
    effectiveGasPrice?: Hex;
    from?: Hex;
    to?: Hex | null;
    contractAddress?: Hex | null;
    l1GasPrice?: Hex;
    l1GasUsed?: Hex;
    l1Fee?: Hex;
    l1BaseFeeScalar?: Hex;
    l1BlobBaseFee?: Hex;
    l1BlobBaseFeeScalar?: Hex;
};

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type SignedAuthorization = {
    address: Address;
    chainId: number;
    nonce: number;
    r: Hex;
    s: Hex;
    yParity: 0 | 1;
};

type SendCallsReceiptLog = {
    address: Hex;
    data: Hex;
    topics: Hex[];
    blockHash?: Hex;
    blockNumber?: Hex;
    blockTimestamp?: Hex;
    transactionHash?: Hex;
    transactionIndex?: Hex;
    logIndex?: Hex;
    removed?: boolean;
};

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Account, Key, sendCalls } from '@megaeth-labs/wallet-intent';
import { parseAbi } from 'viem';

const serverKey = Key.fromSecp256k1({ privateKey: process.env.SERVER_PRIVATE_KEY as `0x${string}` });

const receipt = await sendCalls(relay, {
    account: Account.from('0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0'),
    key: serverKey,
    calls: [
        {
            to: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
            abi: parseAbi(['function store(uint256 value)']),
            functionName: 'store',
            args: [42n],
        },
    ],
});

if (receipt.status !== '0x1') throw new Error(`Reverted: ${receipt.transactionHash}`);
```

## Upgrading Accounts

### `upgradeAccount`

Signs the EIP-7702 authorization that makes an EOA a MOSS account and authorizes its first keys. Nothing is sent: pass
the result as `authorization` to `sendCalls`, `signMessage` or `signTypedData`, and store it until the chain has used it.

```ts title="Types"
upgradeAccount: (client: Client, input: UpgradeAccountInput) => Promise<UpgradeAccountResult>;

type UpgradeAccountInput = {
    account: ViemAccount; // A viem local account, such as privateKeyToAccount(...)
    authorizeKeys: readonly Key[];
};

type UpgradeAccountResult = UpgradeAccount & {
    account: Address;
    status: 'pending';
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type UpgradeAccount = {
    authorization: SignedAuthorization;
    encodedPreCall: Hex;
};

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type SignedAuthorization = {
    address: Address;
    chainId: number;
    nonce: number;
    r: Hex;
    s: Hex;
    yParity: 0 | 1;
};

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Account, Key, sendCalls, upgradeAccount } from '@megaeth-labs/wallet-intent';
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';

const eoa = privateKeyToAccount(generatePrivateKey());
const adminKey = Key.createP256({ role: 'admin' });

const upgrade = await upgradeAccount(relay, { account: eoa, authorizeKeys: [adminKey] });

// The first intent delegates the account on chain.
await sendCalls(relay, {
    account: Account.from({ address: eoa.address, keys: [adminKey] }),
    key: adminKey,
    calls: [],
    authorization: upgrade,
});
```

### `getLegacyAccountUpgrade`

Returns whether an account runs an older implementation the relay no longer executes through, and which one it should
move to.

```ts title="Types"
getLegacyAccountUpgrade: (client: Client, account: Address) => Promise<LegacyAccountUpgrade | undefined>;

type LegacyAccountUpgrade = {
    implementation: Address; // What the account runs now
    target: Address; // What it should move to
};
```

```ts title="Example"
import { getLegacyAccountUpgrade } from '@megaeth-labs/wallet-intent';

const legacy = await getLegacyAccountUpgrade(relay, '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0');

if (legacy) console.log('Move from', legacy.implementation, 'to', legacy.target);
```

### `signLegacyAccountUpgrade`

Signs an older account's move onto the relay's current implementation, as a call anyone can send and pay for.
Resolves `undefined` when there's nothing to upgrade.

```ts title="Types"
signLegacyAccountUpgrade: (
    client: Client,
    input: SignLegacyAccountUpgradeInput,
) => Promise<SignedLegacyAccountUpgrade | undefined>;

type SignLegacyAccountUpgradeInput = {
    account: Address;
    key: Key; // An admin key, or the root key
    webAuthn?: { getFn?: WebAuthnP256.sign.Options['getFn'] };
};

type SignedLegacyAccountUpgrade = LegacyAccountUpgrade & {
    call: Call;
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type LegacyAccountUpgrade = {
    implementation: Address; // What the account runs now
    target: Address; // What it should move to
};

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { signLegacyAccountUpgrade } from '@megaeth-labs/wallet-intent';

const upgrade = await signLegacyAccountUpgrade(relay, {
    account: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0',
    key: adminKey,
});

// Send upgrade.call from any funded account, such as your sponsor.
```

## Signing

### `signMessage`

Signs a message as a MOSS account, giving the same signature the wallet would.
See [Sign Message](https://moss.megaeth.com/developers/methods/signing/sign-message).

```ts title="Types"
signMessage: (client: Client, input: SignMessageInput) => Promise<Hex>;

type SignMessageInput = {
    account: Account;
    key?: Key;
    externalAdminKey?: Key; // Signs for an `address` key
    webAuthn?: { getFn?: WebAuthnP256.sign.Options['getFn'] };
    message: SignableMessage;
    authorization?: UpgradeAccount; // Wraps the signature (ERC-8010) when the account isn't upgraded yet
};

type Account = {
    address: Hex;
    keys?: readonly Key[];
    source: 'porto' | 'privateKey';
    sign?: (parameters: { hash: Hex }) => Promise<Hex>; // Only on privateKey accounts
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type UpgradeAccount = {
    authorization: SignedAuthorization;
    encodedPreCall: Hex;
};

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type SignedAuthorization = {
    address: Address;
    chainId: number;
    nonce: number;
    r: Hex;
    s: Hex;
    yParity: 0 | 1;
};

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { signMessage } from '@megaeth-labs/wallet-intent';

const signature = await signMessage(relay, {
    account: treasury,
    message: 'Hello, World!',
});
```

### `signTypedData`

Signs EIP-712 typed data as a MOSS account.
See [Sign Data](https://moss.megaeth.com/developers/methods/signing/sign-data).

```ts title="Types"
signTypedData: (client: Client, input: SignTypedDataInput) => Promise<Hex>;

type SignTypedDataInput = {
    account: Account;
    key?: Key;
    externalAdminKey?: Key;
    webAuthn?: { getFn?: WebAuthnP256.sign.Options['getFn'] };
    typedData: HashTypedDataParameters; // viem's
    authorization?: UpgradeAccount;
};

type Account = {
    address: Hex;
    keys?: readonly Key[];
    source: 'porto' | 'privateKey';
    sign?: (parameters: { hash: Hex }) => Promise<Hex>; // Only on privateKey accounts
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type UpgradeAccount = {
    authorization: SignedAuthorization;
    encodedPreCall: Hex;
};

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type SignedAuthorization = {
    address: Address;
    chainId: number;
    nonce: number;
    r: Hex;
    s: Hex;
    yParity: 0 | 1;
};

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { signTypedData } from '@megaeth-labs/wallet-intent';

const signature = await signTypedData(relay, {
    account: treasury,
    typedData: {
        domain: { name: 'MyApp', version: '1', chainId: 6343 },
        types: { Person: [{ name: 'name', type: 'string' }] },
        primaryType: 'Person',
        message: { name: 'Alice' },
    },
});
```

### `verifyMessage`

Checks a signed message against a MOSS account, including one from an account that hasn't sent its first transaction.
MOSS signatures are smart account signatures (ERC-1271), so `personal_sign` checks reject them.
See [Verifying Signatures](https://moss.megaeth.com/developers/methods/signing/sign-message#verifying-signatures) and
[wallet-server-verify](https://moss.megaeth.com/developers/packages/wallet-server-verify).

```ts title="Types"
verifyMessage: (client: Client, input: VerifyMessageInput) => Promise<boolean>;

type VerifyMessageInput = Omit<VerifyHashParameters, 'hash'> & { // viem's VerifyHashParameters
    message: SignableMessage;
};
```

```ts title="Example"
import { verifyMessage } from '@megaeth-labs/wallet-intent';

const valid = await verifyMessage(publicClient, {
    address: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0',
    message: 'Hello, World!',
    signature,
});
```

### `erc1271SignPayload`

Returns the payload a key signs so that an account accepts the signature from `isValidSignature`.

```ts title="Types"
erc1271SignPayload: (input: Erc1271SignPayloadInput) => Hex;

type Erc1271SignPayloadInput = {
    account: Address; // The account that verifies the signature
    chainId?: number;
    digest: Hex;
};
```

```ts title="Example"
import { erc1271SignPayload, Key } from '@megaeth-labs/wallet-intent';
import { hashMessage } from 'viem';

const payload = erc1271SignPayload({
    account: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0',
    chainId: 6343,
    digest: hashMessage('Hello, World!'),
});

const signature = await Key.sign(serverKey, { address: null, payload });
```

## Sub Accounts

### `executeAs`

Builds a call that makes a sub-account act, signed by its main account. Put it in the main account's `sendCalls` to
move funds from both accounts in one transaction.
See [Moving Funds Between Accounts](https://moss.megaeth.com/developers/concepts/sub-accounts#moving-funds-between-accounts).

```ts title="Types"
executeAs: (client: Client, input: ExecuteAsInput) => Promise<Call>;

type ExecuteAsInput = {
    account: Address; // The sub-account
    key: Key; // The `address` key on the sub-account that names the main account
    adminKey: Key; // A super-admin key on the main account
    webAuthn?: { getFn?: WebAuthnP256.sign.Options['getFn'] };
    calls: readonly Call[];
    nonceSeqKey?: bigint; // Defaults to EXECUTE_AS_NONCE_SEQ_KEY
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { executeAs, sendCalls } from '@megaeth-labs/wallet-intent';

// The sub-account pays out; the main account tops it up in the same transaction.
const subAccountPays = await executeAs(publicClient, {
    account: subAccountAddress,
    key: mainAccountKey,
    adminKey: passkey,
    calls: [payRecipient],
});

await sendCalls(relay, {
    account: mainAccount,
    key: passkey,
    calls: [topUpSubAccount, subAccountPays],
});
```

### `findSubAccountsByLogs`

Finds accounts that have authorized a main account, by scanning the chain's logs, and checks each is still current.
Treat the results as candidates: anyone can authorize any address.
See [Sub Accounts](https://moss.megaeth.com/developers/concepts/sub-accounts).

```ts title="Types"
findSubAccountsByLogs: (client: Client, input: FindSubAccountsByLogsInput) => Promise<readonly SubAccount[]>;

type FindSubAccountsByLogsInput = {
    parent: Address;
    fromBlock?: bigint; // Defaults to 0n
    toBlock?: bigint | 'latest'; // Defaults to 'latest'
    activeOnly?: boolean; // Defaults to true
};

type SubAccount = {
    address: Address;
    active: boolean; // Whether the main account is an unexpired super admin on it now
    expiry: number; // Unix seconds; 0 never expires
};
```

```ts title="Example"
import { findSubAccountsByLogs } from '@megaeth-labs/wallet-intent';

const subAccounts = await findSubAccountsByLogs(publicClient, {
    parent: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0',
});
```

### `verifySubAccounts`

Checks whether accounts you already know of still have a main account as an active admin.

```ts title="Types"
verifySubAccounts: (
    client: Client,
    input: { parent: Address; addresses: readonly Address[] },
) => Promise<readonly SubAccount[]>;

type SubAccount = {
    address: Address;
    active: boolean; // Whether the main account is an unexpired super admin on it now
    expiry: number; // Unix seconds; 0 never expires
};
```

```ts title="Example"
import { verifySubAccounts } from '@megaeth-labs/wallet-intent';

const checked = await verifySubAccounts(publicClient, {
    parent: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0',
    addresses: storedSubAccounts,
});
```

### `verifySubAccount`

Checks whether one account still has a main account as an active admin.

```ts title="Types"
verifySubAccount: (client: Client, input: { parent: Address; address: Address }) => Promise<SubAccount>;

type SubAccount = {
    address: Address;
    active: boolean; // Whether the main account is an unexpired super admin on it now
    expiry: number; // Unix seconds; 0 never expires
};
```

```ts title="Example"
import { verifySubAccount } from '@megaeth-labs/wallet-intent';

const { active } = await verifySubAccount(publicClient, {
    parent: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0',
    address: subAccountAddress,
});
```

### `keyHashForParent`

Returns the key hash an account stores when it authorizes a main account, for searching logs yourself.

```ts title="Types"
keyHashForParent: (parent: Address) => Hex;
```

```ts title="Example"
import { keyHashForParent } from '@megaeth-labs/wallet-intent';

const keyHash = keyHashForParent('0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0');
```

### `EXECUTE_AS_NONCE_SEQ_KEY`

The nonce sequence `executeAs` uses, kept apart from the one an account's own intents use.

```ts title="Types"
const EXECUTE_AS_NONCE_SEQ_KEY: bigint; // 1n
```

```ts title="Example"
import { EXECUTE_AS_NONCE_SEQ_KEY } from '@megaeth-labs/wallet-intent';
```

## Building Intents

These are the parts `sendCalls` is built from, for when you handle an intent yourself, as a sponsor does.

### `prepareIntent`

Fills in an intent's gas fields and returns it unsigned, with the EIP-712 digest the user signs.

```ts title="Types"
prepareIntent: (
    base: Omit<IntentV06, 'txEntryGas' | 'gasFloor' | 'signature'>,
    calls: readonly Call[],
    domain: IntentDigestDomain,
    keyType?: IntentSigningKeyType, // The type of key that will sign
) => { intent: Omit<IntentV06, 'signature'>; digest: Hex };

type IntentV06 = {
    eoa: Address;
    executionData: Hex;
    nonce: bigint;
    payer: Address;
    paymentToken: Address;
    paymentMaxAmount: bigint; // In the token's smallest unit
    paymentPerGas: bigint; // Multiplied by 10^18
    encodedPreCalls: Hex[];
    encodedFundTransfers: Hex[];
    settler: Address;
    expiry: number;
    isMultichain: boolean;
    funder: Address;
    funderSignature: Hex;
    settlerContext: Hex;
    paymentRecipient: Address;
    signature: Hex;
    paymentSignature: Hex;
    supportedAccountImplementation: Address;
    txEntryGas: bigint;
    gasFloor: bigint;
    txMode: number;
};

type IntentDigestDomain = {
    name: string;
    version: string;
    chainId: number;
    verifyingContract: Address;
};

type IntentSigningKeyType = 'address' | 'p256' | 'secp256k1' | 'webauthn-p256';
```

```ts title="Example"
import { decodeExecutionData, fromJsonRpcIntent, prepareIntent } from '@megaeth-labs/wallet-intent';

// request is the body the wallet sends a sponsor.
const base = fromJsonRpcIntent(request.intent);
const calls = decodeExecutionData(base.executionData);

const { intent, digest } = prepareIntent(base, calls, request.domain, request.keyType);
```

### `computePaymentDigest`

Returns the EIP-712 digest a payer signs to authorize paying an intent's fee.

```ts title="Types"
computePaymentDigest: (intent: PaymentIntentFields, domain: IntentDigestDomain) => Hex;

type PaymentIntentFields = Pick<
    IntentV06,
    | 'eoa'
    | 'executionData'
    | 'nonce'
    | 'payer'
    | 'paymentToken'
    | 'paymentMaxAmount'
    | 'paymentPerGas'
    | 'encodedPreCalls'
    | 'encodedFundTransfers'
    | 'settler'
    | 'expiry'
>;

type IntentDigestDomain = {
    name: string;
    version: string;
    chainId: number;
    verifyingContract: Address;
};

type IntentV06 = {
    eoa: Address;
    executionData: Hex;
    nonce: bigint;
    payer: Address;
    paymentToken: Address;
    paymentMaxAmount: bigint; // In the token's smallest unit
    paymentPerGas: bigint; // Multiplied by 10^18
    encodedPreCalls: Hex[];
    encodedFundTransfers: Hex[];
    settler: Address;
    expiry: number;
    isMultichain: boolean;
    funder: Address;
    funderSignature: Hex;
    settlerContext: Hex;
    paymentRecipient: Address;
    signature: Hex;
    paymentSignature: Hex;
    supportedAccountImplementation: Address;
    txEntryGas: bigint;
    gasFloor: bigint;
    txMode: number;
};
```

```ts title="Example"
import { computePaymentDigest, Key } from '@megaeth-labs/wallet-intent';

const digest = computePaymentDigest({ ...intent, payer: merchantAddress }, request.domain);
const paymentSignature = await Key.sign(merchantKey, { address: null, payload: digest });
```

### `decodeExecutionData`

Decodes an intent's `executionData` into the calls it makes.
See [Choosing What to Sponsor](https://moss.megaeth.com/developers/concepts/sponsoring-gas#choosing-what-to-sponsor).

```ts title="Types"
decodeExecutionData: (executionData: Hex) => Call[];
```

```ts title="Example"
import { decodeExecutionData, fromJsonRpcIntent } from '@megaeth-labs/wallet-intent';

const calls = decodeExecutionData(fromJsonRpcIntent(request.intent).executionData);
const targets = calls.map((call) => call.to);
```

### `toJsonRpcIntent`

Converts an intent to its JSON-RPC form, with numbers as hex.

```ts title="Types"
toJsonRpcIntent: (intent: IntentV06) => JsonRpcIntent;

type IntentV06 = {
    eoa: Address;
    executionData: Hex;
    nonce: bigint;
    payer: Address;
    paymentToken: Address;
    paymentMaxAmount: bigint; // In the token's smallest unit
    paymentPerGas: bigint; // Multiplied by 10^18
    encodedPreCalls: Hex[];
    encodedFundTransfers: Hex[];
    settler: Address;
    expiry: number;
    isMultichain: boolean;
    funder: Address;
    funderSignature: Hex;
    settlerContext: Hex;
    paymentRecipient: Address;
    signature: Hex;
    paymentSignature: Hex;
    supportedAccountImplementation: Address;
    txEntryGas: bigint;
    gasFloor: bigint;
    txMode: number;
};

type JsonRpcIntent = {
    eoa: Address;
    executionData: Hex;
    nonce: Hex;
    payer: Address;
    paymentToken: Address;
    paymentMaxAmount: Hex;
    paymentPerGas: Hex;
    encodedPreCalls: Hex[];
    encodedFundTransfers: Hex[];
    settler: Address;
    expiry: Hex;
    isMultichain: boolean;
    funder: Address;
    funderSignature: Hex;
    settlerContext: Hex;
    paymentRecipient: Address;
    signature: Hex;
    paymentSignature: Hex;
    supportedAccountImplementation: Address;
    txEntryGas: Hex;
    gasFloor: Hex;
    txMode: number;
};
```

```ts title="Example"
import { toJsonRpcIntent } from '@megaeth-labs/wallet-intent';

const body = JSON.stringify({ intent: toJsonRpcIntent(intent) });
```

### `fromJsonRpcIntent`

Converts an intent from its JSON-RPC form, with numbers as `bigint`.

```ts title="Types"
fromJsonRpcIntent: (rpc: JsonRpcIntent) => IntentV06;

type JsonRpcIntent = {
    eoa: Address;
    executionData: Hex;
    nonce: Hex;
    payer: Address;
    paymentToken: Address;
    paymentMaxAmount: Hex;
    paymentPerGas: Hex;
    encodedPreCalls: Hex[];
    encodedFundTransfers: Hex[];
    settler: Address;
    expiry: Hex;
    isMultichain: boolean;
    funder: Address;
    funderSignature: Hex;
    settlerContext: Hex;
    paymentRecipient: Address;
    signature: Hex;
    paymentSignature: Hex;
    supportedAccountImplementation: Address;
    txEntryGas: Hex;
    gasFloor: Hex;
    txMode: number;
};

type IntentV06 = {
    eoa: Address;
    executionData: Hex;
    nonce: bigint;
    payer: Address;
    paymentToken: Address;
    paymentMaxAmount: bigint; // In the token's smallest unit
    paymentPerGas: bigint; // Multiplied by 10^18
    encodedPreCalls: Hex[];
    encodedFundTransfers: Hex[];
    settler: Address;
    expiry: number;
    isMultichain: boolean;
    funder: Address;
    funderSignature: Hex;
    settlerContext: Hex;
    paymentRecipient: Address;
    signature: Hex;
    paymentSignature: Hex;
    supportedAccountImplementation: Address;
    txEntryGas: bigint;
    gasFloor: bigint;
    txMode: number;
};
```

```ts title="Example"
import { fromJsonRpcIntent } from '@megaeth-labs/wallet-intent';

const intent = fromJsonRpcIntent(request.intent);
console.log(intent.eoa, intent.paymentToken);
```

## Fees

### `getPaymentPerGas`

Returns the relay's current gas price in each fee token. Cached for 60 seconds.
See [Gas](https://moss.megaeth.com/developers/concepts/gas).

```ts title="Types"
getPaymentPerGas: (client: Client) => Promise<PaymentPerGasEntry>;

type PaymentPerGasEntry = {
    maxFeePerGas: Hex;
    tokens: readonly PaymentPerGasToken[];
};

type PaymentPerGasToken = {
    uid: string;
    address: Address;
    decimals: number;
    feeToken: boolean;
    symbol: string;
    nativeRate: Hex | null;
    paymentPerGas: Hex | null;
};
```

```ts title="Example"
import { getPaymentPerGas } from '@megaeth-labs/wallet-intent';

const rates = await getPaymentPerGas(relay);
const feeTokens = rates.tokens.filter((token) => token.feeToken).map((token) => token.symbol);
```

### `pickPaymentPerGasFor`

Picks the gas price for one fee token, falling back to the native token's. Throws when there's no usable price.

```ts title="Types"
pickPaymentPerGasFor: (entry: PaymentPerGasEntry, feeToken: Address) => bigint;

type PaymentPerGasEntry = {
    maxFeePerGas: Hex;
    tokens: readonly PaymentPerGasToken[];
};

type PaymentPerGasToken = {
    uid: string;
    address: Address;
    decimals: number;
    feeToken: boolean;
    symbol: string;
    nativeRate: Hex | null;
    paymentPerGas: Hex | null;
};
```

```ts title="Example"
import { getPaymentPerGas, pickPaymentPerGasFor } from '@megaeth-labs/wallet-intent';
import { zeroAddress } from 'viem';

const paymentPerGas = pickPaymentPerGasFor(await getPaymentPerGas(relay), zeroAddress);
```

### `ESTIMATED_GAS_BUDGET`

The gas `sendCalls` budgets for an intent when working out its fee cap.

```ts title="Types"
const ESTIMATED_GAS_BUDGET: bigint; // 10_000_000n
```

```ts title="Example"
import { ESTIMATED_GAS_BUDGET, PAYMENT_PER_GAS_FIXED_POINT_SCALAR } from '@megaeth-labs/wallet-intent';

const maxFee = (ESTIMATED_GAS_BUDGET * paymentPerGas) / PAYMENT_PER_GAS_FIXED_POINT_SCALAR;
```

### `PAYMENT_PER_GAS_PRECISION`

The fixed-point precision of a gas price: the relay quotes `paymentPerGas` multiplied by 10 to this power.

```ts title="Types"
const PAYMENT_PER_GAS_PRECISION: 18n;
```

```ts title="Example"
import { PAYMENT_PER_GAS_PRECISION } from '@megaeth-labs/wallet-intent';

const scale = 10n ** PAYMENT_PER_GAS_PRECISION;
```

### `PAYMENT_PER_GAS_FIXED_POINT_SCALAR`

What to divide gas times `paymentPerGas` by to get a fee in the token's smallest unit, whatever its decimals.

```ts title="Types"
const PAYMENT_PER_GAS_FIXED_POINT_SCALAR: bigint; // 10n ** 18n
```

```ts title="Example"
import { PAYMENT_PER_GAS_FIXED_POINT_SCALAR } from '@megaeth-labs/wallet-intent';

const fee = (gasUsed * paymentPerGas) / PAYMENT_PER_GAS_FIXED_POINT_SCALAR;
```

## Key Utilities

Lower-level functions on the `Key` and `Account` namespaces, used by the ones above.

### `Account.getKey`

Picks an account's signing key: the one you name, or the first admin key that can sign.

```ts title="Types"
Account.getKey: (account: Account, parameters?: GetKeyParameters) => Key | undefined;

type GetKeyParameters = {
    key?: number | Key | null; // A key, or its index in account.keys
    role?: 'admin' | 'session';
};

type Account = {
    address: Hex;
    keys?: readonly Key[];
    source: 'porto' | 'privateKey';
    sign?: (parameters: { hash: Hex }) => Promise<Hex>; // Only on privateKey accounts
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Account } from '@megaeth-labs/wallet-intent';

const sessionKey = Account.getKey(account, { role: 'session' });
```

### `Account.sign`

Signs a payload with one of an account's keys.

```ts title="Types"
Account.sign: (account: Account, parameters: AccountSignParameters) => Promise<Hex>;

type AccountSignParameters = {
    key?: number | Key | null;
    role?: 'admin' | 'session';
    payload: Hex;
    replaySafe?: boolean; // Wraps the payload for ERC-1271 against account.address. Defaults to true
    wrap?: boolean; // Wraps the signature with the key's metadata. Defaults to true
    webAuthn?: { getFn?: WebAuthnP256.sign.Options['getFn'] };
};

type Account = {
    address: Hex;
    keys?: readonly Key[];
    source: 'porto' | 'privateKey';
    sign?: (parameters: { hash: Hex }) => Promise<Hex>; // Only on privateKey accounts
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Account } from '@megaeth-labs/wallet-intent';

const signature = await Account.sign(account, { payload: digest });
```

### `Key.sign`

Signs a payload with a key.

```ts title="Types"
Key.sign: (key: Key, parameters: KeySignParameters) => Promise<Hex>;

type KeySignParameters = {
    address: Hex | null; // An account to sign for, or null to sign the payload as it is
    payload: Hex;
    webAuthn?: { getFn?: WebAuthnP256.sign.Options['getFn'] };
    wrap?: boolean; // Wraps the signature with the key's metadata. Defaults to true
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const signature = await Key.sign(serverKey, { address: null, payload: digest, wrap: false });
```

### `Key.fromRelay`

Converts a key in the relay's `wallet_getKeys` format into a `Key`.

```ts title="Types"
Key.fromRelay: (relayKey: RelayKey, options: { chainId: number }) => Key;

type RelayKey = {
    expiry: Hex;
    prehash?: boolean;
    publicKey: Hex;
    role: 'admin' | 'normal';
    type: 'p256' | 'secp256k1' | 'webauthnp256';
    permissions: readonly (
        | { type: 'call'; selector: Hex; to: Hex }
        | {
              type: 'spend';
              limit: Hex;
              period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
              token?: Hex | null;
          }
    )[];
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const key = Key.fromRelay(relayKey, { chainId: 6343 });
```

### `Key.hash`

Returns a key's hash, which identifies it on the account contract.

```ts title="Types"
Key.hash: (key: Pick<Key, 'publicKey' | 'type'>) => Hex;

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const keyHash = Key.hash(serverKey);
```

### `Key.serialize`

Converts a key to the format the account contract stores.

```ts title="Types"
Key.serialize: (key: Key) => Serialized;

type Serialized = {
    expiry: number;
    isSuperAdmin: boolean;
    keyType: number;
    publicKey: Hex;
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const { keyType, publicKey } = Key.serialize(serverKey);
```

### `Key.serializePublicKey`

Pads a public key to 32 bytes, as the contract stores it.

```ts title="Types"
Key.serializePublicKey: (publicKey: Hex) => Hex;

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const padded = Key.serializePublicKey('0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0');
```

### `Key.wrapSignature`

Adds a key's hash and prehash flag to a raw signature, so the account knows which key signed.

```ts title="Types"
Key.wrapSignature: (signature: Hex, options: WrapSignatureOptions) => Hex;

type WrapSignatureOptions = {
    keyType: 'address' | 'p256' | 'secp256k1' | 'webauthn-p256';
    prehash?: boolean;
    publicKey: Hex;
};

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';

const wrapped = Key.wrapSignature(rawSignature, { keyType: 'p256', publicKey: key.publicKey });
```

### `Key.serializeWebAuthnSignature`

Encodes a WebAuthn signature as the contract's `WebAuthnAuth` struct.

```ts title="Types"
Key.serializeWebAuthnSignature: (options: {
    metadata: SignMetadata; // From ox's WebAuthnP256
    signature: { r: bigint; s: bigint };
}) => Hex;

type Key = AddressKey | P256Key | Secp256k1Key | WebCryptoKey | WebAuthnKey;

type AddressKey = BaseKey<'address', undefined>;

type P256Key = BaseKey<'p256', () => Hex>;

type Secp256k1Key = BaseKey<'secp256k1', () => Hex>;

type WebCryptoKey = BaseKey<'p256', CryptoKey>;

type WebAuthnKey = BaseKey<
    'webauthn-p256',
    | { credential: Pick<P256Credential, 'id' | 'publicKey'>; rpId: string | undefined }
    | { privateKey: () => Hex }
>;

type BaseKey<type, privateKey> = {
    type: type;
    publicKey: Hex; // An address for secp256k1 and address keys
    privateKey?: privateKey;
    role: 'admin' | 'session';
    expiry: number; // Unix seconds; 0 never expires
    hash: Hex;
    id: Hex;
    prehash: boolean;
    chainId?: number;
    permissions?: Permissions;
    feeToken?: FeeToken | null;
    source?: string;
};

type Permissions = {
    calls?: readonly { signature?: string; to?: Hex }[];
    spend?: readonly { limit: bigint; period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; token?: Hex }[];
};

type FeeToken = {
    limit: string;
    symbol?: string;
};
```

```ts title="Example"
import { Key } from '@megaeth-labs/wallet-intent';
import { WebAuthnP256 } from 'ox';

const { metadata, signature } = await WebAuthnP256.sign({ challenge: digest, credentialId });
const encoded = Key.serializeWebAuthnSignature({ metadata, signature });
```
