Skip to content

Commit c9a0e5e

Browse files
authored
chore: consolidate chain queries, 4xx if not found (#673)
* chore: consolidate chain queries, 4xx if not found * fix formatter * fix lint * update getters * type the override getters * clean up error message * use StatusCodes helper
1 parent a8dc428 commit c9a0e5e

File tree

56 files changed

+169
-295
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+169
-295
lines changed

src/db/configuration/updateConfiguration.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Prisma } from "@prisma/client";
1+
import type { Prisma } from "@prisma/client";
22
import { encrypt } from "../../utils/crypto";
33
import { prisma } from "../client";
44

src/server/middleware/error.ts

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { FastifyInstance } from "fastify";
1+
import type { FastifyInstance } from "fastify";
22
import { ReasonPhrases, StatusCodes } from "http-status-codes";
33
import { ZodError } from "zod";
44
import { env } from "../../utils/env";
@@ -22,21 +22,27 @@ export const createCustomError = (
2222
code,
2323
});
2424

25-
export const createCustomDateTimestampError = (key: string): CustomError => {
25+
export const customDateTimestampError = (date: string): CustomError => {
2626
return createCustomError(
27-
`Invalid ${key} Value. Needs to new Date() / new Date().toISOstring() / new Date().getTime() / Unix Epoch`,
28-
404,
27+
`Invalid date: ${date}. Needs to new Date() / new Date().toISOstring() / new Date().getTime() / Unix Epoch`,
28+
StatusCodes.BAD_REQUEST,
2929
"INVALID_DATE_TIME",
3030
);
3131
};
3232

33-
export const createBadAddressError = (key: string): CustomError => {
34-
return createCustomError(
35-
`Invalid ${key} Value. Needs to be a valid EVM address`,
36-
422,
33+
export const badAddressError = (address: string): CustomError =>
34+
createCustomError(
35+
`Invalid address: ${address}. Needs to be a valid EVM address`,
36+
StatusCodes.BAD_REQUEST,
3737
"INVALID_ADDRESS",
3838
);
39-
};
39+
40+
export const badChainError = (chain: string | number): CustomError =>
41+
createCustomError(
42+
`Invalid chain: ${chain}. If this is a custom chain, add it to chain overrides.`,
43+
StatusCodes.BAD_REQUEST,
44+
"INVALID_CHAIN",
45+
);
4046

4147
const flipObject = (data: any) =>
4248
Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));

src/server/routes/auth/access-tokens/create.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ export async function createAccessToken(fastify: FastifyInstance) {
9191

9292
accessTokenCache.clear();
9393

94-
res.status(200).send({
94+
res.status(StatusCodes.OK).send({
9595
result: {
9696
...token,
9797
createdAt: token.createdAt.toISOString(),

src/server/routes/auth/access-tokens/getAll.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ export async function getAllAccessTokens(fastify: FastifyInstance) {
3636
},
3737
handler: async (req, res) => {
3838
const accessTokens = await getAccessTokens();
39-
res.status(200).send({
39+
res.status(StatusCodes.OK).send({
4040
result: accessTokens.map((token) => ({
4141
...token,
4242
createdAt: token.createdAt.toISOString(),

src/server/routes/auth/access-tokens/revoke.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ export async function revokeAccessToken(fastify: FastifyInstance) {
3838

3939
accessTokenCache.clear();
4040

41-
res.status(200).send({
41+
res.status(StatusCodes.OK).send({
4242
result: {
4343
success: true,
4444
},

src/server/routes/auth/access-tokens/update.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ export async function updateAccessToken(fastify: FastifyInstance) {
4040

4141
accessTokenCache.clear();
4242

43-
res.status(200).send({
43+
res.status(StatusCodes.OK).send({
4444
result: {
4545
success: true,
4646
},

src/server/routes/auth/keypair/add.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ export async function addKeypair(fastify: FastifyInstance) {
7777
throw e;
7878
}
7979

80-
res.status(200).send({
80+
res.status(StatusCodes.OK).send({
8181
result: {
8282
keypair: toKeypairSchema(keypair),
8383
},

src/server/routes/auth/keypair/list.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ export async function listPublicKeys(fastify: FastifyInstance) {
2828
handler: async (req, res) => {
2929
const keypairs = await listKeypairs();
3030

31-
res.status(200).send({
31+
res.status(StatusCodes.OK).send({
3232
result: keypairs.map(toKeypairSchema),
3333
});
3434
},

src/server/routes/auth/keypair/remove.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ export async function removePublicKey(fastify: FastifyInstance) {
3939
await deleteKeypair({ hash });
4040
keypairCache.clear();
4141

42-
res.status(200).send({
42+
res.status(StatusCodes.OK).send({
4343
result: { success: true },
4444
});
4545
},

src/server/routes/auth/permissions/getAll.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export async function getAllPermissions(fastify: FastifyInstance) {
3333
},
3434
handler: async (req, res) => {
3535
const permissions = await prisma.permissions.findMany();
36-
res.status(200).send({
36+
res.status(StatusCodes.OK).send({
3737
result: permissions,
3838
});
3939
},

src/server/routes/auth/permissions/grant.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ export async function grantPermissions(fastify: FastifyInstance) {
4343
permissions,
4444
label,
4545
});
46-
res.status(200).send({
46+
res.status(StatusCodes.OK).send({
4747
result: {
4848
success: true,
4949
},

src/server/routes/auth/permissions/revoke.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ export async function revokePermissions(fastify: FastifyInstance) {
3838
await deletePermissions({
3939
walletAddress,
4040
});
41-
res.status(200).send({
41+
res.status(StatusCodes.OK).send({
4242
result: {
4343
success: true,
4444
},

src/server/routes/backend-wallet/signMessage.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ export async function signMessage(fastify: FastifyInstance) {
5555
signedMessage = await signer.signMessage(message);
5656
}
5757

58-
reply.status(200).send({
58+
reply.status(StatusCodes.OK).send({
5959
result: signedMessage,
6060
});
6161
},

src/server/routes/backend-wallet/signTransaction.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ export async function signTransaction(fastify: FastifyInstance) {
6060
const signer = await wallet.getSigner();
6161
const signedMessage = await signer.signTransaction(transaction);
6262

63-
reply.status(200).send({
63+
reply.status(StatusCodes.OK).send({
6464
result: signedMessage,
6565
});
6666
},

src/server/routes/backend-wallet/signTypedData.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ export async function signTypedData(fastify: FastifyInstance) {
4545
const signer = (await wallet.getSigner()) as unknown as TypedDataSigner;
4646
const result = await signer._signTypedData(domain, types, value);
4747

48-
reply.status(200).send({
48+
reply.status(StatusCodes.OK).send({
4949
result: result,
5050
});
5151
},

src/server/routes/chain/get.ts

Lines changed: 11 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,14 @@
1-
import { Static, Type } from "@sinclair/typebox";
2-
import {
3-
Chain,
4-
getChainByChainIdAsync,
5-
getChainBySlugAsync,
6-
minimizeChain,
7-
} from "@thirdweb-dev/chains";
8-
import { FastifyInstance } from "fastify";
1+
import { Type, type Static } from "@sinclair/typebox";
2+
import type { FastifyInstance } from "fastify";
93
import { StatusCodes } from "http-status-codes";
10-
import { getConfig } from "../../../utils/cache/getConfig";
11-
import { createCustomError } from "../../middleware/error";
4+
import { getChainMetadata } from "thirdweb/chains";
5+
import { getChain } from "../../../utils/chain";
126
import {
137
chainRequestQuerystringSchema,
148
chainResponseSchema,
159
} from "../../schemas/chain";
1610
import { standardResponseSchema } from "../../schemas/sharedApiSchemas";
11+
import { getChainIdFromChain } from "../../utils/chain";
1712

1813
// OUTPUT
1914
const responseSchema = Type.Object({
@@ -31,7 +26,7 @@ responseSchema.examples = [
3126
symbol: "MATIC",
3227
decimals: 18,
3328
},
34-
shortName: "polygonamoy",
29+
shortName: "amoy",
3530
chainId: 80002,
3631
testnet: true,
3732
slug: "polygon-amoy-testnet",
@@ -60,37 +55,15 @@ export async function getChainData(fastify: FastifyInstance) {
6055
},
6156
handler: async (request, reply) => {
6257
const { chain } = request.query;
63-
const config = await getConfig();
64-
65-
let chainData: Chain | null = null;
66-
if (config.chainOverrides) {
67-
chainData = JSON.parse(config.chainOverrides).find(
68-
(dt: Chain) => dt.slug === chain || dt.chainId === parseInt(chain),
69-
);
70-
}
71-
72-
if (!chainData) {
73-
chainData = await getChainBySlugAsync(chain);
74-
if (!chainData) {
75-
chainData = await getChainByChainIdAsync(parseInt(chain));
76-
}
77-
}
78-
79-
if (!chainData) {
80-
const error = createCustomError(
81-
"Chain not found",
82-
StatusCodes.NOT_FOUND,
83-
"ChainNotFound",
84-
);
85-
throw error;
86-
}
8758

88-
const minimizeChainData = minimizeChain(chainData);
59+
const chainId = await getChainIdFromChain(chain);
60+
const chainV5 = await getChain(chainId);
61+
const chainMetadata = await getChainMetadata(chainV5);
8962

9063
reply.status(StatusCodes.OK).send({
9164
result: {
92-
...minimizeChainData,
93-
rpc: [chainData.rpc.length === 0 ? "" : minimizeChainData.rpc[0]],
65+
...chainMetadata,
66+
rpc: [...chainMetadata.rpc],
9467
},
9568
});
9669
},

src/server/routes/chain/getAll.ts

Lines changed: 22 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { Static, Type } from "@sinclair/typebox";
2-
import { Chain, fetchChains, minimizeChain } from "@thirdweb-dev/chains";
3-
import { FastifyInstance } from "fastify";
1+
import { Type, type Static } from "@sinclair/typebox";
2+
import { fetchChains } from "@thirdweb-dev/chains";
3+
import type { FastifyInstance } from "fastify";
44
import { StatusCodes } from "http-status-codes";
55
import { getConfig } from "../../../utils/cache/getConfig";
66
import { chainResponseSchema } from "../../schemas/chain";
@@ -64,37 +64,31 @@ export async function getAllChainData(fastify: FastifyInstance) {
6464
},
6565
},
6666
handler: async (request, reply) => {
67-
const allChainsData = await fetchChains();
67+
const allChains = (await fetchChains()) ?? [];
6868
const config = await getConfig();
6969

70-
let chain = (allChainsData ?? ([] as Chain[])).map((chain) => {
71-
const minimizeChainData = minimizeChain(chain);
72-
if (chain.rpc.length === 0) {
73-
return { ...minimizeChainData, rpc: [""] };
74-
}
75-
return { ...minimizeChainData, rpc: [minimizeChainData.rpc[0]] };
76-
});
77-
78-
let chainOverrides: typeof chain = [];
79-
80-
if (config.chainOverrides) {
81-
chainOverrides = (JSON.parse(config.chainOverrides) as Chain[]).map(
82-
(overrideChain) => {
83-
const shortName = overrideChain.shortName
84-
? overrideChain.shortName
85-
: "";
86-
const rpc =
87-
overrideChain.rpc.length === 0 ? [""] : [overrideChain.rpc[0]];
88-
return { ...overrideChain, shortName, rpc };
70+
for (const chain of config.chainOverridesParsed) {
71+
allChains.push({
72+
chainId: chain.id,
73+
name: chain.name ?? "",
74+
rpc: [...chain.rpc],
75+
nativeCurrency: {
76+
name: chain.nativeCurrency?.name ?? "Ether",
77+
symbol: chain.nativeCurrency?.symbol ?? "ETH",
78+
decimals: chain.nativeCurrency?.decimals ?? 18,
8979
},
90-
);
80+
testnet: chain.testnet ?? false,
81+
chain: "",
82+
shortName: "",
83+
slug: "",
84+
});
9185
}
9286

93-
// Concatenate chain and chainOverrides
94-
chain = chain.concat(chainOverrides);
95-
9687
reply.status(StatusCodes.OK).send({
97-
result: chain,
88+
result: allChains.map((chain) => ({
89+
...chain,
90+
rpc: [...chain.rpc],
91+
})),
9892
});
9993
},
10094
});

src/server/routes/configuration/auth/get.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ export async function getAuthConfiguration(fastify: FastifyInstance) {
2828
},
2929
handler: async (req, res) => {
3030
const config = await getConfig();
31-
res.status(200).send({
31+
res.status(StatusCodes.OK).send({
3232
result: {
3333
domain: config.authDomain,
3434
},

src/server/routes/configuration/auth/update.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ export async function updateAuthConfiguration(fastify: FastifyInstance) {
3535

3636
const config = await getConfig(false);
3737

38-
res.status(200).send({
38+
res.status(StatusCodes.OK).send({
3939
result: {
4040
domain: config.authDomain,
4141
},

src/server/routes/configuration/backend-wallet-balance/get.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ export async function getBackendWalletBalanceConfiguration(
3232
},
3333
handler: async (req, res) => {
3434
const config = await getConfig();
35-
res.status(200).send({
35+
res.status(StatusCodes.OK).send({
3636
result: {
3737
minWalletBalance: config.minWalletBalance,
3838
},

src/server/routes/configuration/backend-wallet-balance/update.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ export async function updateBackendWalletBalanceConfiguration(
3737
await updateConfiguration({ ...req.body });
3838
const config = await getConfig(false);
3939

40-
res.status(200).send({
40+
res.status(StatusCodes.OK).send({
4141
result: {
4242
minWalletBalance: config.minWalletBalance,
4343
},

src/server/routes/configuration/cache/get.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ export async function getCacheConfiguration(fastify: FastifyInstance) {
2828
},
2929
handler: async (req, res) => {
3030
const config = await getConfig();
31-
res.status(200).send({
31+
res.status(StatusCodes.OK).send({
3232
result: {
3333
clearCacheCronSchedule: config.clearCacheCronSchedule,
3434
},

src/server/routes/configuration/cache/update.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ export async function updateCacheConfiguration(fastify: FastifyInstance) {
4949
const config = await getConfig(false);
5050
// restarting cache cron with updated cron schedule
5151
await clearCacheCron("server");
52-
res.status(200).send({
52+
res.status(StatusCodes.OK).send({
5353
result: {
5454
clearCacheCronSchedule: config.clearCacheCronSchedule,
5555
},

src/server/routes/configuration/chains/get.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
import { Static, Type } from "@sinclair/typebox";
2-
import { FastifyInstance } from "fastify";
1+
import { Type, type Static } from "@sinclair/typebox";
2+
import type { FastifyInstance } from "fastify";
33
import { StatusCodes } from "http-status-codes";
44
import { getConfig } from "../../../../utils/cache/getConfig";
5+
import { chainResponseSchema } from "../../../schemas/chain";
56
import { standardResponseSchema } from "../../../schemas/sharedApiSchemas";
67

78
export const responseBodySchema = Type.Object({
8-
result: Type.Union([Type.String(), Type.Null()]),
9+
result: Type.Array(chainResponseSchema),
910
});
1011

1112
export async function getChainsConfiguration(fastify: FastifyInstance) {
@@ -26,9 +27,11 @@ export async function getChainsConfiguration(fastify: FastifyInstance) {
2627
},
2728
handler: async (req, res) => {
2829
const config = await getConfig();
29-
res.status(200).send({
30-
result: config.chainOverrides,
31-
});
30+
const result: Static<typeof chainResponseSchema>[] = config.chainOverrides
31+
? JSON.parse(config.chainOverrides)
32+
: [];
33+
34+
res.status(StatusCodes.OK).send({ result });
3235
},
3336
});
3437
}

0 commit comments

Comments
 (0)