-
Notifications
You must be signed in to change notification settings - Fork 77
Add compound APR example that uses multi-call #95
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
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
286bfec
feat: option for multi view call APIs
austinabell 5d34417
update examples to use new APIs
austinabell 2873c31
remove commented out code
austinabell f238fd9
basic functionality to pull data from block at given point
austinabell 05e737c
update example to query yield and switch to multicall like APIs
austinabell 32d7222
update to v3 contract and derive debug/eq for BlockCommitment
austinabell 1d5fad4
add license
austinabell 577dad6
update interface name to match ABI
austinabell 7095e01
Merge branch 'main' into austin/historical_example
Wollac 898a1fd
derive traits for SolCommit
Wollac 5efd59e
fix token stats example
Wollac 272dfe0
fix license
Wollac d28244b
Merge branch 'main' into austin/historical_example
Wollac da65e22
Merge branch 'main' into austin/historical_example
nategraf 4066a91
Apply suggestions from code review
Wollac 899f9fc
Merge branch 'main' into austin/historical_example
Wollac 1ed3fac
add token-stats to examples CI job
Wollac File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,22 @@ | ||
# Examples | ||
|
||
## [erc20] | ||
## [ERC20 Balance Query](./erc20/README.md) | ||
|
||
This example uses the [Steel] view call library to query the ERC20 interface's `balanceOf` method for a specific address within the RISC Zero zkVM. | ||
This introductory example illustrates how to use [Steel] to directly query the `balanceOf` function of any ERC20 token contract, providing a verifiable proof of a user's token balance. | ||
|
||
## [erc20-counter] | ||
## [ERC20 Counter with Off-Chain Proofs](./erc20-counter/README.md) | ||
|
||
This example implements a counter that increments based on off-chain view call proofs submitted to the [Counter] contract. | ||
The contract interacts with ERC-20 tokens, using view call proofs to verify that an account holds at least 1 token before incrementing the counter. | ||
This contract leverages RISC Zero as a [coprocessor] for generating and verifying these proofs. | ||
Explore a more advanced interaction between [Steel] and a custom Ethereum smart contract. This counter contract utilizes off-chain [Steel] proofs to: | ||
- Increment a counter based on user-submitted proofs. | ||
- Verify ERC20 token ownership (minimum 1 token required) before incrementing. | ||
- Leverage RISC Zero as a [coprocessor] for efficient proof generation and verification. | ||
|
||
## [Compound Token Stats (APR Proof)](./token-stats/README.md) | ||
|
||
This example shows how the [Steel] library can be used to call multiple view functions of a contract. | ||
This example generates a proof of a [Compound] cToken's APR (Annual Percentage Rate), showcasing the potential for on-chain verification of complex financial metrics. | ||
|
||
[erc20]: ./erc20/README.md | ||
[erc20-counter]: ./erc20-counter/README.md | ||
[Counter]: ./erc20-counter/contracts/Counter.sol | ||
[coprocessor]: https://www.risczero.com/news/a-guide-to-zk-coprocessors-for-scalability | ||
[Steel]: ../steel | ||
[Compound]: https://compound.finance/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
.DS_Store | ||
target/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
{ | ||
"rust-analyzer.linkedProjects": [ | ||
"./methods/guest/Cargo.toml", | ||
"./host/Cargo.toml", | ||
"./core/Cargo.toml" | ||
] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
[workspace] | ||
resolver = "2" | ||
members = ["core", "host", "methods"] | ||
|
||
[workspace.dependencies] | ||
alloy-primitives = { version = "0.7", features = ["serde", "rlp", "std"] } | ||
alloy-rlp = { version = "0.3", default-features = false } | ||
alloy-rlp-derive = { version = "0.3", default-features = false } | ||
alloy-sol-types = { version = "0.7" } | ||
anyhow = "1.0" | ||
clap = { version = "4.4", features = ["derive", "env"] } | ||
ethers-core = "2.0" | ||
ethers-providers = "2.0" | ||
log = "0.4" | ||
methods = { path = "methods" } | ||
nybbles = { version = "0.2.1", features = ["serde"] } | ||
once_cell = "1.19" | ||
revm = { version = "9.0", default-features = false, features = ["std"] } | ||
risc0-steel = { path = "../../steel" } | ||
risc0-zkvm = { git = "https://github.com/risc0/risc0", branch = "main", default-features = false } | ||
rlp = "0.5.2" | ||
serde = "1.0" | ||
thiserror = "1.0" | ||
tokio = { version = "1.35" } | ||
tracing-subscriber = { version = "0.3", features = ["env-filter"] } | ||
|
||
# Always optimize; building and running the guest takes much longer without optimization. | ||
[profile.dev] | ||
opt-level = 3 | ||
|
||
[profile.dev.build-override] | ||
opt-level = 3 | ||
|
||
[profile.release] | ||
debug = 1 | ||
lto = true | ||
|
||
[profile.release.build-override] | ||
opt-level = 3 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
# Compound Token Stats (APR Proof) | ||
|
||
**An example that calls multiple view functions on the Compound USDC contract to compute the APR.** | ||
|
||
## Prerequisites | ||
|
||
To get started, you need to have Rust installed. If you haven't done so, follow the instructions [here][install-rust]. | ||
|
||
Next, install the `cargo risczero` tool. We'll use `cargo binstall` to facilitate this. Detailed instructions can be found at [cargo-binstall]. | ||
|
||
```bash | ||
cargo install cargo-binstall | ||
cargo binstall cargo-risczero | ||
``` | ||
|
||
Finally, install the `risc0` toolchain with the following command: | ||
|
||
```bash | ||
cargo risczero install | ||
``` | ||
|
||
You'll also need access to an Ethereum RPC node, such as through [Alchemy](www.alchemy.com). | ||
|
||
## Run the example | ||
|
||
To run the example, which computes the current APR of the Compound USDC Token `0xc3d688B66703497DAA19211EEdff47f25384cdc3` on Ethereum, execute the following command: | ||
|
||
```bash | ||
RPC_URL=https://ethereum-rpc.publicnode.com RUST_LOG=info cargo run --release | ||
``` | ||
|
||
The output should resemble the following: | ||
|
||
```text | ||
2024-06-04T20:47:18.785315Z INFO risc0_steel::contract: Executing preflight for 'getUtilization()' on contract 0xc3d688B66703497DAA19211EEdff47f25384cdc3 | ||
2024-06-04T20:47:20.979605Z INFO risc0_steel::contract: Executing preflight for 'getSupplyRate(uint256)' on contract 0xc3d688B66703497DAA19211EEdff47f25384cdc3 | ||
Running the guest with the constructed input: | ||
2024-06-04T20:47:23.011329Z INFO executor: risc0_zkvm::host::server::exec::executor: execution time: 443.8825ms | ||
2024-06-04T20:47:23.011368Z INFO executor: risc0_zkvm::host::server::session: number of segments: 11 | ||
2024-06-04T20:47:23.011371Z INFO executor: risc0_zkvm::host::server::session: total cycles: 11534336 | ||
2024-06-04T20:47:23.011373Z INFO executor: risc0_zkvm::host::server::session: user cycles: 8945420 | ||
Proven APR calculated is: 6.7249996533936% | ||
``` | ||
|
||
[install-rust]: https://doc.rust-lang.org/cargo/getting-started/installation.html | ||
[cargo-binstall]: https://github.com/cargo-bins/cargo-binstall#cargo-binaryinstall |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
[package] | ||
name = "core" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[dependencies] | ||
alloy-primitives = { workspace = true } | ||
alloy-sol-types = { workspace = true } | ||
risc0-steel = { workspace = true } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
// 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. | ||
|
||
use alloy_primitives::{address, Address}; | ||
use alloy_sol_types::sol; | ||
use risc0_steel::SolCommitment; | ||
|
||
/// Address of Compound USDC (cUSDCv3) token. | ||
pub const CONTRACT: Address = address!("c3d688B66703497DAA19211EEdff47f25384cdc3"); | ||
|
||
sol! { | ||
/// Simplified interface of the Compound Finance Comet contract | ||
interface CometMainInterface { | ||
function getSupplyRate(uint utilization) virtual public view returns (uint64); | ||
function getUtilization() public view returns (uint); | ||
} | ||
} | ||
|
||
sol! { | ||
struct APRCommitment { | ||
SolCommitment commitment; | ||
uint64 annualSupplyRate; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
[package] | ||
name = "host" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[dependencies] | ||
alloy-sol-types = { workspace = true } | ||
anyhow = { workspace = true } | ||
clap = { workspace = true } | ||
core = { path = "../core" } | ||
methods = { workspace = true } | ||
risc0-steel = { workspace = true, features = ["host"] } | ||
risc0-zkvm = { workspace = true, features = ["client"] } | ||
tracing-subscriber = { workspace = true } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
// 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. | ||
|
||
use alloy_sol_types::SolValue; | ||
use anyhow::{Context, Result}; | ||
use clap::Parser; | ||
use core::{APRCommitment, CometMainInterface, CONTRACT}; | ||
use methods::TOKEN_STATS_ELF; | ||
use risc0_steel::{config::ETH_MAINNET_CHAIN_SPEC, ethereum::EthEvmEnv, Contract}; | ||
use risc0_zkvm::{default_executor, ExecutorEnv}; | ||
use tracing_subscriber::EnvFilter; | ||
|
||
// Simple program to show the use of Ethereum contract data inside the guest. | ||
#[derive(Parser, Debug)] | ||
#[command(about, long_about = None)] | ||
struct Args { | ||
/// URL of the RPC endpoint | ||
#[arg(short, long, env = "RPC_URL")] | ||
rpc_url: String, | ||
} | ||
|
||
fn main() -> Result<()> { | ||
// Initialize tracing. In order to view logs, run `RUST_LOG=info cargo run` | ||
tracing_subscriber::fmt() | ||
.with_env_filter(EnvFilter::from_default_env()) | ||
.init(); | ||
// Parse the command line arguments. | ||
let args = Args::parse(); | ||
|
||
// Create an EVM environment from an RPC endpoint and a block number. If no block number is | ||
// provided, the latest block is used. | ||
let mut env = EthEvmEnv::from_rpc(&args.rpc_url, None)?; | ||
// The `with_chain_spec` method is used to specify the chain configuration. | ||
env = env.with_chain_spec(Ð_MAINNET_CHAIN_SPEC); | ||
|
||
let block_commitment = env.block_commitment(); | ||
|
||
// Preflight the call to prepare the input that is required to execute the function in | ||
// the guest without RPC access. It also returns the result of the call. | ||
let mut contract = Contract::preflight(CONTRACT, &mut env); | ||
let utilization = contract | ||
.call_builder(&CometMainInterface::getUtilizationCall {}) | ||
.call()? | ||
._0; | ||
contract | ||
.call_builder(&CometMainInterface::getSupplyRateCall { utilization }) | ||
.call()?; | ||
|
||
// Finally, construct the input from the environment. | ||
let input = env.into_input()?; | ||
|
||
println!("Running the guest with the constructed input:"); | ||
let session_info = { | ||
let env = ExecutorEnv::builder() | ||
.write(&input) | ||
.unwrap() | ||
.build() | ||
.context("Failed to build exec env")?; | ||
let exec = default_executor(); | ||
exec.execute(env, TOKEN_STATS_ELF) | ||
.context("failed to run executor")? | ||
}; | ||
|
||
let apr_commit = APRCommitment::abi_decode(&session_info.journal.bytes, true) | ||
.context("failed to decode journal")?; | ||
assert_eq!(block_commitment, apr_commit.commitment); | ||
|
||
// Calculation is handling `/ 10^18 * 100` to match precision for a percentage. | ||
let apr = apr_commit.annualSupplyRate as f64 / 10f64.powi(16); | ||
println!("Proven APR calculated is: {}%", apr); | ||
|
||
Ok(()) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
[package] | ||
name = "methods" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[build-dependencies] | ||
risc0-build = { git = "https://github.com/risc0/risc0", branch = "main" } | ||
|
||
[package.metadata.risc0] | ||
methods = ["guest"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
// 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. | ||
|
||
fn main() { | ||
risc0_build::embed_methods(); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
[package] | ||
name = "token-stats" | ||
version = "0.1.0" | ||
edition = "2021" | ||
|
||
[workspace] | ||
|
||
[dependencies] | ||
alloy-sol-types = { version = "0.7" } | ||
core = { path = "../../core" } | ||
risc0-steel = { path = "../../../../steel" } | ||
risc0-zkvm = { git = "https://github.com/risc0/risc0", branch = "main", default-features = false, features = ["std"] } | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It'd be better to pin to a specific commit rather than using the main branch. It's very easy for this to break in the future. |
||
|
||
# Force the `compile-time-rng` feature, to prevent `getrandom` from being used. | ||
ahash = { version = "0.8", default-features = false, features = ["compile-time-rng"] } | ||
|
||
[patch.crates-io] | ||
# use optimized risc0 circuit | ||
crypto-bigint = { git = "https://github.com/risc0/RustCrypto-crypto-bigint", tag = "v0.5.5-risczero.0" } | ||
k256 = { git = "https://github.com/risc0/RustCrypto-elliptic-curves", tag = "k256/v0.13.3-risczero.0" } | ||
sha2 = { git = "https://github.com/risc0/RustCrypto-hashes", tag = "sha2-v0.10.8-risczero.0" } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
// 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. | ||
|
||
use alloy_sol_types::SolValue; | ||
use core::{APRCommitment, CometMainInterface, CONTRACT}; | ||
use risc0_steel::{config::ETH_MAINNET_CHAIN_SPEC, ethereum::EthEvmInput, Contract}; | ||
use risc0_zkvm::guest::env; | ||
|
||
const SECONDS_PER_YEAR: u64 = 60 * 60 * 24 * 365; | ||
|
||
fn main() { | ||
// Read the input from the guest environment. | ||
let input: EthEvmInput = env::read(); | ||
|
||
// Converts the input into a `EvmEnv` for execution. The `with_chain_spec` method is used | ||
// to specify the chain configuration. It checks that the state matches the state root in the | ||
// header provided in the input. | ||
let env = input.into_env().with_chain_spec(Ð_MAINNET_CHAIN_SPEC); | ||
|
||
// Execute the view calls; it returns the result in the type generated by the `sol!` macro. | ||
let contract = Contract::new(CONTRACT, &env); | ||
let utilization = contract | ||
.call_builder(&CometMainInterface::getUtilizationCall {}) | ||
.call() | ||
._0; | ||
let supply_rate = contract | ||
.call_builder(&CometMainInterface::getSupplyRateCall { utilization }) | ||
.call() | ||
._0; | ||
|
||
// The formula for APR in percentage is the following: | ||
// Seconds Per Year = 60 * 60 * 24 * 365 | ||
// Utilization = getUtilization() | ||
// Supply Rate = getSupplyRate(Utilization) | ||
// Supply APR = Supply Rate / (10 ^ 18) * Seconds Per Year * 100 | ||
// | ||
// And this is calculating: Supply Rate * Seconds Per Year, to avoid float calculations for | ||
// precision. | ||
let annual_supply_rate = supply_rate * SECONDS_PER_YEAR; | ||
|
||
// This commits the APR at current utilization rate for this given block. | ||
let journal = APRCommitment { | ||
commitment: env.block_commitment(), | ||
annualSupplyRate: annual_supply_rate, | ||
}; | ||
env::commit_slice(&journal.abi_encode()); | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Some trickiness with this is that, on main, they will end up using two different versions of the zkVM. One is specified in the Cargo.toml here as the
risc0-zkvm
dependency and will bemain
, and the other is the latest release installed bycargo binstall
. It's unclear whether we are guaranteeing this will work or not, post 1.0.At the very least, the result right now is
This issue is not unique to this example, and we are trying to deal with this on
risc0
as well.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Might be better to just link to the install page on the docs so that if we make changes to the installation (like moving to
rzup
), we don't need to update all the different descriptions of installation.