# wallet-merchant

The server side of sponsored transactions. When a user sends a transaction, the wallet asks your sponsor URL to pay
for it; this package's handler decides whether to, caps the fee and signs the payment from your merchant account. It
works with any server that handles a `POST` and needs no RPC endpoint.
See [Sponsoring Gas](https://moss.megaeth.com/developers/concepts/sponsoring-gas).

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

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

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

## Creating the Handler

### `createMerchant`

Creates the sponsor handler for your merchant account, an EIP-7702 smart account that pays the fees.
See [Create the Sponsor Wallet](https://moss.megaeth.com/developers/concepts/sponsoring-gas#1-create-the-sponsor-wallet) and
[Choosing What to Sponsor](https://moss.megaeth.com/developers/concepts/sponsoring-gas#choosing-what-to-sponsor).

```ts title="Types"
createMerchant: (options: MerchantOptions) => Merchant;

type MerchantOptions = {
    address: `0x${string}`; // Your merchant account
    key: `0x${string}` | { type: 'secp256k1' | 'p256'; privateKey: `0x${string}` };
    sponsor?: boolean | ((request: SponsorRequest) => boolean | Promise<boolean>); // Defaults to true
    paymentMaxAmount?: bigint; // Fixed fee cap per transaction, in the fee token's smallest unit
    paymentGasBudget?: bigint; // Gas budget for the default fee cap
};

type Merchant = {
    fetch: (request: Request) => Promise<Response>;
    handle: (body: unknown) => Promise<MerchantResult>;
};

type SponsorRequest = {
    intent: JsonRpcIntent; // The unsigned intent the wallet built
    domain: IntentDigestDomain;
    keyType?: IntentSigningKeyType; // The type of key the user will sign with
};

type MerchantResult =
    | { status: 200; body: SponsorResponse }
    | { status: 400 | 403 | 500; body: SponsorErrorResponse };

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 IntentDigestDomain = {
    name: string;
    version: string;
    chainId: number;
    verifyingContract: Address;
};

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

type SponsorResponse = {
    intent: JsonRpcIntent; // The intent, with your account as payer and your payment signature
    digest: `0x${string}`; // What the user signs
};

type SponsorErrorResponse = {
    error: { code: number; message: string };
};
```

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

const MY_CONTRACT = '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C';

export const merchant = createMerchant({
    address: process.env.MERCHANT_ADDRESS as `0x${string}`,
    key: process.env.MERCHANT_PRIVATE_KEY as `0x${string}`,
    // Only pay for transactions that call your own contract.
    sponsor: ({ intent }) => {
        const calls = decodeExecutionData(fromJsonRpcIntent(intent).executionData);
        return calls.every((call) => call.to.toLowerCase() === MY_CONTRACT.toLowerCase());
    },
});
```

## Handling Requests

### `merchant.fetch`

Handles a sponsor request as a Fetch API `Request` and returns a `Response`, for servers that use them: Hono, Next.js,
Bun, Deno and Cloudflare Workers.
See [Create the Sponsor Endpoints](https://moss.megaeth.com/developers/concepts/sponsoring-gas#3-create-the-sponsor-endpoints).

```ts title="Types"
fetch: (request: Request) => Promise<Response>;

// The JSON body of the request.
type SponsorRequest = {
    intent: JsonRpcIntent; // The unsigned intent the wallet built
    domain: IntentDigestDomain;
    keyType?: IntentSigningKeyType; // The type of key the user will sign with
};

// The JSON body of a 200 response.
type SponsorResponse = {
    intent: JsonRpcIntent; // The intent, with your account as payer and your payment signature
    digest: `0x${string}`; // What the user signs
};

// The JSON body of a 400, 403 or 500 response.
type SponsorErrorResponse = {
    error: { code: number; message: string };
};

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 IntentDigestDomain = {
    name: string;
    version: string;
    chainId: number;
    verifyingContract: Address;
};

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

```ts title="Example"
// Next.js: app/sponsor/route.ts
export const POST = (request: Request) => merchant.fetch(request);
```

### `merchant.handle`

Handles a sponsor request body your server has already parsed and returns the status and body to send, for servers
such as Express and Fastify. It never throws.
See [Create the Sponsor Endpoints](https://moss.megaeth.com/developers/concepts/sponsoring-gas#3-create-the-sponsor-endpoints).

```ts title="Types"
handle: (body: unknown) => Promise<MerchantResult>;

type MerchantResult =
    | { status: 200; body: SponsorResponse }
    | { status: 400 | 403 | 500; body: SponsorErrorResponse };

type SponsorResponse = {
    intent: JsonRpcIntent;
    digest: `0x${string}`;
};

type SponsorErrorResponse = {
    error: { code: number; message: string };
};

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 express from 'express';

const app = express();

app.post('/sponsor', express.json(), async (req, res) => {
    const { status, body } = await merchant.handle(req.body);
    res.status(status).json(body);
});
```

> [!NOTE]
> The handler doesn't do CORS. The wallet calls your sponsor URL from the user's browser, so allow `POST` with
> `Content-Type: application/json` from the wallet's origin.

## Error Codes

The `code` in an error response.

| Status | Code | When |
| --- | --- | --- |
| 400 | -32700 | The body isn't JSON (`fetch` only) |
| 400 | -32600 | The body isn't a valid sponsor request |
| 403 | -32003 | `sponsor` declined the request |
| 500 | -32000 | Something failed while preparing the intent |
