Skip to content

Commit d3344e9

Browse files
authored
Replace database queries with prisma (#125)
* Replace all server dbOperations with prisma * Update all knex to prisma * Fix sql * Fix trigger
1 parent d46be41 commit d3344e9

File tree

114 files changed

+1500
-1820
lines changed

Some content is hidden

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

114 files changed

+1500
-1820
lines changed

core/database/dbOperation.ts

Lines changed: 0 additions & 154 deletions
This file was deleted.

core/database/dbPrereqs.ts

Lines changed: 1 addition & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { promises as fs } from "fs";
22
import { dirname } from "path";
33
import { fileURLToPath } from "url";
44

5-
import { FastifyInstance, FastifyRequest } from "fastify";
5+
import { FastifyInstance } from "fastify";
66
import { StatusCodes } from "http-status-codes";
77
import { env } from "../env";
88
import { createCustomError } from "../error/customError";
@@ -16,53 +16,6 @@ const connectionString = env.POSTGRES_CONNECTION_URL;
1616
const DATABASE_NAME =
1717
new URL(connectionString).pathname.split("/")[1] || "postgres";
1818

19-
export const checkTablesExistence = async (
20-
server: FastifyInstance,
21-
): Promise<void> => {
22-
try {
23-
const knex = await connectToDatabase();
24-
// Check if the tables Exists
25-
const tablesList: string[] = env.DB_TABLES_LIST.split(",").map(function (
26-
item: any,
27-
) {
28-
return item.trim();
29-
});
30-
31-
if (!tablesList) {
32-
const error = createCustomError(
33-
"DB_TABLES_LIST ENV variable is empty",
34-
StatusCodes.NOT_FOUND,
35-
"DB_TABLES_LIST_NOT_FOUND",
36-
);
37-
throw error;
38-
}
39-
40-
for (const tableName of tablesList) {
41-
const schemaSQL = await fs.readFile(
42-
`${__dirname}/sql-schemas/${tableName}.sql`,
43-
"utf-8",
44-
);
45-
// Create Table using schema
46-
await knex.schema.raw(schemaSQL);
47-
48-
server.log.info(
49-
`SQL for ${tableName} processed successfully on start-up`,
50-
);
51-
}
52-
53-
// Disconnect from DB
54-
await knex.destroy();
55-
} catch (error: any) {
56-
server.log.error(error);
57-
const customError = createCustomError(
58-
"Error while executing Table SQLs on startup",
59-
StatusCodes.INTERNAL_SERVER_ERROR,
60-
"SERVER_STARTUP_TABLES_CREATION_ERROR",
61-
);
62-
throw customError;
63-
}
64-
};
65-
6619
export const implementTriggerOnStartUp = async (
6720
server: FastifyInstance,
6821
): Promise<void> => {
@@ -118,49 +71,3 @@ export const implementTriggerOnStartUp = async (
11871
throw customError;
11972
}
12073
};
121-
122-
export const ensureDatabaseExists = async (
123-
server: FastifyInstance | FastifyRequest,
124-
): Promise<void> => {
125-
try {
126-
// Creating KNEX Config
127-
let modifiedConnectionString = connectionString;
128-
if (DATABASE_NAME !== "postgres") {
129-
// This is required if the Database mentioned in the connection string is not postgres
130-
// as we need to connect to the postgres database to create the user provied database
131-
// and then connect to the user provided database
132-
modifiedConnectionString = connectionString.replace(
133-
`/${DATABASE_NAME}`,
134-
"/postgres",
135-
);
136-
}
137-
138-
let knex = await connectToDatabase(modifiedConnectionString);
139-
140-
// Check if Database Exists & create if it doesn't
141-
let hasDatabase: any;
142-
switch (dbClient) {
143-
case "pg":
144-
server.log.debug("checking if pg database exists");
145-
hasDatabase = await knex.raw(
146-
`SELECT 1 from pg_database WHERE datname = '${DATABASE_NAME}'`,
147-
);
148-
server.log.info(`CHECKING for Database ${DATABASE_NAME}...`);
149-
if (!hasDatabase.rows.length) {
150-
await knex.raw(`CREATE DATABASE ${DATABASE_NAME}`);
151-
} else {
152-
server.log.info(`Database ${DATABASE_NAME} already exists`);
153-
}
154-
break;
155-
default:
156-
throw new Error(
157-
`Unsupported database client: ${dbClient}. Cannot create database ${DATABASE_NAME}`,
158-
);
159-
}
160-
161-
await knex.destroy();
162-
} catch (error) {
163-
server.log.error(error);
164-
throw new Error(`Error creating database ${DATABASE_NAME}`);
165-
}
166-
};

core/index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
export * from "./database/dbConnect";
2-
export * from "./database/dbOperation";
32
export * from "./database/dbPrereqs";
43
export * from "./env";
54
export * from "./error/customError";

core/sdk/sdk.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
WalletConfigType,
1111
walletTableSchema,
1212
} from "../../server/schemas/wallet";
13-
import { getWalletDetails } from "../database/dbOperation";
13+
import { getWalletDetails } from "../../src/db/wallets/getWalletDetails";
1414
import { env } from "../env";
1515
import { networkResponseSchema } from "../schema";
1616

@@ -95,14 +95,17 @@ const cacheSdk = (
9595
};
9696

9797
const walletDataMap: Map<string, string> = new Map();
98-
const getCachedWallet = async (walletAddress: string, chain: string) => {
98+
const getCachedWallet = async (walletAddress: string, chainId: number) => {
9999
walletAddress = walletAddress.toLowerCase();
100100
let walletData;
101101
const cachedWallet = walletDataMap.get(walletAddress);
102102
if (cachedWallet) {
103103
walletData = JSON.parse(cachedWallet);
104104
} else {
105-
walletData = await getWalletDetails(walletAddress, chain);
105+
console.log("Checking details for address", walletAddress);
106+
// TODO: This needs to be changed...
107+
walletData = await getWalletDetails({ address: walletAddress, chainId });
108+
console.log("Received wallet data:", walletData);
106109
if (walletData) {
107110
walletDataMap.set(walletAddress, JSON.stringify(walletData));
108111
}
@@ -144,6 +147,7 @@ export const getSDK = async (
144147

145148
//SDK doesn't exist in cache, so we need to instantiate or create it
146149
if (!walletAddress) {
150+
console.log("Creating sdk...");
147151
//create sdk with no wallet
148152
// TODO set to read only when we can
149153
sdk = new ThirdwebSDK(chain, {
@@ -154,13 +158,13 @@ export const getSDK = async (
154158
return sdk;
155159
}
156160

157-
walletData = await getCachedWallet(walletAddress, chain.name);
161+
walletData = await getCachedWallet(walletAddress, chain.chainId);
158162

159163
if (!walletData) {
160164
throw new Error(`Wallet not found for address: ${walletAddress}`);
161165
}
162166

163-
const walletType = walletData.walletType;
167+
const walletType = walletData.type;
164168
const awsKmsKeyId = walletData.awsKmsKeyId;
165169
const gcpKmsKeyId = walletData.gcpKmsKeyId;
166170
const gcpKmsKeyVersionId = walletData.gcpKmsKeyVersionId;
@@ -235,7 +239,10 @@ export const getSDK = async (
235239
});
236240
cacheSdk(chain.name, sdk, walletAddress);
237241
return sdk;
238-
} else if (walletType === WalletConfigType.ppk) {
242+
} else if (
243+
walletType === WalletConfigType.ppk ||
244+
walletType === WalletConfigType.local
245+
) {
239246
//TODO get private key from encrypted file
240247
wallet = new LocalWallet({
241248
chain,

server/api/contract/extensions/erc1155/write/airdrop.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ import { Static, Type } from "@sinclair/typebox";
22
import { FastifyInstance } from "fastify";
33
import { StatusCodes } from "http-status-codes";
44
import { getContractInstance } from "../../../../../../core";
5-
import { queueTransaction } from "../../../../../helpers";
5+
import { queueTx } from "../../../../../../src/db/transactions/queueTx";
66
import {
77
erc1155ContractParamSchema,
88
standardResponseSchema,
99
transactionWritesResponseSchema,
1010
} from "../../../../../helpers/sharedApiSchemas";
1111
import { web3APIOverridesForWriteRequest } from "../../../../../schemas/web3api-overrides";
12+
import { getChainIdFromChain } from "../../../../../utilities/chain";
1213

1314
// INPUTS
1415
const requestSchema = erc1155ContractParamSchema;
@@ -71,14 +72,15 @@ export async function erc1155airdrop(fastify: FastifyInstance) {
7172
handler: async (request, reply) => {
7273
const { network, contract_address } = request.params;
7374
const { token_id, addresses, web3api_overrides } = request.body;
75+
const chainId = getChainIdFromChain(network);
7476

7577
const contract = await getContractInstance(
7678
network,
7779
contract_address,
7880
web3api_overrides?.from,
7981
);
8082
const tx = await contract.erc1155.airdrop.prepare(token_id, addresses);
81-
const queuedId = await queueTransaction(request, tx, network, "erc1155");
83+
const queuedId = await queueTx({ tx, chainId, extension: "erc1155" });
8284
reply.status(StatusCodes.OK).send({
8385
result: queuedId,
8486
});

0 commit comments

Comments
 (0)