# Call Contract

Use this method to call a smart contract you have deployed. Your request is validated to protect users before executing.

For the best experience:
- Verify your contract on [Etherscan](https://mega.etherscan.io/)
- Avoid unlimited approvals
- [Register](https://moss.megaeth.com/developers/get-started/register) your app
- Manually set maxGasAllowance for large executions
- Use multi-calls to `approve()` before transferring tokens instead of two calls

```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>
    );
}
```

```ts
// Pass an array of requests to batch them into one transaction.
interface CallContractRequest {
    address: `0x${string}`;
    abi?: any;
    functionName?: string;
    args?: any[];
    data?: `0x${string}`;
    value?: bigint | string;
    silent?: boolean;
    silentUIApproveFallback?: boolean;
    sponsor?: boolean;
    maxGasAllowance?: bigint;
}

interface TransactionResult {
    status: 'approved' | 'cancelled' | 'error';
    receipt?: TransactionReceipt;
    receipts?: TransactionReceipt[];
    error?: string;
    silentHasUsedFallback?: boolean;
}
```

## Multiple Calls
Pass an array of requests to execute all calls in one transaction. This is the recommended approach for requesting
`approve()` before transferring tokens.

> [!NOTE]
> When using session keys/permissions, approves are automatically revoked after each transaction so must be
> included in each transfer request.

Each request will be presented to the user along with any warnings for them to review in separate sections.

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

const amount = parseUnits('25', 18);

const result = await mega.callContract([
    {
        address: tokenAddress,
        abi: erc20Abi,
        functionName: 'approve',
        args: [vaultAddress, amount], // approve the exact amount, not unlimited
    },
    {
        address: vaultAddress,
        abi: vaultAbi,
        functionName: 'deposit',
        args: [amount],
    },
]);

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

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

const amount = parseUnits('25', 18);

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

    return (
        <>
            <button
                disabled={isPending}
                onClick={() =>
                    callContract([
                        {
                            address: tokenAddress,
                            abi: erc20Abi,
                            functionName: 'approve',
                            args: [vaultAddress, amount], // approve the exact amount, not unlimited
                        },
                        {
                            address: vaultAddress,
                            abi: vaultAbi,
                            functionName: 'deposit',
                            args: [amount],
                        },
                    ])
                }
            >
                Deposit 25
            </button>
            {data?.status === 'approved' && <p>Deposited: {data.receipt?.hash}</p>}
        </>
    );
}
```

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

const amount = parseUnits('25', 18);

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

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

        const { receipt } = await provider.callContract([
            {
                address: tokenAddress,
                abi: erc20Abi,
                functionName: 'approve',
                args: [vaultAddress, amount], // approve the exact amount, not unlimited
            },
            {
                address: vaultAddress,
                abi: vaultAbi,
                functionName: 'deposit',
                args: [amount],
            },
        ]);

        console.log('Transaction hash:', receipt?.hash);
    }

    return (
        <button onClick={deposit} disabled={!connector}>
            Deposit 25
        </button>
    );
}
```

## Silent Calls
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. The permissions either come from your app or by the user choosing to auto-approve specific
calls.

Calls are silent by default when permissions have been granted. Your flow should be:

1. [Request permissions](https://moss.megaeth.com/developers/methods/calling-contracts/grant-permissions)
2. Make a call contract request
3. Monitor the outcome

To always show the approval screen, set `silent: false` on a request, or `silentDefault: false` in your config to make
that the default.

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.

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

## Large Calls
The MOSS wallet sets a modest default maximum gas spend of ~$0.03 per transaction. This is enough to cover most
transaction
types. However, if your call contains a significant payload (e.g. deploying a contract), you can set a different
`maxGasAllowance` in the request.

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

const result = await mega.callContract({
    address: factoryAddress,
    abi: factoryAbi,
    functionName: 'deployERC721',
    args: [collectionConfig],
    // The most this call may spend on gas, in wei: here 0.0005 ETH.
    maxGasAllowance: parseEther('0.0005'),
});
```

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

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

    return (
        <button
            disabled={isPending}
            onClick={() =>
                callContract({
                    address: factoryAddress,
                    abi: factoryAbi,
                    functionName: 'deployERC721',
                    args: [collectionConfig],
                    // The most this call may spend on gas, in wei: here 0.0005 ETH.
                    maxGasAllowance: parseEther('0.0005'),
                })
            }
        >
            Deploy collection
        </button>
    );
}
```

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

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

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

        await provider.callContract({
            address: factoryAddress,
            abi: factoryAbi,
            functionName: 'deployERC721',
            args: [collectionConfig],
            // The most this call may spend on gas, in wei: here 0.0005 ETH.
            maxGasAllowance: parseEther('0.0005'),
        });
    }

    return (
        <button onClick={deploy} disabled={!connector}>
            Deploy collection
        </button>
    );
}
```
