carbon-marginfi-v2-decoder 1.0.0

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

#[derive(sqlx::FromRow, Debug, Clone)]
pub struct MarginfiAccountRow {
    #[sqlx(flatten)]
    pub account_metadata: AccountRowMetadata,
    pub group: Pubkey,
    pub authority: Pubkey,
    pub lending_account: sqlx::types::Json<LendingAccount>,
    pub account_flags: U64,
    pub emissions_destination_account: Pubkey,
    pub health_cache: sqlx::types::Json<HealthCache>,
    pub migrated_from: Pubkey,
    pub migrated_to: Pubkey,
    pub last_update: U64,
    pub account_index: U16,
    pub third_party_index: U16,
    pub bump: U8,
    pub pad0: Vec<u8>,
    pub liquidation_record: Pubkey,
    pub padding0: Vec<U64>,
}

impl MarginfiAccountRow {
    pub fn from_parts(
        source: crate::accounts::marginfi_account::MarginfiAccount,
        metadata: AccountMetadata,
    ) -> Self {
        Self {
            account_metadata: metadata.into(),
            group: source.group.into(),
            authority: source.authority.into(),
            lending_account: sqlx::types::Json(source.lending_account),
            account_flags: source.account_flags.into(),
            emissions_destination_account: source.emissions_destination_account.into(),
            health_cache: sqlx::types::Json(source.health_cache),
            migrated_from: source.migrated_from.into(),
            migrated_to: source.migrated_to.into(),
            last_update: source.last_update.into(),
            account_index: source.account_index.into(),
            third_party_index: source.third_party_index.into(),
            bump: source.bump.into(),
            pad0: source.pad0.to_vec(),
            liquidation_record: source.liquidation_record.into(),
            padding0: source
                .padding0
                .into_iter()
                .map(|element| element.into())
                .collect(),
        }
    }
}

impl TryFrom<MarginfiAccountRow> for crate::accounts::marginfi_account::MarginfiAccount {
    type Error = carbon_core::error::Error;
    fn try_from(source: MarginfiAccountRow) -> Result<Self, Self::Error> {
        Ok(Self {
            group: *source.group,
            authority: *source.authority,
            lending_account: source.lending_account.0,
            account_flags: *source.account_flags,
            emissions_destination_account: *source.emissions_destination_account,
            health_cache: source.health_cache.0,
            migrated_from: *source.migrated_from,
            migrated_to: *source.migrated_to,
            last_update: *source.last_update,
            account_index: source.account_index.try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert value from postgres primitive".to_string(),
                )
            })?,
            third_party_index: source.third_party_index.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(),
                )
            })?,
            pad0: source.pad0.as_slice().try_into().map_err(|_| {
                carbon_core::error::Error::Custom(
                    "Failed to convert padding from postgres primitive: expected 3 bytes"
                        .to_string(),
                )
            })?,
            liquidation_record: *source.liquidation_record,
            padding0: source
                .padding0
                .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(),
                    )
                })?,
        })
    }
}

impl carbon_core::postgres::operations::Table
    for crate::accounts::marginfi_account::MarginfiAccount
{
    fn table() -> &'static str {
        "marginfi_account_account"
    }

    fn columns() -> Vec<&'static str> {
        vec![
            "__pubkey",
            "__slot",
            "group",
            "authority",
            "lending_account",
            "account_flags",
            "emissions_destination_account",
            "health_cache",
            "migrated_from",
            "migrated_to",
            "last_update",
            "account_index",
            "third_party_index",
            "bump",
            "pad0",
            "liquidation_record",
            "padding0",
        ]
    }
}

#[async_trait::async_trait]
impl carbon_core::postgres::operations::Insert for MarginfiAccountRow {
    async fn insert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"
            INSERT INTO marginfi_account_account (
                "group",
                "authority",
                "lending_account",
                "account_flags",
                "emissions_destination_account",
                "health_cache",
                "migrated_from",
                "migrated_to",
                "last_update",
                "account_index",
                "third_party_index",
                "bump",
                "pad0",
                "liquidation_record",
                "padding0",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17
            )"#,
        )
        .bind(self.group)
        .bind(self.authority)
        .bind(&self.lending_account)
        .bind(&self.account_flags)
        .bind(self.emissions_destination_account)
        .bind(&self.health_cache)
        .bind(self.migrated_from)
        .bind(self.migrated_to)
        .bind(&self.last_update)
        .bind(self.account_index)
        .bind(self.third_party_index)
        .bind(self.bump)
        .bind(&self.pad0)
        .bind(self.liquidation_record)
        .bind(&self.padding0)
        .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 MarginfiAccountRow {
    async fn upsert(&self, pool: &sqlx::PgPool) -> carbon_core::error::CarbonResult<()> {
        sqlx::query(
            r#"INSERT INTO marginfi_account_account (
                "group",
                "authority",
                "lending_account",
                "account_flags",
                "emissions_destination_account",
                "health_cache",
                "migrated_from",
                "migrated_to",
                "last_update",
                "account_index",
                "third_party_index",
                "bump",
                "pad0",
                "liquidation_record",
                "padding0",
                __pubkey, __slot
            ) VALUES (
                $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17
            ) ON CONFLICT (
                __pubkey
            ) DO UPDATE SET
                "group" = EXCLUDED."group",
                "authority" = EXCLUDED."authority",
                "lending_account" = EXCLUDED."lending_account",
                "account_flags" = EXCLUDED."account_flags",
                "emissions_destination_account" = EXCLUDED."emissions_destination_account",
                "health_cache" = EXCLUDED."health_cache",
                "migrated_from" = EXCLUDED."migrated_from",
                "migrated_to" = EXCLUDED."migrated_to",
                "last_update" = EXCLUDED."last_update",
                "account_index" = EXCLUDED."account_index",
                "third_party_index" = EXCLUDED."third_party_index",
                "bump" = EXCLUDED."bump",
                "pad0" = EXCLUDED."pad0",
                "liquidation_record" = EXCLUDED."liquidation_record",
                "padding0" = EXCLUDED."padding0",
                __slot = EXCLUDED.__slot
            "#,
        )
        .bind(self.group)
        .bind(self.authority)
        .bind(&self.lending_account)
        .bind(&self.account_flags)
        .bind(self.emissions_destination_account)
        .bind(&self.health_cache)
        .bind(self.migrated_from)
        .bind(self.migrated_to)
        .bind(&self.last_update)
        .bind(self.account_index)
        .bind(self.third_party_index)
        .bind(self.bump)
        .bind(&self.pad0)
        .bind(self.liquidation_record)
        .bind(&self.padding0)
        .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 MarginfiAccountRow {
    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 marginfi_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 MarginfiAccountRow {
    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 marginfi_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 MarginfiAccountMigrationOperation;

#[async_trait::async_trait]
impl sqlx_migrator::Operation<sqlx::Postgres> for MarginfiAccountMigrationOperation {
    async fn up(
        &self,
        connection: &mut sqlx::PgConnection,
    ) -> Result<(), sqlx_migrator::error::Error> {
        sqlx::query(
            r#"CREATE TABLE IF NOT EXISTS marginfi_account_account (
                -- Account data
                "group" BYTEA NOT NULL,
                "authority" BYTEA NOT NULL,
                "lending_account" JSONB NOT NULL,
                "account_flags" NUMERIC(20) NOT NULL,
                "emissions_destination_account" BYTEA NOT NULL,
                "health_cache" JSONB NOT NULL,
                "migrated_from" BYTEA NOT NULL,
                "migrated_to" BYTEA NOT NULL,
                "last_update" NUMERIC(20) NOT NULL,
                "account_index" INT4 NOT NULL,
                "third_party_index" INT4 NOT NULL,
                "bump" INT2 NOT NULL,
                "pad0" BYTEA NOT NULL,
                "liquidation_record" BYTEA NOT NULL,
                "padding0" NUMERIC(20)[] 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 marginfi_account_account"#)
            .execute(connection)
            .await?;
        Ok(())
    }
}