Skip to content

Commit

Permalink
use alloy
Browse files Browse the repository at this point in the history
  • Loading branch information
capossele committed Oct 3, 2024
1 parent 6ba787d commit fd7e1ce
Show file tree
Hide file tree
Showing 10 changed files with 451 additions and 1,960 deletions.
2,080 changes: 251 additions & 1,829 deletions Cargo.lock

Large diffs are not rendered by default.

17 changes: 9 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,22 @@ version = "0.1.0"
edition = "2021"

[workspace.dependencies]
alloy-primitives = { version = "0.7", default-features = false, features = ["rlp", "serde", "std"] }
alloy-sol-types = { version = "0.7" }
alloy = { version = "=0.3.3", features = ["full"] }
alloy-primitives = { version = "=0.8.3", default-features = false, features = ["rlp", "serde", "std"] }
alloy-sol-types = { version = "=0.8.3" }
anyhow = { version = "1.0.75" }
bincode = { version = "1.3" }
bytemuck = { version = "1.14" }
ethers = { version = "2.0" }
hex = { version = "0.4" }
log = { version = "0.4" }
methods = { path = "./methods" }
risc0-build = { version = "1.1.0-rc.1", features = ["docker"] }
risc0-build-ethereum = { git = "https://github.com/risc0/risc0-ethereum", tag = "v1.1.0-rc.1" }
risc0-ethereum-contracts = { git = "https://github.com/risc0/risc0-ethereum", tag = "v1.1.0-rc.1" }
risc0-zkvm = { version = "1.1.0-rc.1", default-features = false }
risc0-zkp = { version = "1.1.0-rc.1", default-features = false }
risc0-build = { version = "1.1", features = ["docker"] }
risc0-build-ethereum = { git = "https://github.com/risc0/risc0-ethereum", tag = "v1.1.2" }
risc0-ethereum-contracts = { git = "https://github.com/risc0/risc0-ethereum", tag = "v1.1.2" }
risc0-zkvm = { version = "1.1", default-features = false }
risc0-zkp = { version = "1.1", default-features = false }
serde = { version = "1.0", features = ["derive", "std"] }
url = { version = "2.5" }

[profile.release]
debug = 1
Expand Down
3 changes: 2 additions & 1 deletion apps/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ version = { workspace = true }
edition = { workspace = true }

[dependencies]
alloy = { workspace = true }
alloy-primitives = { workspace = true }
alloy-sol-types = { workspace = true }
anyhow = { workspace = true }
clap = { version = "4.0", features = ["derive", "env"] }
env_logger = { version = "0.10" }
ethers = { workspace = true }
log = { workspace = true }
methods = { workspace = true }
risc0-ethereum-contracts = { workspace = true }
risc0-zkvm = { workspace = true, features = ["client"] }
tokio = { version = "1.35", features = ["full"] }
url = { workspace = true }
90 changes: 24 additions & 66 deletions apps/src/bin/publisher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,62 +16,23 @@
// to the Bonsai proving service and publish the received proofs directly
// to your deployed app contract.

use alloy_primitives::U256;
use alloy_sol_types::{sol, SolInterface, SolValue};
use alloy::{
network::EthereumWallet, providers::ProviderBuilder, signers::local::PrivateKeySigner,
sol_types::SolValue,
};
use alloy_primitives::{Address, U256};
use anyhow::{Context, Result};
use clap::Parser;
use ethers::prelude::*;
use methods::IS_EVEN_ELF;
use risc0_ethereum_contracts::encode_seal;
use risc0_zkvm::{default_prover, ExecutorEnv, ProverOpts, VerifierContext};
use url::Url;

// `IEvenNumber` interface automatically generated via the alloy `sol!` macro.
sol! {
interface IEvenNumber {
function set(uint256 x, bytes calldata seal);
}
}

/// Wrapper of a `SignerMiddleware` client to send transactions to the given
/// contract's `Address`.
pub struct TxSender {
chain_id: u64,
client: SignerMiddleware<Provider<Http>, Wallet<k256::ecdsa::SigningKey>>,
contract: Address,
}

impl TxSender {
/// Creates a new `TxSender`.
pub fn new(chain_id: u64, rpc_url: &str, private_key: &str, contract: &str) -> Result<Self> {
let provider = Provider::<Http>::try_from(rpc_url)?;
let wallet: LocalWallet = private_key.parse::<LocalWallet>()?.with_chain_id(chain_id);
let client = SignerMiddleware::new(provider.clone(), wallet.clone());
let contract = contract.parse::<Address>()?;

Ok(TxSender {
chain_id,
client,
contract,
})
}

/// Send a transaction with the given calldata.
pub async fn send(&self, calldata: Vec<u8>) -> Result<Option<TransactionReceipt>> {
let tx = TransactionRequest::new()
.chain_id(self.chain_id)
.to(self.contract)
.from(self.client.address())
.data(calldata);

log::info!("Transaction request: {:?}", &tx);

let tx = self.client.send_transaction(tx, None).await?.await?;

log::info!("Transaction receipt: {:?}", &tx);

Ok(tx)
}
}
alloy::sol!(
#[sol(rpc, all_derives)]
"../contracts/IEvenNumber.sol"
);

/// Arguments of the publisher CLI.
#[derive(Parser, Debug)]
Expand All @@ -83,15 +44,15 @@ struct Args {

/// Ethereum Node endpoint.
#[clap(long, env)]
eth_wallet_private_key: String,
eth_wallet_private_key: PrivateKeySigner,

/// Ethereum Node endpoint.
#[clap(long)]
rpc_url: String,
rpc_url: Url,

/// Application's contract address on Ethereum
#[clap(long)]
contract: String,
contract: Address,

/// The input to provide to the guest binary
#[clap(short, long)]
Expand All @@ -103,13 +64,12 @@ fn main() -> Result<()> {
// Parse CLI Arguments: The application starts by parsing command-line arguments provided by the user.
let args = Args::parse();

// Create a new transaction sender using the parsed arguments.
let tx_sender = TxSender::new(
args.chain_id,
&args.rpc_url,
&args.eth_wallet_private_key,
&args.contract,
)?;
// Create an alloy provider for that private key and URL.
let wallet = EthereumWallet::from(args.eth_wallet_private_key);
let provider = ProviderBuilder::new()
.with_recommended_fillers()
.wallet(wallet)
.on_http(args.rpc_url);

// ABI encode input: Before sending the proof request to the Bonsai proving service,
// the input number is ABI-encoded to match the format expected by the guest code running in the zkVM.
Expand Down Expand Up @@ -140,18 +100,16 @@ fn main() -> Result<()> {
// Construct function call: Using the IEvenNumber interface, the application constructs
// the ABI-encoded function call for the set function of the EvenNumber contract.
// This call includes the verified number, the post-state digest, and the seal (proof).
let calldata = IEvenNumber::IEvenNumberCalls::set(IEvenNumber::setCall {
x,
seal: seal.into(),
})
.abi_encode();
let contract = IEvenNumber::new(args.contract, provider);
let call_builder = contract.set(x, seal.into());

// Initialize the async runtime environment to handle the transaction sending.
let runtime = tokio::runtime::Runtime::new()?;

// Send transaction: Finally, the TxSender component sends the transaction to the Ethereum blockchain,
// Send transaction: Finally, send the transaction to the Ethereum blockchain,
// effectively calling the set function of the EvenNumber contract with the verified number and proof.
runtime.block_on(tx_sender.send(calldata))?;
let pending_tx = runtime.block_on(call_builder.send())?;
runtime.block_on(pending_tx.get_receipt())?;

Ok(())
}
2 changes: 1 addition & 1 deletion contracts/EvenNumber.sol
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {ImageID} from "./ImageID.sol"; // auto-generated contract after running
/// @title A starter application using RISC Zero.
/// @notice This basic application holds a number, guaranteed to be even.
/// @dev This contract demonstrates one pattern for offloading the computation of an expensive
/// or difficult to implement function to a RISC Zero guest running on Bonsai.
/// or difficult to implement function to a RISC Zero guest running on the zkVM.
contract EvenNumber {
/// @notice RISC Zero verifier contract address.
IRiscZeroVerifier public immutable verifier;
Expand Down
29 changes: 29 additions & 0 deletions contracts/IEvenNumber.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright 2024 RISC Zero, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.20;

/// @title A starter application using RISC Zero.
/// @notice This basic application holds a number, guaranteed to be even.
/// @dev This contract demonstrates one pattern for offloading the computation of an expensive
/// or difficult to implement function to a RISC Zero guest running on the zkVM.
interface IEvenNumber {
/// @notice Set the even number stored on the contract. Requires a RISC Zero proof that the number is even.
function set(uint256 x, bytes calldata seal) external;

/// @notice Returns the number stored.
function get() external view returns (uint256);
}
2 changes: 1 addition & 1 deletion lib/risc0-ethereum
Submodule risc0-ethereum updated 109 files
Loading

0 comments on commit fd7e1ce

Please sign in to comment.