Skip to content
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

Database set up with Drizzle #1

Merged
merged 1 commit into from
Jul 26, 2024
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,6 @@ node_modules
.idea

# cli
dist
dist

data/db
68 changes: 19 additions & 49 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,4 @@
# 🏗 Scaffold-ETH 2

<h4 align="center">
<a href="https://docs.scaffoldeth.io">Documentation</a> |
<a href="https://scaffoldeth.io">Website</a>
</h4>

🧪 An open-source, up-to-date toolkit for building decentralized applications (dapps) on the Ethereum blockchain. It's designed to make it easier for developers to create and deploy smart contracts and build user interfaces that interact with those contracts.

⚙️ Built using NextJS, RainbowKit, Hardhat, Wagmi, Viem, and Typescript.

- ✅ **Contract Hot Reload**: Your frontend auto-adapts to your smart contract as you edit it.
- 🪝 **[Custom hooks](https://docs.scaffoldeth.io/hooks/)**: Collection of React hooks wrapper around [wagmi](https://wagmi.sh/) to simplify interactions with smart contracts with typescript autocompletion.
- 🧱 [**Components**](https://docs.scaffoldeth.io/components/): Collection of common web3 components to quickly build your frontend.
- 🔥 **Burner Wallet & Local Faucet**: Quickly test your application with a burner wallet and local faucet.
- 🔐 **Integration with Wallet Providers**: Connect to different wallet providers and interact with the Ethereum network.

![Debug Contracts tab](https://github.com/scaffold-eth/scaffold-eth-2/assets/55535804/b237af0c-5027-4849-a5c1-2e31495cccb1)
## ENS PG

## Requirements

Expand All @@ -24,57 +7,44 @@ Before you begin, you need to install the following tools:
- [Node (>= v18.17)](https://nodejs.org/en/download/)
- Yarn ([v1](https://classic.yarnpkg.com/en/docs/install/) or [v2+](https://yarnpkg.com/getting-started/install))
- [Git](https://git-scm.com/downloads)
- [Docker Engine](https://docs.docker.com/engine/install/)

## Quickstart

To get started with Scaffold-ETH 2, follow the steps below:
## Development Quickstart

1. Install dependencies if it was skipped in CLI:
1. Install dependencies

```
cd my-dapp-example
yarn install
```

2. Run a local network in the first terminal:

```
yarn chain
```

This command starts a local Ethereum network using Hardhat. The network runs on your local machine and can be used for testing and development. You can customize the network configuration in `packages/hardhat/hardhat.config.ts`.

3. On a second terminal, deploy the test contract:
2. Spin up the Postgres database service + create database + seed

```
yarn deploy
docker-compose up -d
yarn drizzle-kit push
yarn seed
```

This command deploys a test smart contract to the local network. The contract is located in `packages/hardhat/contracts` and can be modified to suit your needs. The `yarn deploy` command uses the deploy script located in `packages/hardhat/deploy` to deploy the contract to the network. You can also customize the deploy script.
See more info about the database in the section below

4. On a third terminal, start your NextJS app:
3. Start your NextJS app:

```
yarn start
```

Visit your app on: `http://localhost:3000`. You can interact with your smart contract using the `Debug Contracts` page. You can tweak the app config in `packages/nextjs/scaffold.config.ts`.

Run smart contract test with `yarn hardhat:test`

- Edit your smart contract `YourContract.sol` in `packages/hardhat/contracts`
- Edit your frontend homepage at `packages/nextjs/app/page.tsx`. For guidance on [routing](https://nextjs.org/docs/app/building-your-application/routing/defining-routes) and configuring [pages/layouts](https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts) checkout the Next.js documentation.
- Edit your deployment scripts in `packages/hardhat/deploy`

Visit your app on: `http://localhost:3000`.

## Documentation
## Database (dev info)

Visit our [docs](https://docs.scaffoldeth.io) to learn how to start building with Scaffold-ETH 2.
We are using Drizzle with Postgres. You can run `drizzle-kit` from the root with `yarn drizzle-kit`

To know more about its features, check out our [website](https://scaffoldeth.io).
To iterate on the database:

## Contributing to Scaffold-ETH 2
- Tweak the schema in `schema.ts`
- Run `yarn drizzle-kit push` to apply the changes.
- Tweak `seed.js` if needed + run `yarn seed` (will delete existing data)
- You can explore the database with `yarn drizzle-kit studio`

We welcome contributions to Scaffold-ETH 2!
After the initial iterations, we can start using migrations (`yarn drizzle-kit generate` & `yarn drizzle-kit migrate`)

Please see [CONTRIBUTING.MD](https://github.com/scaffold-eth/scaffold-eth-2/blob/main/CONTRIBUTING.md) for more information and guidelines for contributing to Scaffold-ETH 2.
10 changes: 10 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version: "3"
services:
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: mysecretpassword
ports:
- "5432:5432"
volumes:
- ./data/db:/var/lib/postgresql/data
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"chain": "yarn workspace @se-2/hardhat chain",
"compile": "yarn workspace @se-2/hardhat compile",
"deploy": "yarn workspace @se-2/hardhat deploy",
"drizzle-kit": "yarn workspace @se-2/nextjs drizzle-kit",
"flatten": "yarn workspace @se-2/hardhat flatten",
"fork": "yarn workspace @se-2/hardhat fork",
"format": "yarn next:format && yarn hardhat:format",
Expand All @@ -28,6 +29,7 @@
"next:lint": "yarn workspace @se-2/nextjs lint",
"next:serve": "yarn workspace @se-2/nextjs serve",
"precommit": "lint-staged",
"seed": "yarn workspace @se-2/nextjs seed",
"start": "yarn workspace @se-2/nextjs dev",
"test": "yarn hardhat:test",
"vercel": "yarn workspace @se-2/nextjs vercel",
Expand Down
2 changes: 2 additions & 0 deletions packages/nextjs/.env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

POSTGRES_URL="postgresql://postgres:mysecretpassword@localhost:5432/postgres"
19 changes: 19 additions & 0 deletions packages/nextjs/app/api/submissions/new/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { createSubmission } from "~~/services/database/repositories/submissions";

// TODO This should be a POST request
damianmarti marked this conversation as resolved.
Show resolved Hide resolved
export async function GET() {
const newSubmission = {
title: `Submission Title ${Math.random().toString(36).substring(7)}`,
description: "Description of the new submission",
builder: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
};

try {
const result = await createSubmission(newSubmission);
return NextResponse.json(result, { status: 201 });
} catch (error) {
console.error(error);
return NextResponse.json({ error: "Error creating submission" }, { status: 500 });
}
}
12 changes: 12 additions & 0 deletions packages/nextjs/app/api/submissions/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { NextResponse } from "next/server";
import { getAllSubmissions } from "~~/services/database/repositories/submissions";

export async function GET() {
try {
const grants = await getAllSubmissions();
return NextResponse.json(grants);
} catch (error) {
console.error(error);
return NextResponse.json({ error: "Error fetching submissions" }, { status: 500 });
}
}
13 changes: 13 additions & 0 deletions packages/nextjs/drizzle.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import * as dotenv from "dotenv";
import { defineConfig } from "drizzle-kit";

dotenv.config({ path: ".env.development" });

export default defineConfig({
schema: "./services/database/config/schema.ts",
out: "./services/database/migrations",
dialect: "postgresql",
dbCredentials: {
url: process.env.POSTGRES_URL as string,
},
});
8 changes: 8 additions & 0 deletions packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
"build": "next build",
"check-types": "tsc --noEmit --incremental",
"dev": "next dev",
"drizzle-kit": "drizzle-kit",
"format": "prettier --write . '!(node_modules|.next|contracts)/**/*'",
"lint": "next lint",
"seed": "tsx services/database/seed.ts",
"serve": "next start",
"start": "next dev",
"vercel": "vercel",
Expand All @@ -22,9 +24,12 @@
"blo": "~1.0.1",
"burner-connector": "~0.0.8",
"daisyui": "4.5.0",
"dotenv": "^16.4.5",
"drizzle-orm": "^0.32.1",
"next": "~14.0.4",
"next-themes": "~0.2.1",
"nprogress": "~0.2.0",
"pg": "^8.12.0",
"qrcode.react": "~3.1.0",
"react": "~18.2.0",
"react-copy-to-clipboard": "~5.1.0",
Expand All @@ -40,18 +45,21 @@
"@trivago/prettier-plugin-sort-imports": "~4.3.0",
"@types/node": "^17.0.45",
"@types/nprogress": "^0",
"@types/pg": "^8",
"@types/react": "^18.0.21",
"@types/react-copy-to-clipboard": "^5.0.4",
"@typescript-eslint/eslint-plugin": "~5.40.0",
"abitype": "1.0.5",
"autoprefixer": "~10.4.12",
"drizzle-kit": "^0.23.0",
"eslint": "~8.24.0",
"eslint-config-next": "~14.0.4",
"eslint-config-prettier": "~9.1.0",
"eslint-plugin-prettier": "~5.1.3",
"postcss": "~8.4.16",
"prettier": "~3.3.2",
"tailwindcss": "~3.4.3",
"tsx": "^4.16.2",
"type-fest": "~4.6.0",
"typescript": "5.5.3",
"vercel": "~32.4.1"
Expand Down
12 changes: 12 additions & 0 deletions packages/nextjs/services/database/config/postgresClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import * as schema from "./schema";
import { drizzle } from "drizzle-orm/node-postgres";
import { Client } from "pg";

const client = new Client({
connectionString: process.env.POSTGRES_URL,
});

await client.connect();
const db = drizzle(client, { schema });

export { db };
16 changes: 16 additions & 0 deletions packages/nextjs/services/database/config/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { sql } from "drizzle-orm";
import { pgTable, serial, text, timestamp, varchar } from "drizzle-orm/pg-core";

// TODO: Define the right schema.
export const submissions = pgTable("submissions", {
id: serial("id").primaryKey(),
title: varchar("name", { length: 256 }),
description: text("description"),
submissionTimestamp: timestamp("submission_timestamp").default(sql`now()`),
builder: varchar("builder_id", { length: 256 }).references(() => builders.id),
});

export const builders = pgTable("builders", {
id: varchar("id", { length: 256 }).primaryKey(),
role: varchar("role", { length: 256 }),
});
13 changes: 13 additions & 0 deletions packages/nextjs/services/database/repositories/submissions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { InferInsertModel } from "drizzle-orm";
import { db } from "~~/services/database/config/postgresClient";
import { submissions } from "~~/services/database/config/schema";

export type SubmissionInsert = InferInsertModel<typeof submissions>;

export async function getAllSubmissions() {
return await db.select().from(submissions);
}

export async function createSubmission(submission: SubmissionInsert) {
return await db.insert(submissions).values(submission);
}
53 changes: 53 additions & 0 deletions packages/nextjs/services/database/seed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { builders, submissions } from "./config/schema";
import * as schema from "./config/schema";
import * as dotenv from "dotenv";
import { drizzle } from "drizzle-orm/node-postgres";
import * as path from "path";
import { Client } from "pg";

dotenv.config({ path: path.resolve(__dirname, "../../.env.development") });

// TODO: protect, only for dev.
async function seed() {
const client = new Client({
connectionString: process.env.POSTGRES_URL,
});

await client.connect();
const db = drizzle(client, { schema });

await db.delete(builders).execute();
db.insert(builders)
.values([
{ id: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", role: "admin" },
{ id: "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC", role: "user" },
])
.execute();

await db.delete(submissions).execute();
await db
.insert(submissions)
.values([
{
title: "First submission",
description: "This is the first submission",
builder: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
},
{
title: "Second submission",
description: "This is the second submission",
builder: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
},
])
.execute();

console.log("Database seeded successfully");
}

seed()
.catch(error => {
console.error("Error seeding database:", error);
})
.finally(() => {
process.exit();
});
Loading
Loading