Skip to content

Commit

Permalink
new bindings
Browse files Browse the repository at this point in the history
  • Loading branch information
stackdump committed Sep 16, 2024
1 parent 2cb1ba3 commit e518b1a
Show file tree
Hide file tree
Showing 55 changed files with 31,171 additions and 23,422 deletions.
1,667 changes: 472 additions & 1,195 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[workspace]
members = ["app", "crates"]
members = ["app", "crates/bindings"]
resolver = "2"

[workspace.dependencies]
foundry-contracts = { path = "crates" }
foundry-contracts = { path = "crates/bindings" }
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ bindings:
rm -rf $(BINDINGS_OUT_PATH)

# Generate new bindings
@forge bind --root $(CONTRACTS_PATH) --crate-name $(BINDINGS_FOLDER)
@forge bind --alloy --root $(CONTRACTS_PATH) --crate-name $(BINDINGS_FOLDER)

# Move bindings to the correct location
@mv -f $(BINDINGS_OUT_PATH) $(CRATES_FOLDER)
Expand Down Expand Up @@ -51,4 +51,4 @@ setup:


# Declare phony targets
.PHONY: build build-release clean fmt bindings
.PHONY: build build-release clean fmt bindings
24 changes: 22 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
pflow-rs
--------
# Status

Early Concept

Discover and interact with pflow-xyz contracts using this contract explorer.

## Status
web api
-------

Early Concept
```
pflow --daemon
```

Run a seqeuncer node to aggregate event logs.


cli
---

FIXME - need to target

```
pflow --try '[{ "action": "foo", "seq": 0, "scalar" },...{ "action": "foo", "seq": 0, "scalar" }]'
```

And, execute generalized intent based workflows.
9 changes: 3 additions & 6 deletions TODO.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
OVERVIEW
--------

This is the local UX for p2p users - should be oriented toward private usage.
We're building a generalized intent framework.

For example, whenever we encounter a compatible contract address,
we will index that contract and provide a user interface to interact with it.

TODO: probably keep everything in sqlite!!!
this is an end-user tool, not a developer tool (think courtesy node)

STATUS
------
Expand All @@ -20,6 +15,8 @@ advance the design to be read/write in the same UX

WIP
---
- [ ] integrate w/ Alloy APIs for interaction w/ Optimism

- [ ] refer to contracts by address *ONLY* in URLs
- [ ] should we support loading models from contracts (YES!)
- [ ] optimism.pflow.xyz/contract/0x1234
Expand Down
12 changes: 5 additions & 7 deletions app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@ edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
alloy = { git = "https://github.com/alloy-rs/alloy", features = [
"providers",
"node-bindings",
] }
#foundry-contracts.workspace = true
foundry-contracts.workspace = true
thiserror = "=1.0.56"
axum = "0.7"
axum-server = "0.6.0"
Expand All @@ -27,12 +23,14 @@ tower-http = { version = "0.5", features = ["util", "timeout", "trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
pflow-metamodel = "0.2.0"
webbrowser = "0.8.12"
webbrowser = "0.8"
lazy_static = "1.5.0"
rocksdb = "0.22.0"
async-recursion = "1.1.1"
rusqlite = "0.32.1"
futures-util = "0.3.30"
alloy = { version = "0.3", features = ["network", "providers", "transports", "transport-http", "rpc", "rpc-types", "rpc-client", "contract", "sol-types", "signers"] }
reqwest = "0.12.7"
log = "0.4.22"


[[bin]]
Expand Down
6 changes: 5 additions & 1 deletion app/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,8 @@ clippy:

.PHONY: test
test:
cargo test --all
cargo test --all

.PHONY: run
run:
cargo run --bin pflow
47 changes: 47 additions & 0 deletions app/src/command.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use serde_json::Value;
use std::str::FromStr;
use std::fmt;

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
pub struct Action {
action: String,
scalar: i64,
#[serde(default)]
seq: Option<i64>,
}

impl Default for Action {
fn default() -> Self {
Action {
action: "noop".to_string(),
scalar: 1,
seq: Some(0),
}
}
}

impl FromStr for Action {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let action = serde_json::from_str(s);
match action {
Ok(a) => Ok(a),
Err(e) => Err(e.to_string()),
}
}
}

impl fmt::Display for Action {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", serde_json::to_string(self).unwrap())
}
}

pub fn run_command(action: Action) -> Value {
let result = match action.action.as_str() {
_ => -1,
};

serde_json::json!({"result": result})
}
3 changes: 2 additions & 1 deletion app/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

pub mod server;
pub mod storage;
pub mod command;
pub mod models;
46 changes: 33 additions & 13 deletions app/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,52 @@
use std::error::Error;
use clap::Parser;
use clap::{Parser};
use tokio::task;
use pflow_cli::server::app;
use pflow_cli::command::{run_command, Action};

#[derive(Debug, Parser)]
struct Config {
#[clap(short = 'p', long, default_value = "3000")]
port: u16,

#[clap(short = 'd', long, default_value = "false")]
daemon: bool,

#[clap(short = 'v', long, default_value = "false")]
verbose: bool,

#[clap(value_parser)]
input: Option<Action>,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let config = Config::parse();
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], config.port));
println!("Listening on {}", addr);

let browser_task = task::spawn(async {
if webbrowser::open("http://localhost:3000").is_ok() {
println!("Browser opened successfully");
if config.daemon {
println!("Listening on {}", addr);
let browser_task = task::spawn(async {
if webbrowser::open("http://localhost:3000").is_ok() {
println!("Browser opened successfully");
} else {
println!("Failed to open browser");
}
});

axum_server::bind(addr)
.serve(app().into_make_service())
.await?;

browser_task.await?;
} else {
if config.input.is_none() {
println!("No input provided");
} else {
println!("Failed to open browser");
run_command(config.input.expect("No input provided"));
}
});

axum_server::bind(addr)
.serve(app().into_make_service())
.await?;
return Ok(());
}

browser_task.await?;
Ok(())
}
}
52 changes: 52 additions & 0 deletions app/src/models.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use lazy_static::lazy_static;
use pflow_metamodel::*;

/// Expected CID needs to be updated if the model definition changes
fn check_for_update(cid: &str, model: &Model) {
let zblob = model.net.to_zblob();
assert_eq!(cid, zblob.ipfs_cid, "[MODIFIED] {}\n[pflow] https://pflow.dev?z={:}\n",zblob.ipfs_cid, zblob.base64_zipped);
}

#[macro_export]
macro_rules! pflow_model {
($name:ident, $oid_name:ident, $expected_cid:expr, $($dsl:tt)*) => {
lazy_static! {
pub static ref $name: Model = {
let model = pflow_dsl! {
$($dsl)*
};
check_for_update($expected_cid, &model);
model
};

pub static ref $oid_name: String = $expected_cid.to_string();
}
};
}

/// Declare the model and its OID outside of the test module
/// Expected CID needs to be updated if the model changes
pflow_model!(TEST_MODEL,
TEST_CID, "zb2rhnJobUyvbfHB3yrFDZ3Z4KDhJRSNtrpeU272zri2LYfDT",
declare "petriNet"
cell "place0", 0, 3, [100, 180]
func "txn0", "default", [20, 100]
func "txn1", "default", [180, 100]
func "txn2", "default", [20, 260]
func "txn3", "default", [180, 260]
arrow "txn0", "place0", 1
arrow "place0", "txn1", 3
guard "txn2", "place0", 3
guard "place0", "txn3", 1
);

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_pflow_dsl() {
check_for_update(&**TEST_CID, &TEST_MODEL);
}

}
51 changes: 5 additions & 46 deletions app/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ use crate::storage::{Storage, Zblob};
use axum::{
extract::{Path, Query, State},
http::StatusCode,
response::{IntoResponse, Redirect, Response},
response::{IntoResponse, Response},
routing::get,
Router,
};
use pflow_metamodel::compression::decompress_brotli_decode;
use pflow_metamodel::{oid, zblob};
use pflow_metamodel::oid::Oid;
use tower_http::trace::TraceLayer;

async fn src_handler(
Expand Down Expand Up @@ -86,47 +86,12 @@ fn index_response(cid: String, data: String) -> impl IntoResponse {
.unwrap()
}

async fn model_handler(
Path(ipfs_cid): Path<String>,
req: Query<HashMap<String, String>>,
state: State<Arc<Mutex<Storage>>>,
) -> impl IntoResponse {
let zparam = req.get("z");
let zblob = string_to_zblob(zparam);

let new_blob = state
.lock()
.unwrap()
.create_or_retrieve(
"pflow_models",
&zblob.ipfs_cid,
&zblob.base64_zipped,
&zblob.title,
&zblob.description,
&zblob.keywords,
&zblob.referrer,
)
.unwrap_or(zblob);

// if zparam.is_some() && new_blob.id > 0 {
// return index_response_redirect(new_blob.ipfs_cid).into_response();
// }

let zblob = state
.lock()
.unwrap()
.get_by_cid("pflow_models", &ipfs_cid)
.unwrap_or(Option::from(Zblob::default()))
.unwrap_or_default();

index_response(zblob.ipfs_cid, zblob.base64_zipped).into_response()
}

fn string_to_zblob(data: Option<&String>) -> Zblob {
let mut zblob = Zblob::default();
if data.is_some() {
zblob.base64_zipped = data.unwrap().to_string();
zblob.ipfs_cid = oid::Oid::new(data.unwrap().as_bytes()).unwrap().to_string();
zblob.ipfs_cid = Oid::new(data.unwrap().as_bytes()).unwrap().to_string();
}

zblob
Expand All @@ -137,7 +102,7 @@ async fn index_handler(
state: State<Arc<Mutex<Storage>>>,
) -> impl IntoResponse {
let zblob = string_to_zblob(req.get("z"));
let new_blob = state
let zblob = state
.lock()
.unwrap()
.create_or_retrieve(
Expand All @@ -149,14 +114,8 @@ async fn index_handler(
&zblob.keywords,
&zblob.referrer,
)
.unwrap_or_default();

if new_blob.id > 0 {
let redirect_uri = format!("/p/{}/", zblob.ipfs_cid);
return Redirect::permanent(&redirect_uri).into_response();
}
.unwrap_or(zblob);

let zblob = zblob::Zblob::default();
index_response(zblob.ipfs_cid, zblob.base64_zipped).into_response()
}

Expand Down
10 changes: 0 additions & 10 deletions crates/Cargo.toml

This file was deleted.

Loading

0 comments on commit e518b1a

Please sign in to comment.