Skip to main content

cast/cmd/
storage_credits.rs

1use crate::{
2    cmd::tip20::send_tip20_transaction,
3    tempo::{ensure_tempo_precompile_active, print_payload, tempo_provider},
4    tx::{SendTxOpts, TxParams},
5};
6use alloy_ens::NameOrAddress;
7use alloy_primitives::Address;
8use alloy_sol_types::SolCall;
9use clap::{Parser, ValueEnum};
10use eyre::Result;
11use foundry_cli::opts::RpcOpts;
12use foundry_common::provider::RetryProvider;
13use serde_json::{Value, json};
14use std::str::FromStr;
15use tempo_alloy::{TempoNetwork, chainspec::hardfork::TempoHardfork};
16use tempo_contracts::precompiles::{IStorageCredits, STORAGE_CREDITS_ADDRESS};
17
18/// T7 storage credits operations (Tempo).
19///
20/// Storage credits are a per-account, non-transferable balance minted when an account frees its own
21/// storage and later spent to discount the creation cost of new storage. This wraps the T7
22/// StorageCredits precompile at `0x1060000000000000000000000000000000000000`.
23#[derive(Debug, Parser, Clone)]
24pub enum StorageCreditsSubcommand {
25    /// Show an account's storage credit balance.
26    Balance {
27        /// Account to query.
28        #[arg(value_parser = NameOrAddress::from_str)]
29        account: NameOrAddress,
30
31        #[command(flatten)]
32        rpc: RpcOpts,
33    },
34
35    /// Show an account's storage credit consumption mode.
36    ///
37    /// Mode is transaction-local transient state, so a standalone read reflects the default rather
38    /// than a value set by an earlier `set-mode` transaction.
39    Mode {
40        /// Account to query.
41        #[arg(value_parser = NameOrAddress::from_str)]
42        account: NameOrAddress,
43
44        #[command(flatten)]
45        rpc: RpcOpts,
46    },
47
48    /// Show an account's storage credit spend budget.
49    ///
50    /// Budget is transaction-local transient state, so a standalone read reflects the default
51    /// rather than a value set by an earlier `set-budget` transaction.
52    Budget {
53        /// Account to query.
54        #[arg(value_parser = NameOrAddress::from_str)]
55        account: NameOrAddress,
56
57        #[command(flatten)]
58        rpc: RpcOpts,
59    },
60
61    /// Set the caller's storage credit consumption mode.
62    ///
63    /// The mode only applies within the transaction that sets it; batch it with the storage
64    /// operations it should govern.
65    SetMode {
66        /// Mode to switch to.
67        #[arg(value_enum)]
68        mode: CreditMode,
69
70        #[command(flatten)]
71        send_tx: SendTxOpts,
72
73        #[command(flatten)]
74        tx: TxParams,
75    },
76
77    /// Set the caller's storage credit spend budget, which also selects `direct` mode.
78    ///
79    /// The budget only applies within the transaction that sets it; batch it with the storage
80    /// operations it should govern.
81    SetBudget {
82        /// Maximum number of credits the caller may spend in `direct` mode this transaction.
83        credits: u64,
84
85        #[command(flatten)]
86        send_tx: SendTxOpts,
87
88        #[command(flatten)]
89        tx: TxParams,
90    },
91}
92
93/// CLI-facing spelling of `IStorageCredits::Mode`.
94#[derive(Debug, Clone, Copy, ValueEnum)]
95pub enum CreditMode {
96    /// Pay creation cost upfront, then settle credits as a refund at end of transaction.
97    Refund,
98    /// Pay creation cost upfront and keep freed credits instead of spending them.
99    Preserve,
100    /// Spend existing credits synchronously; selecting this sets an effectively unlimited budget.
101    Direct,
102}
103
104impl StorageCreditsSubcommand {
105    pub async fn run(self) -> Result<()> {
106        match self {
107            Self::Balance { account, rpc } => {
108                read(account, rpc, "balance", "Balance:", |credits, account| async move {
109                    Ok(json!(credits.balanceOf(account).call().await?))
110                })
111                .await
112            }
113            Self::Mode { account, rpc } => {
114                read(account, rpc, "mode", "Mode:   ", |credits, account| async move {
115                    Ok(json!(credits.modeOf(account).call().await?.as_str()))
116                })
117                .await
118            }
119            Self::Budget { account, rpc } => {
120                read(account, rpc, "budget", "Budget: ", |credits, account| async move {
121                    Ok(json!(credits.budgetOf(account).call().await?))
122                })
123                .await
124            }
125            Self::SetMode { mode, send_tx, tx } => {
126                ensure_t7(&send_tx.eth.rpc, "cast storage-credits set-mode").await?;
127                let new_mode = match mode {
128                    CreditMode::Refund => IStorageCredits::Mode::Refund,
129                    CreditMode::Preserve => IStorageCredits::Mode::Preserve,
130                    CreditMode::Direct => IStorageCredits::Mode::Direct,
131                };
132                let data = IStorageCredits::setModeCall { newMode: new_mode }.abi_encode();
133                send_tip20_transaction(STORAGE_CREDITS_ADDRESS, data, send_tx, tx).await
134            }
135            Self::SetBudget { credits, send_tx, tx } => {
136                ensure_t7(&send_tx.eth.rpc, "cast storage-credits set-budget").await?;
137                let data = IStorageCredits::setBudgetCall { credits }.abi_encode();
138                send_tip20_transaction(STORAGE_CREDITS_ADDRESS, data, send_tx, tx).await
139            }
140        }
141    }
142}
143
144type Credits = IStorageCredits::IStorageCreditsInstance<RetryProvider<TempoNetwork>, TempoNetwork>;
145
146/// Reads one account field from the precompile and prints it as `key` in JSON mode and after
147/// `label` otherwise.
148async fn read<F, Fut>(
149    account: NameOrAddress,
150    rpc: RpcOpts,
151    key: &str,
152    label: &str,
153    query: F,
154) -> Result<()>
155where
156    F: FnOnce(Credits, Address) -> Fut,
157    Fut: Future<Output = Result<Value>>,
158{
159    let provider = ensure_t7(&rpc, &format!("cast storage-credits {key}")).await?;
160    let account = account.resolve(&provider).await?;
161    let value = query(IStorageCredits::new(STORAGE_CREDITS_ADDRESS, provider), account).await?;
162    let payload = json!({ "account": format!("{account}"), key: value });
163    print_payload(payload, |payload| {
164        let value = &payload[key];
165        let value = value.as_str().map_or_else(|| value.to_string(), str::to_string);
166        sh_println!("Account: {}\n{label} {value}", payload["account"].as_str().unwrap_or_default())
167    })
168}
169
170/// The StorageCredits precompile only exists on T7+; fail early with a clear message instead of
171/// surfacing a raw revert (or, for writes, a silently successful no-op transaction to an empty
172/// account).
173async fn ensure_t7(rpc: &RpcOpts, command: &str) -> Result<RetryProvider<TempoNetwork>> {
174    let (_, provider) = tempo_provider(rpc)?;
175    ensure_tempo_precompile_active(
176        &provider,
177        TempoHardfork::T7,
178        STORAGE_CREDITS_ADDRESS,
179        &format!("{command} requires a Tempo T7-capable StorageCredits RPC"),
180    )
181    .await?;
182    Ok(provider)
183}