diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 5055852..81afb0e 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -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`) diff --git a/packages/haystack/MIDDLEWARE.md b/packages/haystack/MIDDLEWARE.md index 3fd40da..65441d7 100644 --- a/packages/haystack/MIDDLEWARE.md +++ b/packages/haystack/MIDDLEWARE.md @@ -426,7 +426,13 @@ async adjustQuoteParams(params: FetchQuoteParams): Promise { } ``` -### 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 diff --git a/packages/haystack/README.md b/packages/haystack/README.md index a201195..5442ffe 100644 --- a/packages/haystack/README.md +++ b/packages/haystack/README.md @@ -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. @@ -472,6 +502,7 @@ async newQuote(params: FetchQuoteParams): Promise | `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() @@ -488,6 +519,7 @@ async newSwap(config: SwapComposerConfig): Promise | `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() @@ -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:** diff --git a/packages/haystack/src/client.ts b/packages/haystack/src/client.ts index 5b788bf..ecc481f 100644 --- a/packages/haystack/src/client.ts +++ b/packages/haystack/src/client.ts @@ -27,6 +27,7 @@ import type { FetchSwapTxnsParams, FetchSwapTxnsBody, FetchQuoteParams, + SignerType, SwapQuote, } from './types' @@ -153,6 +154,7 @@ export class RouterClient { optIn, address, slippage, + signerType, _allowNonComposableSwaps = false, } = params @@ -160,6 +162,16 @@ export class RouterClient { 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( @@ -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) } @@ -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(), } } @@ -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 { 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 @@ -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, }) diff --git a/packages/haystack/src/composer.ts b/packages/haystack/src/composer.ts index 130dcdc..5ea4727 100644 --- a/packages/haystack/src/composer.ts +++ b/packages/haystack/src/composer.ts @@ -4,6 +4,7 @@ import { decodeUnsignedTransaction, encodeAddress, getApplicationAddress, + isTransactionWithSigner, isValidAddress, LogicSigAccount, makeApplicationOptInTxnFromObject, @@ -17,7 +18,7 @@ import { type TransactionSigner, type TransactionWithSigner, } from 'algosdk' -import { DEFAULT_CONFIRMATION_ROUNDS } from './constants' +import { DEFAULT_CONFIRMATION_ROUNDS, FALCON_EXTRA_FEE } from './constants' import { toSwapFirstStageQuote } from './firststage' import { toSwapLaunchQuote } from './launch' import { Logger } from './logger' @@ -29,6 +30,7 @@ import type { SwapQuote, MethodCall, QuoteType, + SignerType, SwapSummary, } from './types' @@ -161,6 +163,20 @@ export interface SwapComposerConfig { readonly middleware?: SwapMiddleware[] /** Optional note field for the user-signed input transaction (payment or asset transfer) */ readonly note?: Uint8Array + /** + * The kind of key `address` signs with (default: the quote's `signerType`, + * else `'ed25519'`). For `'falcon'`, the composer adds the extra fee of each + * transaction the account sends to the swap's input transfer as it builds + * the group. + */ + readonly signerType?: SignerType + /** + * Whether `swapTxns`' fees already include a Falcon signer's extra fees: + * the `fetchSwapTransactions()` response's `signerType` is `'falcon'`. Then + * only the transactions the composer adds are counted. Default: false, and + * every transaction the account sends is. + */ + readonly signerFeesIncluded?: boolean /** Debug logging level (propagated from RouterClient) */ readonly debugLevel?: 'none' | 'info' | 'debug' | 'trace' } @@ -201,6 +217,15 @@ export class SwapComposer { private readonly signer: TransactionSigner | SignerFunction private readonly middleware: SwapMiddleware[] private readonly note?: Uint8Array + private readonly signerType: SignerType + private readonly signerFeesIncluded: boolean + /** Transactions the account sends whose Falcon fees the composer adds */ + private signerFeeTxns = 0 + /** The account's first transaction in the group, which carries them when there's no input transfer */ + private firstUserTxn?: Transaction + /** The swap's input transfer, whose fee carries a Falcon signer's extra fees */ + private inputTxn?: Transaction + private signerFeesAdded = false private inputTransactionIndex?: number private outputTransactionIndex?: number private curveTransactionIndex?: number @@ -272,6 +297,8 @@ export class SwapComposer { this.signer = config.signer this.middleware = config.middleware ?? [] this.note = config.note + this.signerType = config.signerType ?? config.quote.signerType ?? 'ed25519' + this.signerFeesIncluded = config.signerFeesIncluded ?? false } /** @@ -325,6 +352,7 @@ export class SwapComposer { } this.atc.addTransaction({ txn: transaction, signer }) + this.trackSignerFee(transaction.sender, transaction) return this } @@ -359,6 +387,13 @@ export class SwapComposer { ...methodCall, signer: methodCall.signer ?? signer, }) + // Its transaction arguments go before it. The ATC builds the call itself, + // so it can't carry the fees + for (const arg of methodCall.methodArgs ?? []) { + if (isTransactionWithSigner(arg)) + this.trackSignerFee(arg.txn.sender, arg.txn) + } + this.trackSignerFee(methodCall.sender) return this } @@ -401,11 +436,14 @@ export class SwapComposer { for (const txnWithSigner of beforeTxns) { this.atc.addTransaction(txnWithSigner) + this.trackSignerFee(txnWithSigner.txn.sender, txnWithSigner.txn) } // Process swap transactions and execute afterSwap hooks const { txns: processedTxns, + apiTxns, + inputTxn, inputTxnRelativeIndex, outputTxnRelativeIndex, curveTxnRelativeIndex, @@ -439,14 +477,23 @@ export class SwapComposer { this.curveTransactionIndex = this.atc.count() + curveTxnRelativeIndex } - // Add swap transactions + // Add swap transactions. The router's own (apiTxns) already include a + // Falcon signer's extra fees when execute said so for (const txnWithSigner of processedTxns) { this.atc.addTransaction(txnWithSigner) + this.trackSignerFee( + txnWithSigner.txn.sender, + txnWithSigner.txn, + this.signerFeesIncluded && apiTxns.has(txnWithSigner.txn), + ) } + // Only now in the group, so it can carry the fees + this.inputTxn = inputTxn // Add afterSwap middleware transactions for (const txnWithSigner of afterTxns) { this.atc.addTransaction(txnWithSigner) + this.trackSignerFee(txnWithSigner.txn.sender, txnWithSigner.txn) } this.swapTransactionsAdded = true @@ -478,6 +525,7 @@ export class SwapComposer { * ``` */ buildGroup(): TransactionWithSigner[] { + this.addSignerFees() return this.atc.buildGroup() } @@ -504,6 +552,7 @@ export class SwapComposer { await this.addSwapTransactions() } + this.addSignerFees() return await this.atc.gatherSignatures() } @@ -528,6 +577,7 @@ export class SwapComposer { await this.addSwapTransactions() } + this.addSignerFees() return await this.atc.submit(this.algodClient) } @@ -560,6 +610,7 @@ export class SwapComposer { await this.addSwapTransactions() } + this.addSignerFees() const { txIDs, ...result } = await this.atc.execute( this.algodClient, waitRounds, @@ -718,6 +769,56 @@ export class SwapComposer { } } + /** + * Counts a transaction from sender toward a Falcon signer's extra fees + * (addSignerFees) when the account sends it, unless the router's fees + * already include it (included). Every way of adding a transaction calls + * it; txn is the transaction when the composer holds it (not a method call + * the ATC builds), which can then carry the fees. + */ + private trackSignerFee( + sender: { toString(): string }, + txn?: Transaction, + included = false, + ): void { + if (sender.toString() !== this.address) return + if (txn) this.firstUserTxn ??= txn + if (!included) this.signerFeeTxns++ + } + + /** + * Adds a Falcon signer's extra fees before the group is built: a Falcon + * signature costs 3 fee units where an ed25519 one costs 1, and fees pool + * across the group, so the fee of the swap's input transfer (which already + * carries the router's fee budget) rises by FALCON_EXTRA_FEE for each + * transaction the account sends that the router's fees don't include. The + * account pays it, like every fee of the group. Runs once, while the group + * is still being built. + */ + private addSignerFees(): void { + if ( + this.signerType !== 'falcon' || + this.signerFeesAdded || + this.getStatus() !== SwapComposerStatus.BUILDING + ) { + return + } + if (this.signerFeeTxns > 0) { + const carrier = this.inputTxn ?? this.firstUserTxn + if (!carrier) { + throw new Error( + `No transaction from ${this.address} in the group to carry its Falcon signature fees`, + ) + } + carrier.fee += FALCON_EXTRA_FEE * BigInt(this.signerFeeTxns) + Logger.debug('Added Falcon signature fees', { + transactions: this.signerFeeTxns, + fee: carrier.fee, + }) + } + this.signerFeesAdded = true + } + /** * Validates an Algorand address */ @@ -735,6 +836,10 @@ export class SwapComposer { */ private async processSwapTransactions(): Promise<{ txns: TransactionWithSigner[] + /** The API's transactions among txns, the app opt-ins left out */ + apiTxns: Set + /** The swap's input transfer among txns */ + inputTxn?: Transaction inputTxnRelativeIndex?: number outputTxnRelativeIndex?: number curveTxnRelativeIndex?: number @@ -812,6 +917,8 @@ export class SwapComposer { return { txns: [...appOptIns, ...swapTxns], + apiTxns: new Set(decoded.map(({ txn }) => txn)), + inputTxn, inputTxnRelativeIndex: inputIndex !== undefined ? appOptIns.length + inputIndex : undefined, outputTxnRelativeIndex, @@ -1042,10 +1149,11 @@ export class SwapComposer { ): Promise { const allTxns: TransactionWithSigner[] = [] - // Convert to SwapQuote if needed + // Convert to SwapQuote if needed, with the signer type the composer + // composes for (a newSwap() override included) const quote: SwapQuote = 'createdAt' in this.quote - ? this.quote + ? { ...this.quote, signerType: this.signerType } : { ...this.quote, quote: this.quote.quote === '' ? 0n : BigInt(this.quote.quote), @@ -1054,6 +1162,7 @@ export class SwapComposer { firstStage: this.quote.firstStage && toSwapFirstStageQuote(this.quote.firstStage), + signerType: this.signerType, createdAt: Date.now(), } diff --git a/packages/haystack/src/constants.ts b/packages/haystack/src/constants.ts index 9bc211b..6ef81d2 100644 --- a/packages/haystack/src/constants.ts +++ b/packages/haystack/src/constants.ts @@ -51,5 +51,11 @@ export const DEFAULT_AUTO_OPT_IN = false /** Default debug level (no debug logging) */ export const DEFAULT_DEBUG_LEVEL = 'none' as const +/** + * What a Falcon (post-quantum) signature adds to its transaction's fee, in + * microAlgos: algod charges a transaction it signs 3 fee units instead of 1 + */ +export const FALCON_EXTRA_FEE = 2_000n + /** Default number of rounds to wait for transaction confirmation */ export const DEFAULT_CONFIRMATION_ROUNDS = 10 diff --git a/packages/haystack/src/types.ts b/packages/haystack/src/types.ts index b515545..98be610 100644 --- a/packages/haystack/src/types.ts +++ b/packages/haystack/src/types.ts @@ -67,6 +67,20 @@ export type Config = Omit< */ export type QuoteType = 'fixed-input' | 'fixed-output' +/** + * The kind of key the swapping account signs with + * + * - `'ed25519'`: an ordinary Algorand account (the default) + * - `'falcon'`: a Falcon-1024 (post-quantum) account, such as a passkey + * account or a Pera or Lute quantum account. Each transaction it signs costs + * 3 fee units (0.003 ALGO) instead of 1, which the swap group's fees must + * cover. + * + * A rekeyed account signs with its auth address's key. With use-wallet, an + * account is Falcon when `getSignatureType(account.emptySignature) === 'pqsig'`. + */ +export type SignerType = 'ed25519' | 'falcon' + /** * Parameters for requesting a swap quote from the Haystack Router API (raw API method) */ @@ -114,6 +128,22 @@ export interface FetchQuoteParams { */ readonly slippage?: number + /** + * The kind of key the swapping account signs with (default: `'ed25519'`) + * + * Pass `'falcon'` for a Falcon (post-quantum) account. The router then + * includes the extra fee of every transaction it builds for the account to + * sign, and the SwapComposer adds it for the transactions it adds (app + * opt-ins, middleware, `addTransaction()`, `addMethodCall()`), all in the + * fee of the swap's input transfer, which the account pays. The router + * can't tell from the address: an unused Falcon account looks like any + * other. + * + * With `fetchQuote()`, pass it to `newSwap()` too: a response from a router + * that doesn't support it doesn't say the quote was for a Falcon signer. + */ + readonly signerType?: SignerType + /** * ⚠️ **ADVANCED USE ONLY - NON-COMPOSABLE SWAPS** ⚠️ * @@ -325,6 +355,14 @@ export interface FetchQuoteResponse { * holding keeps (fixed-input), or all the input holding sends (fixed-output). */ readonly firstStage?: FirstStageQuote + /** + * `'falcon'` when the quote was requested for a Falcon signer and the + * router supports it. Absent otherwise, including from a router that + * doesn't support Falcon signers yet. Whether the swap's transactions + * include the extra fees is the execute response's `signerType` + * ({@link FetchSwapTxnsResponse}), which `newSwap()` reads. + */ + readonly signerType?: 'falcon' } /** @@ -334,7 +372,7 @@ export interface FetchQuoteResponse { */ export type SwapQuote = Omit< FetchQuoteResponse, - 'quote' | 'launch' | 'firstStage' + 'quote' | 'launch' | 'firstStage' | 'signerType' > & { /** * The quoted output amount or input amount (coerced to bigint) @@ -359,6 +397,13 @@ export type SwapQuote = Omit< /** First Stage taxes, present only when the swap wraps a First Stage taxed token's frozen holding */ readonly firstStage?: SwapFirstStageQuote + /** + * The kind of key the quote's account signs with: what `newQuote()` was + * asked for (`'ed25519'` when nothing was), or `'falcon'` copied from a + * `fetchQuote()` response that echoes it + */ + readonly signerType?: SignerType + /** Timestamp when the quote was created (in milliseconds) */ readonly createdAt: number } @@ -421,6 +466,13 @@ export interface FetchSwapTxnsBody { export interface FetchSwapTxnsResponse { /** Array of transaction data */ readonly txns: SwapTransaction[] + /** + * `'falcon'` when the transactions' fees include a Falcon signer's extra + * fees for every transaction the account signs. Absent otherwise, even when + * the quote echoed `signerType` (a router mid-update can build without + * them): a Falcon signer's group then needs them all added. + */ + readonly signerType?: 'falcon' } /** diff --git a/packages/haystack/tests/falcon.test.ts b/packages/haystack/tests/falcon.test.ts new file mode 100644 index 0000000..e7c4bff --- /dev/null +++ b/packages/haystack/tests/falcon.test.ts @@ -0,0 +1,549 @@ +import algosdk from 'algosdk' +import { describe, it, expect, beforeEach, vi } from 'vitest' +import { RouterClient } from '../src/client' +import { SwapComposer } from '../src/composer' +import { FALCON_EXTRA_FEE } from '../src/constants' +import type { SwapMiddleware } from '../src/middleware' +import type { + FetchQuoteResponse, + SignerType, + SwapQuote, + SwapTransaction, +} from '../src/types' + +vi.mock('../src/utils', () => ({ + request: vi.fn(), + HTTPError: class HTTPError extends Error {}, +})) + +/** + * A Falcon (post-quantum) signature costs 3 fee units, so a Falcon signer's + * input transfer carries FALCON_EXTRA_FEE more fee for each transaction the + * account sends. The router includes it for the transactions it builds when + * execute's response says so; the composer adds it for the rest. + */ + +const V4_APP = 3757715482n +const USDC = 31566704n +const ROUTER = algosdk.getApplicationAddress(V4_APP).toString() + +const suggestedParams = { + fee: 1000, + firstValid: 1000, + lastValid: 2000, + minFee: 1000, + genesisID: 'mainnet-v1.0', + genesisHash: Buffer.from( + 'wGHE2Pwdvd7S12BL5FaOP20EGYesN73ktiC1qzkkit8=', + 'base64', + ), +} + +const userAccount = algosdk.generateAccount() +const user = userAccount.addr.toString() +const hotWallet = algosdk.generateAccount() +const other = algosdk.generateAccount().addr.toString() + +const encode = ( + txn: algosdk.Transaction, + signature: SwapTransaction['signature'] = false, +): SwapTransaction => ({ + data: Buffer.from(algosdk.encodeUnsignedTransaction(txn)).toString('base64'), + group: '', + logicSigBlob: false, + signature, +}) + +const pay = (sender: string, receiver: string, note: string, fee = 0) => + algosdk.makePaymentTxnWithSuggestedParamsFromObject({ + sender, + receiver, + amount: 100_000, + suggestedParams: { ...suggestedParams, fee, flatFee: true }, + note: new TextEncoder().encode(note), + }) + +const routerCall = (note: string) => + encode( + algosdk.makeApplicationNoOpTxnFromObject({ + sender: hotWallet.addr, + appIndex: V4_APP, + suggestedParams: { ...suggestedParams, fee: 0, flatFee: true }, + note: new TextEncoder().encode(note), + }), + { type: 'secret_key', value: { ...hotWallet.sk } }, + ) + +/** INPUT_FEE: the router's fee budget on the input transfer */ +const INPUT_FEE = 9000n + +/** + * A v4 USDC→ALGO group: the opt_in pair (the router lacks USDC), the funding + * payment, the input and the route. The user sends three of them. + */ +const v4Group = (): SwapTransaction[] => [ + encode(pay(user, ROUTER, 'opt-in')), + routerCall('opt_in'), + encode(pay(user, ROUTER, 'route-costs')), + encode( + algosdk.makeAssetTransferTxnWithSuggestedParamsFromObject({ + sender: user, + receiver: ROUTER, + amount: 1_000_000, + assetIndex: USDC, + suggestedParams: { + ...suggestedParams, + fee: Number(INPUT_FEE), + flatFee: true, + }, + }), + ), + routerCall('route'), +] +const V4_USER_TXNS = 3n +const ALL_INCLUDED = INPUT_FEE + FALCON_EXTRA_FEE * V4_USER_TXNS + +const quote = (requiredAppOptIns: number[] = []) => + ({ + fromASAID: Number(USDC), + toASAID: 0, + quote: '5000000', + type: 'fixed-input', + route: [], + flattenedRoute: {}, + txnPayload: { iv: 'iv', data: 'data' }, + requiredAppOptIns, + }) as unknown as FetchQuoteResponse + +/** quote() as a SwapQuote, the way an app spreads a fetchQuote() response */ +const swapQuote = (extra: Partial = {}): SwapQuote => ({ + ...(quote() as unknown as Omit), + quote: 5_000_000n, + amount: 1_000_000n, + createdAt: Date.now(), + ...extra, +}) + +const isInput = (t: algosdk.Transaction) => + t.type === algosdk.TransactionType.axfer && + t.assetTransfer?.receiver.toString() === ROUTER + +const noSigs = async (txns: algosdk.Transaction[], idx: number[]) => + idx.map(() => new Uint8Array(0)) + +let algod: algosdk.Algodv2 +let pending: Record + +beforeEach(() => { + pending = {} + algod = { + accountInformation: vi.fn().mockReturnValue({ + do: vi.fn().mockResolvedValue({ appsLocalState: [], assets: [] }), + }), + getTransactionParams: vi.fn().mockReturnValue({ + do: vi.fn().mockResolvedValue(suggestedParams), + }), + pendingTransactionInformation: vi.fn((txId: string) => ({ + do: vi.fn().mockResolvedValue(pending[txId] ?? {}), + })), + sendRawTransaction: vi.fn().mockReturnValue({ + do: vi.fn().mockResolvedValue({ txid: 'sent' }), + }), + } as unknown as algosdk.Algodv2 +}) + +const composer = ( + opts: { + quote?: FetchQuoteResponse | SwapQuote + signerType?: SignerType + signerFeesIncluded?: boolean + requiredAppOptIns?: number[] + middleware?: SwapMiddleware[] + signer?: algosdk.TransactionSigner + } = {}, +) => + new SwapComposer({ + quote: opts.quote ?? quote(opts.requiredAppOptIns), + swapTxns: v4Group(), + algodClient: algod, + address: user, + signer: opts.signer ?? noSigs, + signerType: opts.signerType, + signerFeesIncluded: opts.signerFeesIncluded, + middleware: opts.middleware, + }) + +/** The built group's input transfer, and every other transaction's fee */ +const built = (c: SwapComposer) => { + const txns = c.buildGroup().map(({ txn }) => txn) + const input = txns.find(isInput) + if (!input) throw new Error('no input transfer') + return { input, others: txns.filter((t) => t !== input).map((t) => t.fee) } +} + +/** A middleware adding a payment from sender in hook */ +const paying = ( + sender: string, + hook: 'beforeSwap' | 'afterSwap' = 'beforeSwap', +): SwapMiddleware => ({ + name: 'paying', + version: '1.0.0', + shouldApply: async () => true, + [hook]: async (ctx: { signer: algosdk.TransactionSigner }) => [ + { txn: pay(sender, other, hook, 1000), signer: ctx.signer }, + ], +}) + +describe('Falcon signer fees', () => { + it('leaves an ed25519 signer’s fees alone', async () => { + const c = composer() + await c.addSwapTransactions() + const { input, others } = built(c) + expect(input.fee).toBe(INPUT_FEE) + expect(others).toEqual([0n, 0n, 0n, 0n]) + }) + + it('adds them for every user transaction when the router did not', async () => { + const c = composer({ signerType: 'falcon' }) + await c.addSwapTransactions() + const { input, others } = built(c) + // 2,000 µALGO each: a Falcon signature is 3 fee units, not 1 + expect(input.fee).toBe(9_000n + 3n * 2_000n) + // the fee goes on the input alone + expect(others).toEqual([0n, 0n, 0n, 0n]) + }) + + it('adds them only for what the composer adds when the router included them', async () => { + const c = composer({ signerType: 'falcon', signerFeesIncluded: true }) + await c.addSwapTransactions() + expect(built(c).input.fee).toBe(INPUT_FEE) + }) + + it('takes the signer type from the quote when not given', async () => { + const c = composer({ quote: { ...quote(), signerType: 'falcon' } }) + await c.addSwapTransactions() + expect(built(c).input.fee).toBe(ALL_INCLUDED) + }) + + it('counts app opt-ins, middleware and added transactions from the account', async () => { + const c = composer({ + signerType: 'falcon', + signerFeesIncluded: true, + requiredAppOptIns: [1002541853], + // the other account's payments aren't signed by the user's Falcon key + middleware: [ + paying(user), + paying(other), + paying(user, 'afterSwap'), + paying(other, 'afterSwap'), + ], + }) + c.addTransaction(pay(user, other, 'before', 1000)) + c.addTransaction(pay(other, user, 'before, other', 1000)) + await c.addSwapTransactions() + c.addTransaction(pay(user, other, 'after', 1000)) + // opt-in, two middleware payments, two added payments + expect(built(c).input.fee).toBe(INPUT_FEE + FALCON_EXTRA_FEE * 5n) + }) + + it.each([ + ['from the account with its argument', user, user, 2n], + ['from another account, its argument the account’s', other, user, 1n], + ['and its argument from another account', other, other, 0n], + ])('counts a method call %s', async (_, sender, argSender, counted) => { + const method = algosdk.ABIMethod.fromSignature('deposit(pay)void') + const c = composer({ signerType: 'falcon', signerFeesIncluded: true }) + c.addMethodCall({ + appID: 123, + method, + methodArgs: [ + { + txn: pay( + argSender, + algosdk.getApplicationAddress(123n).toString(), + 'arg', + ), + signer: algosdk.makeEmptyTransactionSigner(), + }, + ], + sender, + suggestedParams, + }) + await c.addSwapTransactions() + expect(built(c).input.fee).toBe(INPUT_FEE + FALCON_EXTRA_FEE * counted) + }) + + it('puts them on the account’s first transaction when there is no swap', () => { + const c = composer({ signerType: 'falcon' }) + c.addTransaction(pay(other, user, 'other', 1000)) + c.addTransaction(pay(user, other, 'first', 1000)) + c.addTransaction(pay(user, other, 'second', 1000)) + const fees = c.buildGroup().map(({ txn }) => txn.fee) + expect(fees).toEqual([1000n, 1000n + FALCON_EXTRA_FEE * 2n, 1000n]) + }) + + it('puts them on a method call’s transaction argument when it is the account’s first', () => { + const c = composer({ signerType: 'falcon' }) + c.addMethodCall({ + appID: 123, + method: algosdk.ABIMethod.fromSignature('deposit(pay)void'), + methodArgs: [ + { + txn: pay(user, algosdk.getApplicationAddress(123n).toString(), 'arg'), + signer: algosdk.makeEmptyTransactionSigner(), + }, + ], + sender: user, + suggestedParams, + }) + // the argument and the call + expect(c.buildGroup()[0]!.txn.fee).toBe(FALCON_EXTRA_FEE * 2n) + }) + + it('throws without a transaction to carry them, then adds them once one is there', async () => { + const c = composer({ signerType: 'falcon' }) + c.addMethodCall({ + appID: 123, + method: algosdk.ABIMethod.fromSignature('noop()void'), + methodArgs: [], + sender: user, + suggestedParams, + }) + expect(() => c.buildGroup()).toThrow('to carry its Falcon signature fees') + await c.addSwapTransactions() + // the method call and the router's three + expect(built(c).input.fee).toBe(INPUT_FEE + FALCON_EXTRA_FEE * 4n) + }) + + it('adds the fees once, however often the group is built', async () => { + const c = composer({ signerType: 'falcon' }) + await c.addSwapTransactions() + c.buildGroup() + c.buildGroup() + expect(built(c).input.fee).toBe(ALL_INCLUDED) + // the group ID covers the raised fee + const txns = c.buildGroup().map(({ txn }) => txn) + const group = txns[0]!.group + const fresh = txns.map((t) => { + const copy = algosdk.decodeUnsignedTransaction( + algosdk.encodeUnsignedTransaction(t), + ) + copy.group = undefined + return copy + }) + expect(algosdk.computeGroupID(fresh)).toEqual(group) + }) + + it.each(['sign', 'submit'] as const)( + 'adds them before %s() hands the group to the signer', + async (method) => { + let fee: bigint | undefined + const c = composer({ + signerType: 'falcon', + signer: async (txns, idx) => { + fee = txns.find(isInput)?.fee + return idx.map( + (i) => algosdk.signTransaction(txns[i]!, userAccount.sk).blob, + ) + }, + }) + await c[method]() + expect(fee).toBe(ALL_INCLUDED) + }, + ) + + it('adds them before execute() submits, and the summary counts them', async () => { + const c = composer({ signerType: 'falcon' }) + await c.addSwapTransactions() + const atc = (c as unknown as { atc: algosdk.AtomicTransactionComposer }).atc + let fee: bigint | undefined + vi.spyOn(atc, 'execute').mockImplementation(async () => { + const txns = atc.buildGroup().map(({ txn }) => txn) + fee = txns.find(isInput)?.fee + const txIDs = txns.map((t) => t.txID()) + pending[txIDs[txIDs.length - 1]!] = { + innerTxns: [ + { + txn: { + txn: algosdk.makePaymentTxnWithSuggestedParamsFromObject({ + sender: ROUTER, + receiver: user, + amount: 5_000_000, + suggestedParams, + }), + }, + }, + ], + } + return { confirmedRound: 1n, txIDs, methodResults: [] } + }) + await c.execute() + expect(fee).toBe(ALL_INCLUDED) + expect(c.getSummary()?.totalFees).toBe(ALL_INCLUDED) + }) + + it('shows middleware the signer type it composes for', async () => { + let seen: SignerType | undefined + const c = composer({ + quote: swapQuote({ signerType: 'ed25519' }), + signerType: 'falcon', + middleware: [ + { + name: 'watching', + version: '1.0.0', + shouldApply: async () => true, + beforeSwap: async (ctx) => { + seen = ctx.quote.signerType + return [] + }, + }, + ], + }) + await c.addSwapTransactions() + expect(seen).toBe('falcon') + }) +}) + +describe('RouterClient signerType', () => { + let mockRequest: ReturnType + let client: RouterClient + + beforeEach(async () => { + client = new RouterClient({ apiKey: 'test-api-key' }) + const utils = vi.mocked(await import('../src/utils'), { partial: true }) + mockRequest = utils.request as ReturnType + mockRequest.mockReset() + }) + + const params = { fromASAID: USDC, toASAID: 0, amount: 1_000_000n } + const sentSignerType = () => + new URL(mockRequest.mock.calls[0]?.[0] as string).searchParams.get( + 'signerType', + ) + + it('asks for a Falcon signer', async () => { + mockRequest.mockResolvedValueOnce({ ...quote(), signerType: 'falcon' }) + const q = await client.newQuote({ ...params, signerType: 'falcon' }) + expect(sentSignerType()).toBe('falcon') + expect(q.signerType).toBe('falcon') + }) + + it('sends nothing for ed25519', async () => { + mockRequest.mockResolvedValueOnce(quote()) + const q = await client.newQuote({ ...params, signerType: 'ed25519' }) + expect(sentSignerType()).toBeNull() + expect(q.signerType).toBe('ed25519') + }) + + it('keeps the caller’s signer type when a middleware’s params leave it out', async () => { + client = new RouterClient({ + apiKey: 'test-api-key', + middleware: [ + { + name: 'rebuilding', + version: '1.0.0', + shouldApply: async () => true, + adjustQuoteParams: async (p) => ({ + fromASAID: p.fromASAID, + toASAID: p.toASAID, + amount: p.amount, + }), + }, + ], + }) + mockRequest.mockResolvedValueOnce(quote()) + const q = await client.newQuote({ ...params, signerType: 'falcon' }) + expect(sentSignerType()).toBeNull() + expect(q.signerType).toBe('falcon') + }) + + it('rejects an unknown signer type', async () => { + await expect( + client.fetchQuote({ ...params, signerType: 'pqsig' as SignerType }), + ).rejects.toThrow('Invalid signerType') + }) + + /** newSwap on q, execute's response saying signerType or not, built */ + const swapFee = async ( + q: FetchQuoteResponse | SwapQuote, + executeSays: 'falcon' | undefined, + override?: SignerType, + ) => { + mockRequest.mockResolvedValueOnce({ + txns: v4Group(), + ...(executeSays && { signerType: executeSays }), + }) + const swap = await client.newSwap({ + quote: q, + address: user, + slippage: 1, + signer: noSigs, + signerType: override, + }) + await swap.addSwapTransactions() + return built(swap).input.fee + } + + it.each([ + [ + 'a fetchQuote() echo, execute including them', + () => ({ ...quote(), signerType: 'falcon' }) as FetchQuoteResponse, + 'falcon', + undefined, + INPUT_FEE, + ], + [ + 'a fetchQuote() echo, execute not (a pod mid-rollout)', + () => ({ ...quote(), signerType: 'falcon' }) as FetchQuoteResponse, + undefined, + undefined, + ALL_INCLUDED, + ], + [ + 'an older router’s fetchQuote() with signerType passed to newSwap()', + quote, + undefined, + 'falcon', + ALL_INCLUDED, + ], + ['an ed25519 fetchQuote()', quote, undefined, undefined, INPUT_FEE], + [ + 'a spread fetchQuote() echo as a SwapQuote, execute including them', + () => swapQuote({ signerType: 'falcon' }), + 'falcon', + undefined, + INPUT_FEE, + ], + [ + 'a SwapQuote from before signerType', + () => swapQuote(), + undefined, + undefined, + INPUT_FEE, + ], + ] as const)( + 'adds the right fees on %s', + async (_, q, executeSays, override, want) => { + expect(await swapFee(q(), executeSays, override)).toBe(want) + }, + ) + + it.each([ + ['including them', 'falcon', INPUT_FEE], + ['not', undefined, ALL_INCLUDED], + ] as const)( + 'adds the right fees from newQuote() through newSwap(), execute %s', + async (_, executeSays, want) => { + mockRequest.mockResolvedValueOnce({ ...quote(), signerType: 'falcon' }) + const q = await client.newQuote({ ...params, signerType: 'falcon' }) + expect(await swapFee(q, executeSays)).toBe(want) + }, + ) + + it('lets newSwap() override an ed25519 newQuote()', async () => { + mockRequest.mockResolvedValueOnce(quote()) + const q = await client.newQuote(params) + expect(q.signerType).toBe('ed25519') + expect(await swapFee(q, undefined, 'falcon')).toBe(ALL_INCLUDED) + }) +})