From dafdce22a7d68a8e115006472336b819d6730fdb Mon Sep 17 00:00:00 2001 From: Alex Freska Date: Tue, 16 Apr 2024 13:57:58 -0400 Subject: [PATCH] refactor: request api, renterd and sia central sdks --- .changeset/chilly-pants-provide.md | 6 + .changeset/odd-pets-fix.md | 5 + .../app/address/[id]/opengraph-image.tsx | 19 ++- apps/explorer/app/address/[id]/page.tsx | 21 ++- .../app/block/[id]/opengraph-image.tsx | 19 ++- apps/explorer/app/block/[id]/page.tsx | 21 ++- .../app/contract/[id]/opengraph-image.tsx | 36 +++-- apps/explorer/app/contract/[id]/page.tsx | 76 +++++------ .../app/host/[id]/opengraph-image.tsx | 36 +++-- apps/explorer/app/host/[id]/page.tsx | 38 +++--- apps/explorer/app/opengraph-image.tsx | 24 +--- apps/explorer/app/page.tsx | 84 +++++------- apps/explorer/app/tx/[id]/opengraph-image.tsx | 19 ++- apps/explorer/app/tx/[id]/page.tsx | 21 ++- .../components/Contract/ContractHeader.tsx | 14 +- apps/explorer/config/siaCentral.ts | 4 + apps/explorer/lib/blocks.ts | 122 +++-------------- apps/website/config/siaCentral.ts | 3 + apps/website/content/exchangeRates.ts | 18 ++- apps/website/content/geoHosts.ts | 15 ++- apps/website/content/stats.ts | 17 +-- apps/website/pages/index.tsx | 2 +- apps/website/pages/map.tsx | 2 +- libs/renterd-js/README.md | 25 ++-- libs/renterd-js/src/example.ts | 17 ++- libs/request/src/index.ts | 48 +++++-- libs/sia-central-js/README.md | 25 +++- libs/sia-central-js/package.json | 4 +- libs/sia-central-js/src/address.ts | 18 --- libs/sia-central-js/src/block.ts | 18 --- libs/sia-central-js/src/blockLatest.ts | 16 --- libs/sia-central-js/src/blocks.ts | 22 --- libs/sia-central-js/src/contract.ts | 18 --- libs/sia-central-js/src/example.ts | 14 ++ libs/sia-central-js/src/exchangeRates.ts | 16 --- libs/sia-central-js/src/fetch.ts | 13 -- libs/sia-central-js/src/host.ts | 18 --- libs/sia-central-js/src/hosts.ts | 31 ----- .../src/hostsNetworkAverages.ts | 16 --- .../sia-central-js/src/hostsNetworkMetrics.ts | 16 --- libs/sia-central-js/src/index.ts | 127 ++++++++++++++++-- libs/sia-central-js/src/search.ts | 18 --- libs/sia-central-js/src/transaction.ts | 18 --- libs/sia-central-mock/project.json | 7 - .../src/useSiaCentralAddress.tsx | 4 +- .../src/useSiaCentralBlock.tsx | 4 +- .../src/useSiaCentralBlockLatest.tsx | 4 +- .../src/useSiaCentralBlocks.tsx | 4 +- .../src/useSiaCentralContract.tsx | 4 +- .../src/useSiaCentralExchangeRates.tsx | 4 +- .../src/useSiaCentralHost.tsx | 4 +- .../src/useSiaCentralHosts.tsx | 7 +- .../src/useSiaCentralHostsNetworkAverages.tsx | 4 +- .../src/useSiaCentralHostsNetworkMetrics.tsx | 4 +- .../src/useSiaCentralSearch.tsx | 4 +- .../src/useSiaCentralTransaction.tsx | 4 +- libs/sia-central-types/src/address.ts | 2 +- libs/sia-central-types/src/block.ts | 2 +- libs/sia-central-types/src/blockLatest.ts | 5 +- libs/sia-central-types/src/blocks.ts | 2 +- libs/sia-central-types/src/config.ts | 2 +- libs/sia-central-types/src/contract.ts | 2 +- libs/sia-central-types/src/exchangeRates.ts | 4 + libs/sia-central-types/src/host.ts | 2 +- libs/sia-central-types/src/hosts.ts | 6 +- .../src/hostsNetworkAverages.ts | 2 + .../src/hostsNetworkMetrics.ts | 2 + libs/sia-central-types/src/search.ts | 2 +- libs/sia-central-types/src/transaction.ts | 2 +- 69 files changed, 530 insertions(+), 683 deletions(-) create mode 100644 .changeset/chilly-pants-provide.md create mode 100644 .changeset/odd-pets-fix.md create mode 100644 apps/explorer/config/siaCentral.ts create mode 100644 apps/website/config/siaCentral.ts delete mode 100644 libs/sia-central-js/src/address.ts delete mode 100644 libs/sia-central-js/src/block.ts delete mode 100644 libs/sia-central-js/src/blockLatest.ts delete mode 100644 libs/sia-central-js/src/blocks.ts delete mode 100644 libs/sia-central-js/src/contract.ts create mode 100644 libs/sia-central-js/src/example.ts delete mode 100644 libs/sia-central-js/src/exchangeRates.ts delete mode 100644 libs/sia-central-js/src/fetch.ts delete mode 100644 libs/sia-central-js/src/host.ts delete mode 100644 libs/sia-central-js/src/hosts.ts delete mode 100644 libs/sia-central-js/src/hostsNetworkAverages.ts delete mode 100644 libs/sia-central-js/src/hostsNetworkMetrics.ts delete mode 100644 libs/sia-central-js/src/search.ts delete mode 100644 libs/sia-central-js/src/transaction.ts diff --git a/.changeset/chilly-pants-provide.md b/.changeset/chilly-pants-provide.md new file mode 100644 index 000000000..fcf734c42 --- /dev/null +++ b/.changeset/chilly-pants-provide.md @@ -0,0 +1,6 @@ +--- +'explorer': minor +'website': minor +--- + +The site now uses the updated Sia Central SDK. diff --git a/.changeset/odd-pets-fix.md b/.changeset/odd-pets-fix.md new file mode 100644 index 000000000..e13c50df1 --- /dev/null +++ b/.changeset/odd-pets-fix.md @@ -0,0 +1,5 @@ +--- +'@siafoundation/sia-central-js': minor +--- + +The SDK has been updated to use the request library. diff --git a/apps/explorer/app/address/[id]/opengraph-image.tsx b/apps/explorer/app/address/[id]/opengraph-image.tsx index 3d599ad70..5cc1673c2 100644 --- a/apps/explorer/app/address/[id]/opengraph-image.tsx +++ b/apps/explorer/app/address/[id]/opengraph-image.tsx @@ -1,8 +1,8 @@ -import { getSiaCentralAddress } from '@siafoundation/sia-central-js' import { humanSiacoin, humanSiafund } from '@siafoundation/units' import { getOGImage } from '../../../components/OGImageEntity' -import { siaCentralApi } from '../../../config' +import { siaCentral } from '../../../config/siaCentral' import { truncate } from '@siafoundation/design-system' +import { to } from '@siafoundation/request' export const revalidate = 0 @@ -16,14 +16,13 @@ export const contentType = 'image/png' export default async function Image({ params }) { const id = params?.id as string - const { data: a } = await getSiaCentralAddress({ - params: { - id, - }, - config: { - api: siaCentralApi, - }, - }) + const [a] = await to( + siaCentral.address({ + params: { + id, + }, + }) + ) if (!a) { return getOGImage( diff --git a/apps/explorer/app/address/[id]/page.tsx b/apps/explorer/app/address/[id]/page.tsx index 13346ef50..d5d0496f3 100644 --- a/apps/explorer/app/address/[id]/page.tsx +++ b/apps/explorer/app/address/[id]/page.tsx @@ -1,11 +1,11 @@ -import { getSiaCentralAddress } from '@siafoundation/sia-central-js' import { Address } from '../../../components/Address' import { Metadata } from 'next' import { routes } from '../../../config/routes' import { buildMetadata } from '../../../lib/utils' -import { siaCentralApi } from '../../../config' +import { siaCentral } from '../../../config/siaCentral' import { notFound } from 'next/navigation' import { truncate } from '@siafoundation/design-system' +import { to } from '@siafoundation/request' export function generateMetadata({ params }): Metadata { const id = decodeURIComponent((params?.id as string) || '') @@ -23,17 +23,16 @@ export const revalidate = 0 export default async function Page({ params }) { const id = params?.id as string - const { data: a, error } = await getSiaCentralAddress({ - params: { - id, - }, - config: { - api: siaCentralApi, - }, - }) + const [a, error] = await to( + siaCentral.address({ + params: { + id, + }, + }) + ) if (error) { - throw Error(error) + throw error } if (a?.unspent_siacoins == undefined) { diff --git a/apps/explorer/app/block/[id]/opengraph-image.tsx b/apps/explorer/app/block/[id]/opengraph-image.tsx index 9ef84573b..3eeb7bb9a 100644 --- a/apps/explorer/app/block/[id]/opengraph-image.tsx +++ b/apps/explorer/app/block/[id]/opengraph-image.tsx @@ -1,8 +1,8 @@ -import { getSiaCentralBlock } from '@siafoundation/sia-central-js' import { humanDate } from '@siafoundation/units' import { getOGImage } from '../../../components/OGImageEntity' -import { siaCentralApi } from '../../../config' +import { siaCentral } from '../../../config/siaCentral' import { truncate } from '@siafoundation/design-system' +import { to } from '@siafoundation/request' export const revalidate = 0 @@ -16,14 +16,13 @@ export const contentType = 'image/png' export default async function Image({ params }) { const id = params?.id as string - const { data: b } = await getSiaCentralBlock({ - params: { - id, - }, - config: { - api: siaCentralApi, - }, - }) + const [b] = await to( + siaCentral.block({ + params: { + id, + }, + }) + ) if (!b || !b.block) { return getOGImage( diff --git a/apps/explorer/app/block/[id]/page.tsx b/apps/explorer/app/block/[id]/page.tsx index e3f26bc2a..5bfceeabd 100644 --- a/apps/explorer/app/block/[id]/page.tsx +++ b/apps/explorer/app/block/[id]/page.tsx @@ -2,10 +2,10 @@ import { getTitleId } from '@siafoundation/design-system' import { Block } from '../../../components/Block' import { routes } from '../../../config/routes' import { Metadata } from 'next' -import { getSiaCentralBlock } from '@siafoundation/sia-central-js' import { buildMetadata } from '../../../lib/utils' -import { siaCentralApi } from '../../../config' +import { siaCentral } from '../../../config/siaCentral' import { notFound } from 'next/navigation' +import { to } from '@siafoundation/request' export function generateMetadata({ params }): Metadata { const id = decodeURIComponent((params?.id as string) || '') @@ -34,17 +34,16 @@ export const revalidate = 0 export default async function Page({ params }) { const id = params?.id as string - const { data: b, error } = await getSiaCentralBlock({ - params: { - id, - }, - config: { - api: siaCentralApi, - }, - }) + const [b, error] = await to( + siaCentral.block({ + params: { + id, + }, + }) + ) if (error) { - throw Error(error) + throw error } if (!b?.block) { diff --git a/apps/explorer/app/contract/[id]/opengraph-image.tsx b/apps/explorer/app/contract/[id]/opengraph-image.tsx index 5a431eb0d..049c3c107 100644 --- a/apps/explorer/app/contract/[id]/opengraph-image.tsx +++ b/apps/explorer/app/contract/[id]/opengraph-image.tsx @@ -1,14 +1,11 @@ -import { - getSiaCentralContract, - getSiaCentralExchangeRates, -} from '@siafoundation/sia-central-js' import { humanBytes, humanDate } from '@siafoundation/units' import { getOGImage } from '../../../components/OGImageEntity' -import { siaCentralApi } from '../../../config' +import { siaCentral } from '../../../config/siaCentral' import { truncate } from '@siafoundation/design-system' import { lowerCase } from '@technically/lodash' import { siacoinToFiat } from '../../../lib/currency' import { CurrencyOption, currencyOptions } from '@siafoundation/react-core' +import { to } from '@siafoundation/request' export const revalidate = 0 @@ -25,20 +22,21 @@ const currency = currencyOptions.find((c) => c.id === 'usd') as CurrencyOption export default async function Image({ params }) { const id = params?.id as string - const [{ data: c }, { data: r }] = await Promise.all([ - getSiaCentralContract({ - params: { - id, - }, - config: { - api: siaCentralApi, - }, - }), - getSiaCentralExchangeRates({ - config: { - api: siaCentralApi, - }, - }), + const [[c], [r]] = await Promise.all([ + to( + siaCentral.contract({ + params: { + id, + }, + }) + ), + to( + siaCentral.exchangeRates({ + params: { + currencies: 'sc', + }, + }) + ), ]) if (!c || !c.contract) { diff --git a/apps/explorer/app/contract/[id]/page.tsx b/apps/explorer/app/contract/[id]/page.tsx index 209d0a818..3a263ca05 100644 --- a/apps/explorer/app/contract/[id]/page.tsx +++ b/apps/explorer/app/contract/[id]/page.tsx @@ -1,16 +1,12 @@ import { SiaCentralContract } from '@siafoundation/sia-central-types' -import { - getSiaCentralContract, - getSiaCentralExchangeRates, - getSiaCentralTransaction, -} from '@siafoundation/sia-central-js' import { ContractView } from '../../../components/ContractView' import { Metadata } from 'next' import { routes } from '../../../config/routes' import { buildMetadata } from '../../../lib/utils' -import { siaCentralApi } from '../../../config' +import { siaCentral } from '../../../config/siaCentral' import { notFound } from 'next/navigation' import { truncate } from '@siafoundation/design-system' +import { to } from '@siafoundation/request' export function generateMetadata({ params }): Metadata { const id = decodeURIComponent((params?.id as string) || '') @@ -28,51 +24,51 @@ export const revalidate = 0 export default async function Page({ params }) { const id = params?.id as string - const [{ data: c, error }, { data: r }] = await Promise.all([ - getSiaCentralContract({ - params: { - id, - }, - config: { - api: siaCentralApi, - }, - }), - getSiaCentralExchangeRates({ - config: { - api: siaCentralApi, - }, - }), + const [[c, error], [r]] = await Promise.all([ + to( + siaCentral.contract({ + params: { + id, + }, + }) + ), + to( + siaCentral.exchangeRates({ + params: { + currencies: 'sc', + }, + }) + ), ]) if (error) { - throw Error(error) + throw error } - if (!c?.contract) { + const contract = c?.contract + + if (!contract) { return notFound() } - const contract = c.contract const formationTxnId = getFormationTxnId(contract) const finalRevisionTxnId = contract?.transaction_id || '' - const [{ data: ft }, { data: rt }] = await Promise.all([ - getSiaCentralTransaction({ - params: { - id: formationTxnId, - }, - config: { - api: siaCentralApi, - }, - }), - getSiaCentralTransaction({ - params: { - id: finalRevisionTxnId, - }, - config: { - api: siaCentralApi, - }, - }), + const [[ft], [rt]] = await Promise.all([ + to( + siaCentral.transaction({ + params: { + id: formationTxnId, + }, + }) + ), + to( + siaCentral.transaction({ + params: { + id: finalRevisionTxnId, + }, + }) + ), ]) const formationTransaction = ft?.transaction diff --git a/apps/explorer/app/host/[id]/opengraph-image.tsx b/apps/explorer/app/host/[id]/opengraph-image.tsx index 50b188f5d..355b15f23 100644 --- a/apps/explorer/app/host/[id]/opengraph-image.tsx +++ b/apps/explorer/app/host/[id]/opengraph-image.tsx @@ -1,9 +1,5 @@ -import { - getSiaCentralExchangeRates, - getSiaCentralHost, -} from '@siafoundation/sia-central-js' import { getOGImage } from '../../../components/OGImageEntity' -import { siaCentralApi } from '../../../config' +import { siaCentral } from '../../../config/siaCentral' import { getDownloadCost, getDownloadSpeed, @@ -14,6 +10,7 @@ import { } from '@siafoundation/units' import { truncate } from '@siafoundation/design-system' import { CurrencyOption, currencyOptions } from '@siafoundation/react-core' +import { to } from '@siafoundation/request' export const revalidate = 0 @@ -29,20 +26,21 @@ export const contentType = 'image/png' export default async function Image({ params }) { const id = params?.id as string - const [{ data: h }, { data: r }] = await Promise.all([ - getSiaCentralHost({ - params: { - id, - }, - config: { - api: siaCentralApi, - }, - }), - getSiaCentralExchangeRates({ - config: { - api: siaCentralApi, - }, - }), + const [[h], [r]] = await Promise.all([ + to( + siaCentral.host({ + params: { + id, + }, + }) + ), + to( + siaCentral.exchangeRates({ + params: { + currencies: 'sc', + }, + }) + ), ]) if (!h || !h.host) { diff --git a/apps/explorer/app/host/[id]/page.tsx b/apps/explorer/app/host/[id]/page.tsx index 30d9bd755..62e8db0f5 100644 --- a/apps/explorer/app/host/[id]/page.tsx +++ b/apps/explorer/app/host/[id]/page.tsx @@ -1,14 +1,11 @@ -import { - getSiaCentralExchangeRates, - getSiaCentralHost, -} from '@siafoundation/sia-central-js' import { Metadata } from 'next' import { routes } from '../../../config/routes' import { buildMetadata } from '../../../lib/utils' import { Host } from '../../../components/Host' -import { siaCentralApi } from '../../../config' import { notFound } from 'next/navigation' import { truncate } from '@siafoundation/design-system' +import { siaCentral } from '../../../config/siaCentral' +import { to } from '@siafoundation/request' export function generateMetadata({ params }): Metadata { const id = decodeURIComponent((params?.id as string) || '') @@ -26,24 +23,25 @@ export const revalidate = 0 export default async function Page({ params }) { const id = params?.id as string - const [{ data: h, error }, { data: r }] = await Promise.all([ - getSiaCentralHost({ - params: { - id, - }, - config: { - api: siaCentralApi, - }, - }), - getSiaCentralExchangeRates({ - config: { - api: siaCentralApi, - }, - }), + const [[h, error], [r]] = await Promise.all([ + to( + siaCentral.host({ + params: { + id, + }, + }) + ), + to( + siaCentral.exchangeRates({ + params: { + currencies: 'sc', + }, + }) + ), ]) if (error) { - throw Error(error) + throw error } if (!h?.host) { diff --git a/apps/explorer/app/opengraph-image.tsx b/apps/explorer/app/opengraph-image.tsx index 2fc57ef11..6be218bd0 100644 --- a/apps/explorer/app/opengraph-image.tsx +++ b/apps/explorer/app/opengraph-image.tsx @@ -1,11 +1,9 @@ -import { - getSiaCentralBlockLatest, - getSiaCentralHostsNetworkMetrics, -} from '@siafoundation/sia-central-js' import { getOGImage } from '../components/OGImage' -import { network, siaCentralApi } from '../config' +import { network } from '../config' import { humanBytes } from '@siafoundation/units' import { PreviewValue } from '../components/OGImage/Preview' +import { siaCentral } from '../config/siaCentral' +import { to } from '@siafoundation/request' export const revalidate = 0 @@ -18,20 +16,12 @@ export const size = { export const contentType = 'image/png' export default async function Image() { - const [{ data: metrics }, { data: latestBlock }] = await Promise.all([ - getSiaCentralHostsNetworkMetrics({ - config: { - api: siaCentralApi, - }, - }), - getSiaCentralBlockLatest({ - config: { - api: siaCentralApi, - }, - }), + const [[metrics], [latestBlock]] = await Promise.all([ + to(siaCentral.hostsNetworkMetrics()), + to(siaCentral.blockLatest()), ]) - const lastBlockHeight = Number(latestBlock?.block.height || 0) + const lastBlockHeight = Number(latestBlock?.block?.height || 0) const values: PreviewValue[] = [] if (latestBlock) { diff --git a/apps/explorer/app/page.tsx b/apps/explorer/app/page.tsx index 9e9a105ea..2bb2590cc 100644 --- a/apps/explorer/app/page.tsx +++ b/apps/explorer/app/page.tsx @@ -1,15 +1,11 @@ import { Metadata } from 'next' -import { appLink, network, siaCentralApi } from '../config' +import { appLink, network } from '../config' import { Home } from '../components/Home' -import { - getSiaCentralBlockLatest, - getSiaCentralExchangeRates, - getSiaCentralHosts, - getSiaCentralHostsNetworkMetrics, -} from '@siafoundation/sia-central-js' import { buildMetadata } from '../lib/utils' import { humanBytes } from '@siafoundation/units' import { getLastFewBlocks } from '../lib/blocks' +import { siaCentral } from '../config/siaCentral' +import { to } from '@siafoundation/request' export function generateMetadata(): Metadata { const title = 'siascan' @@ -28,71 +24,65 @@ export const revalidate = 0 export default async function HomePage() { const [ - { data: m, error: metricsError }, - { data: lb, error: latestBlockError }, - { data: r, error: exchangeRatesError }, - { data: h, error: hostsError }, + [metrics, metricsError], + [latestBlock, latestBlockError], + [exchangeRates, exchangeRatesError], + [hosts, hostsError], ] = await Promise.all([ - getSiaCentralHostsNetworkMetrics({ - config: { - api: siaCentralApi, - }, - }), - getSiaCentralBlockLatest({ - config: { - api: siaCentralApi, - }, - }), - getSiaCentralExchangeRates({ - config: { - api: siaCentralApi, - }, - }), - getSiaCentralHosts({ - params: { - limit: 5, - }, - config: { - api: siaCentralApi, - }, - }), + to(siaCentral.hostsNetworkMetrics()), + to(siaCentral.blockLatest()), + to( + siaCentral.exchangeRates({ + params: { currencies: 'sc' }, + }) + ), + to( + siaCentral.hosts({ + params: { + limit: 5, + }, + }) + ), ]) - const lastBlockHeight = lb?.block.height || 0 - const blocks = await getLastFewBlocks(lb?.block) + const lastBlockHeight = latestBlock?.block?.height || 0 + const [blocks, blocksError] = await getLastFewBlocks(latestBlock?.block) if ( metricsError || latestBlockError || exchangeRatesError || hostsError || - latestBlockError || - blocks.error + blocksError ) { console.log(new Date().toISOString(), { metricsError, latestBlockError, exchangeRatesError, - blocksError: blocks.error, + blocksError, hostsError, }) } console.log(new Date().toISOString(), { - metrics: humanBytes(Buffer.byteLength(JSON.stringify(m || ''))), - latestBlock: humanBytes(Buffer.byteLength(JSON.stringify(lb || ''))), + metrics: humanBytes(Buffer.byteLength(JSON.stringify(metrics || ''))), + latestBlock: humanBytes( + Buffer.byteLength(JSON.stringify(latestBlock || '')) + ), blocks: humanBytes(Buffer.byteLength(JSON.stringify(blocks || ''))), - exchangeRates: humanBytes(Buffer.byteLength(JSON.stringify(r || ''))), - hosts: humanBytes(Buffer.byteLength(JSON.stringify(h || ''))), + exchangeRates: humanBytes( + Buffer.byteLength(JSON.stringify(exchangeRates || '')) + ), + hosts: humanBytes(Buffer.byteLength(JSON.stringify(hosts || ''))), }) return ( ) } diff --git a/apps/explorer/app/tx/[id]/opengraph-image.tsx b/apps/explorer/app/tx/[id]/opengraph-image.tsx index 41fac3ece..35830778e 100644 --- a/apps/explorer/app/tx/[id]/opengraph-image.tsx +++ b/apps/explorer/app/tx/[id]/opengraph-image.tsx @@ -1,8 +1,8 @@ -import { getSiaCentralTransaction } from '@siafoundation/sia-central-js' import { humanDate } from '@siafoundation/units' import { getOGImage } from '../../../components/OGImageEntity' -import { siaCentralApi } from '../../../config' +import { siaCentral } from '../../../config/siaCentral' import { truncate } from '@siafoundation/design-system' +import { to } from '@siafoundation/request' export const revalidate = 0 @@ -17,14 +17,13 @@ export const contentType = 'image/png' export default async function Image({ params }) { const id = params?.id as string - const { data: t } = await getSiaCentralTransaction({ - params: { - id, - }, - config: { - api: siaCentralApi, - }, - }) + const [t] = await to( + siaCentral.transaction({ + params: { + id, + }, + }) + ) if (!t || !t.transaction) { return getOGImage( diff --git a/apps/explorer/app/tx/[id]/page.tsx b/apps/explorer/app/tx/[id]/page.tsx index 65876e03c..2e42fd4d7 100644 --- a/apps/explorer/app/tx/[id]/page.tsx +++ b/apps/explorer/app/tx/[id]/page.tsx @@ -1,11 +1,11 @@ import { Metadata } from 'next' import { routes } from '../../../config/routes' import { Transaction } from '../../../components/Transaction' -import { getSiaCentralTransaction } from '@siafoundation/sia-central-js' import { buildMetadata } from '../../../lib/utils' -import { siaCentralApi } from '../../../config' +import { siaCentral } from '../../../config/siaCentral' import { notFound } from 'next/navigation' import { truncate } from '@siafoundation/design-system' +import { to } from '@siafoundation/request' export function generateMetadata({ params }): Metadata { const id = decodeURIComponent((params?.id as string) || '') @@ -23,17 +23,16 @@ export const revalidate = 0 export default async function Page({ params }) { const id = params?.id as string - const { data: transaction, error } = await getSiaCentralTransaction({ - params: { - id, - }, - config: { - api: siaCentralApi, - }, - }) + const [transaction, error] = await to( + siaCentral.transaction({ + params: { + id, + }, + }) + ) if (error) { - throw Error(error) + throw error } if (!transaction?.transaction) { diff --git a/apps/explorer/components/Contract/ContractHeader.tsx b/apps/explorer/components/Contract/ContractHeader.tsx index e55955b20..c17bdfbdb 100644 --- a/apps/explorer/components/Contract/ContractHeader.tsx +++ b/apps/explorer/components/Contract/ContractHeader.tsx @@ -5,11 +5,11 @@ import { } from '@siafoundation/design-system' import { ArrowLeft16, ArrowRight16 } from '@siafoundation/react-icons' import { SiaCentralContract } from '@siafoundation/sia-central-types' -import { getSiaCentralBlockLatest } from '@siafoundation/sia-central-js' import { lowerCase } from '@technically/lodash' import { routes } from '../../config/routes' import { EntityHeading } from '../EntityHeading' -import { siaCentralApi } from '../../config' +import { siaCentral } from '../../config/siaCentral' +import { to } from '@siafoundation/request' type Props = { contract: SiaCentralContract @@ -23,13 +23,9 @@ export async function ContractHeader({ renewedToId, }: Props) { const { id } = contract - const { data: latest, error } = await getSiaCentralBlockLatest({ - config: { - api: siaCentralApi, - }, - }) + const [latest, error] = await to(siaCentral.blockLatest()) if (error) { - console.error(new Error(error).stack) + console.error(error.stack) } return (
@@ -70,7 +66,7 @@ export async function ContractHeader({ )}
- {latest && ( + {latest?.block && (
{ if (!block) { - return { - error: 'no block', - } + return [undefined, Error('no block')] } const lastBlockHeight = block.height || 0 - const [one, two, three, four] = await Promise.all([ - getSiaCentralBlock({ - params: { - id: String(lastBlockHeight - 1), + const [blocks] = await to( + siaCentral.blocks({ + data: { + heights: range(lastBlockHeight - 4, lastBlockHeight), }, - config: { - api: siaCentralApi, - }, - }), - getSiaCentralBlock({ - params: { - id: String(lastBlockHeight - 2), - }, - config: { - api: siaCentralApi, - }, - }), - getSiaCentralBlock({ - params: { - id: String(lastBlockHeight - 3), - }, - config: { - api: siaCentralApi, - }, - }), - getSiaCentralBlock({ - params: { - id: String(lastBlockHeight - 4), - }, - config: { - api: siaCentralApi, - }, - }), - ]) - - const blocks: SiaCentralBlock[] = [] - if (one.error) { - return { - error: one.error, - } - } - if (two.error) { - return { - error: two.error, - } - } - if (three.error) { - return { - error: three.error, - } - } - if (four.error) { - return { - error: four.error, - } - } - if (block) { - blocks.push(block) - } - if (one.data) { - blocks.push(one.data.block) - } - if (two.data) { - blocks.push(two.data.block) - } - if (three.data) { - blocks.push(three.data.block) - } - if (four.data) { - blocks.push(four.data.block) - } - return { - blocks, - } -} - -export async function getLastFewBlocks(block?: SiaCentralBlock) { - if (!block) { - return { - error: 'no block', - } - } - const lastBlockHeight = block.height || 0 - const response = await getSiaCentralBlocks({ - payload: { - heights: range(lastBlockHeight - 4, lastBlockHeight), - }, - config: { - api: siaCentralApi, - }, - }) - - if (response.data?.blocks) { - return { - blocks: [block, ...response.data.blocks], - } - } - return { - error: response.data?.message, + }) + ) + if (blocks?.blocks) { + return [[block, ...blocks.blocks], undefined] } + return [undefined, Error('no blocks')] } diff --git a/apps/website/config/siaCentral.ts b/apps/website/config/siaCentral.ts new file mode 100644 index 000000000..a0ed68af4 --- /dev/null +++ b/apps/website/config/siaCentral.ts @@ -0,0 +1,3 @@ +import { SiaCentral } from '@siafoundation/sia-central-js' + +export const siaCentral = SiaCentral() diff --git a/apps/website/content/exchangeRates.ts b/apps/website/content/exchangeRates.ts index 92d88c0b0..9d38a0fc8 100644 --- a/apps/website/content/exchangeRates.ts +++ b/apps/website/content/exchangeRates.ts @@ -1,9 +1,23 @@ -import { getSiaCentralExchangeRates } from '@siafoundation/sia-central-js' import { getCacheValue } from '../lib/cache' import { getMinutesInSeconds } from '../lib/time' +import { siaCentral } from '../config/siaCentral' +import { to } from '@siafoundation/request' const maxAge = getMinutesInSeconds(5) export async function getExchangeRates() { - return getCacheValue('exchangeRates', getSiaCentralExchangeRates, maxAge) + return getCacheValue( + 'exchangeRates', + async () => { + const [exchangeRates] = await to( + siaCentral.exchangeRates({ + params: { + currencies: 'sc', + }, + }) + ) + return exchangeRates + }, + maxAge + ) } diff --git a/apps/website/content/geoHosts.ts b/apps/website/content/geoHosts.ts index 9d0397eba..365537e07 100644 --- a/apps/website/content/geoHosts.ts +++ b/apps/website/content/geoHosts.ts @@ -1,7 +1,8 @@ import { SiaCentralHost } from '@siafoundation/sia-central-types' -import { getSiaCentralHosts } from '@siafoundation/sia-central-js' import { getCacheValue } from '../lib/cache' import { getMinutesInSeconds } from '../lib/time' +import { siaCentral } from '../config/siaCentral' +import { to } from '@siafoundation/request' const maxAge = getMinutesInSeconds(5) @@ -12,11 +13,13 @@ export async function getGeoHosts(): Promise { return getCacheValue( 'geoHosts', async () => { - const { data: siaCentralHosts, error } = await getSiaCentralHosts({ - params: { - limit: 300, - }, - }) + const [siaCentralHosts, error] = await to( + siaCentral.hosts({ + params: { + limit: 300, + }, + }) + ) if (error) { return [] } diff --git a/apps/website/content/stats.ts b/apps/website/content/stats.ts index 6688003c2..fdd22480e 100644 --- a/apps/website/content/stats.ts +++ b/apps/website/content/stats.ts @@ -3,10 +3,8 @@ import { humanBytes, humanNumber } from '@siafoundation/units' import { AsyncReturnType } from '../lib/types' import { getCacheValue } from '../lib/cache' import { getMinutesInSeconds } from '../lib/time' -import { - getSiaCentralBlockLatest, - getSiaCentralHostsNetworkMetrics, -} from '@siafoundation/sia-central-js' +import { siaCentral } from '../config/siaCentral' +import { to } from '@siafoundation/request' const maxAge = getMinutesInSeconds(5) @@ -36,12 +34,11 @@ async function readStats() { } } - const [{ data: latestBlock }, { data: hostsStats }, github] = - await Promise.all([ - getSiaCentralBlockLatest(), - getSiaCentralHostsNetworkMetrics(), - getGitHub(), - ]) + const [[latestBlock], [hostsStats], github] = await Promise.all([ + to(siaCentral.blockLatest()), + to(siaCentral.hostsNetworkMetrics()), + getGitHub(), + ]) const stats = { // network diff --git a/apps/website/pages/index.tsx b/apps/website/pages/index.tsx index cd4baa2d7..dc4c0cbdc 100644 --- a/apps/website/pages/index.tsx +++ b/apps/website/pages/index.tsx @@ -281,7 +281,7 @@ export async function getStaticProps() { const featured = await getFeedContent(['sia-all', 'featured'], 5) const tutorials = await getTutorialArticles() const hosts = await getGeoHosts() - const { data: rates } = await getExchangeRates() + const rates = await getExchangeRates() const services = await getProjects('featured', 5) const stats = await getStats() diff --git a/apps/website/pages/map.tsx b/apps/website/pages/map.tsx index b5a922eb6..ba5680397 100644 --- a/apps/website/pages/map.tsx +++ b/apps/website/pages/map.tsx @@ -12,7 +12,7 @@ export default function MapPage({ hosts, rates, stats }: Props) { } export async function getStaticProps() { - const [hosts, { data: rates }, stats] = await Promise.all([ + const [hosts, rates, stats] = await Promise.all([ getGeoHosts(), getExchangeRates(), getStats(), diff --git a/libs/renterd-js/README.md b/libs/renterd-js/README.md index d8c550980..7d6857f4a 100644 --- a/libs/renterd-js/README.md +++ b/libs/renterd-js/README.md @@ -2,18 +2,16 @@ SDK for interacting with `renterd`. -## installation +## Installation ```sh npm install @siafoundation/renterd-js ``` -## usage +## Usage ```js -import { Bus } from './bus' -import { Autopilot } from './autopilot' -import { Worker } from './worker' +import { Bus, Worker, Autopilot } from '@siafoundation/renterd-js' export async function example() { const bus = Bus({ @@ -29,11 +27,14 @@ export async function example() { password: 'password1337', }) - const buckets = await bus.buckets() - - buckets.data.forEach((bucket) => { - console.log(bucket.name, bucket.createdAt, bucket.policy) - }) + try { + const buckets = await bus.buckets() + buckets.data.forEach((bucket) => { + console.log(bucket.name, bucket.createdAt, bucket.policy) + }) + } catch (error) { + console.log(error) + } bus.bucketCreate({ data: { name: 'my-bucket' }, @@ -65,7 +66,7 @@ export async function example() { console.log(host.host.publicKey, host.host.priceTable) }) - worker.objectUpload({ + await worker.objectUpload({ params: { key: 'path/to/file.txt', bucket: 'my-bucket', @@ -78,7 +79,7 @@ export async function example() { }, }) - worker.objectDownload({ + await worker.objectDownload({ params: { key: 'path/to/file.txt', bucket: 'my-bucket', diff --git a/libs/renterd-js/src/example.ts b/libs/renterd-js/src/example.ts index 60767d4e7..844fdcddc 100644 --- a/libs/renterd-js/src/example.ts +++ b/libs/renterd-js/src/example.ts @@ -16,11 +16,14 @@ export async function example() { password: 'password1337', }) - const buckets = await bus.buckets() - - buckets.data.forEach((bucket) => { - console.log(bucket.name, bucket.createdAt, bucket.policy) - }) + try { + const buckets = await bus.buckets() + buckets.data.forEach((bucket) => { + console.log(bucket.name, bucket.createdAt, bucket.policy) + }) + } catch (error) { + console.log(error) + } bus.bucketCreate({ data: { name: 'my-bucket' }, @@ -52,7 +55,7 @@ export async function example() { console.log(host.host.publicKey, host.host.priceTable) }) - worker.objectUpload({ + await worker.objectUpload({ params: { key: 'path/to/file.txt', bucket: 'my-bucket', @@ -65,7 +68,7 @@ export async function example() { }, }) - worker.objectDownload({ + await worker.objectDownload({ params: { key: 'path/to/file.txt', bucket: 'my-bucket', diff --git a/libs/request/src/index.ts b/libs/request/src/index.ts index cbdf3f3af..2c13ca370 100644 --- a/libs/request/src/index.ts +++ b/libs/request/src/index.ts @@ -1,4 +1,10 @@ -import { Axios, AxiosRequestConfig, AxiosRequestHeaders } from 'axios' +import { + Axios, + AxiosError, + AxiosRequestConfig, + AxiosRequestHeaders, + AxiosResponse, +} from 'axios' export type RequestParams = Record< string, @@ -33,7 +39,7 @@ export function buildRequestHandler< Params = void, Data = void, Response = void ->(axios: Axios, method: Method, route: string) { +>(axios: Axios, method: Method, route: string, defaultParams?: Params) { type Args = Params extends void ? Data extends void ? { config?: AxiosRequestConfig } | void @@ -58,18 +64,43 @@ export function buildRequestHandler< data?: Data config?: AxiosRequestConfig } - const paramRoute = - 'params' in a - ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - parameterizeRoute(route, a.params as RequestParams)! - : route + const params = { + ...defaultParams, + ...a.params, + } + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const paramRoute = parameterizeRoute(route, params as RequestParams)! - const data = 'data' in a ? a.data : undefined + const data = 'data' in a ? JSON.stringify(a.data) : undefined return axios[method](paramRoute, data, a?.config) } } +export async function to( + promise: Promise> +): Promise< + [ + AxiosResponse['data'] | undefined, + AxiosError | undefined, + AxiosResponse | undefined + ] +> { + try { + const response = await promise + // Just in case the response is not already JSON + try { + const data = JSON.parse(response.data as string) + return [data, undefined, response] + } catch (e) { + return [response.data, undefined, response] + } + } catch (error) { + return [undefined, error as AxiosError, undefined] + } +} + export function initAxios(api: string, password?: string): Axios { const headers: AxiosRequestHeaders = { 'Content-Type': 'application/json', @@ -80,5 +111,6 @@ export function initAxios(api: string, password?: string): Axios { return new Axios({ baseURL: api, headers, + responseType: 'json', }) } diff --git a/libs/sia-central-js/README.md b/libs/sia-central-js/README.md index 0e54a0556..32f78de2e 100644 --- a/libs/sia-central-js/README.md +++ b/libs/sia-central-js/README.md @@ -2,6 +2,27 @@ Methods and types for interacting with the Sia Central API. -## Running unit tests +## Installation -Run `nx test sia-central-js` to execute the unit tests via [Jest](https://jestjs.io). +```sh +npm install @siafoundation/sia-central-js +``` + +## Usage + +```js +import { SiaCentral } from '@siafoundation/sia-central-js' + +export async function example() { + const siaCentral = SiaCentral() + const latestBlock = await siaCentral.blockLatest() + const metrics = await siaCentral.hostsNetworkMetrics() + const averages = await siaCentral.hostsNetworkAverages() + const exchangeRates = await siaCentral.exchangeRates({ + params: { + currencies: 'sc', + }, + }) + console.log({ latestBlock, metrics, averages, exchangeRates }) +} +``` diff --git a/libs/sia-central-js/package.json b/libs/sia-central-js/package.json index abf832c1c..d10585eb0 100644 --- a/libs/sia-central-js/package.json +++ b/libs/sia-central-js/package.json @@ -4,8 +4,8 @@ "version": "0.4.0", "license": "MIT", "dependencies": { - "@technically/lodash": "^4.17.0", - "@siafoundation/sia-central-types": "0.1.0" + "@siafoundation/sia-central-types": "0.1.0", + "@siafoundation/request": "0.1.0" }, "types": "./src/index.d.ts" } diff --git a/libs/sia-central-js/src/address.ts b/libs/sia-central-js/src/address.ts deleted file mode 100644 index 6dbd7516b..000000000 --- a/libs/sia-central-js/src/address.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { runFetch } from './fetch' -import { - api, - SiaCentralAddressParams, - SiaCentralAddressResponse, -} from '@siafoundation/sia-central-types' - -export async function getSiaCentralAddress(args: { - params: SiaCentralAddressParams - config?: { - api: string - } -}) { - const { params, config } = args - return runFetch( - `${config?.api || api}/wallet/addresses/${params.id}` - ) -} diff --git a/libs/sia-central-js/src/block.ts b/libs/sia-central-js/src/block.ts deleted file mode 100644 index ea2de9d4e..000000000 --- a/libs/sia-central-js/src/block.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { runFetch } from './fetch' -import { - api, - SiaCentralBlockParams, - SiaCentralBlockResponse, -} from '@siafoundation/sia-central-types' - -export async function getSiaCentralBlock(args: { - params: SiaCentralBlockParams - config?: { - api: string - } -}) { - const { params, config } = args - return runFetch( - `${config?.api || api}/explorer/blocks/${params.id}` - ) -} diff --git a/libs/sia-central-js/src/blockLatest.ts b/libs/sia-central-js/src/blockLatest.ts deleted file mode 100644 index 3ab7194be..000000000 --- a/libs/sia-central-js/src/blockLatest.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { runFetch } from './fetch' -import { - api, - SiaCentralBlockLatestResponse, -} from '@siafoundation/sia-central-types' - -export async function getSiaCentralBlockLatest(args?: { - config?: { - api: string - } -}) { - const { config } = args || {} - return runFetch( - `${config?.api || api}/explorer/blocks` - ) -} diff --git a/libs/sia-central-js/src/blocks.ts b/libs/sia-central-js/src/blocks.ts deleted file mode 100644 index ab2e829af..000000000 --- a/libs/sia-central-js/src/blocks.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { - api, - SiaCentralBlocksPayload, - SiaCentralBlocksResponse, -} from '@siafoundation/sia-central-types' -import { runFetch } from './fetch' - -export async function getSiaCentralBlocks(args: { - payload: SiaCentralBlocksPayload - config?: { - api: string - } -}) { - const { payload, config } = args - return runFetch( - `${config?.api || api}/explorer/blocks`, - { - method: 'POST', - body: JSON.stringify(payload), - } - ) -} diff --git a/libs/sia-central-js/src/contract.ts b/libs/sia-central-js/src/contract.ts deleted file mode 100644 index 02d4cb6e1..000000000 --- a/libs/sia-central-js/src/contract.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { runFetch } from './fetch' -import { - api, - SiaCentralContractParams, - SiaCentralContractResponse, -} from '@siafoundation/sia-central-types' - -export async function getSiaCentralContract(args: { - params: SiaCentralContractParams - config?: { - api: string - } -}) { - const { params, config } = args - return runFetch( - `${config?.api || api}/explorer/contracts/${params.id}` - ) -} diff --git a/libs/sia-central-js/src/example.ts b/libs/sia-central-js/src/example.ts new file mode 100644 index 000000000..c8764c99f --- /dev/null +++ b/libs/sia-central-js/src/example.ts @@ -0,0 +1,14 @@ +import { SiaCentral } from '.' + +export async function example() { + const siaCentral = SiaCentral() + const latestBlock = await siaCentral.blockLatest() + const metrics = await siaCentral.hostsNetworkMetrics() + const averages = await siaCentral.hostsNetworkAverages() + const exchangeRates = await siaCentral.exchangeRates({ + params: { + currencies: 'sc', + }, + }) + console.log({ latestBlock, metrics, averages, exchangeRates }) +} diff --git a/libs/sia-central-js/src/exchangeRates.ts b/libs/sia-central-js/src/exchangeRates.ts deleted file mode 100644 index 75fd6cc6e..000000000 --- a/libs/sia-central-js/src/exchangeRates.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { runFetch } from './fetch' -import { - api, - SiaCentralExchangeRatesResponse, -} from '@siafoundation/sia-central-types' - -export async function getSiaCentralExchangeRates(args?: { - config?: { - api: string - } -}) { - const { config } = args || {} - return runFetch( - `${config?.api || api}/market/exchange-rate?currencies=sc` - ) -} diff --git a/libs/sia-central-js/src/fetch.ts b/libs/sia-central-js/src/fetch.ts deleted file mode 100644 index 0d0db14ed..000000000 --- a/libs/sia-central-js/src/fetch.ts +++ /dev/null @@ -1,13 +0,0 @@ -export async function runFetch(url: string, init?: RequestInit): Promise<{ data?: T, error?: string }> { - try { - const bx = await fetch(url, init) - const result: T = await bx.json() - return { - data: result, - } - } catch (e: unknown) { - return { - error: (e as Error).message - } - } -} diff --git a/libs/sia-central-js/src/host.ts b/libs/sia-central-js/src/host.ts deleted file mode 100644 index ec06c60bf..000000000 --- a/libs/sia-central-js/src/host.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { runFetch } from './fetch' -import { - api, - SiaCentralHostParams, - SiaCentralHostResponse, -} from '@siafoundation/sia-central-types' - -export async function getSiaCentralHost(args: { - params: SiaCentralHostParams - config?: { - api: string - } -}) { - const { params, config } = args - return runFetch( - `${config?.api || api}/hosts/${params.id}` - ) -} diff --git a/libs/sia-central-js/src/hosts.ts b/libs/sia-central-js/src/hosts.ts deleted file mode 100644 index 8e9f3f1b5..000000000 --- a/libs/sia-central-js/src/hosts.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { merge } from '@technically/lodash' -import { runFetch } from './fetch' -import { - api, - SiaCentralHostsParams, - SiaCentralHostsResponse, -} from '@siafoundation/sia-central-types' - -export async function getSiaCentralHosts(args?: { - params?: SiaCentralHostsParams - config?: { - api: string - } -}) { - const { params, config } = merge( - { - params: { - limit: 10, - page: 1, - }, - }, - args - ) - return runFetch( - `${ - config?.api || api - }/hosts/list?showinactive=false&sort=used_storage&dir=desc&protocol=rhp3&page=${ - params.page - }&limit=${params.limit}` - ) -} diff --git a/libs/sia-central-js/src/hostsNetworkAverages.ts b/libs/sia-central-js/src/hostsNetworkAverages.ts deleted file mode 100644 index 008ec299d..000000000 --- a/libs/sia-central-js/src/hostsNetworkAverages.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { runFetch } from './fetch' -import { - api, - SiaCentralHostsNetworkAveragesResponse, -} from '@siafoundation/sia-central-types' - -export async function getSiaCentralHostsNetworkAverages(args?: { - config?: { - api: string - } -}) { - const { config } = args || {} - return runFetch( - `${config?.api || api}/hosts/network/averages` - ) -} diff --git a/libs/sia-central-js/src/hostsNetworkMetrics.ts b/libs/sia-central-js/src/hostsNetworkMetrics.ts deleted file mode 100644 index dda6ace05..000000000 --- a/libs/sia-central-js/src/hostsNetworkMetrics.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { runFetch } from './fetch' -import { - api, - SiaCentralHostsNetworkMetricsResponse, -} from '@siafoundation/sia-central-types' - -export async function getSiaCentralHostsNetworkMetrics(args?: { - config?: { - api: string - } -}) { - const { config } = args || {} - return runFetch( - `${config?.api || api}/hosts/network/metrics` - ) -} diff --git a/libs/sia-central-js/src/index.ts b/libs/sia-central-js/src/index.ts index 2d5b3ffe9..3d393a0e9 100644 --- a/libs/sia-central-js/src/index.ts +++ b/libs/sia-central-js/src/index.ts @@ -1,12 +1,115 @@ -export * from './address' -export * from './blockLatest' -export * from './block' -export * from './blocks' -export * from './contract' -export * from './host' -export * from './hosts' -export * from './hostsNetworkAverages' -export * from './hostsNetworkMetrics' -export * from './exchangeRates' -export * from './transaction' -export * from './search' +import { + defaultApi, + SiaCentralAddressParams, + SiaCentralAddressPayload, + SiaCentralAddressResponse, + SiaCentralBlockLatestParams, + SiaCentralBlockLatestPayload, + SiaCentralBlockLatestResponse, + SiaCentralBlockParams, + SiaCentralBlockPayload, + SiaCentralBlockResponse, + SiaCentralBlocksParams, + SiaCentralBlocksPayload, + SiaCentralBlocksResponse, + SiaCentralContractParams, + SiaCentralContractPayload, + SiaCentralContractResponse, + SiaCentralExchangeRatesParams, + SiaCentralExchangeRatesPayload, + SiaCentralExchangeRatesResponse, + SiaCentralHostParams, + SiaCentralHostPayload, + SiaCentralHostResponse, + SiaCentralHostsNetworkAveragesParams, + SiaCentralHostsNetworkAveragesPayload, + SiaCentralHostsNetworkAveragesResponse, + SiaCentralHostsNetworkMetricsParams, + SiaCentralHostsNetworkMetricsPayload, + SiaCentralHostsNetworkMetricsResponse, + SiaCentralHostsParams, + SiaCentralHostsPayload, + SiaCentralHostsResponse, + SiaCentralSearchParams, + SiaCentralSearchPayload, + SiaCentralSearchResponse, + SiaCentralTransactionParams, + SiaCentralTransactionPayload, + SiaCentralTransactionResponse, +} from '@siafoundation/sia-central-types' +import { buildRequestHandler, initAxios } from '@siafoundation/request' + +export function SiaCentral({ api }: { api: string } = { api: defaultApi }) { + const axios = initAxios(api) + return { + address: buildRequestHandler< + SiaCentralAddressParams, + SiaCentralAddressPayload, + SiaCentralAddressResponse + >(axios, 'get', '/wallet/addresses/:id'), + block: buildRequestHandler< + SiaCentralBlockParams, + SiaCentralBlockPayload, + SiaCentralBlockResponse + >(axios, 'get', '/explorer/blocks/:id'), + blockLatest: buildRequestHandler< + SiaCentralBlockLatestParams, + SiaCentralBlockLatestPayload, + SiaCentralBlockLatestResponse + >(axios, 'get', '/explorer/blocks'), + blocks: buildRequestHandler< + SiaCentralBlocksParams, + SiaCentralBlocksPayload, + SiaCentralBlocksResponse + >(axios, 'post', '/explorer/blocks'), + contract: buildRequestHandler< + SiaCentralContractParams, + SiaCentralContractPayload, + SiaCentralContractResponse + >(axios, 'get', '/explorer/contracts/:id'), + exchangeRates: buildRequestHandler< + SiaCentralExchangeRatesParams, + SiaCentralExchangeRatesPayload, + SiaCentralExchangeRatesResponse + >(axios, 'get', '/market/exchange-rate', { + currencies: 'sc', + }), + host: buildRequestHandler< + SiaCentralHostParams, + SiaCentralHostPayload, + SiaCentralHostResponse + >(axios, 'get', '/hosts/:id'), + hosts: buildRequestHandler< + SiaCentralHostsParams, + SiaCentralHostsPayload, + SiaCentralHostsResponse + >(axios, 'get', '/hosts/list', { + showinactive: false, + sort: 'used_storage', + dir: 'desc', + protocol: 'rhp3', + limit: 10, + page: 1, + }), + hostsNetworkAverages: buildRequestHandler< + SiaCentralHostsNetworkAveragesParams, + SiaCentralHostsNetworkAveragesPayload, + SiaCentralHostsNetworkAveragesResponse + >(axios, 'get', '/hosts/network/averages'), + hostsNetworkMetrics: buildRequestHandler< + SiaCentralHostsNetworkMetricsParams, + SiaCentralHostsNetworkMetricsPayload, + SiaCentralHostsNetworkMetricsResponse + >(axios, 'get', '/hosts/network/metrics'), + search: buildRequestHandler< + SiaCentralSearchParams, + SiaCentralSearchPayload, + SiaCentralSearchResponse + >(axios, 'post', '/explorer/search'), + transaction: buildRequestHandler< + SiaCentralTransactionParams, + SiaCentralTransactionPayload, + SiaCentralTransactionResponse + >(axios, 'get', '/explorer/transactions/:id'), + } +} diff --git a/libs/sia-central-js/src/search.ts b/libs/sia-central-js/src/search.ts deleted file mode 100644 index 657102031..000000000 --- a/libs/sia-central-js/src/search.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { runFetch } from './fetch' -import { - api, - SiaCentralSearchParams, - SiaCentralSearchResponse, -} from '@siafoundation/sia-central-types' - -export async function getSiaCentralSearch(args: { - params: SiaCentralSearchParams - config?: { - api: string - } -}) { - const { params, config } = args - return runFetch( - `${config?.api || api}/explorer/search/${params.query}` - ) -} diff --git a/libs/sia-central-js/src/transaction.ts b/libs/sia-central-js/src/transaction.ts deleted file mode 100644 index d99ac64d5..000000000 --- a/libs/sia-central-js/src/transaction.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { - api, - SiaCentralTransactionParams, - SiaCentralTransactionResponse, -} from '@siafoundation/sia-central-types' -import { runFetch } from './fetch' - -export async function getSiaCentralTransaction(args: { - params: SiaCentralTransactionParams - config?: { - api: string - } -}) { - const { params, config } = args - return runFetch( - `${config?.api || api}/explorer/transactions/${params.id}` - ) -} diff --git a/libs/sia-central-mock/project.json b/libs/sia-central-mock/project.json index ae8ffd5fc..2bd8874cd 100644 --- a/libs/sia-central-mock/project.json +++ b/libs/sia-central-mock/project.json @@ -30,13 +30,6 @@ "lint": { "executor": "@nx/eslint:lint", "outputs": ["{options.outputFile}"] - }, - "test": { - "executor": "@nx/jest:jest", - "outputs": ["{workspaceRoot}/coverage/libs/sia-central-mock"], - "options": { - "jestConfig": "libs/sia-central-mock/jest.config.ts" - } } } } diff --git a/libs/sia-central-react/src/useSiaCentralAddress.tsx b/libs/sia-central-react/src/useSiaCentralAddress.tsx index fb74c0393..7bee3c15d 100644 --- a/libs/sia-central-react/src/useSiaCentralAddress.tsx +++ b/libs/sia-central-react/src/useSiaCentralAddress.tsx @@ -4,7 +4,7 @@ import { useGetSwr, } from '@siafoundation/react-core' import { - api, + defaultApi, SiaCentralAddressParams, SiaCentralAddressResponse, } from '@siafoundation/sia-central-types' @@ -14,7 +14,7 @@ export function useSiaCentralAddress( ) { const { settings } = useAppSettings() return useGetSwr({ - api, + api: defaultApi, ...args, route: '/wallet/addresses/:id', disabled: args?.disabled || !settings.siaCentral, diff --git a/libs/sia-central-react/src/useSiaCentralBlock.tsx b/libs/sia-central-react/src/useSiaCentralBlock.tsx index e8240ee25..28558bda2 100644 --- a/libs/sia-central-react/src/useSiaCentralBlock.tsx +++ b/libs/sia-central-react/src/useSiaCentralBlock.tsx @@ -4,7 +4,7 @@ import { useGetSwr, } from '@siafoundation/react-core' import { - api, + defaultApi, SiaCentralBlockParams, SiaCentralBlockResponse, } from '@siafoundation/sia-central-types' @@ -14,7 +14,7 @@ export function useSiaCentralBlock( ) { const { settings } = useAppSettings() return useGetSwr({ - api, + api: defaultApi, ...args, route: '/explorer/blocks/:id', disabled: args?.disabled || !settings.siaCentral, diff --git a/libs/sia-central-react/src/useSiaCentralBlockLatest.tsx b/libs/sia-central-react/src/useSiaCentralBlockLatest.tsx index 34c3b3dd4..3557fd773 100644 --- a/libs/sia-central-react/src/useSiaCentralBlockLatest.tsx +++ b/libs/sia-central-react/src/useSiaCentralBlockLatest.tsx @@ -3,7 +3,7 @@ import { HookArgsSwr, useGetSwr, } from '@siafoundation/react-core' -import { api, SiaCentralBlock } from '@siafoundation/sia-central-types' +import { defaultApi, SiaCentralBlock } from '@siafoundation/sia-central-types' type SiaCentralBlockLatestResponse = { message: string @@ -15,7 +15,7 @@ export function useSiaCentralBlockLatest( ) { const { settings } = useAppSettings() return useGetSwr({ - api, + api: defaultApi, ...args, route: '/explorer/blocks', disabled: args?.disabled || !settings.siaCentral, diff --git a/libs/sia-central-react/src/useSiaCentralBlocks.tsx b/libs/sia-central-react/src/useSiaCentralBlocks.tsx index 026f6572a..1e4db9e35 100644 --- a/libs/sia-central-react/src/useSiaCentralBlocks.tsx +++ b/libs/sia-central-react/src/useSiaCentralBlocks.tsx @@ -4,7 +4,7 @@ import { HookArgsWithPayloadSwr, } from '@siafoundation/react-core' import { - api, + defaultApi, SiaCentralBlock, SiaCentralBlocksPayload, } from '@siafoundation/sia-central-types' @@ -23,7 +23,7 @@ export function useSiaCentralBlocks( ) { const { settings } = useAppSettings() return usePostSwr({ - api, + api: defaultApi, ...args, route: '/explorer/blocks', disabled: args?.disabled || !settings.siaCentral, diff --git a/libs/sia-central-react/src/useSiaCentralContract.tsx b/libs/sia-central-react/src/useSiaCentralContract.tsx index e50df6e58..a59cac1c3 100644 --- a/libs/sia-central-react/src/useSiaCentralContract.tsx +++ b/libs/sia-central-react/src/useSiaCentralContract.tsx @@ -4,7 +4,7 @@ import { HookArgsSwr, } from '@siafoundation/react-core' import { - api, + defaultApi, SiaCentralContractParams, SiaCentralContractResponse, } from '@siafoundation/sia-central-types' @@ -14,7 +14,7 @@ export function useSiaCentralContract( ) { const { settings } = useAppSettings() return useGetSwr({ - api, + api: defaultApi, ...args, route: '/explorer/contracts/:id', disabled: args?.disabled || !settings.siaCentral, diff --git a/libs/sia-central-react/src/useSiaCentralExchangeRates.tsx b/libs/sia-central-react/src/useSiaCentralExchangeRates.tsx index b1f0db9a5..ff873f82f 100644 --- a/libs/sia-central-react/src/useSiaCentralExchangeRates.tsx +++ b/libs/sia-central-react/src/useSiaCentralExchangeRates.tsx @@ -4,7 +4,7 @@ import { HookArgsSwr, } from '@siafoundation/react-core' import { - api, + defaultApi, SiaCentralExchangeRatesResponse, } from '@siafoundation/sia-central-types' @@ -13,7 +13,7 @@ export function useSiaCentralExchangeRates( ) { const { settings } = useAppSettings() return useGetSwr({ - api, + api: defaultApi, ...args, route: '/market/exchange-rate?currencies=sc', disabled: args?.disabled || !settings.siaCentral, diff --git a/libs/sia-central-react/src/useSiaCentralHost.tsx b/libs/sia-central-react/src/useSiaCentralHost.tsx index a2b95fb99..9baddbec5 100644 --- a/libs/sia-central-react/src/useSiaCentralHost.tsx +++ b/libs/sia-central-react/src/useSiaCentralHost.tsx @@ -6,7 +6,7 @@ import { import { SiaCentralHostResponse, SiaCentralHostParams, - api, + defaultApi, } from '@siafoundation/sia-central-types' export function useSiaCentralHost( @@ -14,7 +14,7 @@ export function useSiaCentralHost( ) { const { settings } = useAppSettings() return useGetSwr({ - api, + api: defaultApi, ...args, route: '/hosts/:id', disabled: args?.disabled || !settings.siaCentral, diff --git a/libs/sia-central-react/src/useSiaCentralHosts.tsx b/libs/sia-central-react/src/useSiaCentralHosts.tsx index d79182125..10c0580da 100644 --- a/libs/sia-central-react/src/useSiaCentralHosts.tsx +++ b/libs/sia-central-react/src/useSiaCentralHosts.tsx @@ -3,14 +3,17 @@ import { useAppSettings, HookArgsSwr, } from '@siafoundation/react-core' -import { SiaCentralHostsResponse, api } from '@siafoundation/sia-central-types' +import { + SiaCentralHostsResponse, + defaultApi, +} from '@siafoundation/sia-central-types' export function useSiaCentralHosts( args?: HookArgsSwr ) { const { settings } = useAppSettings() return useGetSwr({ - api, + api: defaultApi, ...args, route: '/hosts/list?showinactive=false&sort=download_speed&dir=desc&protocol=rhp3&page=0&limit=1000', diff --git a/libs/sia-central-react/src/useSiaCentralHostsNetworkAverages.tsx b/libs/sia-central-react/src/useSiaCentralHostsNetworkAverages.tsx index f96eb5552..f5cbd6522 100644 --- a/libs/sia-central-react/src/useSiaCentralHostsNetworkAverages.tsx +++ b/libs/sia-central-react/src/useSiaCentralHostsNetworkAverages.tsx @@ -4,7 +4,7 @@ import { HookArgsSwr, } from '@siafoundation/react-core' import { - api, + defaultApi, SiaCentralHostsNetworkAveragesResponse, } from '@siafoundation/sia-central-types' @@ -13,7 +13,7 @@ export function useSiaCentralHostsNetworkAverages( ) { const { settings } = useAppSettings() return useGetSwr({ - api, + api: defaultApi, ...args, route: '/hosts/network/averages', disabled: args?.disabled || !settings.siaCentral, diff --git a/libs/sia-central-react/src/useSiaCentralHostsNetworkMetrics.tsx b/libs/sia-central-react/src/useSiaCentralHostsNetworkMetrics.tsx index 82c407094..48e61b00e 100644 --- a/libs/sia-central-react/src/useSiaCentralHostsNetworkMetrics.tsx +++ b/libs/sia-central-react/src/useSiaCentralHostsNetworkMetrics.tsx @@ -4,7 +4,7 @@ import { HookArgsSwr, } from '@siafoundation/react-core' import { - api, + defaultApi, SiaCentralHostsNetworkMetricsResponse, } from '@siafoundation/sia-central-types' @@ -13,7 +13,7 @@ export function useSiaCentralHostsNetworkMetrics( ) { const { settings } = useAppSettings() return useGetSwr({ - api, + api: defaultApi, ...args, route: '/hosts/network/metrics', disabled: args?.disabled || !settings.siaCentral, diff --git a/libs/sia-central-react/src/useSiaCentralSearch.tsx b/libs/sia-central-react/src/useSiaCentralSearch.tsx index f245e1117..e8f03489c 100644 --- a/libs/sia-central-react/src/useSiaCentralSearch.tsx +++ b/libs/sia-central-react/src/useSiaCentralSearch.tsx @@ -4,7 +4,7 @@ import { HookArgsCallback, } from '@siafoundation/react-core' import { - api, + defaultApi, SiaCentralSearchParams, SiaCentralSearchResponse, } from '@siafoundation/sia-central-types' @@ -18,7 +18,7 @@ export function useSiaCentralSearch( ) { const { settings } = useAppSettings() return useGetFunc({ - api, + api: defaultApi, ...args, route: '/explorer/search/:query', disabled: args?.disabled || !settings.siaCentral, diff --git a/libs/sia-central-react/src/useSiaCentralTransaction.tsx b/libs/sia-central-react/src/useSiaCentralTransaction.tsx index c3fbd312b..34b9aff0e 100644 --- a/libs/sia-central-react/src/useSiaCentralTransaction.tsx +++ b/libs/sia-central-react/src/useSiaCentralTransaction.tsx @@ -4,7 +4,7 @@ import { HookArgsSwr, } from '@siafoundation/react-core' import { - api, + defaultApi, SiaCentralTransactionParams, SiaCentralTransactionResponse, } from '@siafoundation/sia-central-types' @@ -14,7 +14,7 @@ export function useSiaCentralTransaction( ) { const { settings } = useAppSettings() return useGetSwr({ - api, + api: defaultApi, ...args, route: '/explorer/transactions/:id', disabled: args?.disabled || !settings.siaCentral, diff --git a/libs/sia-central-types/src/address.ts b/libs/sia-central-types/src/address.ts index 1cbdeaff4..9735850fa 100644 --- a/libs/sia-central-types/src/address.ts +++ b/libs/sia-central-types/src/address.ts @@ -3,7 +3,7 @@ import { SiaCentralSiafundOutput, SiaCentralTransaction } from './types' export type SiaCentralAddressParams = { id: string } - +export type SiaCentralAddressPayload = void export type SiaCentralAddressResponse = { message: 'successfully got transactions' type: 'success' diff --git a/libs/sia-central-types/src/block.ts b/libs/sia-central-types/src/block.ts index 507946d70..d81ebb66a 100644 --- a/libs/sia-central-types/src/block.ts +++ b/libs/sia-central-types/src/block.ts @@ -3,7 +3,7 @@ import { SiaCentralBlock } from './types' export type SiaCentralBlockParams = { id: string } - +export type SiaCentralBlockPayload = void export type SiaCentralBlockResponse = { message: string block: SiaCentralBlock diff --git a/libs/sia-central-types/src/blockLatest.ts b/libs/sia-central-types/src/blockLatest.ts index 774927f4e..27a164ab0 100644 --- a/libs/sia-central-types/src/blockLatest.ts +++ b/libs/sia-central-types/src/blockLatest.ts @@ -1,6 +1,9 @@ import { SiaCentralBlock } from './types' +export type SiaCentralBlockLatestParams = void +export type SiaCentralBlockLatestPayload = void export type SiaCentralBlockLatestResponse = { message: string - block: Omit + type: string + block?: Omit } diff --git a/libs/sia-central-types/src/blocks.ts b/libs/sia-central-types/src/blocks.ts index f87441d86..63d6aea2f 100644 --- a/libs/sia-central-types/src/blocks.ts +++ b/libs/sia-central-types/src/blocks.ts @@ -1,10 +1,10 @@ import { SiaCentralBlock } from './types' +export type SiaCentralBlocksParams = void export type SiaCentralBlocksResponse = { message: string blocks: SiaCentralBlock[] } - export type SiaCentralBlocksPayload = { block_ids?: number[] heights?: number[] diff --git a/libs/sia-central-types/src/config.ts b/libs/sia-central-types/src/config.ts index 6a7a2d516..a3528c8b0 100644 --- a/libs/sia-central-types/src/config.ts +++ b/libs/sia-central-types/src/config.ts @@ -1 +1 @@ -export const api = 'https://api.siacentral.com/v2' +export const defaultApi = 'https://api.siacentral.com/v2' diff --git a/libs/sia-central-types/src/contract.ts b/libs/sia-central-types/src/contract.ts index b5b08ea35..616439251 100644 --- a/libs/sia-central-types/src/contract.ts +++ b/libs/sia-central-types/src/contract.ts @@ -3,7 +3,7 @@ import { SiaCentralContract } from './types' export type SiaCentralContractParams = { id: string } - +export type SiaCentralContractPayload = void export type SiaCentralContractResponse = { message: string contract: SiaCentralContract diff --git a/libs/sia-central-types/src/exchangeRates.ts b/libs/sia-central-types/src/exchangeRates.ts index cb9913bd9..beff8b3a7 100644 --- a/libs/sia-central-types/src/exchangeRates.ts +++ b/libs/sia-central-types/src/exchangeRates.ts @@ -17,6 +17,10 @@ export type SiaCentralExchangeRates = { } } +export type SiaCentralExchangeRatesParams = { + currencies?: string +} +export type SiaCentralExchangeRatesPayload = void export type SiaCentralExchangeRatesResponse = { message: string type: string diff --git a/libs/sia-central-types/src/host.ts b/libs/sia-central-types/src/host.ts index 17891589a..841a7e10f 100644 --- a/libs/sia-central-types/src/host.ts +++ b/libs/sia-central-types/src/host.ts @@ -3,7 +3,7 @@ import { SiaCentralHost } from './types' export type SiaCentralHostParams = { id: string } - +export type SiaCentralHostPayload = void export type SiaCentralHostResponse = { message: string type: string diff --git a/libs/sia-central-types/src/hosts.ts b/libs/sia-central-types/src/hosts.ts index d27de8100..e5e7c3aa2 100644 --- a/libs/sia-central-types/src/hosts.ts +++ b/libs/sia-central-types/src/hosts.ts @@ -3,8 +3,12 @@ import { SiaCentralHost } from './types' export type SiaCentralHostsParams = { limit?: number page?: number + showinactive?: boolean + sort?: string + dir?: 'asc' | 'desc' + protocol?: string } - +export type SiaCentralHostsPayload = void export type SiaCentralHostsResponse = { message: string count: number diff --git a/libs/sia-central-types/src/hostsNetworkAverages.ts b/libs/sia-central-types/src/hostsNetworkAverages.ts index 79fb28dd1..423e47a96 100644 --- a/libs/sia-central-types/src/hostsNetworkAverages.ts +++ b/libs/sia-central-types/src/hostsNetworkAverages.ts @@ -1,5 +1,7 @@ import { SiaCentralNetworkStats } from './types' +export type SiaCentralHostsNetworkAveragesParams = void +export type SiaCentralHostsNetworkAveragesPayload = void export type SiaCentralHostsNetworkAveragesResponse = { message: string type: string diff --git a/libs/sia-central-types/src/hostsNetworkMetrics.ts b/libs/sia-central-types/src/hostsNetworkMetrics.ts index b5a4b8c68..54348a6f4 100644 --- a/libs/sia-central-types/src/hostsNetworkMetrics.ts +++ b/libs/sia-central-types/src/hostsNetworkMetrics.ts @@ -1,5 +1,7 @@ import { SiaCentralNetworkStats } from './types' +export type SiaCentralHostsNetworkMetricsParams = void +export type SiaCentralHostsNetworkMetricsPayload = void export type SiaCentralHostsNetworkMetricsResponse = { message: string type: string diff --git a/libs/sia-central-types/src/search.ts b/libs/sia-central-types/src/search.ts index dcb0cdf3d..7adf0d6a9 100644 --- a/libs/sia-central-types/src/search.ts +++ b/libs/sia-central-types/src/search.ts @@ -9,7 +9,7 @@ import { export type SiaCentralSearchParams = { query: string } - +export type SiaCentralSearchPayload = void export type SiaCentralSearchResponse = { message: string blocks?: SiaCentralBlock[] diff --git a/libs/sia-central-types/src/transaction.ts b/libs/sia-central-types/src/transaction.ts index 4253aba1a..9af9415d8 100644 --- a/libs/sia-central-types/src/transaction.ts +++ b/libs/sia-central-types/src/transaction.ts @@ -3,7 +3,7 @@ import { SiaCentralTransaction } from './types' export type SiaCentralTransactionParams = { id: string } - +export type SiaCentralTransactionPayload = void export type SiaCentralTransactionResponse = { message: string type?: 'error'