Skip to content

Commit 2dad809

Browse files
committed
fix: contract call through account, impl: reward
1 parent e5f160c commit 2dad809

File tree

7 files changed

+91
-67
lines changed

7 files changed

+91
-67
lines changed

crates/common/src/job.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,12 @@ pub struct JobData {
5252
}
5353

5454
impl JobData {
55-
pub fn new(reward: u64, cairo_pie_compressed: Vec<u8>, registry_address: FieldElement) -> Self {
55+
pub fn new(tip: u64, cairo_pie_compressed: Vec<u8>, registry_address: FieldElement) -> Self {
5656
let pie = Self::decompress_cairo_pie(&cairo_pie_compressed);
57-
Self {
58-
reward,
59-
num_of_steps: pie.execution_resources.n_steps as u64,
60-
cairo_pie_compressed,
61-
registry_address,
62-
}
57+
let num_of_steps = pie.execution_resources.n_steps as u64;
58+
// TODO - calculate reward based on the number of steps and the tip
59+
let reward = num_of_steps * 100 + tip;
60+
Self { reward, num_of_steps, cairo_pie_compressed, registry_address }
6361
}
6462

6563
fn decompress_cairo_pie(cairo_pie_compressed: &[u8]) -> CairoPie {

crates/common/src/node_account.rs

+46-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
use std::error::Error;
2+
13
use starknet::{
2-
accounts::{ConnectedAccount, ExecutionEncoding, SingleOwnerAccount},
4+
accounts::{Account, Call, ConnectedAccount, ExecutionEncoding, SingleOwnerAccount},
35
core::types::FieldElement,
6+
macros::selector,
47
providers::Provider,
58
signers::{LocalWallet, SigningKey, VerifyingKey},
69
};
@@ -62,4 +65,46 @@ where
6265
pub fn get_verifying_key(&self) -> VerifyingKey {
6366
self.signing_key.verifying_key()
6467
}
68+
69+
pub async fn stake(
70+
&self,
71+
amount: FieldElement,
72+
registry_address: FieldElement,
73+
) -> Result<(), Box<dyn Error>> {
74+
let result = self
75+
.account
76+
.execute(vec![Call {
77+
to: registry_address,
78+
selector: selector!("stake"),
79+
calldata: vec![amount],
80+
}])
81+
.send()
82+
.await
83+
.unwrap();
84+
85+
println!("Stake result: {:?}", result);
86+
Ok(())
87+
}
88+
89+
pub async fn balance_of(
90+
&self,
91+
registry_address: FieldElement,
92+
) -> Result<Vec<FieldElement>, Box<dyn Error>> {
93+
let account_address = self.account.address();
94+
// let call_result = self
95+
// .get_provider()
96+
// .call(
97+
// FunctionCall {
98+
// contract_address: registry_address,
99+
// entry_point_selector: selector!("balanceOf"),
100+
// calldata: vec![account_address],
101+
// },
102+
// BlockId::Tag(BlockTag::Latest),
103+
// )
104+
// .await
105+
// .expect("failed to call contract");
106+
107+
// println!("Stake result: {:?}", call_result);
108+
Ok(vec![FieldElement::from(100u64)])
109+
}
65110
}

crates/compiler/src/cairo_compiler/mod.rs

+14-17
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,8 @@ use async_process::Stdio;
33
use futures::Future;
44
use rand::{thread_rng, Rng};
55
use serde_json::json;
6-
use sharp_p2p_common::job::JobData;
76
use sharp_p2p_common::layout::Layout;
8-
use sharp_p2p_common::{job::Job, process::Process};
9-
use starknet::signers::SigningKey;
10-
use starknet_crypto::FieldElement;
7+
use sharp_p2p_common::process::Process;
118
use std::io::Write;
129
use std::path::PathBuf;
1310
use std::{io::Read, pin::Pin};
@@ -17,25 +14,28 @@ use tracing::debug;
1714

1815
pub mod tests;
1916

20-
pub struct CairoCompiler<'identity> {
21-
signing_key: &'identity SigningKey,
22-
registry_contract: FieldElement,
17+
pub struct CairoCompiler {}
18+
19+
impl CairoCompiler {
20+
pub fn new() -> Self {
21+
Self {}
22+
}
2323
}
2424

25-
impl<'identity> CairoCompiler<'identity> {
26-
pub fn new(signing_key: &'identity SigningKey, registry_contract: FieldElement) -> Self {
27-
Self { signing_key, registry_contract }
25+
impl Default for CairoCompiler {
26+
fn default() -> Self {
27+
Self::new()
2828
}
2929
}
3030

31-
impl<'identity> CompilerController for CairoCompiler<'identity> {
31+
impl CompilerController for CairoCompiler {
3232
fn run(
3333
&self,
3434
program_path: PathBuf,
3535
_program_input_path: PathBuf,
36-
) -> Result<Process<Result<Job, CompilerControllerError>>, CompilerControllerError> {
36+
) -> Result<Process<Result<Vec<u8>, CompilerControllerError>>, CompilerControllerError> {
3737
let (terminate_tx, mut terminate_rx) = mpsc::channel::<()>(10);
38-
let future: Pin<Box<dyn Future<Output = Result<Job, CompilerControllerError>> + '_>> =
38+
let future: Pin<Box<dyn Future<Output = Result<Vec<u8>, CompilerControllerError>> + '_>> =
3939
Box::pin(async move {
4040
let layout: &str = Layout::RecursiveWithPoseidon.into();
4141

@@ -118,10 +118,7 @@ impl<'identity> CompilerController for CairoCompiler<'identity> {
118118
let mut cairo_pie_compressed = Vec::new();
119119
cairo_pie.read_to_end(&mut cairo_pie_compressed)?;
120120

121-
Ok(Job::try_from_job_data(
122-
JobData::new(0, cairo_pie_compressed, self.registry_contract),
123-
self.signing_key,
124-
))
121+
Ok(cairo_pie_compressed)
125122
});
126123

127124
Ok(Process::new(future, terminate_tx))

crates/compiler/src/cairo_compiler/tests/single_job.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,20 @@ use crate::{
33
traits::CompilerController,
44
};
55
use starknet::signers::SigningKey;
6-
use starknet_crypto::FieldElement;
76

87
#[tokio::test]
98
async fn run_single_job() {
109
let fixture = fixture();
11-
let identity = SigningKey::from_random();
12-
let compiler = CairoCompiler::new(&identity, FieldElement::ZERO);
10+
let _identity = SigningKey::from_random();
11+
let compiler = CairoCompiler::new();
1312
compiler.run(fixture.program_path, fixture.program_input_path).unwrap().await.unwrap();
1413
}
1514

1615
#[tokio::test]
1716
async fn abort_single_jobs() {
1817
let fixture = fixture();
19-
let identity = SigningKey::from_random();
20-
let compiler = CairoCompiler::new(&identity, FieldElement::ZERO);
18+
let _identity = SigningKey::from_random();
19+
let compiler = CairoCompiler::new();
2120
let job = compiler.run(fixture.program_path, fixture.program_input_path).unwrap();
2221
job.abort().await.unwrap();
2322
job.await.unwrap_err();

crates/compiler/src/traits.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
11
use crate::errors::CompilerControllerError;
2-
use sharp_p2p_common::{job::Job, process::Process};
2+
use sharp_p2p_common::process::Process;
33
use std::path::PathBuf;
44

55
/*
66
The `CompilerController` trait is responsible for taking a user's program and preparing a `Job` object.
77
This process involves compiling the user's code and creating a Cairo PIE (Proof-of-Inclusion-Execution) object from it.
8-
The resulting `Job` object encapsulates the necessary information for later execution by a `RunnerController`.
9-
The `run` method accepts the paths to the program and its input, returning a `Result` containing a `Process` object.
10-
Upon successful completion, it yields a `Job` object, ready to be utilized by a `RunnerController` to execute the program.
8+
The resulting `Vec<u8>` object that represents the Cairo PIE is then compressed and stored in the `JobData` object.
9+
Later, the `Job` object is then signed by the delegator's private key and sent to the network for execution.
1110
*/
1211

1312
pub trait CompilerController {
1413
fn run(
1514
&self,
1615
program_path: PathBuf,
1716
program_input_path: PathBuf,
18-
) -> Result<Process<Result<Job, CompilerControllerError>>, CompilerControllerError>;
17+
) -> Result<Process<Result<Vec<u8>, CompilerControllerError>>, CompilerControllerError>;
1918
}

crates/delegator/src/main.rs

+17-4
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use futures::{stream::FuturesUnordered, StreamExt};
44
use libp2p::gossipsub::Event;
55
use sharp_p2p_common::{
66
hash,
7-
job::Job,
7+
job::{Job, JobData},
88
network::Network,
99
node_account::NodeAccount,
1010
process::Process,
@@ -60,13 +60,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
6060
let mut message_stream = swarm_runner.run(new_job_topic, send_topic_rx);
6161
let mut event_stream = registry_handler.subscribe_events(vec!["0x0".to_string()]);
6262

63-
let compiler = CairoCompiler::new(node_account.get_signing_key(), registry_address);
63+
let compiler = CairoCompiler::new();
6464

6565
let mut compiler_scheduler =
66-
FuturesUnordered::<Process<'_, Result<Job, CompilerControllerError>>>::new();
66+
FuturesUnordered::<Process<'_, Result<Vec<u8>, CompilerControllerError>>>::new();
6767

6868
// Read cairo program path from stdin
6969
let mut stdin = BufReader::new(stdin()).lines();
70+
// TODO: Accept dynamic tip
71+
let tip = 10;
7072

7173
loop {
7274
tokio::select! {
@@ -104,7 +106,18 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
104106
Some(Ok(event_vec)) = event_stream.next() => {
105107
debug!("{:?}", event_vec);
106108
},
107-
Some(Ok(job)) = compiler_scheduler.next() => {
109+
Some(Ok(cairo_pie_compressed)) = compiler_scheduler.next() => {
110+
let job_data = JobData::new(tip, cairo_pie_compressed,registry_address);
111+
let expected_reward = job_data.reward;
112+
let staked_amount = node_account.balance_of(registry_address).await?;
113+
// TODO: handle error better way
114+
if staked_amount[0] < expected_reward.into() {
115+
// return error
116+
return Err("Staked amount is less than expected reward".into());
117+
}
118+
let job = Job::try_from_job_data(job_data, node_account.get_signing_key());
119+
// info!("Job: {:?}", job.job_data.reward);
120+
// info!("Job: {:?}", job.job_data.num_of_steps);
108121
let serialized_job = serde_json::to_string(&job).unwrap();
109122
send_topic_tx.send(serialized_job.into()).await?;
110123
info!("Sent a new job: {}", hash!(&job));

crates/peer/src/registry.rs

+1-28
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
11
use async_stream::try_stream;
22
use futures::stream::Stream;
33
use starknet::{
4-
accounts::{Account, Call, SingleOwnerAccount},
5-
core::{
6-
types::{BlockId, EmittedEvent, EventFilter, FieldElement},
7-
utils::get_selector_from_name,
8-
},
4+
core::types::{BlockId, EmittedEvent, EventFilter, FieldElement},
95
providers::Provider,
10-
signers::Signer,
116
};
127
use std::{error::Error, pin::Pin};
138
use tracing::trace;
@@ -78,26 +73,4 @@ where
7873
};
7974
Box::pin(stream)
8075
}
81-
82-
pub async fn stake<S>(
83-
&self,
84-
amount: FieldElement,
85-
account: SingleOwnerAccount<P, S>,
86-
) -> Result<(), Box<dyn Error>>
87-
where
88-
S: Signer + Sync + Send + 'static,
89-
{
90-
let result = account
91-
.execute(vec![Call {
92-
to: self.registry_address,
93-
selector: get_selector_from_name("stake").unwrap(),
94-
calldata: vec![amount],
95-
}])
96-
.send()
97-
.await
98-
.unwrap();
99-
100-
trace!("Stake result: {:?}", result);
101-
Ok(())
102-
}
10376
}

0 commit comments

Comments
 (0)