Skip to content
21 changes: 20 additions & 1 deletion docs/sdk/getting-started/auth-services.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,33 @@ Lit hosts default Auth Service instances so you can build without deploying infr
| ----------- | ------------------------------------------- | ------------------------------ | ----- |
| `naga-dev` | `https://naga-dev-auth-service.getlit.dev` | `https://login.litgateway.com` | Use Lit's hosted endpoints while you prototype. Configure your SDK or environment variables with the URLs in this table. |
| `naga-test` | `https://naga-test-auth-service.getlit.dev` | `https://login.litgateway.com` | Start with the hosted endpoints for staging, then switch to your own infrastructure as you scale. |
| `naga` | `Run your own (recommended)` | `Run your own (recommended)` | Lit does not operate public Auth Service or Login Server endpoints for `naga` |
| `naga` | `Run your own (recommended)` | `Run your own (recommended)` | Lit does not (yet) operate public Auth Service or Login Server endpoints for `naga` |

<Note>
The hosted services are best suited for prototyping. Self-host the Auth
Service and Login Server for production traffic or when you need custom
configuration.
</Note>

## Payment Delegation APIs

The Auth Service also exposes lightweight endpoints that sponsor user requests on the network. These are the same APIs the Lit SDK calls when you use `litClient.authService.registerPayer` / `delegateUsers` from the Payment Manager guide.

- `POST /register-payer`
- Headers: `x-api-key`.
- Behaviour: generates a random `payerSecretKey`, hashes it with the API key, and derives a child wallet from `LIT_DELEGATION_ROOT_MNEMONIC`.
- Response: `{ success, payerWalletAddress, payerSecretKey }`. The service **does not** persist the secret—you must store it securely (KMS, vault, etc.).
- Rotation: call the endpoint again with the same API key to rotate the secret and derive a new child wallet.
- `POST /add-users`
- Headers: `x-api-key`, `payer-secret-key`; body is a JSON array of user addresses.
- Behaviour: recomputes the same child wallet on the fly and calls `PaymentManager.delegatePaymentsBatch` so the payer sponsors those users.

<Tip>
Running the Auth Service yourself keeps the derivation mnemonic and payer secrets inside your infrastructure. The Lit-hosted instance is great for quick starts, but you remain responsible for storing the returned `payerSecretKey`.
</Tip>

If you prefer not to run an Auth Service at all, you can still sponsor users manually: create a payer wallet, fund it, and call `paymentManager.delegatePayments*` directly from your backend. See [Payment Manager Setup](/sdk/getting-started/payment-manager-setup#sponsoring-your-users-capacity-delegation-replacement) for sample code.


### Install the SDK

Expand Down
158 changes: 121 additions & 37 deletions docs/sdk/getting-started/payment-manager-setup.mdx
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
---
title: "Payment Manager Setup"
description: "Configure payment system for the Lit JS SDK"
title: 'Payment Manager Setup'
description: 'Configure payment system for the Lit JS SDK'
---

<Warning>
❗️ Currently free on the dev network, so no need to deposit funds. More
details coming soon for test and production networks.
❗️ Payment status by network:
- **naga-dev** – usage is currently free; no deposits required.
- **naga-test** – payments are enabled using test tokens (see faucet link
below).
- **Mainnet** – coming soon; mainnet payment details will be announced
shortly.
</Warning>

<Note>
Expand All @@ -23,10 +27,11 @@ description: "Configure payment system for the Lit JS SDK"

The Payment Manager demonstrates Lit Protocol's payment system - a billing system for decentralised cryptographic services. Users pay for compute resources on the Lit network to access core services like:

- Encryption/Decryption - Secure data with programmable access control
- PKP Signing - Cryptographic keys that can sign transactions based on conditions
- Lit Actions - Serverless functions with cryptographic capabilities
Similar to how you pay AWS for cloud computing, this\system ensures the decentralised network can sustain itself and pay node operators. You can deposit funds, request withdrawals with security delays, and manage balances for yourself or other users (enabling applications to sponsor their users' costs for better UX).
- [Encryption/Decryption](/sdk/auth-context-consumption/encrypt-and-decrypt) - Secure data with programmable access control.
- [PKP Signing](/sdk/auth-context-consumption/pkp-sign) - Cryptographic keys that can sign transactions based on conditions.
- [Lit Actions](/sdk/auth-context-consumption/execute-js) - Serverless functions with cryptographic capabilities.

Similar to how you pay AWS for cloud computing, this system ensures the decentralised network can sustain itself and pay node operators. Each payer keeps a balance in the on-chain Lit Ledger contract funded with `$LITKEY` (or `$tstLPX` on testnet), which the network debits as requests execute. You can deposit funds, request withdrawals with security delays, and manage balances for yourself or other users (enabling applications to sponsor their users' costs for better UX).

<Steps>
<Step title="Payment Manager Setup">
Expand All @@ -40,8 +45,9 @@ const litClient = await createLitClient({ network: nagaTest });

// 2. Get PaymentManager instance (requires account for transactions)
const paymentManager = await litClient.getPaymentManager({
account: yourAccount // viem account instance
account: yourAccount // viem account instance
});

````

</Step>
Expand All @@ -59,7 +65,7 @@ const { data: myAccount } = useWalletClient();

```typescript viem/accounts
// 1. import the privateKeyToAccount function from viem/accounts
import { privateKeyToAccount } from "viem/accounts";
import { privateKeyToAccount } from 'viem/accounts';

// 2. Convert your private key to a viem account object that can be used for payment operations.
const myAccount = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
Expand All @@ -74,7 +80,7 @@ const myAccount = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
```typescript Deposit funds to your own account
// 1. Deposit funds to your own account
const result = await paymentManager.deposit({
amountInEth: "0.1",
amountInEth: '0.1',
});

console.log(`Deposit successful: ${result.hash}`);
Expand All @@ -84,8 +90,8 @@ console.log(`Deposit successful: ${result.hash}`);
```typescript Deposit for another user
// 1. Deposit funds for another user
const result = await paymentManager.depositForUser({
userAddress: "0x742d35Cc6638Cb49f4E7c9ce71E02ef18C53E1d5",
amountInEth: "0.05",
userAddress: '0x742d35Cc6638Cb49f4E7c9ce71E02ef18C53E1d5',
amountInEth: '0.05',
});

console.log(`Deposit successful: ${result.hash}`);
Expand All @@ -97,14 +103,101 @@ console.log(`Deposit successful: ${result.hash}`);

</Steps>

## Auth Service API Endpoints
## Sponsoring Your Users

<Steps>
<Step title="Define spending limit">

Define spending limits for the users you want to sponsor (values are in wei).

<CodeGroup>

```typescript
await paymentManager.setRestriction({
totalMaxPrice: '1000000000000000000', // 1 ETH equivalent limit
requestsPerPeriod: '100', // max number of sponsored requests in a period
periodSeconds: '3600', // rolling window (1 hour in this example)
});
```

</CodeGroup>

</Step>

Leverage the hosted Auth Service to manage delegation without exposing private keys in your application:
<Step title="Delegate users">

- `POST /register-payer` - Send your `x-api-key` header to receive a delegated payer address and `payerSecretKey`. Persist this secret securely; it is required for all future delegation calls.
- `POST /add-users` - Provide headers `x-api-key` and `payer-secret-key` plus a JSON body containing an array of user addresses. The Auth Service uses the Payment Manager internally to delegate payments to each address in a single transaction.
With restrictions set, delegate one or more users to spend from your payer wallet.

> The legacy capacity-credit minting flow has been removed. Payment delegation now interacts directly with the Payment Manager contracts.
<CodeGroup>

```typescript
await paymentManager.delegatePaymentsBatch({
userAddresses: ['0xAlice...', '0xBob...'],
});
```

</CodeGroup>

</Step>

<Step title="Remove users (optional)">

Undelegate users when you no longer want to sponsor them.

<CodeGroup>

```typescript
await paymentManager.undelegatePaymentsBatch({
userAddresses: ['0xAlice...'],
});
```

</CodeGroup>

</Step>
</Steps>

## **Alternatively**

Manage delegation via the hosted or self-hosted Auth Service (see [Auth Services setup](/sdk/getting-started/auth-services) for the full flow).

## After Payment Delegation

**Users decrypt as normal** – we still call `litClient.decrypt` with an auth context; the network draws fees from the delegated payer instead of the user’s wallet.

<Note>
ℹ️ `userMaxPrice` is recommended for sponsored sessions, typically the same value or less than the the restriction the sponsor set; optional guardrail when self-funded.
</Note>

```typescript highlight={18}
// Client-side decrypt with sponsored payments
const authContext = await authManager.createEoaAuthContext({
litClient,
config: { account: walletClient },
authConfig: {
resources: [
['access-control-condition-decryption', '*'],
['lit-action-execution', '*'],
],
},
});

const response = await litClient.decrypt({
data: encryptedData,
unifiedAccessControlConditions: accs,
authContext,
chain: 'ethereum',
userMaxPrice: 1000000000000000000n,
});
```

## Auth Service API Endpoints

Leverage the hosted Auth Service to manage delegation without exposing private keys in your application. Full request/response details live in the [Auth Services setup guide](/sdk/getting-started/auth-services#payment-delegation-apis). In practice you will:

- Call `authService.registerPayer` (hosted or self-hosted) to derive a payer wallet + `payerSecretKey`.
- Call `authService.delegateUsers` (`/add-users`) to sponsor a list of user addresses.
- Or skip the service entirely and use the Payment Manager methods directly (example below).

```typescript
import { createLitClient } from '@lit-protocol/lit-client';
Expand All @@ -113,40 +206,31 @@ import { nagaTest } from '@lit-protocol/networks';
// 1. Create the Lit client for the naga-test environment
const litClient = await createLitClient({ network: nagaTest });

const authServiceBaseUrl = 'https://naga-test-auth-service.example.com';
const apiKey = process.env.LIT_API_KEY!;
const authServiceBaseUrl = 'https://naga-test-auth-service.getlit.dev/';
const apiKey = process.env.YOUR_AUTH_SERVICE_API_KEY!;

// 3. Register a payer wallet (store the secret securely server-side)
const registerResponse = await litClient.authService.registerPayer({
authServiceBaseUrl,
apiKey,
authServiceBaseUrl,
apiKey,
});

console.log('Payer wallet:', registerResponse.payerWalletAddress);
console.log('Payer secret (store securely!):', registerResponse.payerSecretKey);

// 4. Later on, delegate payments for multiple users using the saved secret
const delegateResponse = await litClient.authService.delegateUsers({
authServiceBaseUrl,
apiKey,
payerSecretKey: registerResponse.payerSecretKey,
userAddresses: [
'0x1234...abcd',
'0xabcd...1234',
],
authServiceBaseUrl,
apiKey,
payerSecretKey: registerResponse.payerSecretKey,
userAddresses: ['0x1234...abcd', '0xabcd...1234'],
});

console.log('Delegation submitted with tx hash:', delegateResponse.txHash);

// 5. Continue to use the same payer secret for future delegation calls
````
```

### How the Auth Service derives payer wallets

- The service holds a single root mnemonic (`LIT_DELEGATION_ROOT_MNEMONIC`).
- `/register-payer` combines the `x-api-key` header with a freshly generated `payerSecretKey`. That pair is hashed into a deterministic derivation index, which is then used with the root mnemonic to derive a unique child wallet.
- The response includes the derived wallet address and the random `payerSecretKey`. The server does not store this secret; you must persist it securely on the client side.
- Later, `/add-users` expects both headers (`x-api-key` and `payer-secret-key`). The service recomputes the same derivation index and wallet on the fly, so the same header pair always maps to the same child wallet.
- Calling `/register-payer` again with the same API key issues a new random `payerSecretKey`, which leads to a different child wallet. Choose whether to rotate secrets or keep the original one depending on your application needs.

![](https://www.plantuml.com/plantuml/png/XPAn3jCm48PtFyMfKw8IiKSAQcab1a1K58c1CXpEaLWaJcHVIlFs6DkKcBHYYy-Vl_Floyuo6fxwJh3YZc0_SGjdCbSb2KuuzwGPZjHHWwm6BSJeS2NLYAw-ENJAxMy0BOJFT7ifyz3lGbodv3l5qG3lKMD3nlFn-ndh6RTyr3lSFTN5MYo96Xc_eINOh8F2OT1iKFeUzuKGLGKVgL6MoS28CnceAX5lNhnQ1YpXzE7y2LwQY1SUl-ZiLk2eYXyqvsA1hqw_8Kq6cKARCqb3VD57CkfAy1ExZXY-cw67NbC_Q2LX2quCJfnwdJXSi0ogp_xilguDMNlH2_rRcdt2-0m4aoLZ_viGwxhmv3BSYz2iiDuSAXxwydMLEmwaX8RYBBDSnABR_plY4fmCcToZEbUgMM1Ub0uxGoc7INCk0XNJf509Ibj6pGfvPVyNhUCZnRfzZIpRp4VCHGgxu_TVo1zSlAxuim75WoPy0qEIrCWhPJeBZxPeswUpjvEKP2rix-IET3trtIy0)
- For hosted or self-hosted deployments, see the derivation and rotation notes in the [Auth Services guide](/sdk/getting-started/auth-services#payment-delegation-apis). Manual deployments can always provision and delegate entirely via the `PaymentManager` helper without touching these endpoints.
2 changes: 2 additions & 0 deletions packages/lit-client/src/lib/LitClient/createLitClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -950,6 +950,7 @@ export const _createNagaLitClient = async (
pkpPublicKey: string | Hex;
authContext: AuthContextSchema2;
chainConfig: Chain;
userMaxPrice?: bigint;
}) => {
const _pkpPublicKey = HexPrefixedSchema.parse(params.pkpPublicKey);

Expand All @@ -965,6 +966,7 @@ export const _createNagaLitClient = async (
toSign: data,
authContext: params.authContext,
bypassAutoHashing: options?.bypassAutoHashing,
userMaxPrice: params.userMaxPrice,
});

return res.signature;
Expand Down
Loading