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

Add compound APR example that uses multi-call #95

Merged
merged 17 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
update to v3 contract and derive debug/eq for BlockCommitment
  • Loading branch information
austinabell committed May 1, 2024
commit 32d72220f34d6f07c4fb533fb6ff00782faaf3fd
1 change: 1 addition & 0 deletions examples/token-stats/Cargo.lock

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

1 change: 1 addition & 0 deletions examples/token-stats/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ edition = "2021"
[dependencies]
alloy-primitives = { workspace = true }
alloy-sol-types = { workspace = true }
risc0-steel = { workspace = true }
13 changes: 11 additions & 2 deletions examples/token-stats/core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
use alloy_primitives::{address, Address};
use alloy_sol_types::sol;
use risc0_steel::BlockCommitment;

/// Address of Compound USDC.
pub const CONTRACT: Address = address!("39aa39c021dfbae8fac545936693ac917d5e7563");
pub const CONTRACT: Address = address!("c3d688B66703497DAA19211EEdff47f25384cdc3");

sol! {
/// Simplified interface of Uniswap pair contract using only what is needed.
interface CToken {
function supplyRatePerBlock() external view returns (uint);
function getSupplyRate(uint utilization) virtual public view returns (uint64);
function getUtilization() public view returns (uint);
}
}

sol! {
#[derive(Debug, PartialEq, Eq)]
struct APRCommitment {
BlockCommitment commitment;
uint64 annualSupplyRate;
}
}
27 changes: 12 additions & 15 deletions examples/token-stats/host/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use alloy_sol_types::{SolCall, SolValue};
use alloy_sol_types::SolValue;
use anyhow::{Context, Result};
use clap::Parser;
use core::{CToken, CONTRACT};
use core::{APRCommitment, CToken, CONTRACT};
use methods::TOKEN_STATS_ELF;
use risc0_steel::{config::ETH_MAINNET_CHAIN_SPEC, ethereum::EthViewCallEnv, EvmHeader, ViewCall};
use risc0_steel::{config::ETH_MAINNET_CHAIN_SPEC, ethereum::EthViewCallEnv, ViewCall};
use risc0_zkvm::{default_executor, ExecutorEnv};
use tracing_subscriber::EnvFilter;

Expand All @@ -41,19 +41,13 @@ fn main() -> Result<()> {
// chain configuration.
let mut env =
EthViewCallEnv::from_rpc(&args.rpc_url, None)?.with_chain_spec(&ETH_MAINNET_CHAIN_SPEC);
let number = env.header().number();
let commitment = env.block_commitment();
let block_commitment = env.block_commitment();

// Preflight the view call to construct the input that is required to execute the function in
// the guest. It also returns the result of the call.
let returns = env.preflight(ViewCall::new(CToken::supplyRatePerBlockCall {}, CONTRACT))?;
let utilization = env.preflight(ViewCall::new(CToken::getUtilizationCall {}, CONTRACT))?._0;
env.preflight(ViewCall::new(CToken::getSupplyRateCall { utilization }, CONTRACT))?._0;
let input = env.into_zkvm_input()?;
println!(
"For block {} `{}` returns: {}",
number,
CToken::supplyRatePerBlockCall::SIGNATURE,
returns._0,
);

println!("Running the guest with the constructed input:");
let session_info = {
Expand All @@ -66,9 +60,12 @@ fn main() -> Result<()> {
exec.execute(env, TOKEN_STATS_ELF).context("failed to run executor")?
};

// extract the proof from the session info and validate it
let bytes = session_info.journal.as_ref();
assert_eq!(&bytes[..64], &commitment.abi_encode());
let apr_commit = APRCommitment::abi_decode(&session_info.journal.bytes, true)?;
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(())
}
1 change: 1 addition & 0 deletions examples/token-stats/methods/guest/Cargo.lock

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

26 changes: 18 additions & 8 deletions examples/token-stats/methods/guest/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(unused_doc_comments)]

use alloy_sol_types::SolValue;
use core::{APRCommitment, CToken, CONTRACT};
use risc0_steel::{config::ETH_MAINNET_CHAIN_SPEC, ethereum::EthViewCallInput, ViewCall};
use risc0_zkvm::guest::env;

use core::{CToken, CONTRACT};
const SECONDS_PER_YEAR: u64 = 60 * 60 * 24 * 365;

fn main() {
// Read the input from the guest environment.
Expand All @@ -28,16 +27,27 @@ fn main() {
// to specify the chain configuration. It checks that the state matches the state root in the
// header provided in the input.
let mut view_call_env = input.into_env().with_chain_spec(&ETH_MAINNET_CHAIN_SPEC);
// Commit the block hash and number used when deriving `view_call_env` to the journal.
env::commit_slice(&view_call_env.block_commitment().abi_encode());

// Execute the view call; it returns the result in the type generated by the `sol!` macro.
let returns = view_call_env.execute(ViewCall::new(CToken::supplyRatePerBlockCall {}, CONTRACT));
let utilization =
view_call_env.execute(ViewCall::new(CToken::getUtilizationCall {}, CONTRACT))._0;
let supply_rate: u64 = view_call_env
.execute(ViewCall::new(CToken::getSupplyRateCall { utilization }, CONTRACT))
._0;

// TODO calculate supply APR
// 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
println!("View call result: {}", returns._0);
//
// 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 commitment = view_call_env.block_commitment();
env::commit_slice(
&APRCommitment { commitment, annualSupplyRate: annual_supply_rate }.abi_encode(),
);
}
1 change: 1 addition & 0 deletions steel/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ impl<H: EvmHeader> ViewCallInput<H> {

sol! {
/// Solidity struct representing the committed block used for validation.
#[derive(Debug, PartialEq, Eq)]
struct BlockCommitment {
bytes32 blockHash;
uint blockNumber;
Expand Down