Skip to content

Commit

Permalink
Merge branches 'feat--expose-proposal-api-to-calimero-sdk' and 'maste…
Browse files Browse the repository at this point in the history
…r' of github.com:calimero-network/core into feat--expose-proposal-api-to-calimero-sdk
  • Loading branch information
MatejVukosav committed Nov 8, 2024
2 parents c0eae80 + 6d42c68 commit e00ba00
Show file tree
Hide file tree
Showing 32 changed files with 507 additions and 918 deletions.
11 changes: 1 addition & 10 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,17 +74,8 @@ jobs:
- name: Build
run: cargo build --verbose

- name: Get changed files
id: changed-files
uses: tj-actions/changed-files@v45
with:
files: |
**.rs
- name: Run tests
env:
CHANGED_RUST_FILES: ${{ steps.changed-files.outputs.all_changed_files }}
run: |
chmod +x $GITHUB_WORKSPACE/scripts/build-all-apps.sh
chmod +x $GITHUB_WORKSPACE/scripts/test.sh
$GITHUB_WORKSPACE/scripts/test.sh --local ${CHANGED_RUST_FILES}
$GITHUB_WORKSPACE/scripts/test.sh
9 changes: 3 additions & 6 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,15 @@
echo "Running pre-commit hook..."

# Check for changes in Markdown or MDX files
if git diff --cached --name-only | grep -q '\.mdx?$'; then
if git diff --cached --name-only | grep -qE '\.mdx?$'; then
echo "Markdown or MDX files have been changed."
pnpm format:md
fi

# Check for changes in Rust files
if git diff --cached --name-only | grep -q '\.rs$'; then
if git diff --cached --name-only | grep -qE '\.rs$'; then
echo "Running checks for the Rust code..."
cargo +nightly fmt
# Run tests only for the changed files
# changed_rust_files=$(git diff --cached --name-only | grep -E '\.rs$')
# ./scripts/test.sh --local ${changed_rust_files}
fi

# Check for changes in the 'node-ui' directory (Next.js app)
Expand All @@ -28,4 +25,4 @@ fi
if git diff --cached --name-only | grep -q '^packages/calimero-sdk/'; then
echo "Running checks for the packages/calimero-sdk..."
(cd packages/calimero-sdk && pnpm prettier && pnpm lint:fix)
fi
fi
1 change: 1 addition & 0 deletions Cargo.lock

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

8 changes: 8 additions & 0 deletions crates/context/config/src/client/protocol/near.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ impl<'a> NearTransport<'a> {
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum NearError {
#[error("unsupported protocol `{0}`")]
UnsupportedProtocol(String),
#[error("unknown network `{0}`")]
UnknownNetwork(String),
#[error("invalid response from RPC while {operation}")]
Expand Down Expand Up @@ -191,6 +193,12 @@ impl Transport for NearTransport<'_> {
request: TransportRequest<'_>,
payload: Vec<u8>,
) -> Result<Vec<u8>, Self::Error> {
if request.protocol != Near::PROTOCOL {
return Err(NearError::UnsupportedProtocol(
request.protocol.into_owned(),
));
}

let Some(network) = self.networks.get(&request.network_id) else {
return Err(NearError::UnknownNetwork(request.network_id.into_owned()));
};
Expand Down
8 changes: 8 additions & 0 deletions crates/context/config/src/client/protocol/starknet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ impl<'a> StarknetTransport<'a> {
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum StarknetError {
#[error("unsupported protocol: {0}")]
UnsupportedProtocol(String),
#[error("unknown network `{0}`")]
UnknownNetwork(String),
#[error("invalid response from RPC while {operation}")]
Expand Down Expand Up @@ -174,6 +176,12 @@ impl Transport for StarknetTransport<'_> {
request: TransportRequest<'_>,
payload: Vec<u8>,
) -> Result<Vec<u8>, Self::Error> {
if request.protocol != Starknet::PROTOCOL {
return Err(StarknetError::UnsupportedProtocol(
request.protocol.into_owned(),
));
}

let Some(network) = self.networks.get(&request.network_id) else {
return Err(StarknetError::UnknownNetwork(
request.network_id.into_owned(),
Expand Down
61 changes: 32 additions & 29 deletions crates/context/config/src/client/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,6 @@ pub trait Transport {
) -> Result<Vec<u8>, Self::Error>;
}

impl<L: Transport, R: Transport> Transport for Either<L, R> {
type Error = Either<L::Error, R::Error>;

async fn send(
&self,
request: TransportRequest<'_>,
payload: Vec<u8>,
) -> Result<Vec<u8>, Self::Error> {
match self {
Self::Left(left) => left.send(request, payload).await.map_err(Either::Left),
Self::Right(right) => right.send(request, payload).await.map_err(Either::Right),
}
}
}

#[derive(Debug)]
#[non_exhaustive]
pub struct TransportRequest<'a> {
Expand All @@ -59,6 +44,34 @@ impl<'a> TransportRequest<'a> {
}
}

#[derive(Debug, Error)]
pub enum EitherError<L, R> {
#[error(transparent)]
Left(L),
#[error(transparent)]
Right(R),
#[error("unsupported protocol: {0}")]
UnsupportedProtocol(String),
}

impl<L: Transport, R: Transport> Transport for Either<L, R> {
type Error = EitherError<L::Error, R::Error>;

async fn send(
&self,
request: TransportRequest<'_>,
payload: Vec<u8>,
) -> Result<Vec<u8>, Self::Error> {
match self {
Self::Left(left) => left.send(request, payload).await.map_err(EitherError::Left),
Self::Right(right) => right
.send(request, payload)
.await
.map_err(EitherError::Right),
}
}
}

#[derive(Debug, Serialize, Deserialize)]
#[expect(clippy::exhaustive_enums, reason = "Considered to be exhaustive")]
pub enum Operation<'a> {
Expand All @@ -83,22 +96,12 @@ pub struct Both<L, R> {
pub right: R,
}

#[derive(Debug, Error)]
pub enum BothError<L, R> {
#[error("left error: {0}")]
Left(L),
#[error("right error: {0}")]
Right(R),
#[error("unsupported protocol: {0}")]
UnsupportedProtocol(String),
}

impl<L, R> Transport for Both<L, R>
where
L: AssociatedTransport,
R: AssociatedTransport,
{
type Error = BothError<L::Error, R::Error>;
type Error = EitherError<L::Error, R::Error>;

async fn send(
&self,
Expand All @@ -109,14 +112,14 @@ where
self.left
.send(request, payload)
.await
.map_err(BothError::Left)
.map_err(EitherError::Left)
} else if request.protocol == R::protocol() {
self.right
.send(request, payload)
.await
.map_err(BothError::Right)
.map_err(EitherError::Right)
} else {
return Err(BothError::UnsupportedProtocol(
return Err(EitherError::UnsupportedProtocol(
request.protocol.into_owned(),
));
}
Expand Down
18 changes: 17 additions & 1 deletion crates/context/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,22 @@ impl ContextManager {
self.get_context_identities(context_id, true)
}

pub fn context_has_owned_identity(
&self,
context_id: ContextId,
public_key: PublicKey,
) -> EyreResult<bool> {
let handle = self.store.handle();

let key = ContextIdentityKey::new(context_id, public_key);

let Some(value) = handle.get(&key)? else {
return Ok(false);
};

Ok(value.private_key.is_some())
}

pub fn get_contexts(&self, start: Option<ContextId>) -> EyreResult<Vec<Context>> {
let handle = self.store.handle();

Expand Down Expand Up @@ -838,7 +854,7 @@ impl ContextManager {
}

pub fn has_blob_available(&self, blob_id: BlobId) -> EyreResult<bool> {
Ok(self.blob_manager.has(blob_id)?)
self.blob_manager.has(blob_id)
}

// vv~ these would be more appropriate in an ApplicationManager
Expand Down
7 changes: 5 additions & 2 deletions crates/meroctl/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ use crate::defaults;
use crate::output::{Format, Output, Report};

mod app;
mod call;
mod context;
mod identity;
mod jsonrpc;
mod proxy;

use app::AppCommand;
use call::CallCommand;
use context::ContextCommand;
use identity::IdentityCommand;
use jsonrpc::CallCommand;
Expand Down Expand Up @@ -53,6 +54,7 @@ pub enum SubCommands {
Identity(IdentityCommand),
JsonRpc(CallCommand),
Proxy(ProxyCommand),
Call(CallCommand),
}

#[derive(Debug, Parser)]
Expand All @@ -66,7 +68,7 @@ pub struct RootArgs {
#[arg(short, long, value_name = "NAME")]
pub node_name: String,

#[arg(long, value_name = "FORMAT")]
#[arg(long, value_name = "FORMAT", default_value_t, value_enum)]
pub output_format: Format,
}

Expand All @@ -92,6 +94,7 @@ impl RootCommand {
SubCommands::Identity(identity) => identity.run(&environment).await,
SubCommands::JsonRpc(jsonrpc) => jsonrpc.run(&environment).await,
SubCommands::Proxy(proxy) => proxy.run(&environment).await,
SubCommands::Call(call) => call.run(&environment).await,
};

if let Err(err) = result {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use calimero_primitives::context::ContextId;
use calimero_primitives::identity::PublicKey;
use calimero_server_primitives::jsonrpc::{
ExecuteRequest, Request, RequestId, RequestPayload, Response, Version,
ExecuteRequest, Request, RequestId, RequestPayload, Response, ResponseBody, Version,
};
use clap::{Parser, ValueEnum};
use color_eyre::owo_colors::OwoColorize;
use const_format::concatcp;
use eyre::{bail, Result as EyreResult};
use serde_json::Value;
use serde_json::{json, Value};

use crate::cli::Environment;
use crate::common::{do_request, load_config, multiaddr_to_url, RequestType};
Expand All @@ -29,12 +31,11 @@ pub struct CallCommand {
#[arg(value_name = "METHOD", help = "Method to fetch details")]
pub method: String,

#[arg(
long,
default_value = "{}",
help = "Arguments to the method in the app"
)]
pub args_json: String,
#[arg(long, value_parser = serde_value, help = "JSON arguments to pass to the method")]
pub args: Option<Value>,

#[arg(long = "as", help = "Public key of the executor")]
pub executor: PublicKey,

#[arg(
long,
Expand All @@ -49,11 +50,32 @@ pub enum CallType {
Execute,
}

fn serde_value(s: &str) -> serde_json::Result<Value> {
serde_json::from_str(s)
}

impl Report for Response {
fn report(&self) {
println!("jsonrpc: {:#?}", self.jsonrpc);
println!("id: {:?}", self.id);
println!("result: {:#?}", self.body);
match &self.body {
ResponseBody::Result(result) => {
println!("return value:");
let result = format!(
"(json): {}",
format!("{:#}", result.0)
.lines()
.map(|line| line.cyan().to_string())
.collect::<Vec<_>>()
.join("\n")
);

for line in result.lines() {
println!(" > {line}");
}
}
ResponseBody::Error(error) => {
println!("{error}");
}
}
}
}

Expand All @@ -68,17 +90,11 @@ impl CallCommand {

let url = multiaddr_to_url(multiaddr, "jsonrpc/dev")?;

let json_payload: Value = serde_json::from_str(&self.args_json)?;
let payload = RequestPayload::Execute(ExecuteRequest::new(
self.context_id,
self.method,
json_payload,
config
.identity
.public()
.try_into_ed25519()?
.to_bytes()
.into(),
self.args.unwrap_or(json!({})),
self.executor,
));

let request = Request::new(
Expand All @@ -87,11 +103,6 @@ impl CallCommand {
payload,
);

match serde_json::to_string_pretty(&request) {
Ok(json) => println!("Request JSON:\n{json}"),
Err(e) => println!("Error serializing request to JSON: {e}"),
}

let client = reqwest::Client::new();
let response: Response = do_request(
&client,
Expand Down
1 change: 0 additions & 1 deletion crates/merod/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ pub const EXAMPLES: &str = r"
"Examples:",
EXAMPLES
))]

pub struct RootCommand {
#[command(flatten)]
pub args: RootArgs,
Expand Down
Loading

0 comments on commit e00ba00

Please sign in to comment.