Skip to main content

o2_tools/
prop_deploy.rs

1//! Deployment helpers for the independent prop-account contract family.
2//!
3//! Prop accounts consult a stable account-oracle proxy at runtime. The oracle,
4//! registry and margin pool each retain independent SRC-14 upgrade authority.
5
6/// Test-only: the entry term every fixture session opens on.
7#[cfg(test)]
8use crate::prop::ProlongPeriod;
9use crate::{
10    blob_loader,
11    prop::{
12        PRICE_FEED_BYTECODE,
13        PRICE_FEED_PROXY_BYTECODE,
14        PRICE_FEED_PROXY_STORAGE,
15        PRICE_FEED_STORAGE,
16        PROP_ACCOUNT_BYTECODE,
17        PROP_ACCOUNT_ORACLE_BYTECODE,
18        PROP_ACCOUNT_ORACLE_PROXY_BYTECODE,
19        PROP_ACCOUNT_ORACLE_PROXY_STORAGE,
20        PROP_ACCOUNT_ORACLE_STORAGE,
21        PROP_ACCOUNT_PROXY_BYTECODE,
22        PROP_ACCOUNT_PROXY_STORAGE,
23        PROP_ACCOUNT_STORAGE,
24        PROP_MARGIN_POOL_BYTECODE,
25        PROP_MARGIN_POOL_PROXY_BYTECODE,
26        PROP_MARGIN_POOL_PROXY_STORAGE,
27        PROP_MARGIN_POOL_STORAGE,
28        PriceFeedContract,
29        PriceFeedContractConfigurables,
30        PriceFeedProxyContract,
31        PriceFeedProxyContractConfigurables,
32        PropAccountContract,
33        PropAccountOracleContract,
34        PropAccountOracleContractConfigurables,
35        PropAccountOracleProxyContract,
36        PropAccountOracleProxyContractConfigurables,
37        PropAccountProxyContract,
38        PropAccountProxyContractConfigurables,
39        PropMarginPoolContract,
40        PropMarginPoolContractConfigurables,
41        PropMarginPoolProxyContract,
42        PropMarginPoolProxyContractConfigurables,
43        State,
44    },
45    trade_account_registry::{
46        State as TradeAccountRegistryState,
47        TRADE_ACCOUNT_REGISTER_BYTECODE,
48        TRADE_ACCOUNT_REGISTER_PROXY_BYTECODE,
49        TRADE_ACCOUNT_REGISTER_PROXY_STORAGE,
50        TRADE_ACCOUNT_REGISTER_STORAGE,
51        TradeAccountRegistry,
52        TradeAccountRegistryConfigurables,
53        TradeAccountRegistryDeployConfig,
54        TradeAccountRegistryManager,
55        TradeAccountRegistryProxy,
56        TradeAccountRegistryProxyConfigurables,
57    },
58};
59use anyhow::{
60    Context,
61    Result,
62    ensure,
63};
64use fuels::{
65    core::{
66        Configurable,
67        Configurables,
68    },
69    prelude::*,
70    programs::contract::Regular,
71    tx::StorageSlot,
72    types::{
73        Address,
74        AssetId,
75        ContractId,
76        Identity,
77        transaction_builders::Blob,
78    },
79};
80
81/// An already-deployed shared trade-account registry to reuse for
82/// prop-account registration instead of deploying a dedicated one. The
83/// registry's implementation is UPGRADED in place (new blob, same proxy) to
84/// carry the prop configurables, so the oracle ids it was deployed with must
85/// be repeated — the fresh implementation blob embeds them again.
86#[derive(Clone, Debug)]
87pub struct ExistingRegistry {
88    /// The registry proxy id every account resolution goes through.
89    pub registry_id: ContractId,
90    /// The trade-account oracle the registry validates against.
91    pub trade_account_oracle_id: ContractId,
92    /// The trial-trade-account oracle the registry validates against.
93    pub trial_trade_account_oracle_id: ContractId,
94}
95
96/// Deployment-time settings for the prop-account system.
97#[derive(Clone, Debug)]
98pub struct PropDeployConfig {
99    /// Asset used for collateral and quote accounting by the pool.
100    pub collateral_asset: AssetId,
101    /// Decimal precision of `collateral_asset`.
102    pub collateral_decimals: u8,
103    /// Maximum number of order books in one tier version.
104    pub max_tier_books: u64,
105    /// Fee charged by `repay_base_from_collateral`, in parts per million of the
106    /// quote value of the debt closed. Same scale as the order book's taker fee,
107    /// so `100` is one basis point.
108    pub base_repay_fee_ppm: u64,
109    /// Owner of the oracle implementation, feed, registry implementation and pool.
110    /// Defaults to the deployer.
111    pub owner: Option<Identity>,
112    /// Owner of the oracle, registry and pool SRC-14 proxies. Defaults to the deployer.
113    pub proxy_owner: Option<Identity>,
114    /// Cosigner exposed by every prop account. Defaults to the deployer.
115    pub cosigner: Option<Address>,
116    /// Recipient of the platform share. Defaults to the deployer.
117    pub platform_payout: Option<Identity>,
118    /// Recipient of assets retained during forced settlement. Defaults to the deployer.
119    pub liquidator: Option<Identity>,
120    /// Deterministic salt used for all contracts in this deployment.
121    pub salt: Salt,
122    /// Maximum implementation words placed into each loader data blob.
123    pub max_words_per_blob: usize,
124    /// Reuse (and upgrade) an existing shared trade-account registry
125    /// instead of deploying a dedicated one.
126    pub existing_registry: Option<ExistingRegistry>,
127    /// Reuse an already-deployed price feed instead of deploying one. When
128    /// `None` the PRODUCTION price feed is deployed behind its own SRC-14
129    /// proxy.
130    pub existing_price_feed: Option<ContractId>,
131    /// Submission-age bound written to the feed, in seconds. `None` leaves
132    /// the contract's own default in place; a value is reconciled
133    /// compare-first, so a feed already on it costs no transaction.
134    pub max_offchain_age_seconds: Option<u64>,
135    /// Reuse an already-deployed margin pool instead of deriving its
136    /// address. The derivation depends on the pool BYTECODE (through the
137    /// bootstrap blob the proxy is seeded with), so a release that changes
138    /// the pool derives a new address and forks the pool. Anyone who
139    /// already knows their pool must pin it here to get an upgrade rather
140    /// than a fork.
141    pub existing_pool: Option<ContractId>,
142}
143
144impl PropDeployConfig {
145    pub fn new(collateral_asset: AssetId) -> Self {
146        Self {
147            collateral_asset,
148            collateral_decimals: 6,
149            max_tier_books: 80,
150            base_repay_fee_ppm: 100,
151            owner: None,
152            proxy_owner: None,
153            cosigner: None,
154            platform_payout: None,
155            liquidator: None,
156            salt: Salt::default(),
157            max_words_per_blob: 10_000,
158            existing_registry: None,
159            existing_price_feed: None,
160            max_offchain_age_seconds: None,
161            existing_pool: None,
162        }
163    }
164}
165
166/// Handles and implementation blob IDs produced by a complete deployment.
167#[derive(Clone)]
168pub struct PropDeployment<W> {
169    /// Oracle implementation ABI bound to its stable SRC-14 proxy.
170    pub oracle: PropAccountOracleContract<W>,
171    pub oracle_proxy: PropAccountOracleProxyContract<W>,
172    pub oracle_id: ContractId,
173    pub oracle_blob_id: BlobId,
174    /// The price feed the pool values against, bound through its proxy.
175    pub price_feed: PriceFeedContract<W>,
176    pub price_feed_id: ContractId,
177    /// Shared trade-account registry implementation ABI bound to its SRC-14 proxy.
178    pub registry: TradeAccountRegistry<W>,
179    pub registry_proxy: TradeAccountRegistryProxy<W>,
180    pub registry_id: ContractId,
181    pub registry_blob_id: BlobId,
182    /// Margin-pool implementation ABI bound to its SRC-14 proxy.
183    pub pool: PropMarginPoolContract<W>,
184    pub pool_proxy: PropMarginPoolProxyContract<W>,
185    pub pool_id: ContractId,
186    pub pool_blob_id: BlobId,
187    /// Runtime account implementation selected through the oracle proxy.
188    pub account_blob_id: BlobId,
189    /// Raw configurable account-proxy bytecode consumed by the registry.
190    pub account_proxy_blob_id: BlobId,
191    /// Fixed salt used with parent/index configurables for deterministic children.
192    pub account_salt: Salt,
193    pub deployer_wallet: W,
194}
195
196impl<W> PropDeployment<W>
197where
198    W: Account + Clone,
199{
200    /// Deploy the full system in dependency order.
201    ///
202    /// The registry is deployed before the pool so its ID can be embedded in
203    /// the pool implementation configurables. The pool ID is then stored in
204    /// the account oracle through its stable proxy.
205    pub async fn deploy(deployer_wallet: &W, config: &PropDeployConfig) -> Result<Self> {
206        ensure!(
207            config.collateral_asset != AssetId::zeroed(),
208            "prop collateral asset cannot be zero"
209        );
210        ensure!(
211            config.collateral_decimals <= 18,
212            "prop collateral decimals cannot exceed 18"
213        );
214        ensure!(
215            config.max_tier_books != 0,
216            "prop max tier books cannot be zero"
217        );
218        ensure!(
219            config.max_words_per_blob != 0,
220            "prop loader blob size cannot be zero"
221        );
222
223        let deployer = Identity::Address(deployer_wallet.address());
224        let owner = config.owner.unwrap_or(deployer);
225        let proxy_owner = config.proxy_owner.unwrap_or(deployer);
226        // `initialize` refuses a zero cosigner or liquidator, so the blob this
227        // run uploads has to name SOMETHING - the deployer is the only sensible
228        // bootstrap. In production both arrive as explicit deploy parameters.
229        //
230        // The seed is only ever CONSUMED by `initialize`, which is guarded by
231        // the initialization flag, so on an already-deployed pool or oracle it
232        // is inert: storage keeps the live value and the reconciliation in
233        // `o2-deploy` is what changes it, on request. That is why the warnings
234        // are not raised here - the fallback is not news, USING it is. Warning
235        // at the fallback made an ordinary upgrade announce that the deploy key
236        // had become the residue payee, which was never true and is exactly the
237        // sort of false alarm that gets real ones ignored.
238        let cosigner_defaulted = config.cosigner.is_none();
239        let cosigner = config.cosigner.unwrap_or_else(|| deployer_wallet.address());
240        let platform_payout = config.platform_payout.unwrap_or(deployer);
241        let liquidator_defaulted = config.liquidator.is_none();
242        let liquidator = config.liquidator.unwrap_or(deployer);
243
244        let account_blob_id = upload_implementation(
245            deployer_wallet,
246            PROP_ACCOUNT_BYTECODE,
247            PROP_ACCOUNT_STORAGE,
248            Configurables::default(),
249            config,
250        )
251        .await
252        .context("deploy prop-account implementation blob")?;
253
254        // This must remain raw bytecode: the registry BLDd-loads it and patches
255        // the account-specific configurables before checking the child root.
256        let account_proxy_blob_id = blob_loader::upload_loader_blobs(
257            deployer_wallet,
258            vec![],
259            Blob::new(PROP_ACCOUNT_PROXY_BYTECODE.to_vec()),
260        )
261        .await
262        .context("deploy raw prop-account proxy blob")?;
263
264        // The final oracle implementation embeds the pool ID, while the pool
265        // transitively embeds the stable oracle proxy ID. Point the proxy at a
266        // default-config bootstrap blob first to break that deployment cycle.
267        let oracle_bootstrap_blob_id = upload_implementation(
268            deployer_wallet,
269            PROP_ACCOUNT_ORACLE_BYTECODE,
270            PROP_ACCOUNT_ORACLE_STORAGE,
271            Configurables::default(),
272            config,
273        )
274        .await
275        .context("deploy prop-account oracle implementation blob")?;
276        let oracle_proxy_configurables =
277            PropAccountOracleProxyContractConfigurables::default()
278                .with_INITIAL_OWNER(State::Initialized(proxy_owner))?
279                .with_INITIAL_TARGET(ContractId::from(oracle_bootstrap_blob_id))?;
280        let oracle_proxy_contract = regular_contract_with_implementation_storage(
281            PROP_ACCOUNT_ORACLE_PROXY_BYTECODE,
282            PROP_ACCOUNT_ORACLE_PROXY_STORAGE,
283            PROP_ACCOUNT_ORACLE_STORAGE,
284            config.salt,
285        )?
286        .with_configurables(oracle_proxy_configurables);
287        let (oracle_id, _) = deploy_regular(deployer_wallet, oracle_proxy_contract)
288            .await
289            .context("deploy prop-account oracle proxy")?;
290        let oracle_proxy =
291            PropAccountOracleProxyContract::new(oracle_id, deployer_wallet.clone());
292        let oracle = PropAccountOracleContract::new(oracle_id, deployer_wallet.clone());
293        // State-checked rather than is-new-gated: a run that crashed between
294        // the Create and this call resumes here instead of stranding an
295        // uninitialized proxy forever.
296        let oracle_proxy_target = oracle_proxy
297            .methods()
298            .proxy_target()
299            .simulate(Execution::state_read_only())
300            .await
301            .context("read prop-account oracle proxy target")?
302            .value;
303        if oracle_proxy_target.is_none() {
304            oracle_proxy
305                .methods()
306                .initialize_proxy()
307                .call()
308                .await
309                .context("initialize prop-account oracle proxy")?;
310        }
311
312        // The PRODUCTION price feed, behind its own SRC-14 proxy — not the
313        // test mock, which has neither role administration nor a pause
314        // switch and has no business backing a real pool.
315        let (price_feed, price_feed_id) = match config.existing_price_feed {
316            Some(price_feed_id) => (
317                PriceFeedContract::new(price_feed_id, deployer_wallet.clone()),
318                price_feed_id,
319            ),
320            None => {
321                // Same bootstrap trick the pool and the oracle use: the
322                // proxy's ADDRESS must not depend on the implementation's
323                // configurables, or naming a different owner would derive a
324                // different proxy and fork the feed instead of upgrading it.
325                let feed_bootstrap_blob_id = upload_implementation(
326                    deployer_wallet,
327                    PRICE_FEED_BYTECODE,
328                    PRICE_FEED_STORAGE,
329                    Configurables::default(),
330                    config,
331                )
332                .await
333                .context("deploy price-feed bootstrap implementation blob")?;
334                let feed_proxy_configurables =
335                    PriceFeedProxyContractConfigurables::default()
336                        .with_INITIAL_OWNER(State::Initialized(proxy_owner))?
337                        .with_INITIAL_TARGET(ContractId::from(feed_bootstrap_blob_id))?;
338                let feed_proxy_contract = regular_contract_with_implementation_storage(
339                    PRICE_FEED_PROXY_BYTECODE,
340                    PRICE_FEED_PROXY_STORAGE,
341                    PRICE_FEED_STORAGE,
342                    config.salt,
343                )?
344                .with_configurables(feed_proxy_configurables);
345                let (price_feed_id, _) =
346                    deploy_regular(deployer_wallet, feed_proxy_contract)
347                        .await
348                        .context("deploy price-feed proxy")?;
349                let feed_proxy =
350                    PriceFeedProxyContract::new(price_feed_id, deployer_wallet.clone());
351                let feed_proxy_target = feed_proxy
352                    .methods()
353                    .proxy_target()
354                    .simulate(Execution::state_read_only())
355                    .await
356                    .context("read price-feed proxy target")?
357                    .value;
358                if feed_proxy_target.is_none() {
359                    feed_proxy
360                        .methods()
361                        .initialize_proxy()
362                        .call()
363                        .await
364                        .context("initialize price-feed proxy")?;
365                }
366                upgrade_price_feed_implementation(
367                    deployer_wallet,
368                    price_feed_id,
369                    owner,
370                    config,
371                )
372                .await?;
373                let price_feed =
374                    PriceFeedContract::new(price_feed_id, deployer_wallet.clone());
375                let feed_is_uninitialized = price_feed
376                    .methods()
377                    .owner()
378                    .simulate(Execution::state_read_only())
379                    .await
380                    .context("read price-feed initialization state")?
381                    .value
382                    == State::Uninitialized;
383                if feed_is_uninitialized {
384                    price_feed
385                        .methods()
386                        .initialize()
387                        .call()
388                        .await
389                        .context("initialize price-feed")?;
390                }
391                // `initialize` grants the owner the ADMIN role only —
392                // publishing needs the submitter role named explicitly, and
393                // the deploy seeds its prices as the owner. No widening: the
394                // owner may grant it to itself at will, so withholding it
395                // would only mean the first publish reverts.
396                let owner_can_publish = price_feed
397                    .methods()
398                    .has_role(PRICE_SUBMITTER_ROLE, owner)
399                    .simulate(Execution::state_read_only())
400                    .await
401                    .context("read the price feed's submitter role")?
402                    .value;
403                if !owner_can_publish {
404                    price_feed
405                        .methods()
406                        .add_publisher(owner)
407                        .call()
408                        .await
409                        .context("grant the price feed's owner the submitter role")?;
410                }
411                (price_feed, price_feed_id)
412            }
413        };
414
415        // The submission-age bound, reconciled compare-first against
416        // whatever the feed currently enforces. Opt-in: with nothing
417        // configured the contract's own default stands, so a feed this
418        // deploy does not own is never written to.
419        if let Some(seconds) = config.max_offchain_age_seconds {
420            let current = price_feed
421                .methods()
422                .get_max_offchain_age()
423                .simulate(Execution::state_read_only())
424                .await
425                .context("read the price feed's submission-age bound")?
426                .value;
427            if current != seconds {
428                price_feed
429                    .methods()
430                    .set_max_offchain_age(seconds)
431                    .call()
432                    .await
433                    .context("set the price feed's submission-age bound")?;
434            }
435        }
436
437        let [oracle_offset, parent_offset, index_offset] = prop_account_proxy_offsets()?;
438        let prop_registry_configurables = |base: TradeAccountRegistryConfigurables| {
439            Ok::<_, anyhow::Error>(
440                base.with_PROP_ACCOUNT_ORACLE_CONTRACT_ID(oracle_id)?
441                    .with_DEFAULT_PROP_ACCOUNT_PROXY(ContractId::from(
442                        account_proxy_blob_id,
443                    ))?
444                    .with_PROP_ORACLE_CONFIG_OFFSET(oracle_offset)?
445                    .with_PROP_PARENT_CONFIG_OFFSET(parent_offset)?
446                    .with_PROP_INDEX_CONFIG_OFFSET(index_offset)?,
447            )
448        };
449        let (registry_id, registry_blob_id) = match &config.existing_registry {
450            Some(existing) => {
451                // Upgrade the shared registry's implementation in place:
452                // same proxy, a fresh blob repeating the oracle ids it was
453                // deployed with plus the prop configurables above. Storage
454                // (registered accounts, ownership) rides through untouched.
455                let manager = TradeAccountRegistryManager::new(
456                    deployer_wallet.clone(),
457                    existing.registry_id,
458                );
459                let deploy_config = TradeAccountRegistryDeployConfig {
460                    registry_config: prop_registry_configurables(
461                        TradeAccountRegistryConfigurables::default(),
462                    )?,
463                    ..Default::default()
464                };
465                // Blob uploads are exists-checked; the retarget only fires
466                // when the proxy does not already point at the upgraded
467                // implementation, so a re-run is a no-op.
468                let registry_blob_id = TradeAccountRegistryManager::deploy_register_blob(
469                    deployer_wallet,
470                    existing.trade_account_oracle_id,
471                    existing.trial_trade_account_oracle_id,
472                    &deploy_config,
473                )
474                .await
475                .context("build upgraded shared trade-account registry blob")?;
476                let current_target = manager
477                    .registry_proxy
478                    .methods()
479                    .proxy_target()
480                    .simulate(Execution::state_read_only())
481                    .await
482                    .context("read shared trade-account registry proxy target")?
483                    .value;
484                if current_target != Some(ContractId::from(registry_blob_id)) {
485                    manager
486                        .registry_proxy
487                        .methods()
488                        .set_proxy_target(ContractId::from(registry_blob_id))
489                        .call()
490                        .await
491                        .context("upgrade shared trade-account registry for prop")?;
492                }
493                (existing.registry_id, registry_blob_id)
494            }
495            None => {
496                let registry_configurables = prop_registry_configurables(
497                    TradeAccountRegistryConfigurables::default()
498                        .with_INITIAL_OWNER(TradeAccountRegistryState::Initialized(
499                            owner,
500                        ))?
501                        .with_INITIAL_TRIAL_TRADE_ACCOUNT_CREATOR(owner)?,
502                )?;
503                let registry_blob_id = upload_implementation(
504                    deployer_wallet,
505                    TRADE_ACCOUNT_REGISTER_BYTECODE,
506                    TRADE_ACCOUNT_REGISTER_STORAGE,
507                    registry_configurables,
508                    config,
509                )
510                .await
511                .context("deploy shared trade-account registry implementation blob")?;
512
513                let registry_proxy_configurables =
514                    TradeAccountRegistryProxyConfigurables::default()
515                        .with_INITIAL_OWNER(TradeAccountRegistryState::Initialized(
516                            proxy_owner,
517                        ))?
518                        .with_INITIAL_TARGET(ContractId::from(registry_blob_id))?;
519                let registry_proxy_contract = regular_contract(
520                    TRADE_ACCOUNT_REGISTER_PROXY_BYTECODE,
521                    TRADE_ACCOUNT_REGISTER_PROXY_STORAGE,
522                    config.salt,
523                )?
524                .with_configurables(registry_proxy_configurables);
525                let (registry_id, registry_proxy_is_new) =
526                    deploy_regular(deployer_wallet, registry_proxy_contract)
527                        .await
528                        .context("deploy shared trade-account registry proxy")?;
529                let registry_proxy =
530                    TradeAccountRegistryProxy::new(registry_id, deployer_wallet.clone());
531                let registry =
532                    TradeAccountRegistry::new(registry_id, deployer_wallet.clone());
533                if registry_proxy_is_new {
534                    registry_proxy
535                        .methods()
536                        .initialize_proxy()
537                        .call()
538                        .await
539                        .context("initialize shared trade-account registry proxy")?;
540                    registry
541                        .methods()
542                        .initialize()
543                        .call()
544                        .await
545                        .context("initialize shared trade-account registry")?;
546                }
547                (registry_id, registry_blob_id)
548            }
549        };
550        let registry_proxy =
551            TradeAccountRegistryProxy::new(registry_id, deployer_wallet.clone());
552        let registry = TradeAccountRegistry::new(registry_id, deployer_wallet.clone());
553
554        let pool_configurables = PropMarginPoolContractConfigurables::default()
555            .with_INITIAL_ADMIN(owner)?
556            .with_INITIAL_REGISTRY(registry_id)?
557            .with_INITIAL_PRICE_FEED(price_feed_id)?
558            .with_INITIAL_PLATFORM_PAYOUT(platform_payout)?
559            .with_INITIAL_LIQUIDATOR(liquidator)?
560            .with_COLLATERAL_ASSET(config.collateral_asset)?
561            .with_COLLATERAL_DECIMALS(config.collateral_decimals)?
562            .with_MAX_TIER_BOOKS(config.max_tier_books)?
563            .with_BASE_REPAY_FEE_PPM(config.base_repay_fee_ppm)?;
564        let pool_blob_id = upload_implementation(
565            deployer_wallet,
566            PROP_MARGIN_POOL_BYTECODE,
567            PROP_MARGIN_POOL_STORAGE,
568            pool_configurables,
569            config,
570        )
571        .await
572        .context("deploy prop margin-pool implementation blob")?;
573
574        // The proxy's ADDRESS must not depend on the implementation's
575        // configurables, or changing a runtime value - the liquidator, the
576        // payout party, the feed - would derive a DIFFERENT proxy and fork the
577        // pool instead of upgrading it. Point it at a default-config bootstrap
578        // blob (the same trick the oracle below uses to break its own cycle),
579        // then retarget to the configured implementation.
580        // ...but that only covers CONFIGURABLE changes. The bootstrap blob
581        // id is a hash of the pool BYTECODE, so any release that touches
582        // the pool derives a different `INITIAL_TARGET`, a different proxy
583        // address, and forks the pool instead of upgrading it — silently,
584        // leaving the funded one orphaned. A caller that already knows its
585        // pool pins the id, and derivation is only for the first deploy.
586        let pool_id = match config.existing_pool {
587            Some(pool_id) => pool_id,
588            None => {
589                let pool_bootstrap_blob_id = upload_implementation(
590                    deployer_wallet,
591                    PROP_MARGIN_POOL_BYTECODE,
592                    PROP_MARGIN_POOL_STORAGE,
593                    Configurables::default(),
594                    config,
595                )
596                .await
597                .context("deploy prop margin-pool bootstrap implementation blob")?;
598                let pool_proxy_configurables =
599                    PropMarginPoolProxyContractConfigurables::default()
600                        .with_INITIAL_OWNER(State::Initialized(proxy_owner))?
601                        .with_INITIAL_TARGET(ContractId::from(pool_bootstrap_blob_id))?;
602                let pool_proxy_contract = regular_contract_with_implementation_storage(
603                    PROP_MARGIN_POOL_PROXY_BYTECODE,
604                    PROP_MARGIN_POOL_PROXY_STORAGE,
605                    PROP_MARGIN_POOL_STORAGE,
606                    config.salt,
607                )?
608                .with_configurables(pool_proxy_configurables);
609                let (pool_id, _) = deploy_regular(deployer_wallet, pool_proxy_contract)
610                    .await
611                    .context("deploy prop margin-pool proxy")?;
612                pool_id
613            }
614        };
615        let pool_proxy =
616            PropMarginPoolProxyContract::new(pool_id, deployer_wallet.clone());
617        let pool = PropMarginPoolContract::new(pool_id, deployer_wallet.clone());
618        let pool_proxy_target = pool_proxy
619            .methods()
620            .proxy_target()
621            .simulate(Execution::state_read_only())
622            .await
623            .context("read prop margin-pool proxy target")?
624            .value;
625        if pool_proxy_target.is_none() {
626            pool_proxy
627                .methods()
628                .initialize_proxy()
629                .call()
630                .await
631                .context("initialize prop margin-pool proxy")?;
632        }
633        // The upgrade itself: new configurables mean a new blob, and the
634        // stable proxy is pointed at it. A run that changes nothing computes
635        // the same blob id and retargets nothing.
636        let pool_target = pool_proxy
637            .methods()
638            .proxy_target()
639            .simulate(Execution::state_read_only())
640            .await
641            .context("read configured prop margin-pool proxy target")?
642            .value;
643        if pool_target != Some(ContractId::from(pool_blob_id)) {
644            pool_proxy
645                .methods()
646                .set_proxy_target(ContractId::from(pool_blob_id))
647                .call()
648                .await
649                .context("activate configured prop margin-pool implementation")?;
650        }
651
652        let oracle_configurables = PropAccountOracleContractConfigurables::default()
653            .with_INITIAL_OWNER(owner)?
654            .with_INITIAL_PROP_ACCOUNT_IMPL(ContractId::from(account_blob_id))?
655            .with_INITIAL_COSIGNER(cosigner)?
656            .with_INITIAL_PROP_MARGIN_POOL(pool_id)?;
657        let oracle_blob_id = upload_implementation(
658            deployer_wallet,
659            PROP_ACCOUNT_ORACLE_BYTECODE,
660            PROP_ACCOUNT_ORACLE_STORAGE,
661            oracle_configurables,
662            config,
663        )
664        .await
665        .context("deploy configured prop-account oracle implementation blob")?;
666        let oracle_target = oracle_proxy
667            .methods()
668            .proxy_target()
669            .simulate(Execution::state_read_only())
670            .await
671            .context("read prop-account oracle proxy target")?
672            .value;
673        if oracle_target != Some(ContractId::from(oracle_blob_id)) {
674            oracle_proxy
675                .methods()
676                .set_proxy_target(ContractId::from(oracle_blob_id))
677                .call()
678                .await
679                .context("activate configured prop-account oracle implementation")?;
680        }
681
682        let oracle_is_uninitialized = oracle
683            .methods()
684            .owner()
685            .simulate(Execution::state_read_only())
686            .await
687            .context("read prop-account oracle initialization state")?
688            .value
689            == State::Uninitialized;
690        if oracle_is_uninitialized {
691            // NOW the seed becomes the live cosigner, so now it is worth
692            // saying. An oracle that was already initialized keeps whatever
693            // its storage holds and never reaches this branch.
694            if cosigner_defaulted {
695                tracing::warn!(
696                    "prop deploy: no cosigner given and this oracle is being \
697                     initialized - the deployer becomes the cosigner. The \
698                     backend must run MARGIN_COSIGNER_KEY for this address or \
699                     margin stays inert."
700                );
701            }
702            oracle
703                .methods()
704                .initialize()
705                .call()
706                .await
707                .context("initialize prop-account oracle")?;
708        }
709
710        // The account implementation EVERY margin account resolves through,
711        // reconciled explicitly — the same defect the cosigner already had,
712        // and the price feed had on the pool.
713        //
714        // `INITIAL_PROP_ACCOUNT_IMPL` reaches storage only through the
715        // one-time `initialize` above. On an already-initialized oracle that
716        // branch is skipped, so baking a fresh `account_blob_id` into the
717        // oracle's configurables and retargeting its proxy — both of which
718        // this run does, and both of which succeed — still leaves
719        // `get_prop_account_impl` answering with the PREVIOUS blob. Every
720        // account keeps running the old bytecode while the deploy reports a
721        // clean upgrade, which is the worst shape a bug can take.
722        //
723        // Compare-first, like every other reconcile here: an oracle already
724        // on this implementation costs one read and no transaction.
725        let stored_impl = oracle
726            .methods()
727            .get_prop_account_impl()
728            .simulate(Execution::state_read_only())
729            .await
730            .context("read the prop-account oracle's account implementation")?
731            .value;
732        let account_impl = ContractId::from(account_blob_id);
733        if stored_impl != Some(account_impl) {
734            tracing::info!(
735                "Prop: account implementation {stored_impl:?} -> {account_impl:?}"
736            );
737            oracle
738                .methods()
739                .set_prop_account_impl(account_impl)
740                .call()
741                .await
742                .context("activate the prop-account implementation on the oracle")?;
743        }
744
745        // The account implementation EVERY margin account resolves through,
746        // reconciled explicitly — the same defect the cosigner already had,
747        // and the price feed had on the pool.
748        //
749        // `INITIAL_PROP_ACCOUNT_IMPL` reaches storage only through the
750        // one-time `initialize` above. On an already-initialized oracle that
751        // branch is skipped, so baking a fresh `account_blob_id` into the
752        // oracle's configurables and retargeting its proxy — both of which
753        // this run does, and both of which succeed — still leaves
754        // `get_prop_account_impl` answering with the PREVIOUS blob. Every
755        // account keeps running the old bytecode while the deploy reports a
756        // clean upgrade, which is the worst shape a bug can take.
757        //
758        // Compare-first, like every other reconcile here: an oracle already
759        // on this implementation costs one read and no transaction.
760
761        // State-checked: a resumed run initializes iff the pool has not
762        // been initialized yet, whether or not this run created the proxy.
763        let deployed_collateral = pool
764            .methods()
765            .collateral_asset()
766            .simulate(Execution::state_read_only())
767            .await
768            .context("read deployed prop margin-pool collateral")?
769            .value;
770        ensure!(
771            deployed_collateral == config.collateral_asset,
772            "prop margin-pool collateral configurable mismatch"
773        );
774        ensure!(
775            pool.methods()
776                .collateral_decimals()
777                .simulate(Execution::state_read_only())
778                .await
779                .context("read deployed prop margin-pool collateral decimals")?
780                .value
781                == config.collateral_decimals,
782            "prop margin-pool decimals configurable mismatch"
783        );
784        ensure!(
785            pool.methods()
786                .max_tier_books()
787                .simulate(Execution::state_read_only())
788                .await
789                .context("read deployed prop margin-pool book limit")?
790                .value
791                == config.max_tier_books,
792            "prop margin-pool book-limit configurable mismatch"
793        );
794        let pool_is_initialized = pool
795            .methods()
796            .is_initialized()
797            .simulate(Execution::state_read_only())
798            .await
799            .context("read deployed prop margin-pool initialization state")?
800            .value;
801        if !pool_is_initialized {
802            // Same rule as the oracle's cosigner above: the seed only becomes
803            // the payee here, on a pool that has never been initialized.
804            if liquidator_defaulted {
805                tracing::warn!(
806                    "prop deploy: no liquidator given and this pool is being \
807                     initialized - the deployer becomes the liquidator, and \
808                     will receive the residue of every forced exit."
809                );
810            }
811            pool.methods()
812                .initialize()
813                .call()
814                .await
815                .context("initialize prop margin pool")?;
816        }
817
818        Ok(Self {
819            oracle,
820            oracle_proxy,
821            oracle_id,
822            oracle_blob_id,
823            price_feed,
824            price_feed_id,
825            registry,
826            registry_proxy,
827            registry_id,
828            registry_blob_id,
829            pool,
830            pool_proxy,
831            pool_id,
832            pool_blob_id,
833            account_blob_id,
834            account_proxy_blob_id,
835            account_salt: config.salt,
836            deployer_wallet: deployer_wallet.clone(),
837        })
838    }
839
840    /// Deploy and register one deterministic prop-account child.
841    ///
842    /// `parent_caller` submits the registration transaction and must resolve
843    /// to `parent`; the registry enforces this relationship on chain.
844    pub async fn deploy_account(
845        &self,
846        parent_caller: &W,
847        parent: Identity,
848        index: u64,
849    ) -> Result<PropAccountProxyContract<W>> {
850        ensure!(
851            parent != Identity::Address(Address::zeroed()),
852            "prop-account parent cannot be zero"
853        );
854
855        let configurables = PropAccountProxyContractConfigurables::default()
856            .with_ORACLE_CONTRACT_ID(self.oracle_id)?
857            .with_PARENT(parent)?
858            .with_INDEX(index)?;
859        let child_contract = regular_contract(
860            PROP_ACCOUNT_PROXY_BYTECODE,
861            PROP_ACCOUNT_PROXY_STORAGE,
862            self.account_salt,
863        )?
864        .with_configurables(configurables);
865        let (child_id, _) = deploy_regular(&self.deployer_wallet, child_contract)
866            .await
867            .context("deploy prop-account child")?;
868
869        let child = PropAccountProxyContract::new(child_id, self.deployer_wallet.clone());
870        if !self
871            .registry
872            .methods()
873            .prop_is_valid(child_id)
874            .simulate(Execution::state_read_only())
875            .await?
876            .value
877        {
878            TradeAccountRegistry::new(self.registry_id, parent_caller.clone())
879                .methods()
880                .prop_register_contract(child_id, parent, index)
881                .with_contract_ids(&[self.oracle_id, child_id, self.pool_id])
882                .call()
883                .await
884                .context("register prop-account child")?;
885        }
886
887        Ok(child)
888    }
889
890    /// Bind the implementation ABI to a deployed child proxy.
891    pub fn account(&self, account_id: ContractId) -> PropAccountContract<W> {
892        PropAccountContract::new(account_id, self.deployer_wallet.clone())
893    }
894}
895
896/// Byte offsets of the margin-account proxy's `ORACLE_CONTRACT_ID`,
897/// `PARENT` and `INDEX` configurables, in that order.
898///
899/// A build-time property of the bundled artifact — nothing touches the
900/// chain. Public because the PLAIN registry upgrade has to repeat these
901/// values verbatim or it resets them to zero; see
902/// `live_prop_registry_config` in `o2-deploy`.
903pub fn prop_account_proxy_offsets() -> Result<[u64; 3]> {
904    fn only_offset(configurables: Configurables, name: &str) -> Result<u64> {
905        let offsets: Vec<Configurable> = configurables.offsets_with_data;
906        ensure!(
907            offsets.len() == 1,
908            "expected one {name} configurable, got {}",
909            offsets.len()
910        );
911        Ok(offsets[0].offset)
912    }
913
914    let oracle: Configurables = PropAccountProxyContractConfigurables::default()
915        .with_ORACLE_CONTRACT_ID(ContractId::zeroed())?
916        .into();
917    let parent: Configurables = PropAccountProxyContractConfigurables::default()
918        .with_PARENT(Identity::Address(Address::zeroed()))?
919        .into();
920    let index: Configurables = PropAccountProxyContractConfigurables::default()
921        .with_INDEX(0)?
922        .into();
923
924    Ok([
925        only_offset(oracle, "oracle")?,
926        only_offset(parent, "parent")?,
927        only_offset(index, "index")?,
928    ])
929}
930
931fn storage_slots(bytes: &[u8]) -> Result<Vec<StorageSlot>> {
932    serde_json::from_slice(bytes).context("decode contract storage slots")
933}
934
935fn regular_contract(
936    bytecode: &[u8],
937    storage: &[u8],
938    salt: Salt,
939) -> Result<Contract<Regular>> {
940    Ok(Contract::regular(
941        bytecode.to_vec(),
942        salt,
943        storage_slots(storage)?,
944    ))
945}
946
947fn regular_contract_with_implementation_storage(
948    bytecode: &[u8],
949    proxy_storage: &[u8],
950    implementation_storage: &[u8],
951    salt: Salt,
952) -> Result<Contract<Regular>> {
953    let mut slots = storage_slots(proxy_storage)?;
954    for implementation_slot in storage_slots(implementation_storage)? {
955        ensure!(
956            !slots
957                .iter()
958                .any(|proxy_slot| proxy_slot.key() == implementation_slot.key()),
959            "proxy and implementation storage slots collide"
960        );
961        slots.push(implementation_slot);
962    }
963    Ok(Contract::regular(bytecode.to_vec(), salt, slots))
964}
965
966/// Points a price-feed PROXY at the implementation this build carries,
967/// exactly as the order books are upgraded: read the live target, rebuild
968/// the configured blob, and retarget only when the two differ. A feed
969/// already on this bytecode costs no transaction.
970///
971/// Returns the active implementation id.
972///
973/// `set_proxy_target` is owner-only, so this works on a feed this deployer
974/// owns; a feed owned elsewhere must be upgraded by its own owner.
975pub async fn upgrade_price_feed_implementation<W>(
976    deployer_wallet: &W,
977    price_feed_id: ContractId,
978    owner: Identity,
979    config: &PropDeployConfig,
980) -> Result<ContractId>
981where
982    W: Account + Clone,
983{
984    let feed_proxy = PriceFeedProxyContract::new(price_feed_id, deployer_wallet.clone());
985    let current = feed_proxy
986        .methods()
987        .proxy_target()
988        .simulate(Execution::state_read_only())
989        .await
990        .context(
991            "read the price feed's proxy target - an unproxied feed cannot be \
992             upgraded in place",
993        )?
994        .value;
995    let feed_blob_id = upload_implementation(
996        deployer_wallet,
997        PRICE_FEED_BYTECODE,
998        PRICE_FEED_STORAGE,
999        PriceFeedContractConfigurables::default()
1000            .with_INITIAL_OWNER(State::Initialized(owner))?,
1001        config,
1002    )
1003    .await
1004    .context("deploy configured price-feed implementation blob")?;
1005    let feed_blob_id = ContractId::from(feed_blob_id);
1006    if current != Some(feed_blob_id) {
1007        tracing::info!(
1008            "Upgrade price feed implementation from {current:?} to {feed_blob_id:?}"
1009        );
1010        feed_proxy
1011            .methods()
1012            .set_proxy_target(feed_blob_id)
1013            .call()
1014            .await
1015            .context("activate configured price-feed implementation")?;
1016    }
1017    Ok(feed_blob_id)
1018}
1019
1020/// `PRICE_SUBMITTER_ROLE` on the price feed — the role `add_publisher`
1021/// grants and `publish_prices` demands. Mirrors the contract's constant.
1022pub const PRICE_SUBMITTER_ROLE: u64 = 2;
1023
1024async fn upload_implementation<W>(
1025    deployer_wallet: &W,
1026    bytecode: &[u8],
1027    storage: &[u8],
1028    configurables: impl Into<Configurables>,
1029    config: &PropDeployConfig,
1030) -> Result<BlobId>
1031where
1032    W: Account,
1033{
1034    let (data_blobs, loader_blob) = blob_loader::build_loader_blobs(
1035        bytecode.to_vec(),
1036        config.salt,
1037        storage_slots(storage)?,
1038        configurables,
1039        config.max_words_per_blob,
1040    )?;
1041    blob_loader::upload_loader_blobs(deployer_wallet, data_blobs, loader_blob).await
1042}
1043
1044async fn deploy_regular<W>(
1045    deployer_wallet: &W,
1046    contract: Contract<Regular>,
1047) -> Result<(ContractId, bool)>
1048where
1049    W: Account,
1050{
1051    let contract_id = contract.contract_id();
1052    let is_new = !deployer_wallet
1053        .try_provider()?
1054        .contract_exists(&contract_id)
1055        .await?;
1056    if is_new {
1057        contract
1058            .deploy(deployer_wallet, TxPolicies::default())
1059            .await?;
1060    }
1061    Ok((contract_id, is_new))
1062}
1063
1064#[cfg(test)]
1065mod tests {
1066    use super::*;
1067    use crate::{
1068        order_book_deploy::{
1069            OrderArgs,
1070            OrderBookConfigurables,
1071            OrderBookDeploy,
1072            OrderBookDeployConfig,
1073            OrderType,
1074        },
1075        prop::{
1076            MarginPoolPauseChanged,
1077            MarginPoolPlatformPayoutChanged,
1078            MarginPoolPriceFeedChanged,
1079            MarginPoolRegistryChanged,
1080            MarginTradeAccountWithdrawn,
1081            PriceInput,
1082            PropOrderBookCleanup,
1083            SessionClosed,
1084            SessionSeized,
1085            SettlementReason,
1086            TierParams,
1087        },
1088    };
1089    use fuels::test_helpers::{
1090        AssetConfig,
1091        WalletsConfig,
1092        launch_custom_provider_and_get_wallets,
1093    };
1094    use std::time::{
1095        SystemTime,
1096        UNIX_EPOCH,
1097    };
1098
1099    fn assert_recent_timestamp(timestamp: u64) {
1100        let now = SystemTime::now()
1101            .duration_since(UNIX_EPOCH)
1102            .expect("system time predates the Unix epoch")
1103            .as_secs();
1104        // A generous window on purpose: this catches a garbage stamp - epoch
1105        // zero, a wildly wrong clock - not sub-second precision. A tight
1106        // bound made the whole prop suite serialise behind one mutex just so
1107        // no test was ever starved long enough to blow it; the tests each run
1108        // their own node, so the mutex only ever bought this tolerance. With
1109        // the window widened the tests parallelise and the mutex is gone.
1110        assert!(
1111            timestamp.abs_diff(now) <= 120,
1112            "event timestamp {timestamp} is not close to {now}"
1113        );
1114    }
1115
1116    #[tokio::test]
1117    async fn deploys_independent_prop_system_and_registers_child() {
1118        let collateral_asset = AssetId::new([1; 32]);
1119        let base_asset = AssetId::new([2; 32]);
1120        let initial_balance = 10_000_000_000u64;
1121        let mut wallets = launch_custom_provider_and_get_wallets(
1122            WalletsConfig::new_multiple_assets(
1123                2,
1124                vec![
1125                    AssetConfig {
1126                        id: AssetId::default(),
1127                        num_coins: 2,
1128                        coin_amount: initial_balance,
1129                    },
1130                    AssetConfig {
1131                        id: collateral_asset,
1132                        num_coins: 2,
1133                        coin_amount: initial_balance,
1134                    },
1135                    AssetConfig {
1136                        id: base_asset,
1137                        num_coins: 2,
1138                        coin_amount: initial_balance,
1139                    },
1140                ],
1141            ),
1142            None,
1143            Some(::fuels::test_helpers::ChainConfig::local_testnet()),
1144        )
1145        .await
1146        .unwrap();
1147        let user = wallets.pop().unwrap();
1148        let deployer = wallets.pop().unwrap();
1149
1150        let deployment = PropDeployment::deploy(&deployer, &{
1151            // The production feed bounds a submission's age against the
1152            // block clock; this test publishes at a fixed timestamp.
1153            let mut config = PropDeployConfig::new(collateral_asset);
1154            config.max_offchain_age_seconds = Some(10_000_000_000);
1155            config
1156        })
1157        .await
1158        .unwrap();
1159
1160        let oracle_target = deployment
1161            .oracle
1162            .methods()
1163            .get_prop_account_impl()
1164            .simulate(Execution::state_read_only())
1165            .await
1166            .unwrap()
1167            .value;
1168        assert_eq!(
1169            oracle_target,
1170            Some(ContractId::from(deployment.account_blob_id))
1171        );
1172        assert_eq!(
1173            deployment
1174                .oracle
1175                .methods()
1176                .get_prop_margin_pool()
1177                .simulate(Execution::state_read_only())
1178                .await
1179                .unwrap()
1180                .value,
1181            Some(deployment.pool_id)
1182        );
1183        assert_eq!(
1184            deployment
1185                .registry
1186                .methods()
1187                .get_prop_oracle_id()
1188                .simulate(Execution::state_read_only())
1189                .await
1190                .unwrap()
1191                .value,
1192            deployment.oracle_id
1193        );
1194        assert_eq!(
1195            deployment
1196                .registry
1197                .methods()
1198                .get_prop_pool_id()
1199                .with_contract_ids(&[deployment.oracle_id])
1200                .simulate(Execution::state_read_only())
1201                .await
1202                .unwrap()
1203                .value,
1204            deployment.pool_id
1205        );
1206        assert_eq!(
1207            deployment
1208                .pool
1209                .methods()
1210                .registry()
1211                .simulate(Execution::state_read_only())
1212                .await
1213                .unwrap()
1214                .value,
1215            deployment.registry_id
1216        );
1217        assert_eq!(
1218            deployment
1219                .pool
1220                .methods()
1221                .price_feed()
1222                .simulate(Execution::state_read_only())
1223                .await
1224                .unwrap()
1225                .value,
1226            deployment.price_feed_id
1227        );
1228        let deployer_identity = Identity::Address(deployer.address());
1229
1230        // The float is simply what the pool holds: outside money arrives as a
1231        // plain transfer, with no pool entry point to call.
1232        let inventory_amount = 1_234;
1233        deployer
1234            .force_transfer_to_contract(
1235                deployment.pool.contract_id(),
1236                inventory_amount,
1237                collateral_asset,
1238                TxPolicies::default(),
1239            )
1240            .await
1241            .unwrap();
1242        assert_eq!(
1243            deployment
1244                .pool
1245                .get_balances()
1246                .await
1247                .unwrap()
1248                .get(&collateral_asset)
1249                .copied()
1250                .unwrap_or_default(),
1251            inventory_amount,
1252        );
1253
1254        let registry_update = deployment
1255            .pool
1256            .methods()
1257            .set_registry(deployment.oracle_id)
1258            .call()
1259            .await
1260            .unwrap();
1261        let registry_events = registry_update
1262            .decode_logs_with_type::<MarginPoolRegistryChanged>()
1263            .unwrap();
1264        assert_recent_timestamp(registry_events[0].timestamp.unix);
1265        assert_eq!(
1266            registry_events,
1267            vec![MarginPoolRegistryChanged {
1268                old_registry: deployment.registry_id,
1269                new_registry: deployment.oracle_id,
1270                timestamp: registry_events[0].timestamp.clone(),
1271            }]
1272        );
1273        assert_eq!(
1274            deployment
1275                .pool
1276                .methods()
1277                .registry()
1278                .simulate(Execution::state_read_only())
1279                .await
1280                .unwrap()
1281                .value,
1282            deployment.oracle_id
1283        );
1284        deployment
1285            .pool
1286            .methods()
1287            .set_registry(deployment.registry_id)
1288            .call()
1289            .await
1290            .unwrap();
1291
1292        let price_feed_update = deployment
1293            .pool
1294            .methods()
1295            .set_price_feed(deployment.oracle_id)
1296            .call()
1297            .await
1298            .unwrap();
1299        let price_feed_events = price_feed_update
1300            .decode_logs_with_type::<MarginPoolPriceFeedChanged>()
1301            .unwrap();
1302        assert_recent_timestamp(price_feed_events[0].timestamp.unix);
1303        assert_eq!(
1304            price_feed_events,
1305            vec![MarginPoolPriceFeedChanged {
1306                old_price_feed: deployment.price_feed_id,
1307                new_price_feed: deployment.oracle_id,
1308                timestamp: price_feed_events[0].timestamp.clone(),
1309            }]
1310        );
1311        assert_eq!(
1312            deployment
1313                .pool
1314                .methods()
1315                .price_feed()
1316                .simulate(Execution::state_read_only())
1317                .await
1318                .unwrap()
1319                .value,
1320            deployment.oracle_id
1321        );
1322        deployment
1323            .pool
1324            .methods()
1325            .set_price_feed(deployment.price_feed_id)
1326            .call()
1327            .await
1328            .unwrap();
1329
1330        let platform_payout = Identity::Address(user.address());
1331        let payout_update = deployment
1332            .pool
1333            .methods()
1334            .set_platform_payout(platform_payout)
1335            .call()
1336            .await
1337            .unwrap();
1338        let payout_events = payout_update
1339            .decode_logs_with_type::<MarginPoolPlatformPayoutChanged>()
1340            .unwrap();
1341        assert_recent_timestamp(payout_events[0].timestamp.unix);
1342        assert_eq!(
1343            payout_events,
1344            vec![MarginPoolPlatformPayoutChanged {
1345                old_platform_payout: deployer_identity,
1346                new_platform_payout: platform_payout,
1347                timestamp: payout_events[0].timestamp.clone(),
1348            }]
1349        );
1350        deployment
1351            .pool
1352            .methods()
1353            .set_platform_payout(deployer_identity)
1354            .call()
1355            .await
1356            .unwrap();
1357
1358        let pause_response = deployment.pool.methods().pause().call().await.unwrap();
1359        let pause_events = pause_response
1360            .decode_logs_with_type::<MarginPoolPauseChanged>()
1361            .unwrap();
1362        assert_recent_timestamp(pause_events[0].timestamp.unix);
1363        assert_eq!(pause_events.len(), 1);
1364        assert!(pause_events[0].paused);
1365
1366        let unpause_response = deployment.pool.methods().unpause().call().await.unwrap();
1367        let unpause_events = unpause_response
1368            .decode_logs_with_type::<MarginPoolPauseChanged>()
1369            .unwrap();
1370        assert_recent_timestamp(unpause_events[0].timestamp.unix);
1371        assert_eq!(unpause_events.len(), 1);
1372        assert!(!unpause_events[0].paused);
1373
1374        let user_pool = PropMarginPoolContract::new(deployment.pool_id, user.clone());
1375        assert!(
1376            user_pool
1377                .methods()
1378                .set_registry(deployment.oracle_id)
1379                .call()
1380                .await
1381                .is_err()
1382        );
1383
1384        assert!(
1385            deployment
1386                .pool
1387                .methods()
1388                .has_role(0, deployer_identity)
1389                .simulate(Execution::state_read_only())
1390                .await
1391                .unwrap()
1392                .value
1393        );
1394        let order_book_configurables = OrderBookConfigurables::default()
1395            .with_MAKER_FEE(0u64.into())
1396            .unwrap()
1397            .with_TAKER_FEE(0u64.into())
1398            .unwrap()
1399            .with_MIN_ORDER(1)
1400            .unwrap()
1401            .with_DUST(0)
1402            .unwrap();
1403        let order_book_config =
1404            OrderBookDeployConfig::with_configurables(order_book_configurables);
1405        let order_book = OrderBookDeploy::deploy(
1406            &deployer,
1407            base_asset,
1408            collateral_asset,
1409            &order_book_config,
1410        )
1411        .await
1412        .unwrap();
1413        let mut second_order_book_config = order_book_config.clone();
1414        second_order_book_config.salt = Salt::from([1u8; 32]);
1415        let second_order_book = OrderBookDeploy::deploy(
1416            &deployer,
1417            base_asset,
1418            collateral_asset,
1419            &second_order_book_config,
1420        )
1421        .await
1422        .unwrap();
1423
1424        deployment
1425            .price_feed
1426            .methods()
1427            .set_asset_decimals(collateral_asset, 6)
1428            .call()
1429            .await
1430            .unwrap();
1431        deployment
1432            .price_feed
1433            .methods()
1434            .set_asset_decimals(base_asset, 9)
1435            .call()
1436            .await
1437            .unwrap();
1438        deployment
1439            .price_feed
1440            .methods()
1441            .publish_prices(vec![
1442                PriceInput {
1443                    asset: collateral_asset,
1444                    bid: 1_000_000_000_000_000_000u64.into(),
1445                    ask: 1_000_000_000_000_000_000u64.into(),
1446                    // Strictly above the replay floor of 0, and in the past.
1447                    timestamp: 1,
1448                },
1449                PriceInput {
1450                    asset: base_asset,
1451                    bid: 2_000_000_000_000_000_000u64.into(),
1452                    ask: 2_000_000_000_000_000_000u64.into(),
1453                    timestamp: 1,
1454                },
1455            ])
1456            .call()
1457            .await
1458            .unwrap();
1459        assert!(
1460            deployment
1461                .price_feed
1462                .methods()
1463                .has_price(collateral_asset)
1464                .simulate(Execution::state_read_only())
1465                .await
1466                .unwrap()
1467                .value
1468        );
1469
1470        let tier_params = TierParams {
1471            line: 10_000_000,
1472            leverage: 5,
1473            duration: 86_400,
1474            maintenance_bps: 250,
1475            open_buffer_bps: 375,
1476            liq_price_factor: 9_900,
1477            // The amounts the old bps rates derived from this line: 6, 21,
1478            // 76 and 738 bps of 10_000_000.
1479            prolong_fee: [0, 21_000, 76_000, 738_000],
1480            max_credit_line_bps: 20_000,
1481            max_price_age: 60,
1482            open_fee: 0,
1483            profit_share_bps: 1_000,
1484            price_band_bps: 1_000,
1485        };
1486        assert!(
1487            deployment
1488                .pool
1489                .methods()
1490                .publish_tier_version(
1491                    1,
1492                    TierParams {
1493                        leverage: 0,
1494                        ..tier_params.clone()
1495                    },
1496                    vec![order_book.contract_id],
1497                )
1498                .call()
1499                .await
1500                .is_err()
1501        );
1502        deployment
1503            .pool
1504            .methods()
1505            .publish_tier_version(
1506                1,
1507                tier_params,
1508                vec![order_book.contract_id, second_order_book.contract_id],
1509            )
1510            .with_contract_ids(&[
1511                order_book.contract_id,
1512                second_order_book.contract_id,
1513                deployment.price_feed_id,
1514            ])
1515            .call()
1516            .await
1517            .unwrap();
1518
1519        let tier = deployment
1520            .pool
1521            .methods()
1522            .get_tier(1, 1)
1523            .simulate(Execution::state_read_only())
1524            .await
1525            .unwrap()
1526            .value
1527            .expect("published tier version");
1528        assert_eq!(tier.line, 10_000_000);
1529        assert_eq!(
1530            deployment
1531                .pool
1532                .methods()
1533                .current_tier_version(1)
1534                .simulate(Execution::state_read_only())
1535                .await
1536                .unwrap()
1537                .value,
1538            Some(1)
1539        );
1540        assert_eq!(
1541            deployment
1542                .pool
1543                .methods()
1544                .tier_books(1, 1)
1545                .simulate(Execution::state_read_only())
1546                .await
1547                .unwrap()
1548                .value,
1549            vec![order_book.contract_id, second_order_book.contract_id]
1550        );
1551        let tier_assets = deployment
1552            .pool
1553            .methods()
1554            .tier_assets(1, 1)
1555            .simulate(Execution::state_read_only())
1556            .await
1557            .unwrap()
1558            .value;
1559        assert_eq!(tier_assets.len(), 2);
1560        assert!(tier_assets.contains(&base_asset));
1561        assert!(tier_assets.contains(&collateral_asset));
1562        assert!(
1563            deployment
1564                .pool
1565                .methods()
1566                .get_tier(1, 2)
1567                .simulate(Execution::state_read_only())
1568                .await
1569                .unwrap()
1570                .value
1571                .is_none()
1572        );
1573        assert!(
1574            deployment
1575                .pool
1576                .methods()
1577                .tier_books(1, 2)
1578                .simulate(Execution::state_read_only())
1579                .await
1580                .is_err()
1581        );
1582        assert!(
1583            deployment
1584                .pool
1585                .methods()
1586                .tier_assets(1, 2)
1587                .simulate(Execution::state_read_only())
1588                .await
1589                .is_err()
1590        );
1591
1592        deployment
1593            .price_feed
1594            .methods()
1595            .set_asset_decimals(base_asset, 8)
1596            .call()
1597            .await
1598            .unwrap();
1599        deployment
1600            .price_feed
1601            .methods()
1602            .publish_prices(vec![PriceInput {
1603                // Above this asset's replay floor, which the publish above
1604                // already moved to 1.
1605                asset: base_asset,
1606                bid: 2_000_000_000_000_000_000u64.into(),
1607                ask: 2_000_000_000_000_000_000u64.into(),
1608                timestamp: 2,
1609            }])
1610            .call()
1611            .await
1612            .unwrap();
1613        assert!(
1614            deployment
1615                .pool
1616                .methods()
1617                .set_price_feed(deployment.price_feed_id)
1618                .with_contracts(&[&deployment.price_feed])
1619                .call()
1620                .await
1621                .is_err()
1622        );
1623        deployment
1624            .price_feed
1625            .methods()
1626            .set_asset_decimals(base_asset, 9)
1627            .call()
1628            .await
1629            .unwrap();
1630        deployment
1631            .price_feed
1632            .methods()
1633            .publish_prices(vec![PriceInput {
1634                asset: base_asset,
1635                bid: 2_000_000_000_000_000_000u64.into(),
1636                ask: 2_000_000_000_000_000_000u64.into(),
1637                timestamp: 3,
1638            }])
1639            .call()
1640            .await
1641            .unwrap();
1642
1643        let parent = Identity::Address(user.address());
1644        let registration_error = deployment
1645            .deploy_account(&deployer, parent, 7)
1646            .await
1647            .expect_err("a caller other than the configured parent must be rejected");
1648        assert!(
1649            format!("{registration_error:?}").contains("NotParent"),
1650            "unexpected registration error: {registration_error:?}"
1651        );
1652        let child = deployment.deploy_account(&user, parent, 7).await.unwrap();
1653        assert!(
1654            deployment
1655                .registry
1656                .methods()
1657                .prop_is_valid(child.contract_id())
1658                .simulate(Execution::state_read_only())
1659                .await
1660                .unwrap()
1661                .value
1662        );
1663        assert_eq!(
1664            child
1665                .methods()
1666                .parent()
1667                .simulate(Execution::state_read_only())
1668                .await
1669                .unwrap()
1670                .value,
1671            parent
1672        );
1673        assert_eq!(
1674            child
1675                .methods()
1676                .index()
1677                .simulate(Execution::state_read_only())
1678                .await
1679                .unwrap()
1680                .value,
1681            7
1682        );
1683        assert_eq!(
1684            child
1685                .methods()
1686                .pool()
1687                .with_contract_ids(&[deployment.oracle_id])
1688                .simulate(Execution::state_read_only())
1689                .await
1690                .unwrap()
1691                .value,
1692            deployment.pool_id
1693        );
1694        assert_eq!(
1695            child
1696                .methods()
1697                .oracle()
1698                .simulate(Execution::state_read_only())
1699                .await
1700                .unwrap()
1701                .value,
1702            deployment.oracle_id
1703        );
1704
1705        let collateral = 2_000_000;
1706        let account = PropAccountContract::new(child.contract_id(), user.clone());
1707        let missing_payment_error = account
1708            .methods()
1709            .start_session(1, collateral, ProlongPeriod::SixHours)
1710            .with_contract_ids(&[
1711                deployment.oracle_id,
1712                deployment.pool_id,
1713                deployment.registry_id,
1714            ])
1715            .call()
1716            .await
1717            .unwrap_err();
1718        assert!(
1719            missing_payment_error
1720                .to_string()
1721                .contains("PaymentAmountMismatch"),
1722            "unexpected missing-payment error: {missing_payment_error:#}"
1723        );
1724        let mismatched_payment_error = account
1725            .methods()
1726            .start_session(1, collateral, ProlongPeriod::SixHours)
1727            .call_params(CallParameters::new(
1728                collateral - 1,
1729                collateral_asset,
1730                u64::MAX,
1731            ))
1732            .unwrap()
1733            .with_contract_ids(&[
1734                deployment.oracle_id,
1735                deployment.pool_id,
1736                deployment.registry_id,
1737            ])
1738            .call()
1739            .await
1740            .unwrap_err();
1741        assert!(
1742            mismatched_payment_error
1743                .to_string()
1744                .contains("PaymentAmountMismatch"),
1745            "unexpected mismatched-payment error: {mismatched_payment_error:#}"
1746        );
1747        let wrong_asset_error = account
1748            .methods()
1749            .start_session(1, collateral, ProlongPeriod::SixHours)
1750            .call_params(CallParameters::new(collateral, base_asset, u64::MAX))
1751            .unwrap()
1752            .with_contract_ids(&[
1753                deployment.oracle_id,
1754                deployment.pool_id,
1755                deployment.registry_id,
1756            ])
1757            .call()
1758            .await
1759            .unwrap_err();
1760        assert!(
1761            wrong_asset_error.to_string().contains("WrongAsset"),
1762            "unexpected wrong-asset error: {wrong_asset_error:#}"
1763        );
1764
1765        let collateral_dust = 17;
1766        let base_dust = 23;
1767        user.force_transfer_to_contract(
1768            child.contract_id(),
1769            collateral_dust,
1770            collateral_asset,
1771            TxPolicies::default(),
1772        )
1773        .await
1774        .unwrap();
1775        user.force_transfer_to_contract(
1776            child.contract_id(),
1777            base_dust,
1778            base_asset,
1779            TxPolicies::default(),
1780        )
1781        .await
1782        .unwrap();
1783        account
1784            .methods()
1785            .start_session(1, collateral, ProlongPeriod::SixHours)
1786            .call_params(CallParameters::new(collateral, collateral_asset, u64::MAX))
1787            .unwrap()
1788            .with_contract_ids(&[
1789                deployment.oracle_id,
1790                deployment.pool_id,
1791                deployment.registry_id,
1792            ])
1793            .with_variable_output_policy(VariableOutputPolicy::Exactly(2))
1794            .call()
1795            .await
1796            .unwrap();
1797        let provider = user.provider();
1798        assert_eq!(
1799            provider
1800                .get_contract_asset_balance(&child.contract_id(), &collateral_asset)
1801                .await
1802                .unwrap(),
1803            0
1804        );
1805        assert_eq!(
1806            provider
1807                .get_contract_asset_balance(&child.contract_id(), &base_asset)
1808                .await
1809                .unwrap(),
1810            0
1811        );
1812
1813        assert!(
1814            deployment
1815                .pool
1816                .methods()
1817                .is_call_allowed(child.contract_id(), order_book.contract_id)
1818                .simulate(Execution::state_read_only())
1819                .await
1820                .unwrap()
1821                .value
1822        );
1823        assert!(
1824            deployment
1825                .pool
1826                .methods()
1827                .is_call_allowed(child.contract_id(), second_order_book.contract_id)
1828                .simulate(Execution::state_read_only())
1829                .await
1830                .unwrap()
1831                .value
1832        );
1833        assert!(
1834            !deployment
1835                .pool
1836                .methods()
1837                .is_call_allowed(child.contract_id(), ContractId::new([0x99; 32]))
1838                .simulate(Execution::state_read_only())
1839                .await
1840                .unwrap()
1841                .value
1842        );
1843
1844        let session = deployment
1845            .pool
1846            .methods()
1847            .get_session(child.contract_id())
1848            .simulate(Execution::state_read_only())
1849            .await
1850            .unwrap()
1851            .value
1852            .expect("prop session opened");
1853        assert_eq!(session.session_id, 1);
1854        assert_eq!(session.credit_line, 10_000_000);
1855        assert_eq!(session.collateral, collateral);
1856
1857        assert!(
1858            deployment
1859                .pool
1860                .methods()
1861                .min_sellable(child.contract_id(), base_asset)
1862                .with_contracts(&[&order_book.order_book, &second_order_book.order_book,])
1863                .simulate(Execution::state_read_only())
1864                .await
1865                .is_err()
1866        );
1867
1868        let best_bid = 2_000_000;
1869        let bid_quantity = 1_000_000_000;
1870        order_book
1871            .order_book
1872            .methods()
1873            .create_order(OrderArgs {
1874                price: best_bid,
1875                quantity: bid_quantity,
1876                order_type: OrderType::Spot,
1877            })
1878            .call_params(CallParameters::new(
1879                bid_quantity * best_bid / 1_000_000_000,
1880                collateral_asset,
1881                u64::MAX,
1882            ))
1883            .unwrap()
1884            .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
1885            .call()
1886            .await
1887            .unwrap();
1888        assert_eq!(
1889            order_book
1890                .order_book
1891                .methods()
1892                .get_base_decimals()
1893                .simulate(Execution::state_read_only())
1894                .await
1895                .unwrap()
1896                .value,
1897            1_000_000_000
1898        );
1899        assert_eq!(
1900            deployment
1901                .pool
1902                .methods()
1903                .min_sellable(child.contract_id(), base_asset)
1904                .with_contracts(&[&order_book.order_book, &second_order_book.order_book,])
1905                .simulate(Execution::state_read_only())
1906                .await
1907                .unwrap()
1908                .value,
1909            Some(500)
1910        );
1911
1912        let close = account
1913            .methods()
1914            .close_session(Vec::<PropOrderBookCleanup>::new())
1915            .with_contracts(&[
1916                &deployment.oracle,
1917                &deployment.pool,
1918                &order_book.order_book,
1919                &second_order_book.order_book,
1920            ])
1921            .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
1922            .call()
1923            .await
1924            .unwrap();
1925        let close_events = close.decode_logs_with_type::<SessionClosed>().unwrap();
1926        assert!(
1927            close
1928                .decode_logs_with_type::<SessionSeized>()
1929                .unwrap()
1930                .is_empty()
1931        );
1932        assert_recent_timestamp(close_events[0].timestamp.unix);
1933        assert_eq!(
1934            close_events,
1935            vec![SessionClosed {
1936                account: child.contract_id(),
1937                session_id: 1,
1938                reason: SettlementReason::UserClose,
1939                v: 10_000_000,
1940                v_is_negative: false,
1941                v_liq: 10_000_000,
1942                v_liq_is_negative: false,
1943                profit_abs: 0,
1944                profit_is_negative: false,
1945                fees_accrued: 0,
1946                platform_total: 0,
1947                user_net: collateral,
1948                bad_debt: 0,
1949                cancelled_debt: vec![],
1950                payout_parent: vec![(collateral_asset, collateral)],
1951                payout_platform: vec![],
1952                timestamp: close_events[0].timestamp.clone(),
1953            }]
1954        );
1955        assert!(
1956            !deployment
1957                .pool
1958                .methods()
1959                .has_session(child.contract_id())
1960                .simulate(Execution::state_read_only())
1961                .await
1962                .unwrap()
1963                .value
1964        );
1965
1966        let excess_collateral = 25_000_000;
1967        account
1968            .methods()
1969            .start_session(1, excess_collateral, ProlongPeriod::SixHours)
1970            .call_params(CallParameters::new(
1971                excess_collateral,
1972                collateral_asset,
1973                u64::MAX,
1974            ))
1975            .unwrap()
1976            .with_contract_ids(&[
1977                deployment.oracle_id,
1978                deployment.pool_id,
1979                deployment.registry_id,
1980            ])
1981            .call()
1982            .await
1983            .unwrap();
1984        let excess_session = deployment
1985            .pool
1986            .methods()
1987            .get_session(child.contract_id())
1988            .simulate(Execution::state_read_only())
1989            .await
1990            .unwrap()
1991            .value
1992            .expect("excess-collateral session opened");
1993        assert_eq!(excess_session.session_id, 2);
1994        assert_eq!(excess_session.collateral, excess_collateral);
1995        assert_eq!(excess_session.credit_line, 20_000_000);
1996
1997        let excess_close = account
1998            .methods()
1999            .close_session(Vec::<PropOrderBookCleanup>::new())
2000            .with_contracts(&[
2001                &deployment.oracle,
2002                &deployment.pool,
2003                &order_book.order_book,
2004                &second_order_book.order_book,
2005            ])
2006            .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
2007            .call()
2008            .await
2009            .unwrap();
2010        let excess_close_events = excess_close
2011            .decode_logs_with_type::<SessionClosed>()
2012            .unwrap();
2013        assert_recent_timestamp(excess_close_events[0].timestamp.unix);
2014        assert_eq!(
2015            excess_close_events,
2016            vec![SessionClosed {
2017                account: child.contract_id(),
2018                session_id: 2,
2019                reason: SettlementReason::UserClose,
2020                v: 33_000_000,
2021                v_is_negative: false,
2022                v_liq: 33_000_000,
2023                v_liq_is_negative: false,
2024                profit_abs: 0,
2025                profit_is_negative: false,
2026                fees_accrued: 0,
2027                platform_total: 0,
2028                user_net: excess_collateral,
2029                bad_debt: 0,
2030                cancelled_debt: vec![],
2031                payout_parent: vec![(collateral_asset, excess_collateral)],
2032                payout_platform: vec![],
2033                timestamp: excess_close_events[0].timestamp.clone(),
2034            }]
2035        );
2036
2037        let withdrawal = 1_000;
2038        user.force_transfer_to_contract(
2039            child.contract_id(),
2040            withdrawal,
2041            collateral_asset,
2042            TxPolicies::default(),
2043        )
2044        .await
2045        .unwrap();
2046        let balance_before = user.get_asset_balance(&collateral_asset).await.unwrap();
2047        let withdraw_response = account
2048            .methods()
2049            .withdraw(collateral_asset, withdrawal)
2050            .with_contract_ids(&[deployment.oracle_id, deployment.pool_id])
2051            .with_variable_output_policy(VariableOutputPolicy::Exactly(1))
2052            .call()
2053            .await
2054            .unwrap();
2055        let withdraw_events = withdraw_response
2056            .decode_logs_with_type::<MarginTradeAccountWithdrawn>()
2057            .unwrap();
2058        assert_recent_timestamp(withdraw_events[0].timestamp.unix);
2059        assert_eq!(
2060            withdraw_events,
2061            vec![MarginTradeAccountWithdrawn {
2062                account: child.contract_id(),
2063                parent,
2064                asset_id: collateral_asset,
2065                amount: withdrawal,
2066                timestamp: withdraw_events[0].timestamp.clone(),
2067            }]
2068        );
2069        assert_eq!(
2070            user.get_asset_balance(&collateral_asset).await.unwrap(),
2071            balance_before + withdrawal as u128
2072        );
2073    }
2074}
2075
2076#[cfg(test)]
2077#[path = "prop_deploy_tests.rs"]
2078mod integration_tests;