Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(katana): modify DevApi trait with new endpoints #2490

Open
wants to merge 27 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
5347bc3
Modify DevApi trait with new endpoints
fabrobles92 Oct 1, 2024
75155c0
Implementation of account_balance method
fabrobles92 Oct 3, 2024
e2612e3
clippy.sh and rust_fmt.sh
fabrobles92 Oct 3, 2024
9902cfe
Replace RPC call with querying the storage directly
fabrobles92 Oct 11, 2024
b2e3ad4
-Re implement proxy_get_request.rs
fabrobles92 Oct 22, 2024
3947795
cargo fmt
fabrobles92 Oct 22, 2024
c23d9eb
Merge branch 'main' into feat/expose_dev_endpoints
fabrobles92 Oct 23, 2024
5a3865c
update cargo.lock
fabrobles92 Oct 30, 2024
8c4a8b8
Merge branch 'main' into feat/expose_dev_endpoints
fabrobles92 Oct 30, 2024
8e08862
Keep ProxyGetRequestLayer for / (health) endpoint
fabrobles92 Oct 30, 2024
e4666bc
Enable query param contract_address for endpoint account_balance
fabrobles92 Oct 31, 2024
0bf530d
Merge branch 'main' into feat/expose_dev_endpoints
fabrobles92 Oct 31, 2024
3ec9a5e
cargo fmt
fabrobles92 Oct 31, 2024
378ae06
Remove unused files
fabrobles92 Dec 7, 2024
9411eb5
Update cargo
fabrobles92 Dec 7, 2024
23cd841
Merge branch 'main' into feat/expose_dev_endpoints
fabrobles92 Dec 7, 2024
8e61aa4
- Accepting unit param
fabrobles92 Dec 13, 2024
0f2380d
Merge branch 'main' into feat/expose_dev_endpoints
fabrobles92 Dec 13, 2024
01f69c2
Fix cargo, removing duplicates
fabrobles92 Dec 13, 2024
78c2180
Implement Devnet Proxy Layer in new implementation
fabrobles92 Dec 13, 2024
1aafb25
Merge branch 'main' into feat/expose_dev_endpoints
fabrobles92 Jan 3, 2025
c8d2444
Clean unused code
fabrobles92 Jan 3, 2025
2cb90f1
clippy.sh
fabrobles92 Jan 3, 2025
0c14c03
rust_fmt.sh
fabrobles92 Jan 4, 2025
3d73532
Fix default case in match and early return when invalid route provided
fabrobles92 Jan 4, 2025
17a53b5
Fix error when returning response when route is not known in DevnetPr…
fabrobles92 Jan 4, 2025
5c6981b
Apply code rabbit suggestions
fabrobles92 Jan 9, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions Cargo.lock

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

3 changes: 3 additions & 0 deletions crates/katana/node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ use katana_pool::TxPool;
use katana_primitives::env::{CfgEnv, FeeTokenAddressses};
use katana_rpc::dev::DevApi;
use katana_rpc::metrics::RpcServerMetrics;
use katana_rpc::proxy_get_request::DevnetProxyLayer;
use katana_rpc::saya::SayaApi;
use katana_rpc::starknet::forking::ForkedClient;
use katana_rpc::starknet::StarknetApi;
Expand Down Expand Up @@ -308,6 +309,8 @@ pub async fn spawn<EF: ExecutorFactory>(
let middleware = tower::ServiceBuilder::new()
.option_layer(cors)
.layer(ProxyGetRequestLayer::new("/", "health")?)
.layer(DevnetProxyLayer::new("/account_balance", "dev_accountBalance")?)
.layer(DevnetProxyLayer::new("/fee_token", "dev_feeToken")?)
.timeout(Duration::from_secs(20));

let server = ServerBuilder::new()
Expand Down
9 changes: 9 additions & 0 deletions crates/katana/rpc/rpc-api/src/dev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,13 @@ pub trait DevApi {

#[method(name = "predeployedAccounts")]
async fn predeployed_accounts(&self) -> RpcResult<Vec<Account>>;

#[method(name = "accountBalance")]
async fn account_balance(&self, address: String) -> RpcResult<u128>;

#[method(name = "feeToken")]
async fn fee_token(&self) -> RpcResult<String>;

#[method(name = "mint")]
async fn mint(&self) -> RpcResult<()>;
}
16 changes: 16 additions & 0 deletions crates/katana/rpc/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ anyhow.workspace = true
dojo-metrics.workspace = true
futures.workspace = true
jsonrpsee = { workspace = true, features = [ "server" ] }
jsonrpsee-core = { version = "0.16.3", features = [ "server", "soketto", "http-helpers" ] }
jsonrpsee-types = { version = "0.16.3"}
hyper.workspace = true
tower = { workspace = true, features = [ "full" ] }
http = { version = "0.2.7" }
katana-core.workspace = true
katana-executor.workspace = true
katana-pool.workspace = true
Expand All @@ -26,6 +31,17 @@ thiserror.workspace = true
tokio.workspace = true
tracing.workspace = true
url.workspace = true
serde.workspace = true
serde_json.workspace = true
soketto = { version = "0.7.1", features = ["http"] }
futures-channel = { version = "0.3.14"}
futures-util = { version = "0.3.14", features = [
"io",
"async-await-macro",
]}
tokio-stream = { version = "0.1.7" }
tokio-util = { version = "0.7", features = ["compat"]}
starknet-crypto.workspace = true

[dev-dependencies]
alloy = { git = "https://github.com/alloy-rs/alloy", features = [ "contract", "network", "node-bindings", "provider-http", "providers", "signer-local" ] }
Expand Down
38 changes: 36 additions & 2 deletions crates/katana/rpc/rpc/src/dev.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
use std::str::FromStr;
use std::sync::Arc;

use jsonrpsee::core::{async_trait, Error};
use katana_core::backend::Backend;
use katana_core::service::block_producer::{BlockProducer, BlockProducerMode, PendingExecutor};
use katana_executor::ExecutorFactory;
use katana_primitives::Felt;
use katana_primitives::genesis::constant::{
get_fee_token_balance_base_storage_address, ERC20_NAME_STORAGE_SLOT,
};
use katana_primitives::ContractAddress;
use katana_provider::traits::state::StateFactoryProvider;
use katana_rpc_api::dev::DevApiServer;
use katana_rpc_types::account::Account;
use katana_rpc_types::error::dev::DevApiError;
use starknet_crypto::Felt;

#[allow(missing_debug_implementations)]
pub struct DevApi<EF: ExecutorFactory> {
Expand Down Expand Up @@ -54,7 +60,6 @@

let mut block_context_generator = self.backend.block_context_generator.write();
block_context_generator.block_timestamp_offset += offset as i64;

Ok(())
}
}
Expand Down Expand Up @@ -92,6 +97,35 @@
Ok(())
}

async fn account_balance(&self, address: String) -> Result<u128, Error> {
let account_address: ContractAddress = Felt::from_str(&address).unwrap().into();
let provider = self.backend.blockchain.provider();
let state = provider.latest().unwrap();
// let storage_slot =
// get_storage_var_address("ERC20_balances", &[account_address.into()]).unwrap();
let storage_slot = get_fee_token_balance_base_storage_address(account_address);
let balance_felt = state
.storage(self.backend.chain_spec.fee_contracts.eth, storage_slot)
.unwrap()
.unwrap();
let balance: u128 = balance_felt.to_string().parse().unwrap();
Ok(balance)
}

Check warning on line 113 in crates/katana/rpc/rpc/src/dev.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/dev.rs#L100-L113

Added lines #L100 - L113 were not covered by tests
fabrobles92 marked this conversation as resolved.
Show resolved Hide resolved

async fn fee_token(&self) -> Result<String, Error> {
let provider = self.backend.blockchain.provider();
let state = provider.latest().unwrap();
let fee_token = state
.storage(self.backend.chain_spec.fee_contracts.eth, ERC20_NAME_STORAGE_SLOT)
.unwrap()
.unwrap();
Ok(fee_token.to_string())
}

Check warning on line 123 in crates/katana/rpc/rpc/src/dev.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/dev.rs#L115-L123

Added lines #L115 - L123 were not covered by tests
fabrobles92 marked this conversation as resolved.
Show resolved Hide resolved

async fn mint(&self) -> Result<(), Error> {
Ok(())
}

Check warning on line 127 in crates/katana/rpc/rpc/src/dev.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/dev.rs#L125-L127

Added lines #L125 - L127 were not covered by tests

async fn predeployed_accounts(&self) -> Result<Vec<Account>, Error> {
Ok(self.backend.chain_spec.genesis.accounts().map(|e| Account::new(*e.0, e.1)).collect())
}
Expand Down
216 changes: 216 additions & 0 deletions crates/katana/rpc/rpc/src/future.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
//
// 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.

//! Utilities for handling async code.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use futures_util::future::FutureExt;
use jsonrpsee_core::Error;
use tokio::sync::{watch, OwnedSemaphorePermit, Semaphore, TryAcquireError};
use tokio::time::{self, Duration, Interval};

/// Polling for server stop monitor interval in milliseconds.
const STOP_MONITOR_POLLING_INTERVAL: Duration = Duration::from_millis(1000);

/// This is a flexible collection of futures that need to be driven to completion
/// alongside some other future, such as connection handlers that need to be
/// handled along with a listener for new connections.
///
/// In order to `.await` on these futures and drive them to completion, call
/// `select_with` providing some other future, the result of which you need.
pub(crate) struct FutureDriver<F> {
futures: Vec<F>,
stop_monitor_heartbeat: Interval,
}

impl<F> Default for FutureDriver<F> {
fn default() -> Self {
let mut heartbeat = time::interval(STOP_MONITOR_POLLING_INTERVAL);

heartbeat.set_missed_tick_behavior(time::MissedTickBehavior::Skip);

FutureDriver { futures: Vec::new(), stop_monitor_heartbeat: heartbeat }
}

Check warning on line 60 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L54-L60

Added lines #L54 - L60 were not covered by tests
}

impl<F> FutureDriver<F> {
/// Add a new future to this driver
pub(crate) fn add(&mut self, future: F) {
self.futures.push(future);
}

Check warning on line 67 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L65-L67

Added lines #L65 - L67 were not covered by tests
}

impl<F> FutureDriver<F>
where
F: Future + Unpin,
{
pub(crate) async fn select_with<S: Future>(&mut self, selector: S) -> S::Output {
tokio::pin!(selector);

DriverSelect { selector, driver: self }.await
}

Check warning on line 78 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L74-L78

Added lines #L74 - L78 were not covered by tests

fn drive(&mut self, cx: &mut Context) {
let mut i = 0;

Check warning on line 81 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L80-L81

Added lines #L80 - L81 were not covered by tests

while i < self.futures.len() {
if self.futures[i].poll_unpin(cx).is_ready() {
// Using `swap_remove` since we don't care about ordering
// but we do care about removing being `O(1)`.
//
// We don't increment `i` in this branch, since we now
// have a shorter length, and potentially a new value at
// current index
self.futures.swap_remove(i);
} else {
i += 1;
}

Check warning on line 94 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L83-L94

Added lines #L83 - L94 were not covered by tests
}
}

Check warning on line 96 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L96

Added line #L96 was not covered by tests

fn poll_stop_monitor_heartbeat(&mut self, cx: &mut Context) {
// We don't care about the ticks of the heartbeat, it's here only
// to periodically wake the `Waker` on `cx`.
let _ = self.stop_monitor_heartbeat.poll_tick(cx);
}

Check warning on line 102 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L98-L102

Added lines #L98 - L102 were not covered by tests
}

impl<F> Future for FutureDriver<F>
where
F: Future + Unpin,
{
type Output = ();

fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let this = Pin::into_inner(self);

this.drive(cx);

if this.futures.is_empty() { Poll::Ready(()) } else { Poll::Pending }
}

Check warning on line 117 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L111-L117

Added lines #L111 - L117 were not covered by tests
}

/// This is a glorified select `Future` that will attempt to drive all
/// connection futures `F` to completion on each `poll`, while also
/// handling incoming connections.
struct DriverSelect<'a, S, F> {
selector: S,
driver: &'a mut FutureDriver<F>,
}

impl<'a, R, F> Future for DriverSelect<'a, R, F>
where
R: Future + Unpin,
F: Future + Unpin,
{
type Output = R::Output;

fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let this = Pin::into_inner(self);

this.driver.drive(cx);
this.driver.poll_stop_monitor_heartbeat(cx);

this.selector.poll_unpin(cx)
}

Check warning on line 142 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L135-L142

Added lines #L135 - L142 were not covered by tests
}

#[derive(Debug, Clone)]
pub(crate) struct StopHandle(watch::Receiver<()>);

impl StopHandle {
pub(crate) fn new(rx: watch::Receiver<()>) -> Self {
Self(rx)
}

Check warning on line 151 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L149-L151

Added lines #L149 - L151 were not covered by tests

pub(crate) fn shutdown_requested(&self) -> bool {
// if a message has been seen, it means that `stop` has been called.
self.0.has_changed().unwrap_or(true)
}

Check warning on line 156 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L153-L156

Added lines #L153 - L156 were not covered by tests

pub(crate) async fn shutdown(&mut self) {
// Err(_) implies that the `sender` has been dropped.
// Ok(_) implies that `stop` has been called.
let _ = self.0.changed().await;
}

Check warning on line 162 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L158-L162

Added lines #L158 - L162 were not covered by tests
}

/// Server handle.
///
/// When all [`StopHandle`]'s have been `dropped` or `stop` has been called
/// the server will be stopped.
#[derive(Debug, Clone)]
pub struct ServerHandle(Arc<watch::Sender<()>>);

impl ServerHandle {
/// Create a new server handle.
pub fn new(tx: watch::Sender<()>) -> Self {
Self(Arc::new(tx))
}

Check warning on line 176 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L174-L176

Added lines #L174 - L176 were not covered by tests

/// Tell the server to stop without waiting for the server to stop.
pub fn stop(&self) -> Result<(), Error> {
self.0.send(()).map_err(|_| Error::AlreadyStopped)
}

Check warning on line 181 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L179-L181

Added lines #L179 - L181 were not covered by tests

/// Wait for the server to stop.
pub async fn stopped(self) {
self.0.closed().await
}

Check warning on line 186 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L184-L186

Added lines #L184 - L186 were not covered by tests

/// Check if the server has been stopped.
pub fn is_stopped(&self) -> bool {
self.0.is_closed()
}

Check warning on line 191 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L189-L191

Added lines #L189 - L191 were not covered by tests
}

/// Limits the number of connections.
#[derive(Debug)]
pub(crate) struct ConnectionGuard(Arc<Semaphore>);

impl ConnectionGuard {
pub(crate) fn new(limit: usize) -> Self {
Self(Arc::new(Semaphore::new(limit)))
}

Check warning on line 201 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L199-L201

Added lines #L199 - L201 were not covered by tests

pub(crate) fn try_acquire(&self) -> Option<OwnedSemaphorePermit> {
match self.0.clone().try_acquire_owned() {
Ok(guard) => Some(guard),

Check warning on line 205 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L203-L205

Added lines #L203 - L205 were not covered by tests
Err(TryAcquireError::Closed) => {
unreachable!("Semaphore::Close is never called and can't be closed; qed")

Check warning on line 207 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L207

Added line #L207 was not covered by tests
}
Err(TryAcquireError::NoPermits) => None,

Check warning on line 209 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L209

Added line #L209 was not covered by tests
}
}

Check warning on line 211 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L211

Added line #L211 was not covered by tests

pub(crate) fn available_connections(&self) -> usize {
self.0.available_permits()
}

Check warning on line 215 in crates/katana/rpc/rpc/src/future.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/rpc/rpc/src/future.rs#L213-L215

Added lines #L213 - L215 were not covered by tests
}
5 changes: 5 additions & 0 deletions crates/katana/rpc/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@

pub mod dev;
pub mod metrics;
pub mod proxy_get_request;
pub mod saya;
pub mod starknet;
pub mod torii;

mod future;
mod logger;
mod server;
mod transport;
mod utils;
Loading
Loading