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

example: add factory mode and pglite persistence #123

Merged
merged 4 commits into from
Dec 3, 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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ dist
.turbo
bun.lockb
.vscode
.apibara
.apibara
.persistence
7 changes: 7 additions & 0 deletions change/apibara-5146fc27-9558-48ae-819b-7000820431b8.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "prerelease",
"comment": "cli: add @electric-sql/pglite as external dependency",
"packageName": "apibara",
"email": "[email protected]",
"dependentChangeType": "patch"
}
20 changes: 8 additions & 12 deletions examples/cli/indexers/2-starknet.indexer.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
import { defineIndexer, useSink } from "@apibara/indexer";
import { defineIndexer } from "@apibara/indexer";
import { drizzlePersistence } from "@apibara/indexer/plugins/drizzle-persistence";
import { useLogger } from "@apibara/indexer/plugins/logger";
import { sqlite } from "@apibara/indexer/sinks/sqlite";
import { StarknetStream } from "@apibara/starknet";
import type { ApibaraRuntimeConfig } from "apibara/types";
import Database from "better-sqlite3";
import { sql } from "drizzle-orm";
import { drizzle } from "drizzle-orm/node-postgres";
import { Client } from "pg";
import { drizzle } from "drizzle-orm/pglite";
import { hash } from "starknet";

export default function (runtimeConfig: ApibaraRuntimeConfig) {
console.log("--> Starknet Indexer Runtime Config: ", runtimeConfig);

// Sink Database
const database = new Database(runtimeConfig.databasePath);
database.exec("DROP TABLE IF EXISTS test");
Expand All @@ -21,10 +18,9 @@ export default function (runtimeConfig: ApibaraRuntimeConfig) {
);

// Persistence Database
const client = new Client({
connectionString: "postgres://postgres:postgres@localhost:5432/postgres",
const persistDatabase = drizzle("./.persistence", {
logger: true,
});
Comment on lines +21 to +22
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Avoid hardcoding persistence path

The persistence path should be configurable through runtime configuration rather than hardcoded.

-  const persistDatabase = drizzle("./.persistence", {
+  const persistDatabase = drizzle(runtimeConfig.persistencePath || "./.persistence", {

Committable suggestion skipped: line range outside the PR's diff.

const persistDatabase = drizzle(client);

return defineIndexer(StarknetStream)({
streamUrl: "https://starknet.preview.apibara.org",
Expand Down Expand Up @@ -52,7 +48,7 @@ export default function (runtimeConfig: ApibaraRuntimeConfig) {
async transform({ endCursor, block: { header }, context }) {
const logger = useLogger();
logger.info("Transforming block ", endCursor?.orderKey);
const { writer } = useSink({ context });
// const { writer } = useSink({ context });

// writer.insert([{
// number: header?.blockNumber.toString(),
Expand All @@ -61,8 +57,6 @@ export default function (runtimeConfig: ApibaraRuntimeConfig) {
},
hooks: {
async "run:before"() {
await client.connect();

// Normally user will do migrations of both tables, which are defined in
// ```
// import { checkpoints, filters } from "@apibara/indexer/plugins/drizzle-persistence"
Expand All @@ -75,7 +69,9 @@ export default function (runtimeConfig: ApibaraRuntimeConfig) {
order_key INTEGER NOT NULL,
unique_key TEXT
);

`);

await persistDatabase.execute(sql`
CREATE TABLE IF NOT EXISTS filters (
id TEXT NOT NULL,
filter TEXT NOT NULL,
Expand Down
65 changes: 65 additions & 0 deletions examples/cli/indexers/3-starknet-factory.indexer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { defineIndexer } from "@apibara/indexer";
import { useLogger } from "@apibara/indexer/plugins/logger";
import { StarknetStream } from "@apibara/starknet";
import type { ApibaraRuntimeConfig } from "apibara/types";
import { hash } from "starknet";

const PAIR_CREATED = hash.getSelectorFromName("PairCreated") as `0x${string}`;
const SWAP = hash.getSelectorFromName("Swap") as `0x${string}`;
const shortAddress = (addr?: string) =>
addr ? `${addr.slice(0, 6)}...${addr.slice(-4)}` : "";

export default function (runtimeConfig: ApibaraRuntimeConfig) {
return defineIndexer(StarknetStream)({
streamUrl: "https://starknet.preview.apibara.org",
finality: "accepted",
startingCursor: {
orderKey: 800_000n,
},
filter: {
header: "always",
events: [
{
address:
"0x00dad44c139a476c7a17fc8141e6db680e9abc9f56fe249a105094c44382c2fd",
keys: [PAIR_CREATED],
},
],
},
async factory({ block: { events } }) {
const logger = useLogger();

const poolEvents = (events ?? []).flatMap((event) => {
const pairAddress = event.data?.[2];

logger.log(
"Factory: PairAddress : ",
`\x1b[35m${pairAddress}\x1b[0m`,
);
return {
address: pairAddress,
keys: [SWAP],
};
});
return {
filter: {
events: poolEvents,
},
};
},
async transform({ block, endCursor }) {
const logger = useLogger();
const { events } = block;

logger.log("Transforming... : ", endCursor?.orderKey);
for (const event of events) {
logger.log(
"Event Address : ",
shortAddress(event.address),
"| Txn hash :",
shortAddress(event.transactionHash),
);
}
},
});
}
2 changes: 1 addition & 1 deletion packages/cli/src/rollup/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { appConfig } from "./plugins/config";
import { esmShim } from "./plugins/esm-shim";
import { indexers } from "./plugins/indexers";

const runtimeDependencies = ["better-sqlite3"];
const runtimeDependencies = ["better-sqlite3", "@electric-sql/pglite"];
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Missing required dependency @electric-sql/pglite

The dependency @electric-sql/pglite is listed in runtimeDependencies but is not declared in the package.json dependencies. This needs to be added to ensure proper package installation and functionality.

  • Add @electric-sql/pglite to the dependencies section in packages/cli/package.json
🔗 Analysis chain

Verify pglite dependency declaration

The addition of @electric-sql/pglite looks correct, but ensure it's properly declared in package.json.


Let me check the package.json in the cli package directory since the file under review is in packages/cli.


Let me check if it might be in devDependencies or if there are any other references to this package in package.json files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if dependency is declared in package.json
jq '.dependencies["@electric-sql/pglite"]' package.json

Length of output: 62


Script:

#!/bin/bash
# Check if dependency is declared in cli package.json
jq '.dependencies["@electric-sql/pglite"]' packages/cli/package.json

Length of output: 75


Script:

#!/bin/bash
# Check both dependencies and devDependencies in cli package.json
echo "CLI package.json contents:"
cat packages/cli/package.json

# Search for any package.json files referencing pglite
echo -e "\nSearching for pglite in all package.json files:"
rg -l "@electric-sql/pglite" "**/package.json"

Length of output: 3396


export function getRollupConfig(apibara: Apibara): RollupConfig {
const extensions: string[] = [
Expand Down
Loading