# Permissions

The MOSS wallet comes with a rich permissions model which your app can utilise to give the best experience and
execute transactions faster. When a user has granted permissions to a defined set of calls, no approval screen is
presented to the user and transactions are instantly resolved on chain.

The process of using permissions is:
1. Define the contracts and spend limits
2. Request approval
3. Session created
4. Use [Call Contract](https://moss.megaeth.com/developers/methods/calling-contracts/call-contract) as normal

## Sessions
When permissions have been granted, a session key is generated for your app. This key is used to sign transactions
you request when making silent calls that have been approved by the user.

Session keys can be revoked by a user at any time and are automatically restored on a browser refresh. You can check
the status of your app's session using the [Get Permissions](https://moss.megaeth.com/developers/methods/calling-contracts/get-permissions)
method.

> [!NOTE]
> Only one session may be active at any time. You can append new permissions or replace when requesting
> permissions

## Defining Permissions
Your app can request approval to call certain contracts and spend a predefined set of tokens using the
[Grant Permissions](https://moss.megaeth.com/developers/methods/calling-contracts/grant-permissions) method.

This request consists of:
- An expiry
- Contract calls (address & function)
- Spend allowances (token, period & limit)

The permissions property of the request is defined as:

```ts
interface Permission {
    expiry: number; // unix timestamp in the future
    permissions: {
        calls: {
            signature: string; // function signature
            to: string; // contract address
        }[];
        spend: {
            limit: bigint; // max spend during the period
            period: 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
            token?: `0x${string}`; // token being spent. Blank for ETH
        }[];
    };
}
```

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.

These permissions can then be wrapped up in the permissions request and passed
to [Grant Permissions](https://moss.megaeth.com/developers/methods/calling-contracts/grant-permissions).

## Requesting Permissions
To request permissions, list the contract functions you wish to call and the tokens to spend in the request and call
[Grant Permissions](https://moss.megaeth.com/developers/methods/calling-contracts/grant-permissions).

When requesting permissions, you must choose if you want the session to be replaced or appended. The default
behaviour creates a new key for each request which automatically refreshes allowances.

For example, to request access to our test `store(uint256)` function and to spend a mock token, the request object
would look like:

```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: [
                {
                    signature: 'store(uint256)',
                    to: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
                },
            ],
            spend: [
                {
                    limit: parseEther('10'),
                    period: 'day',
                    token: '0x2715b6d04b6a0AB227631019899282a585Be410F',
                },
            ],
        },
    },
});

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 * 3, // 3 hours
                        permissions: {
                            calls: [
                                {
                                    signature: 'store(uint256)',
                                    to: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
                                },
                            ],
                            spend: [
                                {
                                    limit: parseEther('10'),
                                    period: 'day',
                                    token: '0x2715b6d04b6a0AB227631019899282a585Be410F',
                                },
                            ],
                        },
                    },
                })
            }
        >
            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 * 3, // 3 hours
                permissions: {
                    calls: [
                        {
                            signature: 'store(uint256)',
                            to: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
                        },
                    ],
                    spend: [
                        {
                            limit: parseEther('10'),
                            period: 'day',
                            token: '0x2715b6d04b6a0AB227631019899282a585Be410F',
                        },
                    ],
                },
            },
        });
    }

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

The user is presented with an approval screen which details the contract calls and spend limits you are requesting.

The user can modify the following before approving:
- Expiry
- Spend amount for any token
- Spend period for any token

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

## Executing Transactions
Once permissions have been granted, the same [Call Contract](https://moss.megaeth.com/developers/methods/calling-contracts/call-contract) can
be used as normal, including multi-calls and ERC-20 approvals. Calls the permissions cover are sent without a prompt.
You can change this using `silent: false` on a call to always ask the user.

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

const result = await mega.callContract({
    address: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
    abi: storageAbi,
    functionName: 'store',
    args: [42],
});

if (result.status === 'approved') {
    console.log('Transaction hash:', result.receipt?.hash);
}
```

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

export default function StoreButton() {
    const { mutate: callContract, isPending } = useCallContract();

    return (
        <button
            disabled={isPending}
            onClick={() =>
                callContract({
                    address: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
                    abi: storageAbi,
                    functionName: 'store',
                    args: [42],
                })
            }
        >
            Store 42
        </button>
    );
}
```

```tsx title="Wagmi"
import { useWriteContract } from 'wagmi';

export default function StoreButton() {
    const { writeContract, isPending } = useWriteContract();

    return (
        <button
            disabled={isPending}
            onClick={() =>
                writeContract({
                    address: '0x3e942744C21Eec1D88FBD463Fd0CcE42891Aec5C',
                    abi: storageAbi,
                    functionName: 'store',
                    args: [42n],
                })
            }
        >
            Store 42
        </button>
    );
}
```

The transaction will execute instantly without the user approving.

If permissions do not exist for the call (e.g. expired, spend amount used), the user will see the normal contract
approve screen and can manually approve the transaction. To disable this functionality and instead error, set
`silentUIApproveFallback: false` on any request.

If you attempt a silent call and the fallback is used, `silentHasUsedFallback` in the result will be true, allowing
you to respond by requesting new permissions.

## Defaults
By default, all calls will attempt to use session keys if they exist. You can change this functionality using the
`silentDefault` property when [initialising](https://moss.megaeth.com/developers/methods/connecting/initialise). When `false`, you must use
`silent: true` on a call contract request to use the session key.

If you want a user to explicitly approve an action when `silentDefault` is true or undefined, you can add
`silent: false` to any request object.

## 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 to 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.

## Permissions Status
The [Get Permissions](https://moss.megaeth.com/developers/methods/calling-contracts/get-permissions) method can be used to check the current
approval status and what was approved.

> [!NOTE]
> Spend amounts currently do not indicate remaining balances, only what was originally granted.

## Revoking Permissions
A user can revoke permissions from the embedded wallet or the [dashboard](https://account.megaeth.com) at any time.

Your app can also revoke its own permissions if required, or to provide that experience to your users.

> [!NOTE]
> It is not necessary to revoke before requesting new permissions. The default behaviour of `grantPermissions` is
> to replace the existing session key.
