carbon-marginfi-v2-decoder 1.0.0

MarginfiV2 Decoder
Documentation
//! This code was AUTOGENERATED using the Codama library.
use {
    crate::types::{OrderTriggerType, WrappedI80F48},
    carbon_core::{
        account::AccountMetadata,
        postgres::{
            metadata::AccountRowMetadata,
            primitives::{Pubkey, U16, U32, U64, U8},
        },
    },
};

#[derive(sqlx::FromRow, Debug, Clone)]
pub struct OrderRow {
    #[sqlx(flatten)]
    pub account_metadata: AccountRowMetadata,
    pub marginfi_account: Pubkey,
    pub stop_loss: sqlx::types::Json<WrappedI80F48>,
    pub take_profit: sqlx::types::Json<WrappedI80F48>,
    pub placeholder: U64,
    pub max_slippage: U32,
    pub pad0: Vec<u8>,
    pub tags: Vec<U16>,
    pub pad1: Vec<u8>,
    pub tags_padding: Vec<u8>,
    pub trigger: sqlx::types::Json<OrderTriggerType>,
    pub bump: U8,
    pub pad2: Vec<u8>,
    pub reserved1: sqlx::types::Json<Vec<Vec<u8>>>,
}

impl OrderRow {
    pub fn from_parts(source: crate::accounts::order::Order, metadata: AccountMetadata) -> Self {
        Self {
            account_metadata: metadata.into(),
            marginfi_account: source.marginfi_account.into(),
            stop_loss: sqlx::types::Json(source.stop_loss),
            take_profit: sqlx::types::Json(source.take_profit),
            placeholder: source.placeholder.into(),
            max_slippage: source.max_slippage.into(),
            pad0: source.pad0.to_vec(),
            tags: source
                .tags
                .into_iter()
                .map(|element| element.into())
                .collect(),
            pad1: source.pad1.to_vec(),
            tags_padding: source.tags_padding.to_vec(),
            trigger: sqlx::types::Json(source.trigger),
            bump: source.bump.into(),
            pad2: source.pad2.to_vec(),
            reserved1: sqlx::types::Json(
                source
                    .reserved1
                    .into_iter()
                    .map(|element| element.to_vec())
                    .collect(),
            ),
        }
    }
}

impl TryFrom<OrderRow> for crate::accounts::order::Order {
    type Error = carbon_core::error::Error;
    fn try_from(source: OrderRow) -> Result<Self, Self::Error> {
        Ok(Self {
            marginfi_account: *source.marginfi_account,
            stop_loss: source.stop_loss.0,
            take_profit: source.take_profit.0,
            placeholder: *source.placeholder,
            max_slippage: source.max_slippage.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            pad0: source.pad0.as_slice().try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert padding from postgres primitive: expected 4 bytes"
                        .to_string(),
                )
            })?,
            tags: source
                .tags
                .into_iter()
                .map(|element| {
                    element.try_into().map_err(|_| {
                        carbon_core::error::Error::Custom(
                            "Failed to convert value from postgres primitive".to_string(),
                        )
                    })
                })
                .collect::<Result<Vec<_>, carbon_core::error::Error>>()?
                .try_into()
                .map_err(|_| {
                    carbon_core::error::Error::Custom(
                        "Failed to convert array element to primitive".to_string(),
                    )
                })?,
            pad1: source.pad1.as_slice().try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert padding from postgres primitive: expected 4 bytes"
                        .to_string(),
                )
            })?,
            tags_padding: source.tags_padding.as_slice().try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert padding from postgres primitive: expected 32 bytes"
                        .to_string(),
                )
            })?,
            trigger: source.trigger.0,
            bump: source.bump.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            pad2: source.pad2.as_slice().try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert padding from postgres primitive: expected 6 bytes"
                        .to_string(),
                )
            })?,
            reserved1: source
                .reserved1
                .0
                .into_iter()
                .map(|element| {
                    element.as_slice().try_into().map_err(|_| {
                        carbon_core::error::Error::Custom(
                            "Failed to convert padding from postgres primitive: expected 32 bytes"
                                .to_string(),
                        )
                    })
                })
                .collect::<Result<Vec<_>, carbon_core::error::Error>>()?
                .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::order::Order {
    fn table() -> &'static str {
        "order_account"
    }

    fn columns() -> Vec<&'static str> {
        vec![
            "__pubkey",
            "__slot",
            "marginfi_account",
            "stop_loss",
            "take_profit",
            "placeholder",
            "max_slippage",
            "pad0",
            "tags",
            "pad1",
            "tags_padding",
            "trigger",
            "bump",
            "pad2",
            "reserved1",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for OrderRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"
            INSERT INTO order_account (
                "marginfi_account",
                "stop_loss",
                "take_profit",
                "placeholder",
                "max_slippage",
                "pad0",
                "tags",
                "pad1",
                "tags_padding",
                "trigger",
                "bump",
                "pad2",
                "reserved1",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15
            )"#,
        )
        .bind(self.marginfi_account)
        .bind(&self.stop_loss)
        .bind(&self.take_profit)
        .bind(&self.placeholder)
        .bind(self.max_slippage)
        .bind(&self.pad0)
        .bind(&self.tags)
        .bind(&self.pad1)
        .bind(&self.tags_padding)
        .bind(&self.trigger)
        .bind(self.bump)
        .bind(&self.pad2)
        .bind(&self.reserved1)
        .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 OrderRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"INSERT INTO order_account (
                "marginfi_account",
                "stop_loss",
                "take_profit",
                "placeholder",
                "max_slippage",
                "pad0",
                "tags",
                "pad1",
                "tags_padding",
                "trigger",
                "bump",
                "pad2",
                "reserved1",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15
            ) ON CONFLICT (
                __pubkey
            ) DO UPDATE SET
                "marginfi_account" = EXCLUDED."marginfi_account",
                "stop_loss" = EXCLUDED."stop_loss",
                "take_profit" = EXCLUDED."take_profit",
                "placeholder" = EXCLUDED."placeholder",
                "max_slippage" = EXCLUDED."max_slippage",
                "pad0" = EXCLUDED."pad0",
                "tags" = EXCLUDED."tags",
                "pad1" = EXCLUDED."pad1",
                "tags_padding" = EXCLUDED."tags_padding",
                "trigger" = EXCLUDED."trigger",
                "bump" = EXCLUDED."bump",
                "pad2" = EXCLUDED."pad2",
                "reserved1" = EXCLUDED."reserved1",
                __slot = EXCLUDED.__slot
            "#,
        )
        .bind(self.marginfi_account)
        .bind(&self.stop_loss)
        .bind(&self.take_profit)
        .bind(&self.placeholder)
        .bind(self.max_slippage)
        .bind(&self.pad0)
        .bind(&self.tags)
        .bind(&self.pad1)
        .bind(&self.tags_padding)
        .bind(&self.trigger)
        .bind(self.bump)
        .bind(&self.pad2)
        .bind(&self.reserved1)
        .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 OrderRow {
    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 order_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 OrderRow {
    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 order_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 OrderMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for OrderMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS order_account (
                -- Account data
                "marginfi_account" BYTEA NOT NULL,
                "stop_loss" JSONB NOT NULL,
                "take_profit" JSONB NOT NULL,
                "placeholder" NUMERIC(20) NOT NULL,
                "max_slippage" INT8 NOT NULL,
                "pad0" BYTEA NOT NULL,
                "tags" INT4[] NOT NULL,
                "pad1" BYTEA NOT NULL,
                "tags_padding" BYTEA NOT NULL,
                "trigger" JSONB NOT NULL,
                "bump" INT2 NOT NULL,
                "pad2" BYTEA NOT NULL,
                "reserved1" 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 order_account"#)
            .execute(connection)
            .await?;
        Ok(())
    }
}