# Grant Permissions

Request approval to silently call contracts. When making the grant request, you must decide if the session key
should be extended or replaced using the `append` property (default false).

The `spend` array can only contain one instance of each token you are requesting permissions for. When using `append`
and setting a `spend` for an existing token, the `limit` of existing records will be set to `0` to avoid the user
unknowingly granting more allowance than presented.

> [!NOTE]
> For example, initially requesting 10 USDm per day and then appending to 20 USDm per hour, results in a single
> permission on chain for 20 USDm per hour.

Granting permissions requires the wallet to have gas or be [sponsored](https://moss.megaeth.com/developers/concepts/sponsoring-gas).

[Learn more](https://moss.megaeth.com/developers/concepts/permissions)

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

const result = await mega.grantPermissions({
    permissions: {
        expiry: Math.floor(Date.now() / 1000) + 60 * 60 * 3, // 3 hours
        permissions: {
            calls: [{ to: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C', signature: 'store(uint256)' }],
            spend: [{ limit: parseEther('0.01'), period: 'day' }],
        },
    },
});

if (result.status === 'approved') {
    console.log('Permissions granted');
}
```

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

export default function GrantButton() {
    const { mutate: grantPermissions, isPending } = useGrantPermissions();

    return (
        <button
            disabled={isPending}
            onClick={() =>
                grantPermissions({
                    permissions: {
                        expiry: Math.floor(Date.now() / 1000) + 60 * 60 * 24, // 24 hours
                        permissions: {
                            calls: [{ to: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C', signature: 'store(uint256)' }],
                            spend: [{ limit: parseEther('0.01'), period: 'day' }],
                        },
                    },
                })
            }
        >
            Allow quick actions
        </button>
    );
}
```

```tsx title="Wagmi"
import type { MegaWalletProvider } from '@megaeth-labs/wallet-wagmi-connector';
import { parseEther } from 'viem';
import { useAccount } from 'wagmi';

export default function GrantButton() {
    const { connector } = useAccount();

    async function grant() {
        const provider = (await connector?.getProvider()) as MegaWalletProvider;

        // The user approves this once. It throws if they cancel.
        await provider.grantPermissions({
            permissions: {
                expiry: Math.floor(Date.now() / 1000) + 60 * 60 * 24, // 24 hours
                permissions: {
                    calls: [{ to: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C', signature: 'store(uint256)' }],
                    spend: [{ limit: parseEther('0.01'), period: 'day' }],
                },
            },
        });
    }

    return (
        <button onClick={grant} disabled={!connector}>
            Allow quick actions
        </button>
    );
}
```

```ts
interface GrantPermissionsRequest {
    permissions: Permission;
    externalAddress?: `0x${string}`;
    sponsor?: boolean;
    append?: boolean;
}

interface Permission {
    expiry: number;
    permissions: {
        calls: { signature: string; to: string }[];
        spend: {
            limit: bigint;
            period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
            token?: `0x${string}`;
        }[];
    };
}

type GrantPermissionsResponse = {
    status: 'approved' | 'cancelled';
};
```

## Executing on Your Server
If your app requires a transaction to be executed on your server on behalf of the user, you can add the executing
wallet address to the request using the `externalAddress`. This will grant your wallet the ability to execute
transactions on behalf of the user without their presence or simplify your verification flow.

```ts title="server.ts"
import { Account, Key, sendCalls } from '@megaeth-labs/wallet-intent';
import { createClient, http, parseAbi } from 'viem';
import { megaethTestnet } from 'viem/chains';

const STORAGE_CONTRACT = '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C';
const storageAbi = parseAbi(['function store(uint256 value)']);

// The relay that submits transactions for MOSS accounts.
const relay = createClient({
    chain: megaethTestnet,
    transport: http('https://carrot.megaeth.com/relay'),
});

// Your server's key. Its address is the `externalAddress` the user granted permissions to.
const serverKey = Key.fromSecp256k1({
    privateKey: process.env.SERVER_PRIVATE_KEY as `0x${string}`,
});

export async function storeForUser(user: `0x${string}`, value: bigint) {
    const receipt = await sendCalls(relay, {
        account: Account.from(user),
        key: serverKey,
        calls: [
            {
                to: STORAGE_CONTRACT,
                abi: storageAbi,
                functionName: 'store',
                args: [value],
            },
        ],
    });

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

    return receipt.transactionHash;
}
```

### Example
You are creating a game where the user performs an action which is validated by the server before executing a
transaction.

Typically this would look something like:
- Client makes request to server
- Server verifies and issues a signature
- Client creates a transaction including the signature
- Client broadcasts and waits for response
- Blockchain verifies the signature
- Client gets the response and sends to the server
- Server verifies response on chain
- Server completes internal actions

This can be simplified using permissions by having the user approve the server wallet to send on their behalf. Once
granted the flow becomes:
- Client makes request to server
- Server verifies and broadcasts a `realtime` transaction
- Server completes internal actions

As the server is in full control and can execute the transaction synchronously in a single RPC call, there is no
need to validate the client executed correctly.
