Skip to content

Commit

Permalink
ok fixed that
Browse files Browse the repository at this point in the history
  • Loading branch information
DeepDoge committed Jul 25, 2024
1 parent 1a2f0e8 commit 750fe5b
Show file tree
Hide file tree
Showing 21 changed files with 147 additions and 66 deletions.
25 changes: 16 additions & 9 deletions modules/app/src/features/post/FeedViewer.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { posts_feed } from "@root/service";
import { fragment, tags } from "purify-js";
import { globalSheet } from "~/styles";
import { sw } from "~/sw";
import { Bytes32Hex } from "~/utils/hex";
import { style } from "~/utils/style";
import { PostViewer } from "./PostViewer";
import { FeedPost } from "./types";

const { div, ul, li } = tags;

export function FeedViewer(feedId: Bytes32Hex, startIndexInclusive: bigint = 0n) {
Expand All @@ -14,18 +15,21 @@ export function FeedViewer(feedId: Bytes32Hex, startIndexInclusive: bigint = 0n)

const posts = ul();

let oldestPost: FeedPost | null | undefined;
let newestPost: FeedPost | undefined;
let oldestPost: posts_feed.FeedPost | null | undefined;
let newestPost: posts_feed.FeedPost | undefined;
let busy = false;
loadMore();
async function loadMore() {
if (busy) return;
busy = true;
try {
if (oldestPost === null) return;
const response = await sw
.use("/posts/feed")
.getFeed(feedId, oldestPost ? oldestPost.index - 1n : null, -1n, 256n);
const response = await sw.use("/posts/feed").getFeed({
feedId,
cursor: oldestPost ? oldestPost.index - 1n : null,
direction: -1n,
limit: 256n,
});
posts.children(response.map((post) => li().children(PostViewer(post))));

oldestPost = response.at(-1) ?? null;
Expand All @@ -41,9 +45,12 @@ export function FeedViewer(feedId: Bytes32Hex, startIndexInclusive: bigint = 0n)
if (busy) return;
busy = true;
try {
const response = await sw
.use("/posts/feed")
.getFeed(feedId, newestPost ? newestPost.index + 1n : 0n, 1n, 256n);
const response = await sw.use("/posts/feed").getFeed({
feedId,
cursor: newestPost ? newestPost.index + 1n : 0n,
direction: 1n,
limit: 256n,
});
response.sort((a, b) => b.time - a.time);
posts.element.prepend(...response.map((post) => li().children(PostViewer(post)).element));

Expand Down
8 changes: 0 additions & 8 deletions modules/app/src/features/post/types.ts

This file was deleted.

10 changes: 5 additions & 5 deletions modules/contracts/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { compileSol } from "solc-typed-ast";

const CONTRACTS_DIR = path.resolve("./src");
const NODE_MODULES_DIR = path.resolve("../../node_modules");
const ARTIFACTS_DIR = path.resolve("./artifacts");

async function findSolidityFilesRecursive(dir: string): Promise<string[]> {
const files = await fs.readdir(dir, { withFileTypes: true });
Expand Down Expand Up @@ -35,9 +36,8 @@ const solidityFilesByDir = solidityFiles.reduce(
);

for (const [dirPath, solidityFiles] of Object.entries(solidityFilesByDir)) {
const artifactsDirPath = path.resolve(`${dirPath}/artifacts`);
await fs.rm(artifactsDirPath, { recursive: true }).catch(() => {});
await fs.mkdir(artifactsDirPath, { recursive: true });
await fs.rm(ARTIFACTS_DIR, { recursive: true }).catch(() => {});
await fs.mkdir(ARTIFACTS_DIR, { recursive: true });
for (const filePath of solidityFiles) {
const name = path.basename(filePath, ".sol");
console.log(`> Compiling ${bold(name)} in ${bold(dirPath)}`);
Expand All @@ -51,15 +51,15 @@ for (const [dirPath, solidityFiles] of Object.entries(solidityFilesByDir)) {
const bin: string = result.data["contracts"][filePath][name]["evm"]["bytecode"]["object"];

await fs.writeFile(
path.join(artifactsDirPath, `${name}.ts`),
path.join(ARTIFACTS_DIR, `${name}.ts`),
[
`export type ${name}_ABI = typeof ${name}_ABI;`,
`export const ${name}_ABI = ${JSON.stringify(abi)} as const;`,
// `export const ${name}_BIN = "${bin}";`,
].join("\n"),
);

await fs.writeFile(path.join(artifactsDirPath, `${name}.abi.json`), JSON.stringify(abi));
await fs.writeFile(path.join(ARTIFACTS_DIR, `${name}.abi.json`), JSON.stringify(abi));

console.log(green(`>> ${bold(name)} compiled successfully!`));
}
Expand Down
3 changes: 2 additions & 1 deletion modules/contracts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"type": "module",
"name": "@root/contracts",
"scripts": {
"compile": "tsx ./compile.ts"
"compile": "tsx ./compile.ts",
"dev": "tsx --watch-path ./src ./compile.ts"
},
"exports": {
"./connect": "./connect.ts"
Expand Down

This file was deleted.

2 changes: 0 additions & 2 deletions modules/contracts/src/artifacts/EternisDefaultIndexer.ts

This file was deleted.

This file was deleted.

2 changes: 0 additions & 2 deletions modules/contracts/src/artifacts/EternisProxy_SSTORE.ts

This file was deleted.

1 change: 0 additions & 1 deletion modules/contracts/src/artifacts/IEternisIndexer.abi.json

This file was deleted.

2 changes: 0 additions & 2 deletions modules/contracts/src/artifacts/IEternisIndexer.ts

This file was deleted.

1 change: 0 additions & 1 deletion modules/contracts/src/artifacts/IEternisProxy.abi.json

This file was deleted.

2 changes: 0 additions & 2 deletions modules/contracts/src/artifacts/IEternisProxy.ts

This file was deleted.

48 changes: 33 additions & 15 deletions modules/service/scripts/generate-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,39 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));

const routesPath = path.join(__dirname, "../src/routes");
const outputFilePath = path.join(__dirname, "../src/routes.ts");
const files = await getFiles(routesPath);

const output = `export type Routes = {
${files
.filter((filepath) => {
const basename = path.basename(filepath);
return basename === "+expose.ts";
})
.map((filepath) => {
const key = filepath.slice(routesPath.length, -("+expose.ts".length + 1));
return `${JSON.stringify(key)}: typeof import(${JSON.stringify(path.resolve(filepath))})`;
})
.join(",\n")}
}
`;
const files = (await getFiles(routesPath)).filter((filepath) => {
const basename = path.basename(filepath);
return basename === "+expose.ts";
});

const output = [
files
.map((filepath, index) => {
const from = JSON.stringify(path.resolve(filepath).slice(0, -3));
return `import type * as _${index} from ${from}`;
})
.join("\n"),
[
"export type Routes = {\n\t",
files
.map((filepath, index) => {
const key = filepath.slice(routesPath.length, -("+expose.ts".length + 1));
return `${JSON.stringify(key)}: typeof _${index}`;
})
.join(",\n\t"),
"\n}",
].join(""),
[
"export {\n\t",
files
.map((filepath, index) => {
const key = filepath.slice(routesPath.length + 1, -("+expose.ts".length + 1)).replaceAll("/", "_");
return `_${index} as ${key}`;
})
.join(",\n\t"),
"\n}",
].join(""),
].join("\n\n");

fs.writeFileSync(outputFilePath, output, "utf-8");

Expand Down
2 changes: 1 addition & 1 deletion modules/service/src/exports.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from "./exposed/types";
export type { Routes } from "./routes";
export * from "./routes";
27 changes: 19 additions & 8 deletions modules/service/src/routes/posts/feed/+expose.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,27 @@
import { FeedPost } from "@root/app/src/features/post/types";
import { Bytes32Hex } from "@root/app/src/utils/hex";
import { IEternisIndexer, IEternisProxy } from "@root/contracts/connect";
import { memoizeUntilSettled } from "@root/shared/utils/memoize";
import { JsonRpcProvider, toBeHex } from "ethers";
import { db } from "~/db";
import { Config } from "~/routes/config/module";

export async function getFeed(
feedId: Bytes32Hex,
cursor: bigint | null,
direction: -1n | 1n,
limit: bigint,
): Promise<FeedPost[]> {
export type GetFeedParameters = {
feedId: Bytes32Hex;
cursor: bigint | null;
direction: -1n | 1n;
limit: bigint;
};

export type FeedPost = {
origin: `0x${string}`;
sender: `0x${string}`;
id: string;
index: bigint;
time: number;
contentBytesHex: string;
};

export const getFeed = memoizeUntilSettled(async ({ feedId, cursor, direction, limit }): Promise<FeedPost[]> => {
const config = await Config.get();
const provider = new JsonRpcProvider(config.networks[0].providers[0]);
const indexerContract = IEternisIndexer.connect(provider, config.networks[0].contracts.EternisIndexer);
Expand Down Expand Up @@ -53,4 +64,4 @@ export async function getFeed(
}

return await Promise.all(postPromises);
}
});
2 changes: 1 addition & 1 deletion modules/service/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@
"~/*": ["./src/*"]
}
},
"include": ["src", "../app/src/features/post/types.ts", "../app/src/features/config/broadcastChannels.ts"]
"include": ["src"]
}
4 changes: 4 additions & 0 deletions modules/shared/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"type": "module",
"name": "@root/shared"
}
19 changes: 19 additions & 0 deletions modules/shared/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"lib": ["WebWorker", "DOM", "ESNext"],
"types": ["vite/client", "@total-typescript/ts-reset"], // Both service and client use the vite/client

"module": "ESNext",
"target": "ESNext",

"moduleResolution": "Bundler",
"moduleDetection": "force",
"noEmit": true,

"paths": {
"~/*": ["./*"]
}
},
"include": ["."]
}
36 changes: 36 additions & 0 deletions modules/shared/utils/memoize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
export function memoize<TParams extends unknown[], TReturns>(
fn: (...args: TParams) => TReturns,
key: (...args: TParams) => unknown = (...args) => JSON.stringify(args, (_, value) => String(value)),
) {
const caches = new Map<unknown, TReturns>();
return (...args: TParams): TReturns => {
const cacheKey = key(...args);
const cache = caches.get(cacheKey);
if (cache) {
return cache;
}

const result = fn(...args);
caches.set(cacheKey, result);
return result;
};
}

export function memoizeUntilSettled<TParams extends unknown[], TReturns extends Promise<unknown>>(
fn: (...args: TParams) => TReturns,
key: (...args: TParams) => unknown = (...args) => JSON.stringify(args, (_, value) => String(value)),
) {
const caches = new Map<unknown, TReturns>();
return (...args: TParams): TReturns => {
const cacheKey = key(...args);
const cache = caches.get(cacheKey);
if (cache) {
return cache;
}

const result = fn(...args);
caches.set(cacheKey, result);
result.then(() => caches.delete(cacheKey));
return result;
};
}
14 changes: 9 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"./modules/*"
],
"scripts": {
"dev": "npm-run-all --parallel *:dev",
"dev": "npm run contracts:compile && npm-run-all --parallel *:dev",
"build": "npm run service:build && npm run app:build",
"preview": "npm run preview --prefix ./modules/app",
"postinstall": "npm run contracts:compile",
Expand All @@ -15,6 +15,7 @@
"app:build": "npm run build --prefix ./modules/app",
"service:dev": "npm run dev --prefix ./modules/service",
"service:build": "npm run build --prefix ./modules/service",
"contracts:dev": "npm run dev --prefix ./modules/contracts",
"contracts:compile": "npm run compile --prefix ./modules/contracts"
},
"devDependencies": {
Expand Down

0 comments on commit 750fe5b

Please sign in to comment.