tycho-simulation 0.548.0

Provides tools for interacting with protocol states, calculating spot prices, and quoting token swaps.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use std::{collections::HashMap, fmt::Debug, ops::Range, sync::LazyLock};

use alloy::{
    core::sol,
    primitives::{Address as AlloyAddress, U256},
    sol_types::SolCall,
};
use revm::{primitives::KECCAK_EMPTY, state::AccountInfo, DatabaseRef};
use tycho_common::{
    models::{token::Token, Address},
    simulation::errors::SimulationError,
};
use tycho_ethereum::BytesCodec;

use crate::evm::{
    engine_db::engine_db_interface::EngineDatabaseInterface,
    protocol::{
        erc4626::state::ERC4626State,
        vm::{
            constants::{EXTERNAL_ACCOUNT, MAX_BALANCE},
            erc20_token::{Overwrites, TokenProxyOverwriteFactory},
            utils::get_storage_slot_index_at_key,
        },
    },
    simulation::{SimulationEngine, SimulationParameters},
    ContractCompiler, SlotId,
};

sol! {
    function convertToShares(uint256 assets) public returns (uint256);
    function convertToAssets(uint256 shares) public returns (uint256);
    function maxDeposit(address caller) external returns (uint256);
    function maxWithdraw(address caller) external returns (uint256);
    function maxRedeem(address owner) external returns (uint256);
    function balanceOf(address owner) external view returns (uint256);
    function totalSupply() external view returns (uint256);
}

/// Base slots of the share-balance mapping in the vault layouts in use: a plain Solidity mapping
/// declared among the first ten slots (sDAI at 1, sUSDS and sUSDC at 2, the Spark vaults at 9).
const SHARE_BALANCE_MAPPING_SLOTS: Range<u64> = 0..10;

/// Marker written into the candidate balance slots; far above any real share balance.
static BALANCE_SLOT_SENTINEL: LazyLock<U256> = LazyLock::new(|| U256::from(0x5e17_1e10_u64) << 160);

#[expect(
    clippy::needless_pass_by_value,
    reason = "public API; taking the engine by reference is a breaking change"
)]
pub fn decode_from_vm<D: EngineDatabaseInterface + Clone + Debug>(
    pool: &Address,
    asset_token: &Token,
    share_token: &Token,
    vm_engine: SimulationEngine<D>,
) -> Result<ERC4626State, SimulationError>
where
    <D as DatabaseRef>::Error: Debug,
    <D as EngineDatabaseInterface>::Error: Debug,
{
    let total_supply = simulate_and_decode_call(
        &vm_engine,
        pool,
        AlloyAddress::ZERO,
        &totalSupplyCall {},
        None,
        "totalSupply",
    )?;

    let share_price = simulate_and_decode_call(
        &vm_engine,
        pool,
        AlloyAddress::ZERO,
        &convertToAssetsCall { shares: U256::from(10).pow(U256::from(share_token.decimals)) },
        None,
        "convertToAssets",
    )?;

    let asset_price = simulate_and_decode_call(
        &vm_engine,
        pool,
        AlloyAddress::ZERO,
        &convertToSharesCall { assets: U256::from(10).pow(U256::from(asset_token.decimals)) },
        None,
        "convertToShares",
    )?;

    vm_engine
        .state
        .init_account(
            *EXTERNAL_ACCOUNT,
            AccountInfo { balance: *MAX_BALANCE, nonce: 0, code_hash: KECCAK_EMPTY, code: None },
            None,
            false,
        )
        .map_err(|err| {
            SimulationError::FatalError(format!(
                "Failed to decode from vm: Failed to init external account: {err:?}"
            ))
        })?;

    let mut factory = TokenProxyOverwriteFactory::new(
        AlloyAddress::from_slice(asset_token.address.as_ref()),
        None,
    );
    factory.set_balance(*MAX_BALANCE, *EXTERNAL_ACCOUNT);
    let token_overwrites = factory.get_overwrites();

    let caller = AlloyAddress::from_slice(&*EXTERNAL_ACCOUNT.0);

    // Assume the caller has sufficient tokens. In simulation we only care about
    // the protocol limits, not the caller’s actual token balance.
    let max_deposit = simulate_and_decode_call(
        &vm_engine,
        pool,
        caller,
        &maxDepositCall { caller },
        Some(token_overwrites),
        "maxDeposit",
    )?;

    let max_redeem = read_max_redeem(&vm_engine, pool, caller, total_supply)?;

    Ok(ERC4626State::new(
        pool,
        asset_token,
        share_token,
        asset_price,
        share_price,
        max_deposit,
        max_redeem,
    ))
}

/// Returns the most shares the vault lets one owner redeem: idle liquidity, a utilization cap or a
/// pause, whichever binds.
///
/// `maxRedeem(owner)` is also capped by the owner's share balance, so it is read for an `owner`
/// holding the whole `total_supply`.
fn read_max_redeem<D: EngineDatabaseInterface + Clone + Debug>(
    vm_engine: &SimulationEngine<D>,
    pool: &Address,
    owner: AlloyAddress,
    total_supply: U256,
) -> Result<U256, SimulationError>
where
    <D as DatabaseRef>::Error: Debug,
    <D as EngineDatabaseInterface>::Error: Debug,
{
    let balance_slot = find_share_balance_slot(vm_engine, pool, owner)?;
    let whole_supply_overrides = HashMap::from([(
        AlloyAddress::from_bytes(pool),
        HashMap::from([(balance_slot, total_supply)]),
    )]);
    simulate_and_decode_call(
        vm_engine,
        pool,
        owner,
        &maxRedeemCall { owner },
        Some(whole_supply_overrides),
        "maxRedeem",
    )
}

/// Returns the storage slot of the vault holding `owner`'s share balance.
///
/// Writes `BALANCE_SLOT_SENTINEL + base slot` into `owner`'s entry of a Solidity mapping at every
/// base slot in `SHARE_BALANCE_MAPPING_SLOTS` and reads it back through `balanceOf`, in a single
/// call. Fails when `balanceOf` returns none of them.
fn find_share_balance_slot<D: EngineDatabaseInterface + Clone + Debug>(
    vm_engine: &SimulationEngine<D>,
    pool: &Address,
    owner: AlloyAddress,
) -> Result<SlotId, SimulationError>
where
    <D as DatabaseRef>::Error: Debug,
    <D as EngineDatabaseInterface>::Error: Debug,
{
    let balance_slot = |mapping_slot: u64| {
        get_storage_slot_index_at_key(owner, U256::from(mapping_slot), ContractCompiler::Solidity)
    };
    let mut candidates: Overwrites = HashMap::new();
    for mapping_slot in SHARE_BALANCE_MAPPING_SLOTS {
        candidates
            .insert(balance_slot(mapping_slot), *BALANCE_SLOT_SENTINEL + U256::from(mapping_slot));
    }
    let balance: U256 = simulate_and_decode_call(
        vm_engine,
        pool,
        owner,
        &balanceOfCall { owner },
        Some(HashMap::from([(AlloyAddress::from_bytes(pool), candidates)])),
        "balanceOf",
    )?;

    balance
        .checked_sub(*BALANCE_SLOT_SENTINEL)
        .and_then(|offset| u64::try_from(offset).ok())
        .filter(|mapping_slot| SHARE_BALANCE_MAPPING_SLOTS.contains(mapping_slot))
        .map(balance_slot)
        .ok_or_else(|| {
            SimulationError::FatalError(format!(
                "Vault {pool}: balanceOf returned {balance}, none of the sentinels written into a \
                 Solidity mapping at base slots {SHARE_BALANCE_MAPPING_SLOTS:?}; its share \
                 balances are stored elsewhere or transformed on read"
            ))
        })
}

fn simulate_and_decode_call<D, Call, Ret>(
    vm_engine: &SimulationEngine<D>,
    pool: &Address,
    caller: AlloyAddress,
    call: &Call,
    overrides: Option<HashMap<AlloyAddress, Overwrites>>,
    method: &str,
) -> Result<Ret, SimulationError>
where
    D: EngineDatabaseInterface + Clone + Debug,
    <D as DatabaseRef>::Error: Debug,
    <D as EngineDatabaseInterface>::Error: Debug,
    Call: SolCall<Return = Ret>,
{
    let data = call.abi_encode();
    let to = AlloyAddress::from_bytes(pool);

    let params = SimulationParameters { caller, to, data, overrides, ..Default::default() };

    let res = vm_engine
        .simulate(&params)
        .map_err(|e| SimulationError::FatalError(format!("{method} simulate failed: {e}")))?;

    Call::abi_decode_returns(res.result.as_ref())
        .map_err(|e| SimulationError::FatalError(format!("{method} decode failed: {e}")))
}

#[cfg(test)]
mod test {
    use std::str::FromStr;

    use alloy::primitives::{Address as AlloyAddress, Bytes as AlloyBytes, U256};
    use num_bigint::BigUint;
    use revm::{bytecode::Bytecode, state::AccountInfo};
    use rstest::rstest;
    use tycho_client::feed::BlockHeader;
    use tycho_common::{
        models::{token::Token, Chain},
        simulation::protocol_sim::ProtocolSim,
        Bytes,
    };

    use super::{decode_from_vm, find_share_balance_slot};
    use crate::evm::{
        engine_db::{
            engine_db_interface::EngineDatabaseInterface,
            simulation_db::{EVMProvider, SimulationDB},
            tycho_db::PreCachedDB,
            utils::{get_client, get_runtime},
        },
        protocol::vm::utils::get_storage_slot_index_at_key,
        simulation::SimulationEngine,
        ContractCompiler,
    };

    const VAULT: &str = "0x0000000000000000000000000000000000001234";
    const OWNER: AlloyAddress = AlloyAddress::repeat_byte(0xab);

    /// An engine holding `OWNER` and, at `VAULT`, a contract that runs `runtime` for any call.
    fn engine_with_vault(runtime: &[u8]) -> SimulationEngine<PreCachedDB> {
        let state = PreCachedDB::new().expect("PreCachedDB creation succeeds");
        let bytecode = Bytecode::new_raw(AlloyBytes::copy_from_slice(runtime));
        let account = AccountInfo::new(U256::ZERO, 0, bytecode.hash_slow(), bytecode);
        state
            .init_account(AlloyAddress::from_str(VAULT).unwrap(), account, None, true)
            .expect("vault account init succeeds");
        // The zero address is the block's coinbase, which revm loads on every call.
        for account in [OWNER, AlloyAddress::ZERO] {
            state
                .init_account(account, AccountInfo::default(), None, true)
                .expect("account init succeeds");
        }
        state
            .update(Vec::new(), Some(BlockHeader { number: 1, timestamp: 2, ..Default::default() }))
            .expect("block header update succeeds");
        SimulationEngine::new(state, false)
    }

    #[rstest]
    #[case::sdai(1)]
    #[case::susds_susdc(2)]
    #[case::spark(9)]
    fn test_find_share_balance_slot_in_solidity_mapping(#[case] mapping_slot: u8) {
        // Returns `sload(keccak256(abi.encode(calldataload(4), mapping_slot)))`: a `balanceOf`
        // reading a mapping declared at `mapping_slot`.
        let engine = engine_with_vault(&[
            0x60,
            0x04,
            0x35, // CALLDATALOAD(4)
            0x60,
            0x00,
            0x52, // MSTORE(0, owner)
            0x60,
            mapping_slot,
            0x60,
            0x20,
            0x52, // MSTORE(32, mapping_slot)
            0x60,
            0x40,
            0x60,
            0x00,
            0x20, // KECCAK256(0, 64)
            0x54, // SLOAD
            0x60,
            0x00,
            0x52, // MSTORE(0, balance)
            0x60,
            0x20,
            0x60,
            0x00,
            0xf3, // RETURN(0, 32)
        ]);
        let slot = find_share_balance_slot(&engine, &Bytes::from_str(VAULT).unwrap(), OWNER)
            .expect("a known layout");

        assert_eq!(
            slot,
            get_storage_slot_index_at_key(
                OWNER,
                U256::from(mapping_slot),
                ContractCompiler::Solidity
            )
        );
    }

    #[test]
    fn test_find_share_balance_slot_fails_for_unknown_layout() {
        // `balanceOf` returns 7 whatever the storage holds.
        let engine = engine_with_vault(&[
            0x60, 0x07, 0x60, 0x00, 0x52, // MSTORE(0, 7)
            0x60, 0x20, 0x60, 0x00, 0xf3, // RETURN(0, 32)
        ]);

        let result = find_share_balance_slot(&engine, &Bytes::from_str(VAULT).unwrap(), OWNER);

        let Err(err) = result else { panic!("found a slot in a vault without balances") };
        assert!(
            err.to_string()
                .contains("balanceOf returned 7, none of the sentinels"),
            "{err}"
        );
    }

    fn token(address: &str, symbol: &str, decimals: u32) -> Token {
        Token::new(
            &Bytes::from_str(address).unwrap(),
            symbol,
            decimals,
            0,
            &[Some(20000)],
            Chain::Ethereum,
            100,
        )
    }

    fn rpc_engine(block: BlockHeader) -> SimulationEngine<SimulationDB<EVMProvider>> {
        let mut db = SimulationDB::new(get_client(None).unwrap(), get_runtime().unwrap(), None);
        db.set_block(Some(block));
        SimulationEngine::new(db, false)
    }

    #[test]
    #[ignore = "Requires RPC_URL to be set in environment variables or .env file"]
    fn test_decode_simulation_db() {
        let usdc = token("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "usdc", 6);
        let sp_usdc = token("0x28B3a8fb53B741A8Fd78c0fb9A6B2393d896a43d", "sp_usdc", 6);

        let block = BlockHeader {
            number: 23881700,
            hash: Bytes::from_str(
                "0xb11cb57ba2620d0f31da3a3c531977707569b796003ba65c44eaca990e6f2957",
            )
            .unwrap(),
            timestamp: 1764145355,
            ..Default::default()
        };

        decode_from_vm(
            &Bytes::from("0x28B3a8fb53B741A8Fd78c0fb9A6B2393d896a43d"),
            &usdc,
            &sp_usdc,
            rpc_engine(block),
        )
        .expect("decoding failed");
    }

    /// The redeem limit decoded at block 26332682 equals the vault's `maxRedeem` for an owner of
    /// the whole supply, read from chain at that block.
    #[rstest]
    #[case::speth_idle_liquidity(
        // 10.0% of the 23,746.5 spETH supply: only the WETH held by the vault can be withdrawn.
        "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
        "WETH",
        "0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f",
        "spETH",
        2_374_640_878_418_395_742_859
    )]
    #[case::susds_whole_supply(
        "0xdc035d45d973e3ec169d2276ddab16f1e407384f",
        "USDS",
        "0xa3931d71877c0e7a3148cb7eb4463524fec27fbd",
        "sUSDS",
        4_072_928_603_697_856_501_415_619_567
    )]
    #[ignore = "Requires RPC_URL to be set in environment variables or .env file"]
    fn test_redeem_limit_is_max_redeem_of_whole_supply(
        #[case] asset: &str,
        #[case] asset_symbol: &str,
        #[case] vault: &str,
        #[case] symbol: &str,
        #[case] expected: u128,
    ) {
        let asset = token(asset, asset_symbol, 18);
        let share = token(vault, symbol, 18);
        let block = BlockHeader {
            number: 26332682,
            hash: Bytes::from_str(
                "0xaf14ba2c3bc28c67197fbf5b38f3e2f3aed42b174f86e612ea219308a670a2bd",
            )
            .unwrap(),
            timestamp: 1793689739,
            ..Default::default()
        };

        let state =
            decode_from_vm(&Bytes::from_str(vault).unwrap(), &asset, &share, rpc_engine(block))
                .expect("decoding failed");

        let (max_shares_in, _) = state
            .get_limits(share.address, asset.address)
            .expect("limits");
        assert_eq!(max_shares_in, BigUint::from(expected));
    }
}