o2-tools 0.4.6-rc2

Reusable tooling for trade account and order book contract interactions on Fuel
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! Deployment and live depth for the House book paired with a canonical book.

use anyhow::Result;
use fuels::{
    prelude::*,
    types::Identity,
};

pub use crate::order_book_deploy::{
    DepthLevel,
    HouseExecutionResult,
    HouseOrderBook,
    HouseOrderBookConfigurables,
    SharedExecutionEvent,
    SharedOrderMatchedEvent,
    Side,
};
use crate::{
    blob_loader,
    order_book_deploy::{
        OrderBook,
        OrderBookDeploy,
        OrderBookDeployConfig,
        State,
    },
};

/// House membership is managed on the canonical book.
pub const HOUSE_ROLE: u64 = 2;
const HOUSE_BYTECODE: &[u8] =
    include_bytes!("../artifacts/house-order-book/house-order-book.bin");
const HOUSE_STORAGE: &[u8] =
    include_bytes!("../artifacts/house-order-book/house-order-book-storage_slots.json");

#[derive(Clone)]
pub struct HouseOrderBookDeployConfig {
    /// Independent House fees. Shared market settings are copied on-chain from canonical
    /// when its owner attaches this deployment with `set_sidecar`.
    pub configurables: HouseOrderBookConfigurables,
    /// House administrator; defaults to the deploying wallet.
    pub owner: Option<Identity>,
    /// Independent proxy upgrade authority; defaults to the deploying wallet.
    pub proxy_owner: Option<Identity>,
    /// Distinguishes deployments with otherwise identical configuration.
    pub salt: Salt,
    /// Maximum blob chunk size, matching the canonical deployment helper.
    pub max_words_per_blob: usize,
}

impl Default for HouseOrderBookDeployConfig {
    fn default() -> Self {
        Self {
            configurables: HouseOrderBookConfigurables::default(),
            owner: None,
            proxy_owner: None,
            salt: Salt::default(),
            max_words_per_blob: 10_000,
        }
    }
}

#[derive(Clone)]
pub struct HouseOrderBookDeploy<W: Account + Clone> {
    pub house: HouseOrderBook<W>,
    pub canonical: OrderBook<W>,
    /// Common orderbook methods for existing managers and transaction builders.
    pub book: OrderBookDeploy<W>,
}

impl<W: Account + Clone> HouseOrderBookDeploy<W> {
    /// Deploy the proxy and blob loader without initializing the House implementation.
    /// The canonical owner calls `set_sidecar` with House as a contract input to attach
    /// and initialize it atomically. House roles are granted on canonical.
    pub async fn deploy(
        wallet: &W,
        canonical: &OrderBook<W>,
        config: &HouseOrderBookDeployConfig,
    ) -> Result<Self> {
        let base = canonical
            .methods()
            .get_base_asset()
            .simulate(Execution::state_read_only())
            .await?
            .value;
        let quote = canonical
            .methods()
            .get_quote_asset()
            .simulate(Execution::state_read_only())
            .await?
            .value;
        let owner = config.owner.unwrap_or(Identity::Address(wallet.address()));
        let configurables = config
            .configurables
            .clone()
            .with_CANONICAL_BOOK(canonical.contract_id())?
            .with_INITIAL_OWNER(State::Initialized(owner))?;
        let (data, loader) = blob_loader::build_loader_blobs(
            HOUSE_BYTECODE.to_vec(),
            config.salt,
            serde_json::from_slice(HOUSE_STORAGE)?,
            configurables,
            config.max_words_per_blob,
        )?;
        let blob = blob_loader::upload_loader_blobs(wallet, data, loader).await?;
        let proxy_config = OrderBookDeployConfig {
            proxy_owner: config.proxy_owner,
            salt: config.salt,
            ..Default::default()
        };
        let (proxy, initialize) =
            OrderBookDeploy::deploy_order_book_proxy(wallet, &blob, &proxy_config)
                .await?;
        let house = HouseOrderBook::new(proxy.contract_id(), wallet.clone());
        if initialize {
            proxy.methods().initialize_proxy().call().await?;
        }
        Ok(Self {
            house,
            canonical: canonical.clone(),
            book: OrderBookDeploy::new(wallet.clone(), proxy.contract_id(), base, quote),
        })
    }

    /// Include both venues when building House trades or canonical shared-order creation calls.
    pub fn contract_ids(&self) -> [ContractId; 2] {
        [self.book.contract_id, self.canonical.contract_id()]
    }

    /// Decode shared fills emitted by the paired canonical book.
    pub fn decode_shared_matches(
        &self,
        receipts: &[fuels::tx::Receipt],
    ) -> Result<Vec<SharedOrderMatchedEvent>> {
        decode_legacy_shared_matches(self.canonical.contract_id(), receipts)
    }

    /// Explicitly take resting Turbo orders using this caller's canonical inventory.
    pub fn execute_turbo_orders(
        &self,
        source_order_id: fuels::types::Bits256,
        max_base_quantity: u64,
        max_fills: u64,
    ) -> fuels::programs::calls::CallHandler<
        W,
        fuels::programs::calls::ContractCall,
        HouseExecutionResult,
    > {
        self.canonical
            .methods()
            .execute_turbo_orders(source_order_id, max_base_quantity, max_fills)
            .with_contracts(&[&self.house])
    }

    /// Decode the paired canonical emitter's self-contained shared executions.
    pub fn decode_shared_executions(
        &self,
        receipts: &[fuels::tx::Receipt],
    ) -> Result<Vec<SharedExecutionEvent>> {
        Ok(self
            .canonical
            .log_decoder()
            .decode_logs_with_type::<SharedExecutionEvent>(receipts)?)
    }

    /// Current connection and pause status for execution previews.
    pub async fn is_execution_enabled(&self) -> Result<bool> {
        if self
            .canonical
            .methods()
            .get_sidecar_state()
            .simulate(Execution::state_read_only())
            .await?
            .value
            != Some(self.book.contract_id)
        {
            return Ok(false);
        }
        if self
            .house
            .methods()
            .is_paused()
            .simulate(Execution::state_read_only())
            .await?
            .value
        {
            return Ok(false);
        }
        Ok(!self
            .canonical
            .methods()
            .is_paused()
            .simulate(Execution::state_read_only())
            .await?
            .value)
    }

    /// Live quantities of eligible House quotes. Pair with `is_execution_enabled` for previews.
    pub async fn executable_depth(
        &self,
        side: Side,
        max_levels: u64,
    ) -> Result<Vec<DepthLevel>> {
        Ok(self
            .house
            .methods()
            .get_executable_depth(side, max_levels)
            .with_contracts(&[&self.canonical])
            .simulate(Execution::state_read_only())
            .await?
            .value)
    }
}

/// Historical decoder remains independent of the current implementation's log schema.
pub fn decode_legacy_shared_matches(
    canonical: ContractId,
    receipts: &[fuels::tx::Receipt],
) -> Result<Vec<SharedOrderMatchedEvent>> {
    use fuels::core::codec::{
        Log,
        LogDecoder,
        LogFormatter,
        log_formatters_lookup,
    };
    let decoder = LogDecoder::new(
        log_formatters_lookup(
            vec![(
                SharedOrderMatchedEvent::LOG_ID_U64.to_string(),
                LogFormatter::new_log::<SharedOrderMatchedEvent>(),
            )],
            canonical,
        ),
        Default::default(),
    );
    Ok(decoder.decode_logs_with_type::<SharedOrderMatchedEvent>(receipts)?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        order_book_deploy::OrderBookConfigurables,
        order_book_registry::{
            MarketId,
            OrderBookRegistryDeployConfig,
            OrderBookRegistryManager,
        },
    };

    #[tokio::test]
    async fn house_deployment_preserves_owners_and_is_discovered_through_canonical() {
        let wallets = launch_custom_provider_and_get_wallets(
            WalletsConfig::new(Some(2), Some(1), Some(1_000_000_000)),
            None,
            Some(fuels::test_helpers::ChainConfig::local_testnet()),
        )
        .await
        .unwrap();
        let deployer = &wallets[0];
        let owner = Identity::Address(wallets[1].address());
        let base = AssetId::new([1; 32]);
        let quote = AssetId::new([2; 32]);
        let canonical = OrderBookDeploy::deploy(
            deployer,
            base,
            quote,
            &OrderBookDeployConfig::with_configurables(
                OrderBookConfigurables::default()
                    .with_BASE_DECIMALS(1_000_000)
                    .unwrap()
                    .with_MIN_ORDER(50_000_000)
                    .unwrap()
                    .with_PRICE_PRECISION(10_000)
                    .unwrap(),
            ),
        )
        .await
        .unwrap();
        let config = HouseOrderBookDeployConfig {
            owner: Some(owner),
            proxy_owner: Some(owner),
            configurables: HouseOrderBookConfigurables::default()
                .with_MAKER_FEE(123u64.into())
                .unwrap(),
            ..Default::default()
        };
        let house =
            HouseOrderBookDeploy::deploy(deployer, &canonical.order_book, &config)
                .await
                .unwrap();
        assert_eq!(
            house.house.methods().owner().call().await.unwrap().value,
            State::Uninitialized
        );
        canonical
            .order_book
            .methods()
            .set_sidecar(Some(house.book.contract_id))
            .with_contracts(&[&house.house])
            .call()
            .await
            .unwrap();
        assert_eq!(
            house.house.methods().owner().call().await.unwrap().value,
            State::Initialized(owner)
        );
        assert_eq!(
            house
                .book
                .order_book_proxy
                .methods()
                .proxy_owner()
                .call()
                .await
                .unwrap()
                .value,
            State::Initialized(owner)
        );
        assert_eq!(
            house
                .house
                .methods()
                .get_base_decimals()
                .call()
                .await
                .unwrap()
                .value,
            1_000_000
        );
        assert_eq!(
            house
                .house
                .methods()
                .get_maker_fee()
                .call()
                .await
                .unwrap()
                .value,
            123
        );
        assert_eq!(
            house
                .house
                .methods()
                .get_minimum_trade_amount()
                .call()
                .await
                .unwrap()
                .value,
            50_000_000
        );
        assert_eq!(
            house
                .house
                .methods()
                .get_price_precision()
                .call()
                .await
                .unwrap()
                .value,
            10_000
        );
        assert!(
            !house
                .house
                .methods()
                .get_allow_fractional_price()
                .call()
                .await
                .unwrap()
                .value
        );
        assert_eq!(
            house
                .house
                .methods()
                .get_canonical_orderbook()
                .call()
                .await
                .unwrap()
                .value,
            canonical.contract_id
        );
        assert_eq!(
            house.contract_ids(),
            [house.book.contract_id, canonical.contract_id]
        );
        let repeated =
            HouseOrderBookDeploy::deploy(deployer, &canonical.order_book, &config)
                .await
                .unwrap();
        assert_eq!(repeated.book.contract_id, house.book.contract_id);

        let registry = OrderBookRegistryManager::deploy(
            deployer,
            &OrderBookRegistryDeployConfig::default(),
        )
        .await
        .unwrap();
        let market = MarketId {
            base_asset: base,
            quote_asset: quote,
        };
        assert!(
            registry
                .get_house_order_book(market.clone())
                .await
                .unwrap()
                .is_none()
        );
        registry
            .register_order_book(market.clone(), canonical.contract_id)
            .await
            .unwrap();
        assert_eq!(
            registry.get_house_order_book(market.clone()).await.unwrap(),
            Some(house.book.contract_id)
        );
        canonical
            .order_book
            .methods()
            .set_sidecar(Some(house.book.contract_id))
            .call()
            .await
            .unwrap();
        assert!(house.is_execution_enabled().await.unwrap());
        let house_owner = house.house.clone().with_account(wallets[1].clone());
        house_owner.methods().pause().call().await.unwrap();
        assert!(!house.is_execution_enabled().await.unwrap());
        house_owner.methods().unpause().call().await.unwrap();
        canonical.order_book.methods().pause().call().await.unwrap();
        assert!(!house.is_execution_enabled().await.unwrap());
        canonical
            .order_book
            .methods()
            .unpause()
            .call()
            .await
            .unwrap();
        assert!(house.is_execution_enabled().await.unwrap());
        assert_eq!(
            registry.get_house_order_book(market.clone()).await.unwrap(),
            Some(house.book.contract_id)
        );
        assert_eq!(
            registry.get_order_book(market.clone()).await.unwrap(),
            Some(canonical.contract_id)
        );
        assert!(
            house
                .executable_depth(Side::Sell, 10)
                .await
                .unwrap()
                .is_empty()
        );
        canonical
            .order_book
            .methods()
            .set_sidecar(None)
            .call()
            .await
            .unwrap();
        assert!(!house.is_execution_enabled().await.unwrap());
        assert!(
            registry
                .get_house_order_book(market)
                .await
                .unwrap()
                .is_none()
        );
    }
}