carbon-zeta-decoder 2.0.0

Zeta Program Decoder
Documentation
//! This code was AUTOGENERATED using the Codama library.
use {
    crate::types::{AnchorDecimal, Asset, MarginAccountType, ProductLedger},
    carbon_core::{
        account::AccountMetadata,
        postgres::{
            metadata::AccountRowMetadata,
            primitives::{Pubkey, U64, U8},
        },
    },
};

#[derive(sqlx::FromRow, Debug, Clone)]
pub struct MarginAccountRow {
    #[sqlx(flatten)]
    pub account_metadata: AccountRowMetadata,
    pub authority: Pubkey,
    pub nonce: U8,
    pub balance: U64,
    pub force_cancel_flag: bool,
    pub open_orders_nonce: Vec<u8>,
    pub series_expiry: Vec<U64>,
    pub series_expiry_padding: U64,
    pub product_ledgers: sqlx::types::Json<Vec<ProductLedger>>,
    pub product_ledgers_padding: sqlx::types::Json<Vec<ProductLedger>>,
    pub perp_product_ledger: sqlx::types::Json<ProductLedger>,
    pub rebalance_amount: i64,
    pub asset: sqlx::types::Json<Asset>,
    pub account_type: sqlx::types::Json<MarginAccountType>,
    pub last_funding_delta: sqlx::types::Json<AnchorDecimal>,
    pub delegated_pubkey: Pubkey,
    pub padding: Vec<u8>,
}

impl MarginAccountRow {
    pub fn from_parts(
        source: crate::accounts::margin_account::MarginAccount,
        metadata: AccountMetadata,
    ) -> Self {
        Self {
            account_metadata: metadata.into(),
            authority: source.authority.into(),
            nonce: source.nonce.into(),
            balance: source.balance.into(),
            force_cancel_flag: source.force_cancel_flag,
            open_orders_nonce: source.open_orders_nonce.to_vec(),
            series_expiry: source
                .series_expiry
                .into_iter()
                .map(|element| element.into())
                .collect(),
            series_expiry_padding: source.series_expiry_padding.into(),
            product_ledgers: sqlx::types::Json(source.product_ledgers.to_vec()),
            product_ledgers_padding: sqlx::types::Json(source.product_ledgers_padding.to_vec()),
            perp_product_ledger: sqlx::types::Json(source.perp_product_ledger),
            rebalance_amount: source.rebalance_amount,
            asset: sqlx::types::Json(source.asset),
            account_type: sqlx::types::Json(source.account_type),
            last_funding_delta: sqlx::types::Json(source.last_funding_delta),
            delegated_pubkey: source.delegated_pubkey.into(),
            padding: source.padding.to_vec(),
        }
    }
}

impl TryFrom<MarginAccountRow> for crate::accounts::margin_account::MarginAccount {
    type Error = carbon_core::error::Error;
    fn try_from(source: MarginAccountRow) -> Result<Self, Self::Error> {
        Ok(Self {
            authority: *source.authority,
            nonce: source.nonce.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            balance: *source.balance,
            force_cancel_flag: source.force_cancel_flag,
            open_orders_nonce: source
                .open_orders_nonce
                .as_slice()
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert padding from postgres primitive: expected 138 bytes"
                            .to_string(),
                    )
                })?,
            series_expiry: source
                .series_expiry
                .into_iter()
                .map(|element| Ok(*element))
                .collect::<Result<Vec<_>, carbon_core::error::Error>>()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to collect array elements".to_string(),
                    )
                })?
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert array element to primitive".to_string(),
                    )
                })?,
            series_expiry_padding: *source.series_expiry_padding,
            product_ledgers: source
                .product_ledgers
                .0
                .into_iter()
                .collect::<Vec<_>>()
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert value from postgres primitive".to_string(),
                    )
                })?,
            product_ledgers_padding: source
                .product_ledgers_padding
                .0
                .into_iter()
                .collect::<Vec<_>>()
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert value from postgres primitive".to_string(),
                    )
                })?,
            perp_product_ledger: source.perp_product_ledger.0,
            rebalance_amount: source.rebalance_amount,
            asset: source.asset.0,
            account_type: source.account_type.0,
            last_funding_delta: source.last_funding_delta.0,
            delegated_pubkey: *source.delegated_pubkey,
            padding: source.padding.as_slice().try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert padding from postgres primitive: expected 338 bytes"
                        .to_string(),
                )
            })?,
        })
    }
}

impl carbon_core::postgres::operations::Table for crate::accounts::margin_account::MarginAccount {
    fn table() -> &'static str {
        "margin_account_account"
    }

    fn columns() -> Vec<&'static str> {
        vec![
            "__pubkey",
            "__slot",
            "authority",
            "nonce",
            "balance",
            "force_cancel_flag",
            "open_orders_nonce",
            "series_expiry",
            "series_expiry_padding",
            "product_ledgers",
            "product_ledgers_padding",
            "perp_product_ledger",
            "rebalance_amount",
            "asset",
            "account_type",
            "last_funding_delta",
            "delegated_pubkey",
            "padding",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for MarginAccountRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"
            INSERT INTO margin_account_account (
                "authority",
                "nonce",
                "balance",
                "force_cancel_flag",
                "open_orders_nonce",
                "series_expiry",
                "series_expiry_padding",
                "product_ledgers",
                "product_ledgers_padding",
                "perp_product_ledger",
                "rebalance_amount",
                "asset",
                "account_type",
                "last_funding_delta",
                "delegated_pubkey",
                "padding",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18
            )"#,
        )
        .bind(self.authority)
        .bind(self.nonce)
        .bind(&self.balance)
        .bind(self.force_cancel_flag)
        .bind(&self.open_orders_nonce)
        .bind(&self.series_expiry)
        .bind(&self.series_expiry_padding)
        .bind(&self.product_ledgers)
        .bind(&self.product_ledgers_padding)
        .bind(&self.perp_product_ledger)
        .bind(self.rebalance_amount)
        .bind(&self.asset)
        .bind(&self.account_type)
        .bind(&self.last_funding_delta)
        .bind(self.delegated_pubkey)
        .bind(&self.padding)
        .bind(self.account_metadata.pubkey)
        .bind(&self.account_metadata.slot)
        .execute(pool)
        .await
        .map_err(|e| carbon_core::error::Error::Custom(e.to_string()))?;
        Ok(())
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Upsert for MarginAccountRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"INSERT INTO margin_account_account (
                "authority",
                "nonce",
                "balance",
                "force_cancel_flag",
                "open_orders_nonce",
                "series_expiry",
                "series_expiry_padding",
                "product_ledgers",
                "product_ledgers_padding",
                "perp_product_ledger",
                "rebalance_amount",
                "asset",
                "account_type",
                "last_funding_delta",
                "delegated_pubkey",
                "padding",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18
            ) ON CONFLICT (
                __pubkey
            ) DO UPDATE SET
                "authority" = EXCLUDED."authority",
                "nonce" = EXCLUDED."nonce",
                "balance" = EXCLUDED."balance",
                "force_cancel_flag" = EXCLUDED."force_cancel_flag",
                "open_orders_nonce" = EXCLUDED."open_orders_nonce",
                "series_expiry" = EXCLUDED."series_expiry",
                "series_expiry_padding" = EXCLUDED."series_expiry_padding",
                "product_ledgers" = EXCLUDED."product_ledgers",
                "product_ledgers_padding" = EXCLUDED."product_ledgers_padding",
                "perp_product_ledger" = EXCLUDED."perp_product_ledger",
                "rebalance_amount" = EXCLUDED."rebalance_amount",
                "asset" = EXCLUDED."asset",
                "account_type" = EXCLUDED."account_type",
                "last_funding_delta" = EXCLUDED."last_funding_delta",
                "delegated_pubkey" = EXCLUDED."delegated_pubkey",
                "padding" = EXCLUDED."padding",
                __slot = EXCLUDED.__slot
            "#,
        )
        .bind(self.authority)
        .bind(self.nonce)
        .bind(&self.balance)
        .bind(self.force_cancel_flag)
        .bind(&self.open_orders_nonce)
        .bind(&self.series_expiry)
        .bind(&self.series_expiry_padding)
        .bind(&self.product_ledgers)
        .bind(&self.product_ledgers_padding)
        .bind(&self.perp_product_ledger)
        .bind(self.rebalance_amount)
        .bind(&self.asset)
        .bind(&self.account_type)
        .bind(&self.last_funding_delta)
        .bind(self.delegated_pubkey)
        .bind(&self.padding)
        .bind(self.account_metadata.pubkey)
        .bind(&self.account_metadata.slot)
        .execute(pool)
        .await
        .map_err(|e| carbon_core::error::Error::Custom(e.to_string()))?;
        Ok(())
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Delete for MarginAccountRow {
    type Key = carbon_core::postgres::primitives::Pubkey;

    async fn delete(key: Self::Key, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"DELETE FROM margin_account_account WHERE
                __pubkey = $1
            "#,
        )
        .bind(key)
        .execute(pool)
        .await
        .map_err(|e| carbon_core::error::Error::Custom(e.to_string()))?;
        Ok(())
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Lookup for MarginAccountRow {
    type Key = carbon_core::postgres::primitives::Pubkey;

    async fn lookup(
        key: Self::Key,
        pool: &sqlx::PgPool,
    ) -> carbon_core::error::CarbonResult<Option<Self>> {
        let row = sqlx::query_as(
            r#"SELECT * FROM margin_account_account WHERE
                __pubkey = $1
            "#,
        )
        .bind(key)
        .fetch_optional(pool)
        .await
        .map_err(|e| carbon_core::error::Error::Custom(e.to_string()))?;
        Ok(row)
    }
}

pub struct MarginAccountMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for MarginAccountMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS margin_account_account (
                -- Account data
                "authority" BYTEA NOT NULL,
                "nonce" INT2 NOT NULL,
                "balance" NUMERIC(20) NOT NULL,
                "force_cancel_flag" BOOLEAN NOT NULL,
                "open_orders_nonce" BYTEA NOT NULL,
                "series_expiry" NUMERIC(20)[] NOT NULL,
                "series_expiry_padding" NUMERIC(20) NOT NULL,
                "product_ledgers" JSONB NOT NULL,
                "product_ledgers_padding" JSONB NOT NULL,
                "perp_product_ledger" JSONB NOT NULL,
                "rebalance_amount" INT8 NOT NULL,
                "asset" JSONB NOT NULL,
                "account_type" JSONB NOT NULL,
                "last_funding_delta" JSONB NOT NULL,
                "delegated_pubkey" BYTEA NOT NULL,
                "padding" BYTEA NOT NULL,
                -- Account metadata
                __pubkey BYTEA NOT NULL,
                __slot NUMERIC(20),
                PRIMARY KEY (__pubkey)
            )"#,
        )
        .execute(connection)
        .await?;
        Ok(())
    }

    async fn down(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(r#"DROP TABLE IF EXISTS margin_account_account"#)
            .execute(connection)
            .await?;
        Ok(())
    }
}