Skip to content

Commit

Permalink
chore: split api into separate parts to not override endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
ice-chillios committed Feb 18, 2025
1 parent 929e681 commit 768b206
Show file tree
Hide file tree
Showing 12 changed files with 46 additions and 74 deletions.
7 changes: 7 additions & 0 deletions docs/MIGRATE_CORE_v4.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,17 @@ $ bun install @swapkit/helpers

#### @swapkit/api => @swapkit/helpers/api

Methods were scoped under `SwapKitApi` object and split into related api endpoints.

- `computeHashForGet` -> use `computeHash` directly
- `computeHashForPost` -> use `computeHash` directly
- `getSwapQuoteV2` -> use `getSwapQuote` directly
- `getTokenListV2` -> use `getTokenList` directly
- for thornode requests use `SwapKitApi.thornode`
- for mayachain midgard requests use `SwapKitApi.mayachainMidgard`
- for thorchain midgard requests use `SwapKitApi.thorchainMidgard`
- for microgard requests use `SwapKitApi.microgard`


#### @swapkit/core

Expand Down
2 changes: 1 addition & 1 deletion lefthook.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ pre-commit:
commands:
lint:
glob: "*.{jsx,tsx,ts,js,json}"
run: biome check --write {staged_files} && git add {staged_files}
run: bun biome check --write {staged_files} && git add {staged_files}
type-check:
glob: "*.{ts,tsx}"
run: bun type-check
21 changes: 0 additions & 21 deletions packages/core/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,27 +393,6 @@ export function SwapKit<Plugins extends PluginsType, Wallets extends WalletsType
}
}

// TODO: REMOVE THAT:
// const swapkitConfig = config.swapkitConfig || {};
// const swapkitApiKey = swapkitConfig?.swapkitApiKey || config?.swapkitApiKey;
// const referer = swapkitConfig.useHashedApiKey ? swapkitConfig.referer : undefined;

// const api = swapkitApiKey
// ? {
// getGasRate: () => SwapKitApi.getGasRate(isDev, swapkitApiKey, referer),
// getPrice: (body: PriceRequest) => SwapKitApi.getPrice(body, isDev, swapkitApiKey, referer),
// getSwapQuote: (params: QuoteRequest) =>
// SwapKitApi.getSwapQuote(params, isDev, swapkitApiKey, referer),
// getTokenList: (provider: string) => SwapKitApi.getTokenList(provider),
// getTokenListProviders: () =>
// SwapKitApi.getTokenListProvidersV2(isDev, swapkitApiKey, referer),
// getTokenTradingPairs: (providers: PluginNameEnum[]) =>
// SwapKitApi.getTokenTradingPairs(providers, isDev, swapkitApiKey, referer),
// getTrackerDetails: (payload: TrackerParams) =>
// SwapKitApi.getTrackerDetails(payload, swapkitApiKey, referer),
// }
// : { undefined };

return {
...availablePlugins,
...connectWalletMethods,
Expand Down
37 changes: 17 additions & 20 deletions packages/helpers/fetchTokenLists.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,6 @@
import { Chain, ChainId, ProviderName } from "@swapkit/helpers";
import { Chain, ChainId, ProviderName } from "./src";
import { SwapKitApi } from "./src/api";

function parseChain(chain: string) {
if (chain === "ARBITRUM") return Chain.Arbitrum;
return chain;
}

function parseIdentifier(identifier: string) {
if (identifier.startsWith("ARBITRUM.")) {
return identifier.replace("ARBITRUM.", `${Chain.Arbitrum}.`);
}
return identifier;
}

const providers = (await SwapKitApi.getTokenListProviders()).filter(
(provider) =>
![
Expand All @@ -23,11 +11,9 @@ const providers = (await SwapKitApi.getTokenListProviders()).filter(
].includes(provider.provider),
);

console.info(providers);

console.info(
`🚀 Fetching token lists from ${providers.length} providers:\n${providers
.map(({ provider }) => provider)
.map(({ provider, count }) => ` ${provider}: ${count} tokens`)
.join("\n-")}`,
);

Expand All @@ -48,8 +34,7 @@ for (const { provider } of providers) {
chainId: token.chainId === "thorchain-mainnet-v1" ? thorchainChainId : token.chainId,
decimals: token.decimals,
identifier: parseIdentifier(token.identifier),
logoURI: token.logoURL,
// @ts-expect-error ?
logoURI: token.logoURI,
shortCode: token.shortCode,
ticker: token.ticker,
}))
Expand All @@ -61,7 +46,19 @@ for (const { provider } of providers) {
`src/tokens/lists/${provider.toLowerCase()}.ts`,
`export const list = ${JSON.stringify(tokenListWithTokens, null, 2)} as const;`,
);
} catch (_error) {
console.error(provider);
} catch (error) {
console.error(provider, error);
}
}

function parseChain(chain: string) {
if (chain === "ARBITRUM") return Chain.Arbitrum;
return chain;
}

function parseIdentifier(identifier: string) {
if (identifier.startsWith("ARBITRUM.")) {
return identifier.replace("ARBITRUM.", `${Chain.Arbitrum}.`);
}
return identifier;
}
1 change: 1 addition & 0 deletions packages/helpers/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"build": "bun run ./build.ts",
"clean": "rm -rf dist node_modules *.tsbuildinfo",
"lint": "biome check --diagnostic-level=error --write ./src",
"generate-tokens": "bun --bun ./fetchTokenLists.ts",
"test": "bun test",
"test:coverage": "bun test --coverage",
"type-check": "tsc --noEmit"
Expand Down
27 changes: 9 additions & 18 deletions packages/helpers/src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,19 @@
import * as microgardEndpoints from "./microgard/endpoints";
import * as microgard from "./microgard/endpoints";
import { mayachainMidgard, thorchainMidgard } from "./midgard/endpoints";
import * as swapkitApiEndpoints from "./swapkitApi/endpoints";
import * as thornodeEndpoints from "./thornode/endpoints";
import * as thorswapStaticEndpoints from "./thorswapStatic/endpoints";
import * as swapkit from "./swapkitApi/endpoints";
import * as thornode from "./thornode/endpoints";
import * as tsStatic from "./thorswapStatic/endpoints";

export * from "./microgard/types";
export * from "./thorswapStatic/types";
export * from "./thornode/types";
export * from "./swapkitApi/types";

export {
mayachainMidgard,
microgardEndpoints,
swapkitApiEndpoints,
thorchainMidgard,
thornodeEndpoints,
thorswapStaticEndpoints,
};

export const SwapKitApi = {
...microgardEndpoints,
...thornodeEndpoints,
...swapkitApiEndpoints,
...thorswapStaticEndpoints,
thorchainMidgard,
...swapkit,
...tsStatic,
mayachainMidgard,
microgard,
thorchainMidgard,
thornode,
};
2 changes: 1 addition & 1 deletion packages/helpers/src/api/thorswapStatic/endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { TokensResponse } from "./types";

const baseUrl = "https://static.thorswap.net";

export function getTokenList(tokenListName: string) {
export function getStaticTokenList(tokenListName: string) {
return RequestClient.get<TokensResponse>(`${baseUrl}/token-list/${tokenListName}.json`);
}

Expand Down
9 changes: 3 additions & 6 deletions packages/helpers/src/modules/requestClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ type Options = Parameters<typeof fetch>[1] & {
json?: unknown;
};

const clientConfig: Options = {};

export const defaultRequestHeaders =
typeof window !== "undefined"
? ({} as Record<string, string>)
Expand All @@ -22,13 +20,13 @@ async function fetchWithConfig(
) {
const { searchParams, json, body } = options;
const urlInstance = new URL(url);
const bodyToSend = json ? JSON.stringify(json) : body;
const isJson = json || url.endsWith(".json");
const bodyToSend = isJson ? JSON.stringify(json) : body;

const headers = {
...defaultRequestHeaders,
...clientConfig.headers,
...options.headers,
...(json ? { "Content-Type": "application/json" } : {}),
...(isJson ? { "Content-Type": "application/json" } : {}),
} as Record<string, string>;

if (searchParams) {
Expand All @@ -40,7 +38,6 @@ async function fetchWithConfig(

try {
const response = await fetch(urlInstance.toString(), {
...clientConfig,
...options,
method,
body: bodyToSend,
Expand Down
4 changes: 2 additions & 2 deletions packages/helpers/src/tokens/lists/camelot_v3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ export const list = {
provider: "CAMELOT_V3",
chainId: "42161",
name: "Camelot V3",
timestamp: "1737552726554",
count: 1591,
timestamp: "1739867485937",
count: 1596,
tokens: [
{
address: "0xda39A32c9c5Bb2C9E99d4e2a24bc55A418599F90",
Expand Down
4 changes: 2 additions & 2 deletions packages/plugins/src/chainflip/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
type SwapKitPluginParams,
type UTXOWallets,
} from "@swapkit/helpers";
import { swapkitApiEndpoints } from "@swapkit/helpers/api";
import { SwapKitApi } from "@swapkit/helpers/api";
import type { RequestSwapDepositAddressParams } from "./types";

type SupportedChain = keyof (EVMWallets & SubstrateWallets & UTXOWallets & SolanaWallets);
Expand Down Expand Up @@ -52,7 +52,7 @@ function plugin({ getWallet }: SwapKitPluginParams) {
throw new SwapKitError("core_wallet_connection_not_found");
}

const { depositAddress } = await swapkitApiEndpoints.getChainflipDepositChannel({
const { depositAddress } = await SwapKitApi.getChainflipDepositChannel({
...chainflip,
destinationAddress: recipient || chainflip.destinationAddress,
maxBoostFeeBps: maxBoostFeeBps || chainflip.maxBoostFeeBps,
Expand Down
4 changes: 2 additions & 2 deletions packages/plugins/src/thorchain/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ function getInboundDataFunction(type?: THORNodeType) {
return { gas_rate: "0", router: "", address: "", halted: false, chain };
}

const inboundData = await SwapKitApi.getInboundAddresses(type);
const inboundData = await SwapKitApi.thornode.getInboundAddresses(type);
const chainAddressData = inboundData.find((item) => item.chain === chain);

if (!chainAddressData) throw new SwapKitError("core_inbound_data_not_found");
Expand Down Expand Up @@ -202,7 +202,7 @@ function createTCBasedPlugin<T extends PluginChain>({
}

async function depositToProtocol({ memo, assetValue }: { assetValue: AssetValue; memo: string }) {
const mimir = await SwapKitApi.getMimirInfo(pluginType);
const mimir = await SwapKitApi.thornode.getMimirInfo(pluginType);

// check if trading is halted or not
if (mimir.HALTCHAINGLOBAL >= 1 || mimir.HALTTHORCHAIN >= 1) {
Expand Down
2 changes: 1 addition & 1 deletion playgrounds/vite/src/TNS/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default function TNS({ skClient }: { skClient: SwapKitClient }) {
const [tnsDetail, setTnsDetail] = useState<THORNameDetails>();

const checkTns = useCallback(async () => {
const tnsDetail = await SwapKitApi.getTHORNameDetails(tnsSearch);
const tnsDetail = await SwapKitApi.microgard.getTHORNameDetails(tnsSearch);
setTnsDetail(tnsDetail);
}, [tnsSearch]);

Expand Down

0 comments on commit 768b206

Please sign in to comment.