Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .claude/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ The public API is whatever `src/index.ts` re-exports: client, composer, constant
- Launch-token swaps (`quote.launch`): the user-signed HayLaunch curve call is found by ABI selector (`launchCurveSide()` in `composer.ts`). A buy's output is the curve call's ARC-4 uint64 return, not an inner transfer; a sell's input is the `tokensToSell` app arg.
- Every other API txn carries a logic-sig or secret-key `signature` and is re-signed locally by `createSwapSigner()`. The API's group ID is stripped and reassigned by the ATC.
- The user signer can be an `algosdk.TransactionSigner` or an ARC-1 `SignerFunction`. `defaultSigner` filters out the `null`s that ARC-1 wallets return.
- Falcon signers (`signerType: 'falcon'` on `newQuote()`, sent as the `signerType` query param): a Falcon signature costs 3 fee units, so `addSignerFees()` adds `FALCON_EXTRA_FEE` (2000n) to the input txn's fee for each txn sent from `address` whose extra fee the router's fees don't include, once, before the ATC builds the group (`buildGroup`/`sign`/`submit`/`execute`). The user pays every fee; the router includes the extra in the fees of the txns it builds, and says so in the execute response (`FetchSwapTxnsResponse.signerType === 'falcon'`, which `newSwap()` passes as `signerFeesIncluded`). Never decide that from the quote's echo: a router pod mid-rollout can quote with it and build without. Then only the composer's own txns are counted (`trackSignerFee` at each add: app opt-ins, middleware, `addTransaction`, `addMethodCall` and its txn args). Every new way of adding a txn must call `trackSignerFee`. `SwapQuote.signerType` only says the account is Falcon (requested, or copied from a raw echo); the composer defaults to it.

### Middleware (`middleware.ts`, docs in `packages/haystack/MIDDLEWARE.md`)

Expand Down
8 changes: 7 additions & 1 deletion packages/haystack/MIDDLEWARE.md
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,13 @@ async adjustQuoteParams(params: FetchQuoteParams): Promise<FetchQuoteParams> {
}
```

### 3. Additional Best Practices
### 3. Keep the Caller's Params and Leave Falcon Fees to the SDK

Return `{ ...params, ... }` from `adjustQuoteParams()` rather than a new object, so the caller's other params reach the router. A dropped `signerType`, for example, makes the router plan and build for an ed25519 signer.

Don't add a Falcon signer's extra fees to the transactions you return from `beforeSwap()` or `afterSwap()`. The `SwapComposer` counts every transaction sent from the swap's `address` and adds 0.002 ALGO for each to the swap's input transfer when the account is a Falcon signer (`context.quote.signerType === 'falcon'`). Raising your own fees too charges the user twice.

### 4. Additional Best Practices
- **Minimize transactions**: Only add when absolutely necessary
- **Cache queries**: Avoid redundant smart contract calls
- **Handle errors**: Return empty arrays to avoid breaking swaps
Expand Down
33 changes: 33 additions & 0 deletions packages/haystack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,36 @@ if (quote.firstStage) {

Without `address`, the swap is built without First Stage's calls, which fails for a frozen holding. Don't use a First Stage middleware (such as `@firststage/deflex-middleware`) with the router: its calls and the router's would be added twice, and the group fails. This applies to ORDER_ROUTER v4 swaps, and is on for API keys by default; contact TxnLab if your key's integration still wraps these swaps itself.

### Falcon (Post-Quantum) Accounts

A transaction signed with a Falcon-1024 key (passkey accounts, Pera and Lute quantum accounts) costs 3 fee units instead of 1, so the swap group's fees must cover 0.002 ALGO more for each transaction the account signs. Pass `signerType: 'falcon'`:

```typescript
import { getSignatureType } from '@txnlab/use-wallet'

const quote = await router.newQuote({
fromASAID: 0,
toASAID: 31566704,
amount: 1_000_000,
address: activeAddress,
signerType:
getSignatureType(activeAccount.emptySignature) === 'pqsig'
? 'falcon'
: 'ed25519',
})
```

The router includes the extra in the fees of the transactions it builds, and the `SwapComposer` adds it for the ones it or your code adds: app opt-ins, middleware transactions, `addTransaction()` and `addMethodCall()` calls sent from `address`. It all goes on the fee of the swap's input transfer, which the account pays, before the group ID is assigned, so no transaction is added. `buildGroup()`'s fees and `getSummary().totalFees` include it.

`newSwap()` reads whether the router's transactions include it from the router's response to the swap request (its `signerType`), not from the quote. When they don't (a router that doesn't support it, or one mid-update), the composer adds it for those too.

With `fetchQuote()`, pass `signerType` to `newSwap()` as well. A router that doesn't support Falcon signers returns a quote that doesn't say it was requested for one, so the composer would otherwise compose for ed25519:

```typescript
const raw = await router.fetchQuote({ ...params, signerType: 'falcon' })
const swap = await router.newSwap({ quote: raw, address, slippage, signer, signerType: 'falcon' })
```

### Transaction Signing

The SDK supports both standard `algosdk.TransactionSigner` and ARC-1 compliant signer functions.
Expand Down Expand Up @@ -472,6 +502,7 @@ async newQuote(params: FetchQuoteParams): Promise<SwapQuote>
| `maxDepth` | Maximum swap hops | `number` | `4` |
| `optIn` | Override auto opt-in behavior | `boolean` | `undefined` |
| `slippage` | Slippage % you will execute with, in [0, 100); required for accurate launch token quotes | `number` | `undefined` |
| `signerType` | Key type `address` signs with; `'falcon'` adds a [Falcon signer's extra fees](#falcon-post-quantum-accounts) | `'ed25519' \| 'falcon'` | `'ed25519'` |

#### RouterClient.newSwap()

Expand All @@ -488,6 +519,7 @@ async newSwap(config: SwapComposerConfig): Promise<SwapComposer>
| `slippage` | Slippage tolerance as percentage (e.g., 1 for 1%) | `number` |
| `signer` | Transaction signer function | `algosdk.TransactionSigner \| ((txnGroup: Transaction[], indexesToSign: number[]) => Promise<(Uint8Array \| null)[]>)` |
| `note` | Optional note for the user-signed input transaction (for tracking purposes) | `Uint8Array` |
| `signerType` | Optional key type `address` signs with (default: the quote's, else `'ed25519'`). Pass it with a `fetchQuote()` response | `'ed25519' \| 'falcon'` |

#### RouterClient.needsAssetOptIn()

Expand Down Expand Up @@ -515,6 +547,7 @@ Plain object returned by [`newQuote()`](#routerclientnewquote). Extends the raw
| `address` | User address (if provided) | `string \| undefined` |
| `slippage` | Slippage sent with the quote request (if provided) | `number \| undefined` |
| `launch` | Bonding-curve details for a pre-bonding launch token (amounts as `bigint`) | `SwapLaunchQuote \| undefined` |
| `signerType` | Key type the quote was requested for (`'ed25519'` when none was) | `'ed25519' \| 'falcon' \| undefined` |
| `createdAt` | Timestamp when quote was created | `number` |

**All properties from API response:**
Expand Down
36 changes: 36 additions & 0 deletions packages/haystack/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import type {
FetchSwapTxnsParams,
FetchSwapTxnsBody,
FetchQuoteParams,
SignerType,
SwapQuote,
} from './types'

Expand Down Expand Up @@ -153,13 +154,24 @@ export class RouterClient {
optIn,
address,
slippage,
signerType,
_allowNonComposableSwaps = false,
} = params

if (slippage !== undefined) {
this.validateSlippage(slippage)
}

if (
signerType !== undefined &&
signerType !== 'ed25519' &&
signerType !== 'falcon'
) {
throw new Error(
`Invalid signerType: ${String(signerType)}. Must be 'ed25519' or 'falcon'`,
)
}

// Validate incompatible parameter combinations
if (_allowNonComposableSwaps && (optIn === true || this.config.autoOptIn)) {
throw new Error(
Expand Down Expand Up @@ -217,6 +229,12 @@ export class RouterClient {
url.searchParams.append('slippage', String(slippage))
}

// A Falcon signer's transactions cost 3 fee units, which the router then
// plans for and includes in the fees of the transactions it builds
if (signerType === 'falcon') {
url.searchParams.append('signerType', signerType)
}

if (this.config.referrerAddress) {
url.searchParams.append('referrerAddress', this.config.referrerAddress)
}
Expand Down Expand Up @@ -393,6 +411,9 @@ export class RouterClient {
slippage: adjustedParams.slippage,
launch: launch && toSwapLaunchQuote(launch),
firstStage: firstStage && toSwapFirstStageQuote(firstStage),
// The caller's, should a middleware's adjusted params leave it out: the
// router then plans without it, and the composer adds every extra fee
signerType: adjustedParams.signerType ?? params.signerType ?? 'ed25519',
createdAt: Date.now(),
}
}
Expand Down Expand Up @@ -452,8 +473,19 @@ export class RouterClient {
signer: TransactionSigner | SignerFunction
/** Optional note field for the user-signed input transaction (payment or asset transfer) */
note?: Uint8Array
/**
* The kind of key `address` signs with. Defaults to the quote's
* `signerType`: what `newQuote()` was asked for, or `'falcon'` when a
* `fetchQuote()` response echoes it. Pass it with a `fetchQuote()`
* response, which a router that doesn't support Falcon signers leaves
* without it. For `'falcon'`, the composer adds the extra fees the
* router's transactions don't include.
*/
signerType?: SignerType
}): Promise<SwapComposer> {
const { quote, address, slippage, signer, note } = config
const signerType: SignerType =
config.signerType ?? quote.signerType ?? 'ed25519'

// A launch quote prices the curve on the slippage it was fetched with, so
// executing at a different slippage makes the quoted output inaccurate
Expand Down Expand Up @@ -482,6 +514,10 @@ export class RouterClient {
signer,
middleware: this.middleware,
note,
signerType,
// Execute's word, not the quote's: a router mid-update can quote with
// the echo and build without the extra fees
signerFeesIncluded: swapResponse.signerType === 'falcon',
debugLevel: this.config.debugLevel,
})

Expand Down
Loading
Loading