Skip to content

Commit

Permalink
add example
Browse files Browse the repository at this point in the history
  • Loading branch information
shardAstronaut committed Jun 26, 2024
1 parent 53d4276 commit 8b927b8
Show file tree
Hide file tree
Showing 9 changed files with 156 additions and 69 deletions.
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1 +1 @@
DATABASE_URL=mysql://user:password@host:port/database
export DATABASE_URL=postgres://0.0.0.0:postgres@postgres:5432/db
23 changes: 11 additions & 12 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
version: '3.8'
services:
mysql:
image: mysql:8.0
command: --default-authentication-plugin=mysql_native_password
cap_add:
- SYS_NICE
postgres:
image: postgres:15
restart: always
user: postgres
volumes:
- db_data:/var/lib/postgresql/data
ports:
- '3306:3306'
- 5432:5432
environment:
- MYSQL_ROOT_PASSWORD=default_password
- MYSQL_DATABASE=checkpoint
volumes:
- mysql:/var/lib/mysql
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: db
volumes:
mysql:
driver: local
db_data:
18 changes: 18 additions & 0 deletions makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
include .env

checkpoint-gen:
yarn checkpoint generate \
-c src/config.json \
-s src/schema.gql

# Dev
dev-build: dev-down
docker compose -f docker-compose.yml build

dev-up: dev-down
docker compose -f docker-compose.yml up

dev-down:
docker compose -f docker-compose.yml down -v

.PHONY: checkpoint-gen
6 changes: 4 additions & 2 deletions src/checkpoints.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
[
{
"contract": "0x03aa7630a4f9c5108bf3cd1910c7d45404cba865fc0fc0756bf9eedc073a98a9",
"blocks": [65308, 65309]
"contract": "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
"blocks": [
219242, 219248, 219256, 235989, 235991, 236293, 236310, 247266, 250884, 250948, 250990
]
}
]
11 changes: 5 additions & 6 deletions src/config.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
{
"network_node_url": "https://starknet-sepolia.infura.io/v3/c82b1cf516984b599108487a1b6481c4",
"network_node_url": "https://starknet-mainnet.infura.io/v3/c82b1cf516984b599108487a1b6481c4",
"optimistic_indexing": false,
"sources": [
{
"contract": "0x03aa7630a4f9c5108bf3cd1910c7d45404cba865fc0fc0756bf9eedc073a98a9",
"start": 65137,
"abi": "Poster",
"contract": "0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
"start": 219242,
"events": [
{
"name": "NewPost",
"fn": "handleNewPost"
"name": "Transfer",
"fn": "liquity_eth_Transfer"
}
]
}
Expand Down
32 changes: 14 additions & 18 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,22 @@
import 'dotenv/config';
import express from 'express';
import cors from 'cors';
// import express from 'express';
// import cors from 'cors';
import path from 'path';
import fs from 'fs';
import Checkpoint, { starknet, LogLevel } from '@snapshot-labs/checkpoint';
import config from './config.json';
import * as writers from './writers';
import { writers } from './writers';
import checkpointBlocks from './checkpoints.json';
import Poster from './abis/Poster.json';

const dir = __dirname.endsWith('dist/src') ? '../' : '';
const schemaFile = path.join(__dirname, `${dir}../src/schema.gql`);
const schema = fs.readFileSync(schemaFile, 'utf8');

const indexer = new starknet.StarknetIndexer(writers);
const indexer = new starknet.StarknetIndexer(writers());
const checkpoint = new Checkpoint(config, indexer, schema, {
logLevel: LogLevel.Info,
logLevel: LogLevel.Debug,
prettifyLogs: true,
fetchInterval: 15000,
abis: {
Poster
}
dbConnection: 'postgres://postgres:postgres@0.0.0.0:5432/db',
fetchInterval: 15000
});

async function run() {
Expand All @@ -32,11 +28,11 @@ async function run() {

run();

const app = express();
app.use(express.json({ limit: '4mb' }));
app.use(express.urlencoded({ limit: '4mb', extended: false }));
app.use(cors({ maxAge: 86400 }));
app.use('/', checkpoint.graphql);
// const app = express();
// app.use(express.json({ limit: '4mb' }));
// app.use(express.urlencoded({ limit: '4mb', extended: false }));
// app.use(cors({ maxAge: 86400 }));
// app.use('/', checkpoint.graphql);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening at http://localhost:${PORT}`));
// const PORT = process.env.PORT || 3000;
// app.listen(PORT, () => console.log(`Listening at http://localhost:${PORT}`));
27 changes: 18 additions & 9 deletions src/schema.gql
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
scalar Text
scalar BigInt

type Post {
id: String!
author: String!
content: Text!
tag: String
tx_hash: String!
created_at: Int!
created_at_block: Int!
type Liquity_Collateral {
id: ID!
trove: String!
user: String!
block: Int!
balance: BigInt!
count: Int!
timestamp: Int!
}

type Liquity_Daily_Collateral {
id: ID!
trove: String!
user: String!
block: Int!
balance: BigInt!
timestamp: Int!
}
5 changes: 0 additions & 5 deletions src/utils.ts

This file was deleted.

101 changes: 85 additions & 16 deletions src/writers.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,91 @@
import { validateAndParseAddress } from 'starknet';
import { uint256, validateAndParseAddress } from 'starknet';
import { starknet } from '@snapshot-labs/checkpoint';
import { Post } from '../.checkpoint/models';
import { longStringToText } from './utils';
import { Liquity_Collateral, Liquity_Daily_Collateral } from '../.checkpoint/models';
import { Event } from '@snapshot-labs/checkpoint/dist/src/providers/starknet';

export const handleNewPost: starknet.Writer = async ({ block, tx, rawEvent, event }) => {
if (!block || !event || !rawEvent) return;
export const ZeroAddress = '0x0000000000000000000000000000000000000000000000000000000000000000';

const author = validateAndParseAddress(rawEvent.from_address);
const content = longStringToText(event.content);
const tag = longStringToText(event.tag);
export const writers = (): Record<string, starknet.Writer> => {
return {
liquity_eth_Transfer: async ({ block, tx, rawEvent, event }) => {

Check warning on line 10 in src/writers.ts

View workflow job for this annotation

GitHub Actions / lint-build

'tx' is defined but never used
if (!block || !event || !rawEvent) return;
const { data } = rawEvent as Event;

const post = new Post(`${author}/${tx.transaction_hash}`);
post.author = author;
post.content = content;
post.tag = tag;
post.tx_hash = tx.transaction_hash;
post.created_at = block.timestamp;
post.created_at_block = block.block_number;
const from = validateAndParseAddress(data[0]);
const to = validateAndParseAddress(data[1]);
const amount = uint256.uint256ToBN({ low: data[2], high: data[3] });

await post.save();
const timestamp = block.timestamp - (block.timestamp % 86400);

let collateral: Liquity_Collateral | null;
let dailyColl: Liquity_Daily_Collateral | null;

if (from == ZeroAddress || to == ZeroAddress) {
// Ignore RequestBatch/ResponseBatch when bridge tokens from L2 <> L1.
return;
} else if (
to == '0x03580a65260563b5511ddf2eafb83d6b309dce7fc25271df8c040a437f09a399' ||
to == '0x02a67288e48a8c4e2881aee422da7841fc11fef195e0a81f929871c77f07509d'
) {
// Borrow the `from` is the user and the `to` is the trove address.
const totalcollateralId = `${to}_${from}`;
const dailyCollId = `${to}_${from}_${timestamp}`;

collateral = await Liquity_Collateral.loadEntity(totalcollateralId);
if (!collateral) {
collateral = new Liquity_Collateral(totalcollateralId);
collateral.user = from;
collateral.trove = to;
collateral.balance = 0n;
}
collateral.balance = BigInt(collateral.balance) + amount;
collateral.count++;

dailyColl = await Liquity_Daily_Collateral.loadEntity(dailyCollId);
if (!dailyColl) {
dailyColl = new Liquity_Daily_Collateral(dailyCollId);
dailyColl.user = from;
dailyColl.trove = to;
dailyColl.balance = collateral.balance;
} else {
dailyColl.balance = BigInt(dailyColl.balance) + amount;
}
} else if (
from == '0x03580a65260563b5511ddf2eafb83d6b309dce7fc25271df8c040a437f09a399' ||
from == '0x02a67288e48a8c4e2881aee422da7841fc11fef195e0a81f929871c77f07509d'
) {
// Repay the `to` is the trove address and the `from` is the user.

const totalcollateralId = `${from}_${to}`;
const dailyCollId = `${from}_${to}_${timestamp}`;
collateral = await Liquity_Collateral.loadEntity(totalcollateralId);
if (!collateral) return;
let remaining = BigInt(collateral.balance) - amount;
// Info: This check is required because we are tracking the LUSD balance the users receive but nio
collateral.balance = remaining > 0n ? remaining : 0n;
collateral.count++;

dailyColl = await Liquity_Daily_Collateral.loadEntity(dailyCollId);
if (!dailyColl) {
dailyColl = new Liquity_Daily_Collateral(dailyCollId);
dailyColl.user = to;
dailyColl.trove = from;
dailyColl.balance = collateral.balance;
} else {
remaining = BigInt(dailyColl.balance) - amount;
dailyColl.balance = remaining > 0n ? remaining : 0n;
}
} else {
return;
}

collateral.timestamp = timestamp;
collateral.block = block.block_number;
dailyColl.timestamp = timestamp;
dailyColl.block = block.block_number;

await collateral.save();
await dailyColl.save();
}
};
};

0 comments on commit 8b927b8

Please sign in to comment.