import { get } from '@capchase/http-client';
import { tracer } from '@capchase/tracer';
import { URL } from 'url';
import { getNewToken } from './auth';
import { getDhBaseUrl, constructDhQueryString } from './utils';
import { DhEntry, DhFetchParams } from './types';
type ErrorResponse = {
status: string;
reason: string;
errorDetails: string;
};
const internalDhFetch = async (
actionBy: string,
params?: DhFetchParams
): Promise<DhEntry[]> => {
if (!actionBy || actionBy.length === 0) {
throw new Error(
'Executor information (`actionBy`) is required for this action'
);
}
const span = tracer?.scope()?.active();
span?.addTags({
actionBy,
});
const url = new URL(getDhBaseUrl());
url.search = constructDhQueryString(params).toString();
span?.addTags({
url: url.toString(),
});
const token = await getNewToken(actionBy);
let response: Response;
try {
response = await get(url.toString(), {
authorization: token,
});
} catch (err) {
throw new Error(
`Unexpected failure while fetching Kantox DH entries: ${err.message}`
);
}
let body: any;
try {
body = await response.json();
} catch (err) {
throw new Error(
`Could not serialise Kantox DH entries response body from JSON: ${err.message}`
);
}
span?.addTags({
status: response.status,
});
if (response.status !== 200) {
const error = body as ErrorResponse;
throw new Error(
`Failed to fetch Kantox DH entries (${response.status}) [${error.status} ${error.reason}]: ${error.errorDetails}`
);
}
const entries = body as DhEntry[];
span?.addTags({
body_length: entries?.length,
});
return entries;
};
/**
* Fetches Kantox DH (Dynamic Hedging) entries based on the given parameters.
*
* @param {string} actionBy The action caller, i.e. executor.
* @param {DhFetchParams?} [params] Fetch parameters.
* @return {DhEntry[]} A list of Kantox DH entries.
*
* @throws {Error}
*
* @async
* @function
* @memberOf module:fxs/providers/kantox
* @access public
*/
export const dhFetch =
tracer?.wrap('fxs.providers.kantox.dhFetch', internalDhFetch) ||
internalDhFetch;