carbon-openbook-v2-decoder 2.0.0

Openbook V2 Decoder
Documentation
//! This code was AUTOGENERATED using the Codama library.
use {
    crate::types::{NonZeroPubkeyOption, OpenOrder, Position},
    carbon_core::{
        account::AccountMetadata,
        postgres::{
            metadata::AccountRowMetadata,
            primitives::{Pubkey, U32, U8},
        },
    },
};

#[derive(sqlx::FromRow, Debug, Clone)]
pub struct OpenOrdersAccountRow {
    #[sqlx(flatten)]
    pub account_metadata: AccountRowMetadata,
    pub owner: Pubkey,
    pub market: Pubkey,
    pub name: Vec<u8>,
    pub delegate: sqlx::types::Json<NonZeroPubkeyOption>,
    pub account_num: U32,
    pub bump: U8,
    pub version: U8,
    pub padding: Vec<u8>,
    pub position: sqlx::types::Json<Position>,
    pub open_orders: sqlx::types::Json<Vec<OpenOrder>>,
}

impl OpenOrdersAccountRow {
    pub fn from_parts(
        source: crate::accounts::open_orders_account::OpenOrdersAccount,
        metadata: AccountMetadata,
    ) -> Self {
        Self {
            account_metadata: metadata.into(),
            owner: source.owner.into(),
            market: source.market.into(),
            name: source.name.to_vec(),
            delegate: sqlx::types::Json(source.delegate),
            account_num: source.account_num.into(),
            bump: source.bump.into(),
            version: source.version.into(),
            padding: source.padding.to_vec(),
            position: sqlx::types::Json(source.position),
            open_orders: sqlx::types::Json(source.open_orders.to_vec()),
        }
    }
}

impl TryFrom<OpenOrdersAccountRow> for crate::accounts::open_orders_account::OpenOrdersAccount {
    type Error = carbon_core::error::Error;
    fn try_from(source: OpenOrdersAccountRow) -> Result<Self, Self::Error> {
        Ok(Self {
            owner: *source.owner,
            market: *source.market,
            name: source.name.as_slice().try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert padding from postgres primitive: expected 32 bytes"
                        .to_string(),
                )
            })?,
            delegate: source.delegate.0,
            account_num: source.account_num.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            bump: source.bump.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            version: source.version.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            padding: source.padding.as_slice().try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert padding from postgres primitive: expected 2 bytes"
                        .to_string(),
                )
            })?,
            position: source.position.0,
            open_orders: source
                .open_orders
                .0
                .into_iter()
                .collect::<Vec<_>>()
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert value from postgres primitive".to_string(),
                    )
                })?,
        })
    }
}

impl carbon_core::postgres::operations::Table
    for crate::accounts::open_orders_account::OpenOrdersAccount
{
    fn table() -> &'static str {
        "open_orders_account_account"
    }

    fn columns() -> Vec<&'static str> {
        vec![
            "__pubkey",
            "__slot",
            "owner",
            "market",
            "name",
            "delegate",
            "account_num",
            "bump",
            "version",
            "padding",
            "position",
            "open_orders",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for OpenOrdersAccountRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"
            INSERT INTO open_orders_account_account (
                "owner",
                "market",
                "name",
                "delegate",
                "account_num",
                "bump",
                "version",
                "padding",
                "position",
                "open_orders",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12
            )"#,
        )
        .bind(self.owner)
        .bind(self.market)
        .bind(&self.name)
        .bind(&self.delegate)
        .bind(self.account_num)
        .bind(self.bump)
        .bind(self.version)
        .bind(&self.padding)
        .bind(&self.position)
        .bind(&self.open_orders)
        .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 OpenOrdersAccountRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"INSERT INTO open_orders_account_account (
                "owner",
                "market",
                "name",
                "delegate",
                "account_num",
                "bump",
                "version",
                "padding",
                "position",
                "open_orders",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12
            ) ON CONFLICT (
                __pubkey
            ) DO UPDATE SET
                "owner" = EXCLUDED."owner",
                "market" = EXCLUDED."market",
                "name" = EXCLUDED."name",
                "delegate" = EXCLUDED."delegate",
                "account_num" = EXCLUDED."account_num",
                "bump" = EXCLUDED."bump",
                "version" = EXCLUDED."version",
                "padding" = EXCLUDED."padding",
                "position" = EXCLUDED."position",
                "open_orders" = EXCLUDED."open_orders",
                __slot = EXCLUDED.__slot
            "#,
        )
        .bind(self.owner)
        .bind(self.market)
        .bind(&self.name)
        .bind(&self.delegate)
        .bind(self.account_num)
        .bind(self.bump)
        .bind(self.version)
        .bind(&self.padding)
        .bind(&self.position)
        .bind(&self.open_orders)
        .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 OpenOrdersAccountRow {
    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 open_orders_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 OpenOrdersAccountRow {
    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 open_orders_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 OpenOrdersAccountMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for OpenOrdersAccountMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS open_orders_account_account (
                -- Account data
                "owner" BYTEA NOT NULL,
                "market" BYTEA NOT NULL,
                "name" BYTEA NOT NULL,
                "delegate" JSONB NOT NULL,
                "account_num" INT8 NOT NULL,
                "bump" INT2 NOT NULL,
                "version" INT2 NOT NULL,
                "padding" BYTEA NOT NULL,
                "position" JSONB NOT NULL,
                "open_orders" JSONB 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 open_orders_account_account"#)
            .execute(connection)
            .await?;
        Ok(())
    }
}