> ## Documentation Index
> Fetch the complete documentation index at: https://docs.biconomy.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 4. Execute Workflow

> Submit signed supertransaction quotes for on-chain execution

The `/v1/execute` endpoint submits signed quotes for on-chain execution. After receiving a quote and signing the required payloads, this endpoint orchestrates the execution of your multi-chain operations via MEE nodes.

## Overview

The execute endpoint:

1. **Accepts signed quotes** - Takes the complete quote response with user signatures
2. **Submits to MEE network** - Routes transaction to MEE nodes for orchestration
3. **Handles multi-chain execution** - Manages cross-chain operations asynchronously
4. **Returns transaction hash** - Provides supertransaction hash for tracking

<Info>
  The execute endpoint expects the **complete quote response** with an updated `payloadToSign` array containing your signatures. Simply spread the quote and override the `payloadToSign` field.
</Info>

## Complete Workflow

<Steps>
  <Step title="Get Quote">
    Request a quote from `/v1/quote` with your operations defined in `composeFlows`
  </Step>

  <Step title="Sign Payloads">
    Sign the payloads based on the returned `quoteType`:

    * `permit`: Sign EIP-712 typed data (gasless)
    * `onchain`: Send approval transaction and get hash
    * `simple`: Sign raw message
  </Step>

  <Step title="Execute">
    Submit the entire quote response with signed payloads to `/v1/execute`
  </Step>

  <Step title="Monitor">
    Track execution using the returned `supertxHash` on MEE explorer
  </Step>
</Steps>

## Request Structure

```
POST /v1/execute
```

### Request Body

The request body is the complete quote response with an updated `payloadToSign` array:

```typescript theme={null}
{
  ...quoteResponse,           // Spread entire quote response
  payloadToSign: signedPayloads  // Override with signed payloads
}
```

### Key Fields

| Field           | Type   | Required | Description                                           |
| --------------- | ------ | -------- | ----------------------------------------------------- |
| `ownerAddress`  | string | Yes      | Owner wallet address (from quote)                     |
| `mode`          | string | Yes      | Execution mode: `eoa`, `smart-account`, or `eoa-7702` |
| `fee`           | object | Yes      | Fee details from quote response                       |
| `quoteType`     | string | Yes      | Signature type: `permit`, `onchain`, or `simple`      |
| `quote`         | object | Yes      | Complete quote object from quote response             |
| `payloadToSign` | array  | Yes      | Array of signed payloads with signatures              |
| `returnedData`  | array  | No       | Original data from composeFlows (from quote)          |

## Example Requests

<CodeGroup>
  ```typescript TypeScript theme={null}
  import { createWalletClient, createPublicClient, http } from 'viem';
  import { privateKeyToAccount } from 'viem/accounts';
  import { base } from 'viem/chains';

  const account = privateKeyToAccount('0x...');
  const walletClient = createWalletClient({
    account,
    chain: base,
    transport: http()
  });

  // Step 1: Get quote (see quote endpoint docs)
  const quote = await fetch('https://api.biconomy.io/v1/quote', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      mode: 'eoa',
      ownerAddress: account.address,
      fundingTokens: [...],
      composeFlows: [...]
    })
  }).then(r => r.json());

  // Step 2: Sign payloads (see previous section for details)
  const signedPayload = await signPayloads(quote, walletClient, account);

  // Step 3: Execute with signed payloads
  const executeResponse = await fetch('https://api.biconomy.io/v1/execute', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      ...quote,                    // Spread entire quote response
      payloadToSign: signedPayload // Override with signed payloads
    })
  });

  const result = await executeResponse.json();
  console.log('Supertx Hash:', result.supertxHash);
  console.log('MEE Explorer:', `https://meescan.biconomy.io/details/${result.supertxHash}`);
  ```

  ```bash cURL theme={null}
  # After getting quote and signing payloads
  curl -X POST https://api.biconomy.io/v1/execute \
    -H "Content-Type: application/json" \
    -d '{
      "ownerAddress": "0x742d35cc6639cb8d4b5d1c5d7b8b5e2e7c0c7a8a",
      "mode": "eoa",
      "fee": {
        "amount": "50000000000000000",
        "token": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
        "chainId": 8453
      },
      "quoteType": "permit",
      "quote": {
        "hash": "0xabcdef...",
        "node": "0x123456...",
        "commitment": "0xdeadbeef...",
        "paymentInfo": {...},
        "userOps": [...],
        "fundingTokens": [...]
      },
      "payloadToSign": [
        {
          "signablePayload": {
            "domain": {...},
            "types": {...},
            "primaryType": "Permit",
            "message": {...}
          },
          "metadata": {...},
          "signature": "0x1234567890abcdef..."
        }
      ],
      "returnedData": [...]
    }'
  ```

  ```python Python theme={null}
  import requests

  # After getting quote and signing payloads
  response = requests.post(
      'https://api.biconomy.io/v1/execute',
      headers={'Content-Type': 'application/json'},
      json={
          **quote,  # Spread quote response
          'payloadToSign': signed_payloads  # Override with signed payloads
      }
  )

  result = response.json()
  print(f"Supertx Hash: {result['supertxHash']}")
  print(f"MEE Explorer: https://meescan.biconomy.io/details/{result['supertxHash']}")
  ```
</CodeGroup>

## Response

Returns execution status and transaction hash:

```json theme={null}
{
  "success": true,
  "supertxHash": "0x9a72f87a93c55d8f88e3f8c2a7b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2",
  "error": null
}
```

### Response Fields

| Field         | Type           | Description                                       |
| ------------- | -------------- | ------------------------------------------------- |
| `success`     | boolean        | Indicates if execution was successful             |
| `supertxHash` | string \| null | Transaction hash of the executed supertransaction |
| `error`       | string \| null | Error message if execution failed                 |

## Monitoring Execution

After receiving the `supertxHash`, you can:

1. **Track on MEE Explorer**: `https://meescan.biconomy.io/details/{supertxHash}`
2. **Wait for completion** using MEE SDK:
   ```typescript theme={null}
   import { createMeeClient } from '@biconomy/mee-sdk';

   const meeClient = createMeeClient({...});
   const receipt = await meeClient.waitForSupertransactionReceipt({
     hash: result.supertxHash
   });

   console.log('Status:', receipt.status); // 'success' or 'failed'
   ```

For detailed monitoring guidance, see [Monitor Execution & Completion](https://docs.biconomy.io/new/getting-started/monitor-execution-completion).

## Complete Example by Mode

<Tabs>
  <Tab title="EOA Mode">
    **With Permit Signature (Gasless Approval)**

    ```typescript theme={null}
    // 1. Get quote
    const quote = await fetch('https://api.biconomy.io/v1/quote', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        mode: 'eoa',
        ownerAddress: account.address,
        fundingTokens: [{
          tokenAddress: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
          chainId: 8453,
          amount: parseUnits('100', 6).toString()
        }],
        feeToken: {
          address: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
          chainId: 8453
        },
        composeFlows: [
          {
            type: '/instructions/intent-simple',
            data: {
              srcChainId: 8453,
              dstChainId: 10,
              srcToken: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
              dstToken: '0x94b008aa00579c1307b0ef2c499ad98a8ce58e58',
              amount: parseUnits('100', 6).toString(),
              slippage: 0.01
            }
          },
          // Withdrawal instruction
          {
            type: '/instructions/build',
            data: {
              functionSignature: 'function transfer(address to, uint256 value)',
              args: [
                account.address,
                {
                  type: 'runtimeErc20Balance',
                  tokenAddress: '0x94b008aa00579c1307b0ef2c499ad98a8ce58e58',
                  constraints: { gte: '1' }
                }
              ],
              to: '0x94b008aa00579c1307b0ef2c499ad98a8ce58e58',
              chainId: 10
            }
          }
        ]
      })
    }).then(r => r.json());

    // 2. Sign permit (quoteType: 'permit')
    const permitPayload = quote.payloadToSign[0];
    const signature = await walletClient.signTypedData({
      ...permitPayload.signablePayload,
      account
    });

    // 3. Execute
    const result = await fetch('https://api.biconomy.io/v1/execute', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ...quote,
        payloadToSign: [{ ...permitPayload, signature }]
      })
    }).then(r => r.json());

    console.log('Supertx Hash:', result.supertxHash);
    ```
  </Tab>

  <Tab title="Smart Account">
    **Always Simple Signature**

    ```typescript theme={null}
    // 1. Get quote
    const quote = await fetch('https://api.biconomy.io/v1/quote', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        mode: 'smart-account',
        ownerAddress: account.address,
        // No fundingTokens - using existing Nexus balance
        // No feeToken - using sponsorship (gasless)
        composeFlows: [
          {
            type: '/instructions/intent-simple',
            data: {
              srcChainId: 8453,
              dstChainId: 10,
              srcToken: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
              dstToken: '0x94b008aa00579c1307b0ef2c499ad98a8ce58e58',
              amount: parseUnits('50', 6).toString(),
              slippage: 0.01
            }
          }
        ]
      })
    }).then(r => r.json());

    // 2. Sign simple message (quoteType: 'simple')
    const simplePayload = quote.payloadToSign[0];
    const signature = await walletClient.signMessage({
      ...simplePayload,
      account
    });

    // 3. Execute
    const result = await fetch('https://api.biconomy.io/v1/execute', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ...quote,
        payloadToSign: [{ ...simplePayload, signature }]
      })
    }).then(r => r.json());

    console.log('Supertx Hash:', result.supertxHash);
    ```
  </Tab>

  <Tab title="EIP-7702">
    **With Authorization (First Time)**

    ```typescript theme={null}
    // 1. Try quote without authorization
    let quoteResponse = await fetch('https://api.biconomy.io/v1/quote', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        mode: 'eoa-7702',
        ownerAddress: account.address,
        composeFlows: [...]
      })
    });

    // 2. Handle 412 response (authorization needed)
    if (quoteResponse.status === 412) {
      const error = await quoteResponse.json();

      // Sign authorizations
      const signedAuths = await Promise.all(
        error.authorizations.map(async (authItem) => {
          const authorization = await walletClient.signAuthorization({
            ...authItem,
            account
          });
          return {
            ...authorization,
            yParity: authorization.yParity,
            v: authorization.v?.toString()
          };
        })
      );

      // Retry quote with authorizations
      quoteResponse = await fetch('https://api.biconomy.io/v1/quote', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          mode: 'eoa-7702',
          ownerAddress: account.address,
          authorizations: signedAuths,
          composeFlows: [...]
        })
      });
    }

    const quote = await quoteResponse.json();

    // 3. Sign simple message (quoteType: 'simple')
    const signature = await walletClient.signMessage({
      account,
      message: quote.payloadToSign[0].message
    });

    // 4. Execute (delegation + operations happen atomically)
    const result = await fetch('https://api.biconomy.io/v1/execute', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ...quote,
        payloadToSign: [{ ...quote.payloadToSign[0], signature }]
      })
    }).then(r => r.json());

    console.log('Supertx Hash:', result.supertxHash);
    ```
  </Tab>
</Tabs>

## Error Handling

The endpoint returns appropriate HTTP status codes:

### 200 Success

```json theme={null}
{
  "success": true,
  "supertxHash": "0x9a72f87a93c55d8f88e3f8c2a7b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2",
  "error": null
}
```

### 400 Bad Request

```json theme={null}
{
  "code": "VALIDATION_ERROR",
  "message": "Invalid request parameters",
  "errors": [
    {
      "code": "INVALID_SIGNATURE",
      "path": ["payloadToSign", "0", "signature"],
      "message": "Invalid signature format"
    }
  ]
}
```

### 500 Internal Server Error

```json theme={null}
{
  "code": "INTERNAL_ERROR",
  "message": "An unexpected error occurred",
  "errors": [
    {
      "code": "SERVER_ERROR",
      "path": [],
      "message": "Internal server error"
    }
  ]
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="Verify Quote Before Execution">
    Always validate fee amounts and expected outputs before signing:

    ```typescript theme={null}
    // Check execution fee
    const feeInUSDC = formatUnits(BigInt(quote.fee.amount), 6);
    if (feeInUSDC > 0.5) {
      throw new Error(`Fee too high: ${feeInUSDC}`);
    }

    // Verify expected output
    const minOutput = quote.returnedData[0]?.minOutputAmount;
    console.log('Minimum output after slippage:', minOutput);
    ```
  </Accordion>

  <Accordion title="Handle All Signature Types">
    Implement handlers for all three quote types:

    ```typescript theme={null}
    let signedPayload;

    if (quote.quoteType === 'permit') {
      // Handle EIP-2612 signature
      signedPayload = await signPermit(quote);
    } else if (quote.quoteType === 'onchain') {
      // Handle on-chain approval
      signedPayload = await sendApprovalTx(quote);
    } else {
      // Handle simple signature
      signedPayload = await signSimple(quote);
    }
    ```
  </Accordion>

  <Accordion title="Wait for On-Chain Approvals">
    For `onchain` quote type, always wait for transaction confirmation:

    ```typescript theme={null}
    const txHash = await walletClient.sendTransaction({
      to: payload.to,
      data: payload.data,
      value: payload.value || 0n
    });

    // Critical: Wait for confirmation before executing
    await publicClient.waitForTransactionReceipt({ hash: txHash });

    // Use txHash as signature
    const signedPayload = [{ ...payload, signature: txHash }];
    ```
  </Accordion>

  <Accordion title="Monitor Execution Status">
    Track supertransaction completion using MEE SDK:

    ```typescript theme={null}
    const result = await executeQuote(quote);

    // Wait for completion
    const receipt = await meeClient.waitForSupertransactionReceipt({
      hash: result.supertxHash,
      timeout: 120000 // 2 minutes
    });

    if (receipt.status !== 'success') {
      throw new Error('Supertransaction failed');
    }
    ```
  </Accordion>

  <Accordion title="Handle Execution Errors">
    Check the `success` field and handle errors appropriately:

    ```typescript theme={null}
    const result = await fetch('/v1/execute', {...}).then(r => r.json());

    if (!result.success) {
      console.error('Execution failed:', result.error);
      // Handle specific error cases
      if (result.error.includes('insufficient balance')) {
        // Notify user about balance issue
      }
      throw new Error(`Execution failed: ${result.error}`);
    }
    ```
  </Accordion>
</AccordionGroup>
