diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cd55f9a..c3614ac5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- changed: (Houdini) DEX-route swaps confirm through edge-autobot-server even after the app closes + ## 2.62.1 (2026-11-14) - fixed: (0x Gasless) Save swaps under the transaction hash that mines, not a submitted one the relayer can replace and leave pending diff --git a/src/swap/central/houdini.ts b/src/swap/central/houdini.ts index ae3dfbbb..3a06acac 100644 --- a/src/swap/central/houdini.ts +++ b/src/swap/central/houdini.ts @@ -53,6 +53,7 @@ import { getAddress, memoType, nativeToDenomination, + promiseWithTimeout, snooze } from '../../util/utils' import { getUnifiedTransparentAddress } from '../../util/zcashUnifiedAddress' @@ -77,7 +78,11 @@ export const swapInfo: EdgeSwapInfo = { // (no `Bearer`); every endpoint returns 402 without it. const asInitOptions = asObject({ apiKey: asString, - apiSecret: asString + apiSecret: asString, + // The edge-autobot-server that takes dex reports and confirms them with + // Houdini on its own schedule, which outlives an app closed right after the + // broadcast. Without it, dex reports go to Houdini directly. + autobotUrl: asOptional(asString) }) // The order status page is on the app host, keyed by a query parameter. The @@ -311,6 +316,9 @@ const RATE_LIMIT_MESSAGE = const DEX_CONFIRM_MAX_ATTEMPTS = 3 const DEX_CONFIRM_RETRY_DELAY_MS = 1000 +// How long a dex report waits on autobot before confirming directly. +const AUTOBOT_REPORT_TIMEOUT_MS = 10000 + /** * How long to wait before retrying a 429, given the attempt number and the * `retryAfter` seconds the API reported (if any). @@ -467,7 +475,7 @@ function floatToNativeAmount( export function makeHoudiniPlugin(opts: EdgeCorePluginOptions): EdgeSwapPlugin { const { io, log } = opts const { fetchCors = io.fetch } = io - const { apiKey, apiSecret } = asInitOptions(opts.initOptions) + const { apiKey, apiSecret, autobotUrl } = asInitOptions(opts.initOptions) const headers = { 'Content-Type': 'application/json', @@ -647,10 +655,10 @@ export function makeHoudiniPlugin(opts: EdgeCorePluginOptions): EdgeSwapPlugin { } /** - * Tells Houdini a dex order's transaction is on chain, which is what starts - * the order on its side. The funds have already left the wallet by then, so - * a failure here is logged for support rather than reported as a failed - * send. + * Tells Houdini directly that a dex order's transaction is on chain, the + * fallback for a report autobot could not take. The funds have already left + * the wallet by then, so a failure here is logged for support rather than + * reported as a failed send. * * The broadcast cannot be repeated and this report is the only thing tying * the transaction to the order on Houdini's side, so a dropped call or a 5xx @@ -683,6 +691,40 @@ export function makeHoudiniPlugin(opts: EdgeCorePluginOptions): EdgeSwapPlugin { } } + /** + * Hands a dex order's transaction to autobot, which confirms it with Houdini + * and keeps trying until Houdini accepts or refuses it. A dex order starts + * on Houdini's side only once this report lands, and an app closed right + * after the broadcast would drop a report made from here. Without an + * autobot configured, or when autobot does not take the report within + * `AUTOBOT_REPORT_TIMEOUT_MS`, the report goes to Houdini directly instead. + */ + async function reportDexTx(orderId: string, txHash: string): Promise { + if (autobotUrl == null) { + await confirmDexTx(orderId, txHash) + return + } + let failure: string + try { + const response = await promiseWithTimeout( + io.fetch(new URL('/api/houdini', autobotUrl).toString(), { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ orderId, txHash }) + }), + AUTOBOT_REPORT_TIMEOUT_MS + ) + if (response.ok) return + failure = `${response.status} ${await response.text()}` + } catch (error: unknown) { + failure = String(error) + } + log.warn( + `Autobot did not take the report for Houdini order ${orderId}, tx ${txHash}, confirming directly: ${failure}` + ) + await confirmDexTx(orderId, txHash) + } + const fetchSwapQuoteInner = async ( request: EdgeSwapRequestPlugin, probeOnly: boolean = false @@ -1368,7 +1410,7 @@ export function makeHoudiniPlugin(opts: EdgeCorePluginOptions): EdgeSwapPlugin { ...quote, async approve(opts?: EdgeSwapApproveOptions): Promise { const result = await quote.approve(opts) - await confirmDexTx(dexOrderId, result.transaction.txid) + await reportDexTx(dexOrderId, result.transaction.txid) return result } } diff --git a/test/houdini.test.ts b/test/houdini.test.ts index 0464d00b..31b97c1e 100644 --- a/test/houdini.test.ts +++ b/test/houdini.test.ts @@ -587,6 +587,15 @@ interface Script { * rule as `quoteStatuses`. */ confirmStatuses?: number[] + /** + * HTTP statuses autobot hands to successive dex reports, same repeat-last + * rule as `quoteStatuses`. + */ + autobotStatuses?: number[] + /** Autobot's report call fails without an answer, as on a network error. */ + autobotThrows?: boolean + /** Leave `autobotUrl` out of the init options. */ + noAutobot?: boolean } interface ScriptedRun { @@ -599,6 +608,8 @@ interface ScriptedRun { orderBodies: string[] /** Every `dex/confirmTx` body posted, in order. */ confirmBodies: string[] + /** Every dex report body sent to autobot, in order. */ + autobotBodies: string[] warnings: string[] } @@ -624,7 +635,10 @@ const makeScriptedPlugin = (script: Script): ScriptedRun => { retryAfter, orderOverrides = {}, dexMetadata = {}, - confirmStatuses = [200] + confirmStatuses = [200], + autobotStatuses = [200], + autobotThrows = false, + noAutobot = false } = script const run: ScriptedRun = { plugin: (undefined as unknown) as ReturnType, @@ -632,12 +646,14 @@ const makeScriptedPlugin = (script: Script): ScriptedRun => { tokenUrls: [], orderBodies: [], confirmBodies: [], + autobotBodies: [], warnings: [] } let quoteCall = 0 let tokenCall = 0 let orderCall = 0 let confirmCall = 0 + let autobotCall = 0 const reply = (status: number, body: unknown): FetchResponseLike => { const text = JSON.stringify(body) @@ -653,6 +669,15 @@ const makeScriptedPlugin = (script: Script): ScriptedRun => { url: string, opts: { method?: string; body?: string } = {} ): Promise => { + if (url === 'https://autobot-wusa1.edge.app/api/houdini') { + expect(opts.method).equals('PUT') + run.autobotBodies.push(opts.body ?? '') + if (autobotThrows) throw new Error('socket hang up') + const autobotStatus = + autobotStatuses[Math.min(autobotCall++, autobotStatuses.length - 1)] + return reply(autobotStatus, autobotStatus === 200 ? {} : 'report failed') + } + const path = url.slice(url.indexOf('/v2/') + 4) if (path.startsWith('tokens')) { @@ -771,7 +796,11 @@ const makeScriptedPlugin = (script: Script): ScriptedRun => { }) run.plugin = makeHoudiniPlugin(({ - initOptions: { apiKey: 'SCRIPTED', apiSecret: 'SCRIPTED' }, + initOptions: { + apiKey: 'SCRIPTED', + apiSecret: 'SCRIPTED', + ...(noAutobot ? {} : { autobotUrl: 'https://autobot-wusa1.edge.app' }) + }, io: { fetch: scriptedFetch, fetchCors: scriptedFetch }, log } as unknown) as Parameters[0]) @@ -964,19 +993,79 @@ describe('houdini offline behaviors', function () { expect(capture.nativeAmount).equals(SONIC_NATIVE_AMOUNT) expect(capture.memos).deep.equals([{ type: 'hex', value: 'abcdef' }]) + // Autobot confirms the order with Houdini, which keeps working after + // the app closes, so the plugin does not also confirm it: + await quote.approve() + expect(JSON.parse(run.autobotBodies[0])).deep.equals({ + orderId: 'order-q-dex', + txHash: '0xtxhash' + }) + expect(run.confirmBodies.length).equals(0) + }) + + it('confirms a dex order directly when autobot cannot take the report', async function () { + const run = makeScriptedPlugin({ + nativeAddress: '', + quotes: [dexQuote], + autobotStatuses: [503] + }) + const quote = await quoteSonicToStellar(run) + + await quote.approve() + expect(run.autobotBodies.length).equals(1) + expect(JSON.parse(run.confirmBodies[0])).deep.equals({ + id: 'order-q-dex', + txHash: '0xtxhash' + }) + // The fallback names the order and the transaction: + const fallbacks = run.warnings.filter(line => line.includes('Autobot')) + expect(fallbacks.length).equals(1) + expect(fallbacks[0]).contains('order-q-dex') + expect(fallbacks[0]).contains('0xtxhash') + }) + + it('confirms a dex order directly when the autobot call throws', async function () { + const run = makeScriptedPlugin({ + nativeAddress: '', + quotes: [dexQuote], + autobotThrows: true + }) + const quote = await quoteSonicToStellar(run) + + await quote.approve() + expect(run.autobotBodies.length).equals(1) + expect(JSON.parse(run.confirmBodies[0])).deep.equals({ + id: 'order-q-dex', + txHash: '0xtxhash' + }) + const fallbacks = run.warnings.filter(line => line.includes('Autobot')) + expect(fallbacks.length).equals(1) + expect(fallbacks[0]).contains('socket hang up') + }) + + it('confirms a dex order directly when no autobot is configured', async function () { + const run = makeScriptedPlugin({ + nativeAddress: '', + quotes: [dexQuote], + noAutobot: true + }) + const quote = await quoteSonicToStellar(run) + await quote.approve() + expect(run.autobotBodies.length).equals(0) expect(JSON.parse(run.confirmBodies[0])).deep.equals({ id: 'order-q-dex', txHash: '0xtxhash' }) }) - it('retries a dex confirmation the provider failed to take', async function () { + it('retries a direct dex confirmation the provider failed to take', async function () { // The transaction is already out, so the report is retried rather than // dropped on the first 5xx. const run = makeScriptedPlugin({ nativeAddress: '', quotes: [dexQuote], + autobotStatuses: [503], confirmStatuses: [503, 200] }) const quote = await quoteSonicToStellar(run) @@ -995,6 +1084,7 @@ describe('houdini offline behaviors', function () { const run = makeScriptedPlugin({ nativeAddress: '', quotes: [dexQuote], + autobotStatuses: [503], confirmStatuses: [500] }) const quote = await quoteSonicToStellar(run) @@ -1008,10 +1098,11 @@ describe('houdini offline behaviors', function () { ).equals(3) }) - it('does not retry a dex confirmation the provider refused', async function () { + it('does not retry a direct dex confirmation the provider refused', async function () { const run = makeScriptedPlugin({ nativeAddress: '', quotes: [dexQuote], + autobotStatuses: [503], confirmStatuses: [400] }) const quote = await quoteSonicToStellar(run)