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

# 7702 Execution Mode

> Run workflows with an EOA delegated via EIP‑7702 to a smart account implementation.

# EIP-7702 Execution Mode

EIP-7702 enables Externally Owned Accounts (EOAs) to temporarily delegate their execution logic to a smart account implementation. This provides EOAs with advanced capabilities like batch transactions and sponsored operations while maintaining full control.

## Key Benefits

<CardGroup cols={3}>
  <Card title="Keep Your Address" icon="fingerprint">
    No need to migrate to a new address - use your existing EOA
  </Card>

  <Card title="Atomic Delegation" icon="bolt">
    Delegation and execution happen in a single supertransaction
  </Card>

  <Card title="Reversible" icon="rotate">
    Delegation can be revoked at any time
  </Card>
</CardGroup>

## Key Advantages Over Standard EOA

* **Smart Account Features**: Batch transactions, custom validation, sponsorship
* **Gasless Operations**: Enable sponsored transactions through delegation
* **No Address Migration**: Keep using your existing EOA address
* **Full Control**: Delegation is opt-in and revocable

## How It Works

EIP-7702 mode uses a **412 fallback pattern** for authorization:

1. **Initial Quote Attempt**: Try to get quote without authorization
2. **412 Response**: If EOA not delegated, API returns 412 with needed authorizations
3. **Sign Authorizations**: Sign the returned authorization data
4. **Retry Quote**: Include signed authorizations in new quote request
5. **Atomic Execution**: Delegation + operations happen in single supertransaction

<Info>
  **Important**: When authorization is provided, the supertransaction **atomically performs both delegation and execution**. There's no need to wait for delegation to be mined separately.
</Info>

## Requirements

* **Must NOT provide**: `fundingTokens` field (not needed)
* **If not delegated**: Must provide `authorizations` after receiving 412 response
* **Signature type**: API always returns `simple`
* **Prerequisites**: EOA must have funds for operations or use Nexus balance

## Complete Flow Example

Here's the recommended flow using the 412 fallback pattern:

```typescript theme={null}
import { createWalletClient, http, parseUnits } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { base } from 'viem/chains';

const API_BASE_URL = 'https://api.biconomy.io';
const account = privateKeyToAccount('0x...');

const walletClient = createWalletClient({
  account,
  chain: base,
  transport: http()
});

async function eip7702CrossChainSwap() {
  // Step 1: Build initial quote request (without authorizations)
  const quoteRequestBase = {
    mode: 'eoa-7702',
    ownerAddress: account.address,
    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
        }
      }
    ]
  };

  // Step 2: Try to get quote
  let quote;
  let quoteResponse = await fetch(`${API_BASE_URL}/v1/quote`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(quoteRequestBase)
  });

  // Step 3: Handle 412 response (missing authorization)
  if (quoteResponse.status === 412) {
    console.log('❌ EOA not delegated - need to authorize first');

    const error = await quoteResponse.json();
    const authItems = error.authorizations;

    console.log(`✅ Got ${authItems.length} authorization(s) to sign`);

    // Step 4: Sign authorizations
    const signedAuths = await Promise.all(
      authItems.map(async (authItem) => {
        const authorization = await walletClient.signAuthorization({
          ...authItem,
          account
        });

        return {
          ...authorization,
          yParity: authorization.yParity,
          v: authorization.v?.toString()
        };
      })
    );

    console.log('✅ Signed authorizations');

    // Step 5: Retry quote with authorizations
    quoteResponse = await fetch(`${API_BASE_URL}/v1/quote`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ...quoteRequestBase,
        authorizations: signedAuths
      })
    });

    console.log('Note: When executed, this will atomically:');
    console.log('1. Delegate the EOA (using the signed authorization)');
    console.log('2. Execute all compose flows in the same transaction');
  } else {
    console.log('✅ EOA already delegated - will just execute operations');
  }

  quote = await quoteResponse.json();
  console.log('Fee:', quote.fee.amount, 'wei');
  console.log('Quote type:', quote.quoteType); // Always 'simple'

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

  const signedPayload = [{ ...quote.payloadToSign[0], signature }];

  // Step 7: Execute (delegation + operations happen atomically if auth was provided)
  const executeResponse = await fetch(`${API_BASE_URL}/v1/execute`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      ...quote,
      payloadToSign: signedPayload
    })
  });

  const result = await executeResponse.json();
  console.log('Transaction hash:', result.transactionHash);
  console.log('UserOps:', result.userOps);

  return result;
}

// Execute
eip7702CrossChainSwap();
```

## Authorization Structure

The 412 error response includes authorization data:

```typescript theme={null}
// 412 Response
{
  "error": "MISSING_AUTHORIZATION",
  "message": "EIP-7702 authorization required",
  "authorizations": [
    {
      "chainId": 8453,
      "address": "0x00000069E0Fb590E092Dd0E36FF93ac28ff11a3a",
      "nonce": 38
    }
  ]
}
```

Sign each authorization using viem's `signAuthorization`:

```typescript theme={null}
const authorization = await walletClient.signAuthorization({
  chainId: authItem.chainId,
  address: authItem.address,
  nonce: authItem.nonce,
  account
});

// Return with proper format
const signedAuth = {
  ...authorization,
  yParity: authorization.yParity,
  v: authorization.v?.toString()
};
```

## Authorization Fields

| Field     | Description                                      |
| --------- | ------------------------------------------------ |
| `address` | Smart account implementation contract address    |
| `chainId` | Target chain (or 0 for multi-chain)              |
| `nonce`   | Prevents replay attacks                          |
| `r`, `s`  | ECDSA signature components (after signing)       |
| `yParity` | EIP-2098 compact signature value (after signing) |

<Tip>
  **Chain ID Options:**

  * Use `0` for multi-chain authorization (works across all chains)
  * Use specific chain ID for chain-specific delegation
</Tip>

## Advanced Example: Multi-Step DeFi

Complete example with DeFi operations:

```typescript theme={null}
const quoteRequestBase = {
  mode: 'eoa-7702',
  ownerAddress: account.address,
  composeFlows: [
    // Cross-chain swap
    {
      type: '/instructions/intent-simple',
      data: {
        srcChainId: 8453,
        dstChainId: 10,
        srcToken: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
        dstToken: '0x94b008aa00579c1307b0ef2c499ad98a8ce58e58',
        amount: parseUnits('100', 6).toString(),
        slippage: 0.01
      }
    },
    // Approve Aave
    {
      type: '/instructions/build',
      data: {
        functionSignature: 'function approve(address spender, uint256 amount)',
        args: [
          '0x...aavePool',
          {
            type: 'runtimeErc20Balance',
            tokenAddress: '0x94b008aa00579c1307b0ef2c499ad98a8ce58e58'
          }
        ],
        to: '0x94b008aa00579c1307b0ef2c499ad98a8ce58e58',
        chainId: 10
      }
    },
    // Supply to Aave
    {
      type: '/instructions/build',
      data: {
        functionSignature: 'function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode)',
        args: [
          '0x94b008aa00579c1307b0ef2c499ad98a8ce58e58',
          {
            type: 'runtimeErc20Balance',
            tokenAddress: '0x94b008aa00579c1307b0ef2c499ad98a8ce58e58'
          },
          account.address,
          0
        ],
        to: '0x...aavePool',
        chainId: 10,
        gasLimit: '350000'
      }
    }
  ]
};

// Handle 412 fallback pattern (same as above)
```

## Best Practices

<AccordionGroup>
  <Accordion title="Use 412 Fallback Pattern">
    Always use the 412 fallback pattern - don't preemptively check delegation:

    ```typescript theme={null}
    // ✅ GOOD - Let API tell you what's needed
    try {
      quote = await getQuote(requestWithoutAuth);
    } catch (error) {
      if (error.status === 412) {
        const signedAuths = await signAuthorizations(error.authorizations);
        quote = await getQuote({ ...request, authorizations: signedAuths });
      }
    }

    // ❌ BAD - Don't check delegation status yourself
    if (await isDelegated()) {
      quote = await getQuote(request);
    } else {
      // Manual delegation logic
    }
    ```
  </Accordion>

  <Accordion title="Understand Atomic Execution">
    Delegation and operations happen in a single supertransaction:

    * **No separate delegation transaction needed**
    * **No waiting for delegation to be mined**
    * **Everything is atomic**: either all succeeds or all fails

    ```typescript theme={null}
    // When authorization is provided:
    // 1. EOA is delegated
    // 2. Operations execute
    // All in ONE supertransaction ✨
    ```
  </Accordion>

  <Accordion title="Cache Authorizations">
    Once delegated, authorizations remain valid until revoked:

    ```typescript theme={null}
    // First time: 412 → sign auth → retry
    // Subsequent requests: No 412, just execute

    // You can check delegation status if needed:
    const isDelegated = await checkDelegationStatus(ownerAddress, chainId);
    ```
  </Accordion>

  <Accordion title="Multi-Chain Authorizations">
    Use `chainId: 0` for operations across multiple chains:

    ```typescript theme={null}
    const authorization = await walletClient.signAuthorization({
      chainId: 0,  // Works for all chains
      address: '0x...',
      nonce: 38,
      account
    });
    ```
  </Accordion>

  <Accordion title="Handle Authorization Errors">
    Always handle both 412 and other potential errors:

    ```typescript theme={null}
    try {
      quote = await getQuote(request);
    } catch (error) {
      if (error.status === 412) {
        // Handle missing authorization
      } else if (error.status === 400) {
        // Handle invalid request
      } else {
        // Handle other errors
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Comparison with Other Modes

| Feature                | EIP-7702         | EOA            | Smart Account |
| ---------------------- | ---------------- | -------------- | ------------- |
| Funds Location         | EOA (delegated)  | EOA            | Nexus         |
| Setup Complexity       | **Medium**       | Low            | Low           |
| Authorization Required | Yes (first time) | No             | No            |
| Delegation + Execution | **Atomic**       | N/A            | N/A           |
| Signature Type         | simple           | permit/onchain | simple        |
| Batch Transactions     | **Yes**          | No             | Yes           |
| Sponsored Transactions | **Yes**          | No             | Yes           |
| Address Change         | **No**           | No             | No            |
| Reversible             | **Yes**          | N/A            | N/A           |
| Gas for Approval       | **No**           | Sometimes      | No            |

## Troubleshooting

<AccordionGroup>
  <Accordion title="412 error on first request">
    **This is expected behavior!** The API returns 412 when the EOA needs delegation:

    1. Extract `authorizations` from the 412 response
    2. Sign each authorization with `walletClient.signAuthorization()`
    3. Retry quote with signed authorizations
    4. Execute normally - delegation happens atomically
  </Accordion>

  <Accordion title="Authorization signature invalid">
    Verify you're signing with the correct account:

    ```typescript theme={null}
    // Ensure account matches ownerAddress
    const authorization = await walletClient.signAuthorization({
      ...authItem,
      account  // Must match ownerAddress in quote request
    });
    ```
  </Accordion>

  <Accordion title="Already delegated but getting 412">
    This may happen if:

    * Delegation was revoked
    * Different chain requires delegation
    * Nonce has changed

    Simply follow the 412 fallback pattern again.
  </Accordion>

  <Accordion title="How to revoke delegation">
    To revoke delegation, set the delegation address to `0x0`:

    ```typescript theme={null}
    // This would need to be done through a direct transaction
    // Not currently supported via Supertransaction API
    // Contact support for assistance
    ```
  </Accordion>
</AccordionGroup>

## Security Considerations

<Warning>
  **Authorization Safety:**

  * Always verify the delegation address is an official smart account implementation
  * Check the chain ID matches your intended scope (0 for multi-chain, specific for single-chain)
  * Monitor nonce values to prevent replay attacks
  * Authorizations can be revoked by setting delegation address to `0x0`
  * Only sign authorizations you trust
</Warning>

## Workflow Diagram

```
┌─────────────────────────────────────────────────────────┐
│ 1. Try Quote (without authorization)                    │
└────────────────┬────────────────────────────────────────┘
                 │
                 ├─ Already Delegated → Get Quote → Execute
                 │
                 └─ Not Delegated (412)
                        │
                        ▼
              ┌──────────────────────┐
              │ 2. Receive 412       │
              │    with authorizations│
              └──────────┬───────────┘
                        │
                        ▼
              ┌──────────────────────┐
              │ 3. Sign               │
              │    authorizations     │
              └──────────┬───────────┘
                        │
                        ▼
              ┌──────────────────────┐
              │ 4. Retry Quote       │
              │    with signed auths │
              └──────────┬───────────┘
                        │
                        ▼
              ┌──────────────────────┐
              │ 5. Execute           │
              │    (delegation +     │
              │     operations       │
              │     atomic)          │
              └──────────────────────┘
```
