Skip to content

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 17 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 3 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,9 @@ jobs:
- name: build erc20-Counter
run: cargo build
working-directory: examples/erc20-counter
- name: build token-stats
run: cargo build
working-directory: examples/token-stats
- name: test erc20-Counter
run: ./test-local-deployment.sh
working-directory: examples/erc20-counter
Expand Down
21 changes: 13 additions & 8 deletions examples/README.md
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/
2 changes: 2 additions & 0 deletions examples/token-stats/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.DS_Store
target/
7 changes: 7 additions & 0 deletions examples/token-stats/.vscode/settings.json
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"
]
}
39 changes: 39 additions & 0 deletions examples/token-stats/Cargo.toml
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
46 changes: 46 additions & 0 deletions examples/token-stats/README.md
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
Comment on lines +12 to +13
Copy link
Contributor

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 be main, and the other is the latest release installed by cargo 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

called `Result::unwrap()` on an `Err` value: incompatible client version: 1.1.0-alpha.1, server version: 1.0.1

This issue is not unique to this example, and we are trying to deal with this on risc0 as well.

Copy link
Member

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.

```

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
9 changes: 9 additions & 0 deletions examples/token-stats/core/Cargo.toml
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 }
35 changes: 35 additions & 0 deletions examples/token-stats/core/src/lib.rs
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;
}
}
14 changes: 14 additions & 0 deletions examples/token-stats/host/Cargo.toml
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 }
84 changes: 84 additions & 0 deletions examples/token-stats/host/src/main.rs
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(&ETH_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(())
}
10 changes: 10 additions & 0 deletions examples/token-stats/methods/Cargo.toml
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"]
17 changes: 17 additions & 0 deletions examples/token-stats/methods/build.rs
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();
}
21 changes: 21 additions & 0 deletions examples/token-stats/methods/guest/Cargo.toml
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"] }
Copy link
Member

Choose a reason for hiding this comment

The 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" }
58 changes: 58 additions & 0 deletions examples/token-stats/methods/guest/src/main.rs
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(&ETH_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());
}
Loading
Loading