> For the complete documentation index, see [llms.txt](https://docs.peach.ag/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.peach.ag/documentation/arc/aggregator/core-features/delegated-execution-with-permit2-witness.md).

# Delegated Swaps

Prepare swaps for a payer and a separate executor using Permit2 Witness authorization.

**SDK 1.3.0:** The examples below use aliases for `swapPermit2()` and `swapPermit2Build()`. For a single quote request, call `permit2Swap()`, sign the authorization, then call `completePermit2Swap()`.

### Roles and allowances

| Item                     | Requirement                                                    |
| ------------------------ | -------------------------------------------------------------- |
| Payer                    | Input-token owner; must differ from executor                   |
| Executor                 | Final transaction sender, bound into the execution plan        |
| Recipient                | Required explicitly; receives output and need not be the payer |
| ERC-20 allowance spender | `0x000000000022D473030F116dDEE9F6B43aC78BA3`                   |
| Permit2 Witness spender  | Arc Execution Router                                           |
| Transaction destination  | Arc Execution Router                                           |

The ERC-20 allowance and the Witness signature authorize different layers. Approving Permit2 does not itself authorize an arbitrary swap. Conversely, signing the Witness does not create an ERC-20 allowance. The payer needs input tokens and, when an approval is needed, gas for that approval. The executor needs gas for execution.

The current API and SDK flow use an ECDSA payer authorization. Do not assume EIP-1271 smart-contract-wallet signatures are supported by this prepare/build path. Native input is unsupported, and current Arc execution is ERC-20-only for both directions.

### Prepare, sign and build

Use **prepare → payer signature → build** when payer and executor differ. `prepareDelegatedSwap()` returns the quote and authorization together. Review and accept those prepared terms before signing; `buildDelegatedSwap()` builds the transaction from that same plan without another route search.

| Method                                          | Result                                                                      |
| ----------------------------------------------- | --------------------------------------------------------------------------- |
| `prepareDelegatedSwap(params)`                  | Quote, roles, plan hash and payer authorization; `PAYER_SIGNATURE_REQUIRED` |
| `signPayerAuthorization(prepared, payerWallet)` | Payer's Permit2 Witness signature                                           |
| `buildDelegatedSwap(prepared, signature)`       | Validated transaction; `TRANSACTION_READY`                                  |

Before signing, display `prepared.amountIn`, `prepared.expectAmountOut`, `BigInt(prepared.raw.amount_out_min)`, recipient, payer, executor, fees and authorization deadline. Signing authorizes execution by the designated executor; a later UI confirmation cannot revoke that signature.

### Complete helpers

Import `ArcClient`, `ARC_TESTNET_CONFIG`, `arcTestnet` and `PreparedDelegatedSwap` from the SDK, and `Address`, `PublicClient`, `WalletClient` types from viem. These examples use Arc Testnet. `delegatedSwap()` gets the quote for review; after payer acceptance, pass the unchanged result to `submitDelegatedSwap()`.

```typescript
/** Delegated: prepare returns the quote and authorization for payer review. */
export async function delegatedSwap(
  publicClient: PublicClient, from: Address, target: Address, amount: bigint,
  payer: Address, executor: Address, recipient: Address,
) {
  const arc = new ArcClient(ARC_TESTNET_CONFIG, publicClient);
  return arc.prepareDelegatedSwap({ from, target, amount, payer, executor, recipient, slippageBps: 50, deadlineSecs: 120 });
}

/** Call only after the payer accepts the prepared terms, including the minimum output. */
export async function submitDelegatedSwap(
  publicClient: PublicClient, payerWallet: WalletClient,
  executorWallet: WalletClient, prepared: PreparedDelegatedSwap,
) {
  const payerAccount = payerWallet.account ?? (await payerWallet.getAddresses())[0];
  const executorAccount = executorWallet.account ?? (await executorWallet.getAddresses())[0];
  if (!payerAccount || !executorAccount) throw new Error("Connect payer and executor accounts first");
  const payer = typeof payerAccount === "string" ? payerAccount : payerAccount.address;
  const executor = typeof executorAccount === "string" ? executorAccount : executorAccount.address;
  if (payer.toLowerCase() !== prepared.payer.toLowerCase() || executor.toLowerCase() !== prepared.executor.toLowerCase()) throw new Error("Wallet account changed");
  if (await payerWallet.getChainId() !== ARC_TESTNET_CONFIG.chainId || await executorWallet.getChainId() !== ARC_TESTNET_CONFIG.chainId) throw new Error("Switch both wallets to Arc Testnet");
  const arc = new ArcClient(ARC_TESTNET_CONFIG, publicClient);
  const approval = await arc.buildPermit2TokenApproval(prepared.tokenIn, payer, prepared.amountIn);
  if (approval) {
    const hash = await payerWallet.sendTransaction({ ...approval, account: payerAccount, chain: arcTestnet });
    const receipt = await publicClient.waitForTransactionReceipt({ hash });
    if (receipt.status !== "success") throw new Error(`Permit2 approval reverted: ${hash}`);
  }
  // Signing and build validate expiry. If approval consumed the deadline, prepare and confirm again.
  const signature = await arc.signPayerAuthorization(prepared, payerWallet);
  const ready = await arc.buildDelegatedSwap(prepared, signature);
  await publicClient.call({ ...ready.tx, account: executor });
  const hash = await executorWallet.sendTransaction({ ...ready.tx, account: executorAccount, chain: arcTestnet });
  console.log("Transaction hash:", hash);
  const receipt = await publicClient.waitForTransactionReceipt({ hash });
  if (receipt.status !== "success") throw new Error(`Swap reverted: ${hash}`);
  return { hash, receipt };
}
```

The Permit2 approval helper defaults to the exact input amount and returns `undefined` when allowance is sufficient. Approval and the Witness signature are separate authorizations. If the plan expires while approving, prepare again and have the payer review and sign the replacement terms.

The SDK checks that the build matches the prepared quote, including the minimum net output. Preserve the complete object and all accepted inputs. A changed token, amount, account, recipient, network, routing, fee or slippage requires a new preparation and confirmation. See [Slippage](https://docs.peach.ag/documentation/arc/aggregator/core-features/slippage).

### What is available at each step

| Step    | Available data                                                                 | Not yet established                                               |
| ------- | ------------------------------------------------------------------------------ | ----------------------------------------------------------------- |
| Prepare | Quote amounts, roles, plan hash, aggregator signature and `payerAuthorization` | Full plan, route and executable transaction are absent            |
| Sign    | Payer signature over the typed authorization                                   | No transaction has been submitted; allowance still needs to exist |
| Build   | `tx`, decoded `execution`, and retained prepared result                        | On-chain execution success is not guaranteed                      |
| Confirm | Receipt status and execution events                                            | A failed receipt must not be shown as a successful swap           |

Both result types use `executionMode: "PERMIT2_WITNESS"`. `PreparedDelegatedSwap` has `status: "PAYER_SIGNATURE_REQUIRED"`, IDs, roles, amounts, requested fees, `payerAuthorization`, `constraints` and raw prepare data. `ReadyDelegatedSwap` has `status: "TRANSACTION_READY"`, IDs, roles, `tx`, decoded `execution`, retained `prepared` and raw build data. Build does not re-route or accept changed amounts, roles, fees or deadlines. Its JSON request consists only of `quote_id` and `payer_signature`.

### Signature binding and trust boundary

`signPayerAuthorization` verifies the payer account and authorization fields, converts integer strings to the expected EIP-712 values, and signs the Witness. A bound wallet account must match the prepared payer; an unbound browser wallet must expose that payer in its addresses.

The deployed prepare response does not include the full plan or route. Before signing, the payer therefore trusts the API to bind the displayed quote and requested fees to the returned plan hash. After build, the SDK decodes and validates the full transaction against those prepared terms. A failed build validation prevents a ready transaction from being returned, but does not revoke a signature already sent to the API.

Keep the complete prepared object unchanged. A changed payer, recipient, amount or fee requires a fresh prepare and signature. The authorization binds a nonce and deadline; a mined execution cannot be replayed as a new order.

### Failure recovery

| Failure                                 | Action                                                                        |
| --------------------------------------- | ----------------------------------------------------------------------------- |
| Wallet rejects signing                  | Stop; allow the user to restart explicitly                                    |
| Bound account does not match payer      | Connect the correct payer; do not silently substitute another account         |
| Quote artifact or authorization expired | Prepare again and obtain a new signature                                      |
| Build rejected or attempt limit reached | Inspect the error; do not loop on build requests                              |
| Full-plan validation failed             | Stop and investigate; do not bypass the SDK and submit raw calldata           |
| Submission outcome unknown              | Check the known hash and executor nonce before attempting another transaction |

Never place payer signatures in query strings, application logs, analytics or error reporting. Build uses POST JSON and execution responses must not be cached. See [Build API](https://docs.peach.ag/api-reference/arc-aggregator/build) and [Transaction Safety](https://docs.peach.ag/documentation/arc/aggregator/core-features/validation-approvals-and-expiry).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.peach.ag/documentation/arc/aggregator/core-features/delegated-execution-with-permit2-witness.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
