diff --git a/apps/api/src/chain/services/block-http/block-http.service.spec.ts b/apps/api/src/chain/services/block-http/block-http.service.spec.ts index 802d3d863..c7dbd9cf9 100644 --- a/apps/api/src/chain/services/block-http/block-http.service.spec.ts +++ b/apps/api/src/chain/services/block-http/block-http.service.spec.ts @@ -2,23 +2,26 @@ import "@test/mocks/logger-service.mock"; import { BlockHttpService as BlockHttpServiceCommon } from "@akashnetwork/http-sdk"; import { faker } from "@faker-js/faker"; +import axios from "axios"; import { BlockHttpService } from "./block-http.service"; describe(BlockHttpService.name, () => { - let service: BlockHttpService; - let blockHttpService: BlockHttpServiceCommon; + it("should get current height", async () => { + const { height, blockHttpService } = setup(); + + const result = await blockHttpService.getCurrentHeight(); - beforeEach(() => { - blockHttpService = new BlockHttpServiceCommon(); - service = new BlockHttpService(blockHttpService); + expect(result).toBe(height); }); - it("should get current height", async () => { + const setup = () => { + const blockHttpServiceCommon = new BlockHttpServiceCommon(axios.create()); + const blockHttpService = new BlockHttpService(blockHttpServiceCommon); + const height = faker.number.int({ min: 1000000, max: 10000000 }); - jest.spyOn(blockHttpService, "getCurrentHeight").mockResolvedValue(height); - const result = await service.getCurrentHeight(); + jest.spyOn(blockHttpServiceCommon, "getCurrentHeight").mockResolvedValue(height); - expect(result).toBe(height); - }); + return { height, blockHttpServiceCommon, blockHttpService }; + }; }); diff --git a/apps/api/src/core/providers/http-sdk.provider.ts b/apps/api/src/core/providers/http-sdk.provider.ts index 3533af11e..68222185e 100644 --- a/apps/api/src/core/providers/http-sdk.provider.ts +++ b/apps/api/src/core/providers/http-sdk.provider.ts @@ -11,6 +11,7 @@ import { NodeHttpService, ProviderHttpService } from "@akashnetwork/http-sdk"; +import axios from "axios"; import { container } from "tsyringe"; import { apiNodeUrl, nodeApiBasePath } from "@src/utils/constants"; @@ -26,8 +27,8 @@ const SERVICES = [ CosmosHttpService ]; -SERVICES.forEach(Service => container.register(Service, { useValue: new Service({ baseURL: apiNodeUrl }) })); +SERVICES.forEach(Service => container.register(Service, { useValue: new Service(axios.create({ baseURL: apiNodeUrl })) })); -container.register(GitHubHttpService, { useValue: new GitHubHttpService({ baseURL: "https://raw.githubusercontent.com" }) }); -container.register(CoinGeckoHttpService, { useValue: new CoinGeckoHttpService({ baseURL: "https://api.coingecko.com" }) }); -container.register(NodeHttpService, { useValue: new NodeHttpService({ baseURL: nodeApiBasePath }) }); +container.register(GitHubHttpService, { useValue: new GitHubHttpService(axios.create({ baseURL: "https://raw.githubusercontent.com" })) }); +container.register(CoinGeckoHttpService, { useValue: new CoinGeckoHttpService(axios.create({ baseURL: "https://api.coingecko.com" })) }); +container.register(NodeHttpService, { useValue: new NodeHttpService(axios.create({ baseURL: nodeApiBasePath })) }); diff --git a/apps/api/test/services/test-wallet.service.ts b/apps/api/test/services/test-wallet.service.ts index 48432b2bd..6adafb406 100644 --- a/apps/api/test/services/test-wallet.service.ts +++ b/apps/api/test/services/test-wallet.service.ts @@ -2,6 +2,7 @@ import { BalanceHttpService } from "@akashnetwork/http-sdk"; import type { EncodeObject } from "@cosmjs/proto-signing"; import { coins } from "@cosmjs/proto-signing"; import { calculateFee, GasPrice, SigningStargateClient } from "@cosmjs/stargate"; +import axios from "axios"; import dotenv from "dotenv"; import dotenvExpand from "dotenv-expand"; import * as fs from "fs"; @@ -19,9 +20,11 @@ const MIN_AMOUNTS: Record = { }; export class TestWalletService { - private readonly balanceHttpService = new BalanceHttpService({ - baseURL: config!.API_NODE_ENDPOINT - }); + private readonly balanceHttpService = new BalanceHttpService( + axios.create({ + baseURL: config!.API_NODE_ENDPOINT + }) + ); private mnemonics: Record = {}; diff --git a/apps/deploy-web/src/components/turnstile/Turnstile.tsx b/apps/deploy-web/src/components/turnstile/Turnstile.tsx index d33f32356..e59d701ec 100644 --- a/apps/deploy-web/src/components/turnstile/Turnstile.tsx +++ b/apps/deploy-web/src/components/turnstile/Turnstile.tsx @@ -27,10 +27,10 @@ let originalFetch: typeof fetch | undefined; const addResponseInterceptor = (intercept: (service: Axios, value: AxiosError) => AxiosResponse | Promise) => { const removes = HTTP_SERVICES.map(service => { - const interceptorId = service.interceptors.response.use(null, error => intercept(service, error)); + const interceptorId = service.axios.interceptors.response.use(null, error => intercept(service.axios, error)); return () => { - service.interceptors.response.eject(interceptorId); + service.axios.interceptors.response.eject(interceptorId); }; }); diff --git a/apps/deploy-web/src/context/ServicesProvider/ServicesProvider.tsx b/apps/deploy-web/src/context/ServicesProvider/ServicesProvider.tsx index c7c5599c7..21466ae7a 100644 --- a/apps/deploy-web/src/context/ServicesProvider/ServicesProvider.tsx +++ b/apps/deploy-web/src/context/ServicesProvider/ServicesProvider.tsx @@ -31,7 +31,7 @@ export function useServices() { function createAppContainer(settings: Settings, services: T) { const di = createChildContainer(rootContainer, { - authzHttpService: () => new AuthzHttpService({ baseURL: settings?.apiEndpoint }), + authzHttpService: () => new AuthzHttpService(rootContainer.createAxios({ baseURL: settings?.apiEndpoint })), walletBalancesService: () => new WalletBalancesService(di.authzHttpService, di.chainApiHttpClient, browserEnvConfig.NEXT_PUBLIC_MASTER_WALLET_ADDRESS), certificatesService: () => new CertificatesService(di.chainApiHttpClient), chainApiHttpClient: () => rootContainer.createAxios({ baseURL: settings?.apiEndpoint }), diff --git a/apps/deploy-web/src/queries/useBalancesQuery.ts b/apps/deploy-web/src/queries/useBalancesQuery.ts index 1d99c8d9a..b63a1e95d 100644 --- a/apps/deploy-web/src/queries/useBalancesQuery.ts +++ b/apps/deploy-web/src/queries/useBalancesQuery.ts @@ -10,7 +10,7 @@ export function useBalances(address?: string, options?: Omit (address ? di.walletBalancesService.getBalances(address) : null), - enabled: !!address && !!di.authzHttpService.getUri(), + enabled: !!address && !!di.authzHttpService.axios.getUri(), ...options }); } diff --git a/apps/deploy-web/src/queries/useGrantsQuery.spec.tsx b/apps/deploy-web/src/queries/useGrantsQuery.spec.tsx index c62d509ae..6d81c8c19 100644 --- a/apps/deploy-web/src/queries/useGrantsQuery.spec.tsx +++ b/apps/deploy-web/src/queries/useGrantsQuery.spec.tsx @@ -28,7 +28,9 @@ describe("useGrantsQuery", () => { }; const authzHttpService = mock({ - defaults: { baseURL: "https://api.akash.network" }, + axios: { + defaults: { baseURL: "https://api.akash.network" } + } as AxiosInstance, getPaginatedDepositDeploymentGrants: jest.fn().mockResolvedValue(mockData) }); const { result } = setupQuery(() => useGranterGrants("test-address", 0, 1000), { @@ -46,7 +48,9 @@ describe("useGrantsQuery", () => { it("does not fetch when address is not provided", () => { const authzHttpService = mock({ - defaults: { baseURL: "https://api.akash.network" }, + axios: { + defaults: { baseURL: "https://api.akash.network" } + } as AxiosInstance, getPaginatedDepositDeploymentGrants: jest.fn().mockResolvedValue([]) }); setupQuery(() => useGranterGrants("", 0, 1000), { @@ -69,7 +73,9 @@ describe("useGrantsQuery", () => { } ]; const authzHttpService = mock({ - defaults: { baseURL: "https://api.akash.network" }, + axios: { + defaults: { baseURL: "https://api.akash.network" } + } as AxiosInstance, getAllDepositDeploymentGrants: jest.fn().mockResolvedValue(mockData) }); @@ -88,7 +94,9 @@ describe("useGrantsQuery", () => { it("does not fetch when address is not provided", () => { const authzHttpService = mock({ - defaults: { baseURL: "https://api.akash.network" }, + axios: { + defaults: { baseURL: "https://api.akash.network" } + } as AxiosInstance, getAllDepositDeploymentGrants: jest.fn().mockResolvedValue([]) }); setupQuery(() => useGranteeGrants(""), { @@ -108,7 +116,9 @@ describe("useGrantsQuery", () => { pagination: { total: 1 } }; const authzHttpService = mock({ - defaults: { baseURL: "https://api.akash.network" }, + axios: { + defaults: { baseURL: "https://api.akash.network" } + } as AxiosInstance, getPaginatedFeeAllowancesForGranter: jest.fn().mockResolvedValue(mockData) }); @@ -127,7 +137,9 @@ describe("useGrantsQuery", () => { it("does not fetch when address is not provided", () => { const authzHttpService = mock({ - defaults: { baseURL: "https://api.akash.network" }, + axios: { + defaults: { baseURL: "https://api.akash.network" } + } as AxiosInstance, getPaginatedFeeAllowancesForGranter: jest.fn().mockResolvedValue([]) }); setupQuery(() => useAllowancesIssued("", 0, 1000), { diff --git a/apps/deploy-web/src/queries/useGrantsQuery.ts b/apps/deploy-web/src/queries/useGrantsQuery.ts index fd63dcd8d..1f2d61cc9 100644 --- a/apps/deploy-web/src/queries/useGrantsQuery.ts +++ b/apps/deploy-web/src/queries/useGrantsQuery.ts @@ -17,7 +17,7 @@ export function useGranterGrants( const { authzHttpService } = useServices(); const offset = page * limit; - options.enabled = options.enabled !== false && !!address && !!authzHttpService.defaults.baseURL; + options.enabled = options.enabled !== false && !!address && !!authzHttpService.axios.defaults.baseURL; return useQuery({ queryKey: QueryKeys.getGranterGrants(address, page, offset), @@ -29,7 +29,7 @@ export function useGranterGrants( export function useGranteeGrants(address: string, options: Omit, "queryKey" | "queryFn"> = {}) { const { authzHttpService } = useServices(); - options.enabled = options.enabled !== false && !!address && !!authzHttpService.defaults.baseURL; + options.enabled = options.enabled !== false && !!address && !!authzHttpService.axios.defaults.baseURL; return useQuery({ queryKey: QueryKeys.getGranteeGrants(address || "UNDEFINED"), @@ -47,7 +47,7 @@ export function useAllowancesIssued( const { authzHttpService } = useServices(); const offset = page * limit; - options.enabled = options.enabled !== false && !!address && !!authzHttpService.defaults.baseURL; + options.enabled = options.enabled !== false && !!address && !!authzHttpService.axios.defaults.baseURL; return useQuery({ queryKey: QueryKeys.getAllowancesIssued(address, page, offset), diff --git a/apps/deploy-web/src/services/app-di-container/app-di-container.ts b/apps/deploy-web/src/services/app-di-container/app-di-container.ts index 18f777668..5b81f9f29 100644 --- a/apps/deploy-web/src/services/app-di-container/app-di-container.ts +++ b/apps/deploy-web/src/services/app-di-container/app-di-container.ts @@ -13,7 +13,7 @@ import { StripeService } from "@akashnetwork/http-sdk/src/stripe/stripe.service" import { LoggerService } from "@akashnetwork/logging"; import { getTraceData } from "@sentry/nextjs"; import { MutationCache, QueryCache, QueryClient } from "@tanstack/react-query"; -import type { Axios, AxiosInstance, AxiosResponse, CreateAxiosDefaults, InternalAxiosRequestConfig } from "axios"; +import type { Axios, AxiosInstance, AxiosRequestConfig, AxiosResponse, CreateAxiosDefaults, InternalAxiosRequestConfig } from "axios"; import axios from "axios"; import { analyticsService } from "@src/services/analytics/analytics.service"; @@ -27,7 +27,30 @@ import { ProviderProxyService } from "../provider-proxy/provider-proxy.service"; export const createAppRootContainer = (config: ServicesConfig) => { const apiConfig = { baseURL: config.BASE_API_MAINNET_URL }; + const container = createContainer({ + getAxiosInstance: () => (config?: AxiosRequestConfig) => { + const { headers, ...defaults } = axios.defaults; + + return axios.create({ + ...defaults, + ...config + }); + }, + axiosWithDefaultInterceptors: () => (config?: AxiosRequestConfig) => { + return container.applyAxiosInterceptors(container.getAxiosInstance(config), { + request: [container.authService.withAnonymousUserHeader] + }); + }, + + defaultAxios: () => container.axiosWithDefaultInterceptors(), + mainnetAxios: () => container.axiosWithDefaultInterceptors(apiConfig), + mainNetAxiosWithNoAnonymousUserHeaderInterceptor: () => container.applyAxiosInterceptors(container.getAxiosInstance(apiConfig)), + managedWalletAxios: () => + container.axiosWithDefaultInterceptors({ + baseURL: container.apiUrlService.getBaseApiUrlFor(config.MANAGED_WALLET_NETWORK_ID) + }), + getTraceData: () => getTraceData, applyAxiosInterceptors: (): typeof withInterceptors => { const otelInterceptor = (config: InternalAxiosRequestConfig) => { @@ -36,51 +59,37 @@ export const createAppRootContainer = (config: ServicesConfig) => { if (traceData?.baggage) config.headers.set("Baggage", traceData.baggage); return config; }; + return (axiosInstance, interceptors?) => withInterceptors(axiosInstance, { request: [config.globalRequestMiddleware, otelInterceptor, ...(interceptors?.request || [])], - response: [...(interceptors?.response || [])] + response: [ + response => { + if (response.config.url?.startsWith("/v1/anonymous-users") && response.config.method === "post" && response.status === 200) { + container.analyticsService.track("anonymous_user_created", { category: "user", label: "Anonymous User Created" }); + } + return response; + }, + response => { + if (response.config.url === "v1/start-trial" && response.config.method === "post" && response.status === 200) { + container.analyticsService.track("trial_started", { category: "billing", label: "Trial Started" }); + } + return response; + }, + ...(interceptors?.response || []) + ] }); }, authService: () => new AuthService(), - user: () => - container.applyAxiosInterceptors(new UserHttpService(apiConfig), { - request: [container.authService.withAnonymousUserHeader], - response: [ - response => { - if (response.config.url?.startsWith("/v1/anonymous-users") && response.config.method === "post" && response.status === 200) { - container.analyticsService.track("anonymous_user_created", { category: "user", label: "Anonymous User Created" }); - } - return response; - } - ] - }), - stripe: () => - container.applyAxiosInterceptors(new StripeService(apiConfig), { - request: [container.authService.withAnonymousUserHeader] - }), - tx: () => - container.applyAxiosInterceptors(new TxHttpService(customRegistry, apiConfig), { - request: [container.authService.withAnonymousUserHeader] - }), - template: () => container.applyAxiosInterceptors(new TemplateHttpService(apiConfig)), - usage: () => - container.applyAxiosInterceptors(new UsageHttpService(apiConfig), { - request: [container.authService.withAnonymousUserHeader] - }), - auth: () => - container.applyAxiosInterceptors(new AuthHttpService(apiConfig), { - request: [container.authService.withAnonymousUserHeader] - }), + user: () => new UserHttpService(container.mainnetAxios), + stripe: () => new StripeService(container.mainnetAxios), + tx: () => new TxHttpService(container.mainnetAxios, customRegistry), + template: () => new TemplateHttpService(container.mainNetAxiosWithNoAnonymousUserHeaderInterceptor), + usage: () => new UsageHttpService(container.mainnetAxios), + auth: () => new AuthHttpService(container.mainnetAxios), providerProxy: () => new ProviderProxyService(container.applyAxiosInterceptors(container.createAxios({ baseURL: config.BASE_PROVIDER_PROXY_URL }), {})), - deploymentSetting: () => - container.applyAxiosInterceptors(new DeploymentSettingHttpService(apiConfig), { - request: [container.authService.withAnonymousUserHeader] - }), - apiKey: () => - container.applyAxiosInterceptors(new ApiKeyHttpService(), { - request: [container.authService.withAnonymousUserHeader] - }), + deploymentSetting: () => new DeploymentSettingHttpService(container.mainnetAxios), + apiKey: () => new ApiKeyHttpService(container.defaultAxios), externalApiHttpClient: () => container.createAxios({ headers: { @@ -97,26 +106,7 @@ export const createAppRootContainer = (config: ServicesConfig) => { certificateManager: () => certificateManager, analyticsService: () => analyticsService, apiUrlService: config.apiUrlService, - managedWalletService: () => - container.applyAxiosInterceptors( - new ManagedWalletHttpService( - { - baseURL: container.apiUrlService.getBaseApiUrlFor(config.MANAGED_WALLET_NETWORK_ID) - }, - container.analyticsService - ), - { - request: [container.authService.withAnonymousUserHeader], - response: [ - response => { - if (response.config.url === "v1/start-trial" && response.config.method === "post" && response.status === 200) { - container.analyticsService.track("trial_started", { category: "billing", label: "Trial Started" }); - } - return response; - } - ] - } - ), + managedWalletService: () => new ManagedWalletHttpService(container.managedWalletAxios, container.analyticsService), queryClient: () => new QueryClient({ queryCache: new QueryCache({ diff --git a/apps/deploy-web/src/services/http/http-browser.service.ts b/apps/deploy-web/src/services/http/http-browser.service.ts index 19ee21bce..e6508a380 100644 --- a/apps/deploy-web/src/services/http/http-browser.service.ts +++ b/apps/deploy-web/src/services/http/http-browser.service.ts @@ -19,7 +19,7 @@ const rootContainer = createAppRootContainer({ }); export const services = createChildContainer(rootContainer, { - userProviderService: () => new UserProviderService(), + userProviderService: () => new UserProviderService(services.defaultAxios), notificationsApi: () => createAPIClient({ requestFn, diff --git a/apps/deploy-web/src/services/managed-wallet-http/managed-wallet-http.service.ts b/apps/deploy-web/src/services/managed-wallet-http/managed-wallet-http.service.ts index 424893c77..2c4494240 100644 --- a/apps/deploy-web/src/services/managed-wallet-http/managed-wallet-http.service.ts +++ b/apps/deploy-web/src/services/managed-wallet-http/managed-wallet-http.service.ts @@ -1,6 +1,6 @@ import type { ApiManagedWalletOutput, ApiWalletOutput } from "@akashnetwork/http-sdk"; import { ManagedWalletHttpService as ManagedWalletHttpServiceOriginal } from "@akashnetwork/http-sdk"; -import type { AxiosRequestConfig } from "axios"; +import type { AxiosInstance } from "axios"; import type { AnalyticsService } from "@src/services/analytics/analytics.service"; @@ -8,10 +8,10 @@ export class ManagedWalletHttpService extends ManagedWalletHttpServiceOriginal { private checkoutSessionId: string | null = null; constructor( - config: AxiosRequestConfig, + axios: AxiosInstance, private readonly analyticsService: AnalyticsService ) { - super(config); + super(axios); this.extractSessionResults(); } diff --git a/apps/deploy-web/src/services/user-provider/user-provider.service.ts b/apps/deploy-web/src/services/user-provider/user-provider.service.ts index 80dec011f..2169b1997 100644 --- a/apps/deploy-web/src/services/user-provider/user-provider.service.ts +++ b/apps/deploy-web/src/services/user-provider/user-provider.service.ts @@ -1,14 +1,15 @@ import { HttpService } from "@akashnetwork/http-sdk"; import type { UserProfile } from "@auth0/nextjs-auth0/client"; -import type { InternalAxiosRequestConfig } from "axios"; +import type { AxiosInstance, InternalAxiosRequestConfig } from "axios"; import { ANONYMOUS_USER_TOKEN_KEY } from "@src/config/auth.config"; export class UserProviderService extends HttpService { - constructor() { - super(); + constructor(axios: AxiosInstance) { + super(axios); + this.getProfile = this.getProfile.bind(this); - this.interceptors.request.use((config: InternalAxiosRequestConfig) => { + this.axios.interceptors.request.use((config: InternalAxiosRequestConfig) => { const token = localStorage.getItem(ANONYMOUS_USER_TOKEN_KEY); if (token) { diff --git a/apps/notifications/src/modules/alert/providers/http-sdk.provider.ts b/apps/notifications/src/modules/alert/providers/http-sdk.provider.ts index d28d248b5..b8e14ebe3 100644 --- a/apps/notifications/src/modules/alert/providers/http-sdk.provider.ts +++ b/apps/notifications/src/modules/alert/providers/http-sdk.provider.ts @@ -1,6 +1,7 @@ import { DeploymentHttpService, LeaseHttpService } from "@akashnetwork/http-sdk"; import type { Provider } from "@nestjs/common"; import { ConfigService } from "@nestjs/config"; +import axios from "axios"; import type { AlertConfig } from "@src/modules/alert/config"; @@ -9,16 +10,20 @@ export const HTTP_SDK_PROVIDERS: Provider[] = [ provide: DeploymentHttpService, inject: [ConfigService], useFactory: (configService: ConfigService) => - new DeploymentHttpService({ - baseURL: configService.getOrThrow("alert.API_NODE_ENDPOINT") - }) + new DeploymentHttpService( + axios.create({ + baseURL: configService.getOrThrow("alert.API_NODE_ENDPOINT") + }) + ) }, { provide: LeaseHttpService, inject: [ConfigService], useFactory: (configService: ConfigService) => - new LeaseHttpService({ - baseURL: configService.getOrThrow("alert.API_NODE_ENDPOINT") - }) + new LeaseHttpService( + axios.create({ + baseURL: configService.getOrThrow("alert.API_NODE_ENDPOINT") + }) + ) } ]; diff --git a/packages/http-sdk/src/api-http/api-http.service.ts b/packages/http-sdk/src/api-http/api-http.service.ts index c7eee4d57..49ead8811 100644 --- a/packages/http-sdk/src/api-http/api-http.service.ts +++ b/packages/http-sdk/src/api-http/api-http.service.ts @@ -7,10 +7,6 @@ export interface ApiOutput { } export class ApiHttpService extends HttpService { - constructor(config?: AxiosRequestConfig) { - super(config); - } - post>, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise { return super.post(url, data, config); } diff --git a/packages/http-sdk/src/auth/auth-http.service.ts b/packages/http-sdk/src/auth/auth-http.service.ts index 60bf64560..15d4c5094 100644 --- a/packages/http-sdk/src/auth/auth-http.service.ts +++ b/packages/http-sdk/src/auth/auth-http.service.ts @@ -1,12 +1,6 @@ -import type { AxiosRequestConfig } from "axios"; - import { HttpService } from "../http/http.service"; export class AuthHttpService extends HttpService { - constructor(config?: Pick) { - super(config); - } - async sendVerificationEmail(userId: string) { return this.post("/v1/send-verification-email", { data: { userId } }); } diff --git a/packages/http-sdk/src/authz/authz-http.service.ts b/packages/http-sdk/src/authz/authz-http.service.ts index ef43d61f2..f2cf9ade9 100644 --- a/packages/http-sdk/src/authz/authz-http.service.ts +++ b/packages/http-sdk/src/authz/authz-http.service.ts @@ -1,4 +1,3 @@ -import type { AxiosRequestConfig } from "axios"; import { isFuture } from "date-fns"; import { HttpService } from "../http/http.service"; @@ -59,10 +58,6 @@ export class AuthzHttpService extends HttpService { private readonly FEE_ALLOWANCE_TYPE: FeeAllowance["allowance"]["@type"] = "/cosmos.feegrant.v1beta1.BasicAllowance"; - constructor(config?: Pick) { - super(config); - } - async getFeeAllowancesForGrantee(address: string) { const allowances = this.extractData(await this.get(`cosmos/feegrant/v1beta1/allowances/${address}`)); return allowances.allowances; diff --git a/packages/http-sdk/src/balance/balance-http.service.ts b/packages/http-sdk/src/balance/balance-http.service.ts index ea965b89d..0332b3825 100644 --- a/packages/http-sdk/src/balance/balance-http.service.ts +++ b/packages/http-sdk/src/balance/balance-http.service.ts @@ -1,5 +1,3 @@ -import type { AxiosRequestConfig } from "axios"; - import { HttpService } from "../http/http.service"; import type { Denom } from "../types/denom.type"; @@ -18,10 +16,6 @@ interface BalanceResponse { } export class BalanceHttpService extends HttpService { - constructor(config?: Pick) { - super(config); - } - async getBalance(address: string, denom: string): Promise { const response = this.extractData(await this.get(`cosmos/bank/v1beta1/balances/${address}/by_denom?denom=${denom}`)); return response.balance ? { amount: parseFloat(response.balance.amount), denom: response.balance.denom } : undefined; diff --git a/packages/http-sdk/src/bid/bid-http.service.ts b/packages/http-sdk/src/bid/bid-http.service.ts index 3d2616d67..f914d3204 100644 --- a/packages/http-sdk/src/bid/bid-http.service.ts +++ b/packages/http-sdk/src/bid/bid-http.service.ts @@ -1,5 +1,3 @@ -import type { AxiosRequestConfig } from "axios"; - import { HttpService } from "../http/http.service"; type Bid = { @@ -51,10 +49,6 @@ type RestAkashBidListResponse = { }; export class BidHttpService extends HttpService { - constructor(config?: Pick) { - super(config); - } - public async list(owner: string, dseq: string): Promise { const response = this.extractData(await this.get(`/akash/market/v1beta4/bids/list?filters.owner=${owner}&filters.dseq=${dseq}`)); diff --git a/packages/http-sdk/src/block/block-http.service.ts b/packages/http-sdk/src/block/block-http.service.ts index bcb29b8ba..a450d4ba2 100644 --- a/packages/http-sdk/src/block/block-http.service.ts +++ b/packages/http-sdk/src/block/block-http.service.ts @@ -1,5 +1,3 @@ -import type { AxiosRequestConfig } from "axios"; - import { HttpService } from "../http/http.service"; interface BlockResponse { @@ -11,10 +9,6 @@ interface BlockResponse { } export class BlockHttpService extends HttpService { - constructor(config?: Pick) { - super(config); - } - async getCurrentHeight() { const response = this.extractData(await this.get("blocks/latest")); diff --git a/packages/http-sdk/src/coin-gecko/coin-gecko-http.service.ts b/packages/http-sdk/src/coin-gecko/coin-gecko-http.service.ts index 9b0b5bb43..94950fdc8 100644 --- a/packages/http-sdk/src/coin-gecko/coin-gecko-http.service.ts +++ b/packages/http-sdk/src/coin-gecko/coin-gecko-http.service.ts @@ -1,4 +1,4 @@ -import type { AxiosError, AxiosInstance, AxiosRequestConfig } from "axios"; +import type { AxiosError, AxiosInstance } from "axios"; import axiosRetry from "axios-retry"; import { HttpService } from "../http/http.service"; @@ -8,10 +8,10 @@ const RETRY_COUNT = 3; const RETRY_DELAY_MILLISECONDS = 100; export class CoinGeckoHttpService extends HttpService { - constructor(config?: Pick) { - super(config); + constructor(axios: AxiosInstance) { + super(axios); - axiosRetry(this as unknown as AxiosInstance, { + axiosRetry(axios, { retries: RETRY_COUNT, retryDelay: retryCount => Math.pow(2, retryCount) * RETRY_DELAY_MILLISECONDS, retryCondition: (error: AxiosError) => axiosRetry.isNetworkError(error) || (error.response?.status !== undefined && error.response.status >= 500) diff --git a/packages/http-sdk/src/cosmos/cosmos-http.service.ts b/packages/http-sdk/src/cosmos/cosmos-http.service.ts index 10f8e09c9..97b38c50b 100644 --- a/packages/http-sdk/src/cosmos/cosmos-http.service.ts +++ b/packages/http-sdk/src/cosmos/cosmos-http.service.ts @@ -1,4 +1,4 @@ -import type { AxiosError, AxiosInstance, AxiosRequestConfig } from "axios"; +import type { AxiosError, AxiosInstance } from "axios"; import axiosRetry from "axios-retry"; import { HttpService } from "../http/http.service"; @@ -24,10 +24,10 @@ const RETRY_COUNT = 3; const RETRY_DELAY_MILLISECONDS = 100; export class CosmosHttpService extends HttpService { - constructor(config?: Pick) { - super(config); + constructor(axios: AxiosInstance) { + super(axios); - axiosRetry(this as unknown as AxiosInstance, { + axiosRetry(axios, { retries: RETRY_COUNT, retryDelay: retryCount => Math.pow(2, retryCount) * RETRY_DELAY_MILLISECONDS, retryCondition: (error: AxiosError) => axiosRetry.isNetworkError(error) || (error.response?.status !== undefined && error.response.status >= 500) diff --git a/packages/http-sdk/src/deployment-setting/deployment-setting-http.service.ts b/packages/http-sdk/src/deployment-setting/deployment-setting-http.service.ts index 4df4fd5ce..7cbae2345 100644 --- a/packages/http-sdk/src/deployment-setting/deployment-setting-http.service.ts +++ b/packages/http-sdk/src/deployment-setting/deployment-setting-http.service.ts @@ -1,5 +1,3 @@ -import type { AxiosRequestConfig } from "axios"; - import { ApiHttpService } from "../api-http/api-http.service"; export interface DeploymentSettingOutput { @@ -29,10 +27,6 @@ export interface FindDeploymentSettingParams { } export class DeploymentSettingHttpService extends ApiHttpService { - constructor(config?: Pick) { - super(config); - } - async findByUserIdAndDseq(params: FindDeploymentSettingParams): Promise { return this.extractApiData(await this.get(`/v1/deployment-settings/${params.userId}/${params.dseq}`)); } diff --git a/packages/http-sdk/src/deployment/deployment-http.service.ts b/packages/http-sdk/src/deployment/deployment-http.service.ts index 63f2fce21..f610810c9 100644 --- a/packages/http-sdk/src/deployment/deployment-http.service.ts +++ b/packages/http-sdk/src/deployment/deployment-http.service.ts @@ -1,4 +1,3 @@ -import type { AxiosRequestConfig } from "axios"; import z from "zod"; import { HttpService } from "../http/http.service"; @@ -132,10 +131,6 @@ interface PaginationParams { } export class DeploymentHttpService extends HttpService { - constructor(config?: Pick) { - super(config); - } - public async findByOwnerAndDseq(owner: string, dseq: string): Promise { return this.extractData( await this.get("/akash/deployment/v1beta3/deployments/info", { @@ -156,7 +151,7 @@ export class DeploymentHttpService extends HttpService { * @returns Paginated response with deployments */ public async loadDeploymentList(owner: string, state?: "active" | "closed", pagination?: PaginationParams): Promise { - const baseUrl = this.getUri({ + const baseUrl = this.axios.getUri({ url: `/akash/deployment/v1beta3/deployments/list?filters.owner=${owner}${state ? `&filters.state=${state}` : ""}` }); const defaultLimit = 1000; diff --git a/packages/http-sdk/src/git-hub/git-hub-http.service.ts b/packages/http-sdk/src/git-hub/git-hub-http.service.ts index b93dbc783..46903a85d 100644 --- a/packages/http-sdk/src/git-hub/git-hub-http.service.ts +++ b/packages/http-sdk/src/git-hub/git-hub-http.service.ts @@ -1,5 +1,3 @@ -import type { AxiosRequestConfig } from "axios"; - import { HttpService } from "../http/http.service"; type ProviderAttributeSchemaDetailValue = { key: string; description: string; value?: string }; @@ -54,10 +52,6 @@ export class GitHubHttpService extends HttpService { private readonly repository = "console"; private readonly branch = "main"; - constructor(config?: Pick) { - super(config); - } - async getProviderAttributesSchema() { return this.extractData(await this.get(this.getFullPath("/config/provider-attributes.json"))); } diff --git a/packages/http-sdk/src/http/http.service.ts b/packages/http-sdk/src/http/http.service.ts index bc6cb40bd..ab3977bad 100644 --- a/packages/http-sdk/src/http/http.service.ts +++ b/packages/http-sdk/src/http/http.service.ts @@ -1,15 +1,33 @@ -import axios, { Axios, type AxiosRequestConfig, type AxiosResponse } from "axios"; +import { type AxiosInstance, type AxiosResponse } from "axios"; -export class HttpService extends Axios { - constructor(config?: AxiosRequestConfig) { - const { headers, ...defaults } = axios.defaults; - super({ - ...defaults, - ...config - }); - } +export class HttpService { + constructor(private readonly _axios: AxiosInstance) {} protected extractData(response: AxiosResponse): AxiosResponse["data"] { return response.data; } + + get>(...args: Parameters): Promise { + return this.axios.get(...args); + } + + post>(...args: Parameters): Promise { + return this.axios.post(...args); + } + + patch>(...args: Parameters): Promise { + return this.axios.patch(...args); + } + + put>(...args: Parameters): Promise { + return this.axios.put(...args); + } + + delete>(...args: Parameters): Promise { + return this.axios.delete(...args); + } + + get axios() { + return this._axios; + } } diff --git a/packages/http-sdk/src/lease/lease-http.service.ts b/packages/http-sdk/src/lease/lease-http.service.ts index 790a90dcd..76764fed1 100644 --- a/packages/http-sdk/src/lease/lease-http.service.ts +++ b/packages/http-sdk/src/lease/lease-http.service.ts @@ -1,5 +1,3 @@ -import type { AxiosRequestConfig } from "axios"; - import { HttpService } from "../http/http.service"; export type RestAkashLeaseListResponse = { @@ -55,10 +53,6 @@ type LeaseListParams = { }; export class LeaseHttpService extends HttpService { - constructor(config?: Pick) { - super(config); - } - public async list({ owner, dseq, state }: LeaseListParams): Promise { return this.extractData( await this.get("/akash/market/v1beta4/leases/list", { diff --git a/packages/http-sdk/src/node/node-http.service.ts b/packages/http-sdk/src/node/node-http.service.ts index afcb2fa82..7d08a6e0f 100644 --- a/packages/http-sdk/src/node/node-http.service.ts +++ b/packages/http-sdk/src/node/node-http.service.ts @@ -1,4 +1,4 @@ -import type { AxiosError, AxiosInstance, AxiosRequestConfig } from "axios"; +import type { AxiosError, AxiosInstance } from "axios"; import axiosRetry from "axios-retry"; import { HttpService } from "../http/http.service"; @@ -8,10 +8,10 @@ const RETRY_COUNT = 3; const RETRY_DELAY_MILLISECONDS = 100; export class NodeHttpService extends HttpService { - constructor(config?: Pick) { - super(config); + constructor(axios: AxiosInstance) { + super(axios); - axiosRetry(this as unknown as AxiosInstance, { + axiosRetry(axios, { retries: RETRY_COUNT, retryDelay: retryCount => Math.pow(2, retryCount) * RETRY_DELAY_MILLISECONDS, retryCondition: (error: AxiosError) => axiosRetry.isNetworkError(error) || (error.response?.status !== undefined && error.response.status >= 500) diff --git a/packages/http-sdk/src/provider/provider-http.service.ts b/packages/http-sdk/src/provider/provider-http.service.ts index 17eb57cac..f4033f454 100644 --- a/packages/http-sdk/src/provider/provider-http.service.ts +++ b/packages/http-sdk/src/provider/provider-http.service.ts @@ -1,13 +1,7 @@ -import type { AxiosRequestConfig } from "axios"; - import { HttpService } from "../http/http.service"; import type { GetProviderResponse } from "./types"; export class ProviderHttpService extends HttpService { - constructor(config?: Pick) { - super(config); - } - async getProvider(address: string): Promise { return this.extractData(await this.get(`/akash/provider/v1beta3/providers/${address}`)); } diff --git a/packages/http-sdk/src/stripe/stripe.service.ts b/packages/http-sdk/src/stripe/stripe.service.ts index f40e60d99..4ed83617a 100644 --- a/packages/http-sdk/src/stripe/stripe.service.ts +++ b/packages/http-sdk/src/stripe/stripe.service.ts @@ -13,10 +13,6 @@ import type { } from "./stripe.types"; export class StripeService extends ApiHttpService { - constructor(config?: AxiosRequestConfig) { - super(config); - } - // Payment Methods async createSetupIntent(config?: AxiosRequestConfig): Promise { return this.extractApiData(await this.post("/v1/stripe/payment-methods/setup", {}, config)); diff --git a/packages/http-sdk/src/template/template-http.service.ts b/packages/http-sdk/src/template/template-http.service.ts index de12eb652..7cbfa4262 100644 --- a/packages/http-sdk/src/template/template-http.service.ts +++ b/packages/http-sdk/src/template/template-http.service.ts @@ -1,5 +1,3 @@ -import type { AxiosRequestConfig } from "axios"; - import type { ApiOutput } from "../api-http/api-http.service"; import { ApiHttpService } from "../api-http/api-http.service"; @@ -33,10 +31,6 @@ export interface TemplateCategory { } export class TemplateHttpService extends ApiHttpService { - constructor(config?: Pick) { - super(config); - } - async findById(id: string): Promise { return this.extractApiData(await this.get(`/v1/templates/${id}`)); } diff --git a/packages/http-sdk/src/tx-http/tx-http.service.ts b/packages/http-sdk/src/tx-http/tx-http.service.ts index 698f04580..915a80298 100644 --- a/packages/http-sdk/src/tx-http/tx-http.service.ts +++ b/packages/http-sdk/src/tx-http/tx-http.service.ts @@ -1,7 +1,7 @@ import type { Registry } from "@cosmjs/proto-signing"; import type { EncodeObject } from "@cosmjs/proto-signing/build/registry"; import type { DeliverTxResponse } from "@cosmjs/stargate"; -import type { AxiosRequestConfig } from "axios"; +import type { AxiosInstance } from "axios"; import { ApiHttpService } from "../api-http/api-http.service"; @@ -14,10 +14,10 @@ export type TxOutput = Pick ({ ...m, value: Buffer.from(this.registry.encode(m)).toString("base64") })); diff --git a/packages/http-sdk/src/usage/usage-http.service.ts b/packages/http-sdk/src/usage/usage-http.service.ts index 69fd56388..646aa2dbe 100644 --- a/packages/http-sdk/src/usage/usage-http.service.ts +++ b/packages/http-sdk/src/usage/usage-http.service.ts @@ -1,4 +1,3 @@ -import type { AxiosRequestConfig } from "axios"; import { format } from "date-fns"; import { HttpService } from "../http/http.service"; @@ -11,10 +10,6 @@ type UsageParams = { }; export class UsageHttpService extends HttpService { - constructor(config?: AxiosRequestConfig) { - super(config); - } - async getUsage(params: UsageParams): Promise { return this.extractData( await this.get("/v1/usage/history", { diff --git a/packages/http-sdk/src/user-http/user-http.service.ts b/packages/http-sdk/src/user-http/user-http.service.ts index fa0cee52e..0ae41f2a9 100644 --- a/packages/http-sdk/src/user-http/user-http.service.ts +++ b/packages/http-sdk/src/user-http/user-http.service.ts @@ -1,4 +1,4 @@ -import type { AxiosRequestConfig } from "axios"; +import type { AxiosInstance } from "axios"; import memoize from "lodash/memoize"; import type { ApiOutput } from "../api-http/api-http.service"; @@ -25,8 +25,9 @@ export type UserCreateResponse = { }; export class UserHttpService extends HttpService { - constructor(config?: AxiosRequestConfig) { - super(config); + constructor(axios: AxiosInstance) { + super(axios); + this.getOrCreateAnonymousUser = memoize(this.getOrCreateAnonymousUser.bind(this)); }