UNPKG

@reservoir0x/relay-kit-hooks

Version:

Relay is the Fastest and Cheapest Way to Bridge and Transact Across Chains.

89 lines 2.82 kB
import { MAINNET_RELAY_API, RelayClient } from '@reservoir0x/relay-sdk'; import { axiosPostFetcher } from '../fetcher.js'; import { useQuery } from '@tanstack/react-query'; import { useCallback, useMemo } from 'react'; export const queryQuote = function (baseApiUrl = MAINNET_RELAY_API, options, config) { return new Promise((resolve, reject) => { const url = new URL(`${baseApiUrl}/quote`); axiosPostFetcher(url.href, options, config) .then((response) => { const request = { url: url.href, method: 'post', data: options }; resolve({ ...response, request }); }) .catch((e) => { reject(e); }); }); }; export default function (client, wallet, options, onRequest, onResponse, queryOptions, onError, config) { const queryKey = ['useQuote', options]; const response = useQuery({ queryKey: queryKey, queryFn: () => { onRequest?.(options, config); if (options && client?.source && !options.referrer) { options.referrer = client.source; } const promise = queryQuote(client?.baseApiUrl, options, { ...config, headers: { 'relay-sdk-version': client?.version ?? 'unknown', 'relay-kit-ui-version': client?.uiVersion ?? 'unknown' } }); promise .then((response) => { onResponse?.(response, options); }) .catch((e) => { if (onError) { onError?.(e); } else { throw e; } }); return promise; }, enabled: client !== undefined && options !== undefined, retry: false, ...queryOptions }); const executeQuote = useCallback((onProgress) => { if (!wallet) { throw 'Missing a valid wallet'; } if (!response.data) { throw 'Missing a quote'; } const promise = client?.actions?.execute({ wallet, quote: response.data, onProgress }); return promise; }, [response.data, wallet, client]); return useMemo(() => ({ ...response, data: response.error ? undefined : response.data, queryKey, executeQuote }), [ response.data, response.error, response.isLoading, response.isFetching, response.isRefetching, response.dataUpdatedAt, executeQuote, queryKey ]); } //# sourceMappingURL=useQuote.js.map