Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
jmcph4 committed Jun 12, 2024
0 parents commit f744e1a
Show file tree
Hide file tree
Showing 11 changed files with 294 additions and 0 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: CI

on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]

env:
CARGO_TERM_COLOR: always

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3
- name: Clippy
run: cargo clippy
- name: Check format
run: cargo fmt -- --check
- name: Build
run: cargo build --verbose
- name: Run tests
run: cargo test --verbose
27 changes: 27 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Generated by Cargo
# will have compiled files and executables
debug/
target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk

# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb

# RustRover
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

# Miscellaneous
msg.tmp
*.tmp
*.secret

5 changes: 5 additions & 0 deletions CODEOWNERS
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# These owners will be the default owners for everything in
# the repo. Unless a later match takes precedence,
# @jmcph4 will be requested for review when someone opens
# a pull request.
* @jmcph4
36 changes: 36 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
[package]
name = "mkcheckpoint"
version = "0.1.0"
description = "Generate amms-rs-style checkpoints"
edition = "2021"

[dependencies]
amms = { git = "https://github.com/darkforestry/amms-rs", rev = "7d9980a" }
alloy = { git = "https://github.com/alloy-rs/alloy", rev = "dd7a999", features = [
"contract",
"network",
"providers",
"rpc",
"rpc-types",
"rpc-types-eth",
"transports",
"provider-http",
"provider-ws",
"rpc-client",
"pubsub",
"rpc",
"node-bindings",
"transport-ws",
"reqwest",
"serde",
"getrandom",
] }
eyre = "^0.6.0"
csv = "^1.0.0"
clap = { version = "4.5.4", features = ["derive"] }
futures = "0.3.30"
log = "0.4.21"
pretty_env_logger = "0.5.0"
tokio = { version = "^1.0", features = ["full"] }
serde = { version = "1.0.197", features = ["derive"] }
url = "2.5.0"
22 changes: 22 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2024 Jack McPherson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# mkcheckpoint #

`mkcheckpoint` is a program that generates [`amms-rs`](https://github.com/darkforestry/amms-rs)-style checkpoints from CSV data.

2 changes: 2 additions & 0 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[toolchain]
channel = "stable"
2 changes: 2 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
max_width = 80

73 changes: 73 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
use std::{path::PathBuf, sync::Arc};

use alloy::providers::{Provider, ProviderBuilder};
use amms::amm::factory::Factory;
use amms::{amm::AMM, sync::checkpoint::construct_checkpoint};
use clap::Parser;
use log::{error, info};
use url::Url;

use crate::spec::CheckpointSpecification;

mod spec;
mod variant;

const DEFAULT_RPC_URL: &str = "https://eth.merkle.io";
const DEFAULT_OUTPUT_PATH: &str = ".cfmms-checkpoint.json";

#[derive(Parser)]
struct Opts {
#[clap(short, long)]
rpc: Option<Url>,
r#in: PathBuf,
out: Option<PathBuf>,
}

#[tokio::main]
async fn main() -> eyre::Result<()> {
pretty_env_logger::init_timed();
let opts: Opts = Opts::parse();

let provider = Arc::new(
ProviderBuilder::new().on_http(
opts.rpc.unwrap_or(
DEFAULT_RPC_URL
.parse::<Url>()
.expect("Invalid hardcoded RPC URL"),
),
),
);

/* seems repetitive but minimises network requests! */
let spec = CheckpointSpecification::load(opts.r#in)?;
let factories_and_pools = match spec.fetch(provider.clone()).await {
Ok(t) => {
info!("Retrieved all {} pools", t.len());
t
}
Err(e) => {
error!("Failed to retrieve all pools: {:?}", e);
return Err(e);
}
};
let (factories, pools): (Vec<Factory>, Vec<AMM>) = (
factories_and_pools
.iter()
.map(|(factory, _)| factory)
.cloned()
.collect(),
factories_and_pools
.iter()
.map(|(_, pool)| pool)
.cloned()
.collect(),
);

construct_checkpoint(
factories,
&pools,
provider.get_block_number().await?,
opts.out.unwrap_or(DEFAULT_OUTPUT_PATH.into()),
)?;
Ok(())
}
90 changes: 90 additions & 0 deletions src/spec.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
use std::{path::Path, sync::Arc};

use alloy::primitives::{Address, BlockNumber};
use alloy::providers::ReqwestProvider;
use amms::amm::{
factory::Factory,
uniswap_v2::{factory::UniswapV2Factory, UniswapV2Pool},
uniswap_v3::{factory::UniswapV3Factory, UniswapV3Pool},
AMM,
};
use csv::Reader;
use futures::future::join_all;
use serde::{Deserialize, Serialize};

use crate::variant::AmmVariant;

pub const DEFAULT_FEE: u32 = 300;

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SpecificationEntry {
pub variant: AmmVariant,
pub factory: Address,
pub factory_created: BlockNumber,
pub pool: Address,
}

impl SpecificationEntry {
async fn fetch(
&self,
provider: Arc<ReqwestProvider>,
) -> eyre::Result<(Factory, AMM)> {
Ok(match self.variant {
AmmVariant::UniswapV2 => (
Factory::UniswapV2Factory(UniswapV2Factory::new(
self.factory,
self.factory_created,
DEFAULT_FEE,
)),
AMM::UniswapV2Pool(
UniswapV2Pool::new_from_address(
self.pool,
DEFAULT_FEE,
provider.clone(),
)
.await?,
),
),
AmmVariant::UniswapV3 => (
Factory::UniswapV3Factory(UniswapV3Factory::new(
self.factory,
self.factory_created,
)),
AMM::UniswapV3Pool(
UniswapV3Pool::new_from_address(
self.pool,
DEFAULT_FEE.into(),
provider.clone(),
)
.await?,
),
),
})
}
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct CheckpointSpecification(pub Vec<SpecificationEntry>);

impl CheckpointSpecification {
pub fn load<P>(path: P) -> eyre::Result<Self>
where
P: AsRef<Path>,
{
Ok(Self(
Reader::from_path(path)?
.deserialize()
.collect::<Result<Vec<SpecificationEntry>, csv::Error>>()?,
))
}

pub async fn fetch(
&self,
provider: Arc<ReqwestProvider>,
) -> eyre::Result<Vec<(Factory, AMM)>> {
join_all(self.0.iter().map(|x| x.fetch(provider.clone())))
.await
.into_iter()
.collect::<eyre::Result<Vec<(Factory, AMM)>>>()
}
}
7 changes: 7 additions & 0 deletions src/variant.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use serde::{Deserialize, Serialize};

#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
pub enum AmmVariant {
UniswapV2,
UniswapV3,
}

0 comments on commit f744e1a

Please sign in to comment.