# Sponsoring Gas

MOSS supports the ability for your app to pay gas fees on behalf of your users using your server to approve
transactions.

Sponsoring is configured by choosing a `sponsorMode`, `sponsorToken` and providing a `sponsorUrl` when initialising
the wallet.

## Sponsor Modes
You can choose what level of sponsorship you wish to support in the config object:

- **Explicit**: Only requests where `sponsor` is true will request sponsorship

- **App Only**: All requests from your app will request sponsorship. Other actions in the wallet require the
wallet's gas

- **Everything**: All requests and all actions in the wallet will request sponsorship

## Sponsor Token
The `sponsorToken` config option can be either `native` (ETH) or `usdm` (USDm). This is the token which the
transaction will request the sponsoring wallet use to pay for the transaction.

## Sponsor URL
To approve sponsorship requests, your app wallet must also sign the transaction to approve the spending. This wallet
cannot exist on the client and so must be hosted on your server.

To simplify the process of receiving and signing requests, the `@megaeth-labs/wallet-merchant` package can be
installed and configured. This package is server agnostic and provides the ability to choose which transactions to
sponsor.

> [!NOTE]
> View the package [here](https://github.com/megaeth-labs/wallet-merchant)

The following steps are required to set up sponsoring:
1. Create a sponsor wallet
2. Install the package on your server
3. Create the sponsor endpoints
4. Provide the `sponsorUrl` on initialisation

### 1. Create the Sponsor Wallet
The sponsor wallet must be an EIP-7702 smart wallet to sign and fund transactions. The `@megaeth-labs/wallet-merchant`
contains a script which aids you in creating a sponsor wallet.

```bash
git clone https://github.com/megaeth-labs/wallet-merchant.git
cd wallet-merchant
npm install
npm run merchant
```

The script will generate a new wallet and then ask for funds on mainnet and testnet. Funds are required to pay for
the gas to upgrade the account on chain. Once funds are detected, the account will be upgraded and the keys printed
to the console.

### 2. Install the Package on Your Server
Using your package manager of choice, install the `@megaeth-labs/wallet-merchant` package.

### 3. Create the Sponsor Endpoints
Initialise the merchant object in your routes and create a POST endpoint.

```ts
import { createMerchant } from '@megaeth-labs/wallet-merchant';

const merchant = createMerchant({
    address: process.env.MERCHANT_ADDRESS as `0x${string}`,
    key: process.env.MERCHANT_PRIVATE_KEY as `0x${string}`,
    sponsor: true,
});
```

```ts title="Hono"
import { Hono } from 'hono';

const app = new Hono();

app.post('/sponsor', (c) => merchant.fetch(c.req.raw));

export default app;
```

```ts title="Express"
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);
});

app.listen(3000);
```

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

```ts title="Fastify"
import Fastify from 'fastify';

const fastify = Fastify();

fastify.post('/sponsor', async (request, reply) => {
    const { status, body } = await merchant.handle(request.body);
    return reply.code(status).send(body);
});

await fastify.listen({ port: 3000 });
```

```ts title="Bun"
Bun.serve({
    routes: {
        '/sponsor': { POST: (request) => merchant.fetch(request) },
    },
});
```

```ts title="Cloudflare Workers"
export default {
    fetch(request) {
        const url = new URL(request.url);
        if (request.method !== 'POST' || url.pathname !== '/sponsor') {
            return new Response('Not found', { status: 404 });
        }

        return merchant.fetch(request);
    },
} satisfies ExportedHandler;
```

> [!NOTE]
> You may want to create two endpoints: one for testnet which sponsors all requests and another for mainnet which
> is restricted. You can then set the URL you need during initialisation.

### 4. Provide the Sponsor URL
When initialising the wallet, set the sponsorship properties.


```ts title="Pure JS"
import { mega } from '@megaeth-labs/wallet-sdk';

const status = await mega.initialise({
    network: 'testnet',
    sponsorUrl: 'http://localhost:3000/sponsor',
    sponsorMode: 'explicit'
});
```

```tsx title="React"
import { MegaProvider } from '@megaeth-labs/wallet-sdk-react';

export default function App() {
    return (
        <MegaProvider config={{
            network: 'testnet',
            sponsorUrl: 'http://localhost:3000/sponsor',
            sponsorMode: 'explicit'
        }}>
         {/* ...your app */}
        </MegaProvider>
    );
}
```

```ts title="Wagmi"
import { mossWallet } from '@megaeth-labs/wallet-wagmi-connector';
import { megaethTestnet } from 'viem/chains';
import { createConfig, http } from 'wagmi';

export const config = createConfig({
    chains: [megaethTestnet],
    connectors: [
        mossWallet({
            network: 'testnet',
            sponsorUrl: 'http://localhost:3000/sponsor',
            sponsorMode: 'explicit',
        }),
    ],
    transports: {
        [megaethTestnet.id]: http(),
    },
});
```

## Choosing What to Sponsor
The `createMerchant` method accepts a `sponsor` function which you can use to determine if a request should be
sponsored. For example, you may want to only sponsor calls to your own contracts.

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

const MY_CONTRACT = '0x…';

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.length > 0 && calls.every((call) => call.to.toLowerCase() === MY_CONTRACT.toLowerCase());
    },
});
```

For more configuration options and code samples, [view the package docs](https://github.com/megaeth-labs/wallet-merchant)
