From ccf1faaa2a9c3b09004705d30e436b15f2725a81 Mon Sep 17 00:00:00 2001 From: Matthew Little Date: Sun, 10 Dec 2023 14:13:04 +0100 Subject: [PATCH] fix: handle `NoEstimateAvailable` text error body --- packages/transactions/src/builders.ts | 13 +++++++++++-- packages/transactions/tests/builder.test.ts | 15 ++++++++++++++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/packages/transactions/src/builders.ts b/packages/transactions/src/builders.ts index 3b6b72101..621a46ad9 100644 --- a/packages/transactions/src/builders.ts +++ b/packages/transactions/src/builders.ts @@ -209,9 +209,18 @@ export async function estimateTransaction( const response = await derivedNetwork.fetchFn(url, options); if (!response.ok) { - const body = await response.json().catch(() => ({})); + const body = await response.text().then(str => { + try { + return JSON.parse(str); + } catch (error) { + return str; + } + }); - if (body?.reason === 'NoEstimateAvailable') { + if ( + body?.reason === 'NoEstimateAvailable' || + (typeof body === 'string' && body.includes('NoEstimateAvailable')) + ) { throw new NoEstimateAvailableError(body?.reason_data?.message ?? ''); } diff --git a/packages/transactions/tests/builder.test.ts b/packages/transactions/tests/builder.test.ts index b6d7eefd3..dd06161a2 100644 --- a/packages/transactions/tests/builder.test.ts +++ b/packages/transactions/tests/builder.test.ts @@ -1245,6 +1245,19 @@ test('Estimate transaction fee fallback', async () => { const resultEstimateFee = await estimateTransactionFeeWithFallback(tx, testnet); expect(resultEstimateFee).toBe(201n); + // Test with plain-text response + // http://localhost:3999/v2/fees/transaction + fetchMock.once( + `Estimator RPC endpoint failed to estimate tx TokenTransfer: NoEstimateAvailable`, + { status: 400 } + ); + + // http://localhost:3999/v2/fees/transfer + fetchMock.once('1'); + + const resultEstimateFee2 = await estimateTransactionFeeWithFallback(tx, testnet); + expect(resultEstimateFee2).toBe(201n); + // http://localhost:3999/v2/fees/transaction fetchMock.once( `{"error":"Estimation could not be performed","reason":"NoEstimateAvailable","reason_data":{"message":"No estimate available for the provided payload."}}`, @@ -1257,7 +1270,7 @@ test('Estimate transaction fee fallback', async () => { const doubleRate = await estimateTransactionFeeWithFallback(tx, testnet); expect(doubleRate).toBe(402n); - expect(fetchMock.mock.calls.length).toEqual(6); + expect(fetchMock.mock.calls.length).toEqual(8); }); test('Single-sig transaction byte length must include signature', async () => {