Skip to content

[SDK] Optimize payment token fetching in payment widgets #7536

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/happy-pans-sneeze.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"thirdweb": patch
---

Optimize fetching payment tokens in payment widgets
37 changes: 23 additions & 14 deletions packages/thirdweb/src/bridge/Chains.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ThirdwebClient } from "../client/client.js";
import { getThirdwebBaseUrl } from "../utils/domains.js";
import { getClientFetch } from "../utils/fetch.js";
import { withCache } from "../utils/promise/withCache.js";
import type { Chain } from "./types/Chain.js";
import { ApiError } from "./types/Errors.js";

Expand Down Expand Up @@ -54,22 +55,30 @@ import { ApiError } from "./types/Errors.js";
export async function chains(options: chains.Options): Promise<chains.Result> {
const { client } = options;

const clientFetch = getClientFetch(client);
const url = new URL(`${getThirdwebBaseUrl("bridge")}/v1/chains`);
return withCache(
async () => {
const clientFetch = getClientFetch(client);
const url = new URL(`${getThirdwebBaseUrl("bridge")}/v1/chains`);

const response = await clientFetch(url.toString());
if (!response.ok) {
const errorJson = await response.json();
throw new ApiError({
code: errorJson.code || "UNKNOWN_ERROR",
correlationId: errorJson.correlationId || undefined,
message: errorJson.message || response.statusText,
statusCode: response.status,
});
}
const response = await clientFetch(url.toString());
if (!response.ok) {
const errorJson = await response.json();
throw new ApiError({
code: errorJson.code || "UNKNOWN_ERROR",
correlationId: errorJson.correlationId || undefined,
message: errorJson.message || response.statusText,
statusCode: response.status,
});
}

const { data }: { data: Chain[] } = await response.json();
return data;
const { data }: { data: Chain[] } = await response.json();
return data;
},
{
cacheKey: "bridge-chains",
cacheTime: 1000 * 60 * 60 * 1, // 1 hours
},
);
}

export declare namespace chains {
Expand Down
8 changes: 0 additions & 8 deletions packages/thirdweb/src/chains/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,6 @@ export type ChainMetadata = {
stackType: string;
};

/**
* @chain
*/
export type ChainService = {
service: string;
enabled: boolean;
};

/**
* @chain
*/
Expand Down
61 changes: 10 additions & 51 deletions packages/thirdweb/src/chains/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import type {
Chain,
ChainMetadata,
ChainOptions,
ChainService,
LegacyChain,
} from "./types.js";

Expand Down Expand Up @@ -323,62 +322,22 @@ export function getChainMetadata(chain: Chain): Promise<ChainMetadata> {
);
}

type FetchChainServiceResponse =
| {
data: {
services: ChainService[];
};
error?: never;
}
| {
data?: never;
error: unknown;
};

/**
* Retrieves a list of services available on a given chain
* @param chain - The chain object containing the chain ID.
* @returns A Promise that resolves to chain services.
* @throws If there is an error fetching the chain services.
* @example
* ```ts
* const chain = defineChain({ id: 1 });
* const chainServices = await getChainServices(chain);
* console.log(chainServices);
* ```
* @chain
*/
export function getChainServices(chain: Chain): Promise<ChainService[]> {
const chainId = chain.id;
export async function getInsightEnabledChainIds(): Promise<number[]> {
return withCache(
async () => {
try {
const res = await fetch(
`https://api.thirdweb.com/v1/chains/${chainId}/services`,
const res = await fetch(
`https://api.thirdweb.com/v1/chains/services?service=insight`,
);
if (!res.ok) {
throw new Error(
`Failed to fetch services. ${res.status} ${res.statusText}`,
);
if (!res.ok) {
throw new Error(
`Failed to fetch services for chainId ${chainId}. ${res.status} ${res.statusText}`,
);
}

const response = (await res.json()) as FetchChainServiceResponse;
if (response.error) {
throw new Error(`Failed to fetch services for chainId ${chainId}`);
}
if (!response.data) {
throw new Error(`Failed to fetch services for chainId ${chainId}`);
}

const services = response.data.services;

return services;
} catch {
throw new Error(`Failed to fetch services for chainId ${chainId}`);
}
const response = (await res.json()) as { data: Record<number, boolean> };
return Object.keys(response.data).map((chainId) => Number(chainId));
},
{
cacheKey: `chain:${chainId}:services`,
cacheKey: `chain:insight-enabled`,
cacheTime: 24 * 60 * 60 * 1000, // 1 day
},
);
Expand Down
24 changes: 8 additions & 16 deletions packages/thirdweb/src/insight/common.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,21 @@
import type { Chain } from "../chains/types.js";
import { getChainServices } from "../chains/utils.js";
import { getInsightEnabledChainIds } from "../chains/utils.js";

export async function assertInsightEnabled(chains: Chain[]) {
const chainData = await Promise.all(
chains.map((chain) =>
isInsightEnabled(chain).then((enabled) => ({
chain,
enabled,
})),
),
);

const insightEnabled = chainData.every((c) => c.enabled);
const chainIds = await getInsightEnabledChainIds();
const insightEnabled = chains.every((c) => chainIds.includes(c.id));

if (!insightEnabled) {
throw new Error(
`Insight is not available for chains ${chainData
.filter((c) => !c.enabled)
.map((c) => c.chain.id)
`Insight is not available for chains ${chains
.filter((c) => !chainIds.includes(c.id))
.map((c) => c.id)
.join(", ")}`,
);
}
}

export async function isInsightEnabled(chain: Chain) {
const chainData = await getChainServices(chain);
return chainData.some((c) => c.service === "insight" && c.enabled);
const chainIds = await getInsightEnabledChainIds();
return chainIds.includes(chain.id);
}
Loading
Loading