Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom deserialision #20

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
[workspace]
resolver = "2"
members = [
"jupiter-swap-api-client",
"example",
Expand Down
15 changes: 8 additions & 7 deletions jupiter-swap-api-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use anyhow::{anyhow, Result};
use quote::{InternalQuoteRequest, QuoteRequest, QuoteResponse};
use reqwest::{Client, Response};
use serde::de::DeserializeOwned;
use swap::{SwapInstructionsResponse, SwapInstructionsResponseInternal, SwapRequest, SwapResponse};
use swap::{SwapInstructionsResponse, SwapRequest, SwapResponse};

pub mod quote;
pub mod route_plan_with_metadata;
Expand All @@ -15,6 +15,7 @@ pub mod transaction_config;
#[derive(Clone)]
pub struct JupiterSwapApiClient {
pub base_path: String,
client: Client,
}

async fn check_is_success(response: Response) -> Result<Response> {
Expand All @@ -38,14 +39,15 @@ async fn check_status_code_and_deserialize<T: DeserializeOwned>(response: Respon

impl JupiterSwapApiClient {
pub fn new(base_path: String) -> Self {
Self { base_path }
let client = Client::new();
Self { base_path, client }
}

pub async fn quote(&self, quote_request: &QuoteRequest) -> Result<QuoteResponse> {
let url = format!("{}/quote", self.base_path);
let extra_args = quote_request.quote_args.clone();
let internal_quote_request = InternalQuoteRequest::from(quote_request.clone());
let response = Client::new()
let response = self.client
.get(url)
.query(&internal_quote_request)
.query(&extra_args)
Expand All @@ -59,7 +61,7 @@ impl JupiterSwapApiClient {
swap_request: &SwapRequest,
extra_args: Option<HashMap<String, String>>,
) -> Result<SwapResponse> {
let response = Client::new()
let response = self.client
.post(format!("{}/swap", self.base_path))
.query(&extra_args)
.json(swap_request)
Expand All @@ -72,13 +74,12 @@ impl JupiterSwapApiClient {
&self,
swap_request: &SwapRequest,
) -> Result<SwapInstructionsResponse> {
let response = Client::new()
let response = self.client
.post(format!("{}/swap-instructions", self.base_path))
.json(swap_request)
.send()
.await?;
check_status_code_and_deserialize::<SwapInstructionsResponseInternal>(response)
check_status_code_and_deserialize::<SwapInstructionsResponse>(response)
.await
.map(Into::into)
}
}
19 changes: 19 additions & 0 deletions jupiter-swap-api-client/src/serde_helpers/field_as_base64.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use {
serde::{Deserializer, Serializer},
serde::{Deserialize, Serialize},
};
use base64::{engine::general_purpose::STANDARD, Engine};

pub fn serialize<S: Serializer>(v: &Vec<u8>, s: S) -> Result<S::Ok, S::Error> {
String::serialize(&STANDARD.encode(v), s)
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
D: Deserializer<'de>,
{
STANDARD
.decode(String::deserialize(deserializer)?)
.map_err(|e| serde::de::Error::custom(format!("base64 decoding error {:?}", e)))
}

95 changes: 95 additions & 0 deletions jupiter-swap-api-client/src/serde_helpers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,97 @@
use serde::{Deserialize, Deserializer};
use solana_sdk::instruction::{AccountMeta, Instruction};
use solana_sdk::pubkey::Pubkey;

pub mod field_as_string;
pub mod option_field_as_string;
pub mod field_as_base64;

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct InstructionHelper {
#[serde(with = "field_as_string")]
program_id: Pubkey,
accounts: Vec<AccountMetaHelper>,
#[serde(with = "field_as_base64")]
data: Vec<u8>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct AccountMetaHelper {
#[serde(with = "field_as_string")]
pubkey: Pubkey,
is_signer: bool,
is_writable: bool,
}

impl From<InstructionHelper> for Instruction {
fn from(helper: InstructionHelper) -> Self {
Instruction {
program_id: helper.program_id,
accounts: helper
.accounts
.into_iter()
.map(|acc| AccountMeta {
pubkey: acc.pubkey,
is_signer: acc.is_signer,
is_writable: acc.is_writable,
})
.collect(),
data: helper.data,
}
}
}

pub mod field_as_instruction {
use super::*;

pub fn deserialize<'de, D>(deserializer: D) -> Result<Instruction, D::Error>
where
D: Deserializer<'de>,
{
Ok(InstructionHelper::deserialize(deserializer)?.into())
}
}

pub mod option_field_as_instruction {
use super::*;

pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Instruction>, D::Error>
where
D: Deserializer<'de>,
{
Ok(Option::<InstructionHelper>::deserialize(deserializer)?.map(Into::into))
}
}

pub mod vec_field_as_instruction {
use super::*;

pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Instruction>, D::Error>
where
D: Deserializer<'de>,
{
Ok(Vec::<InstructionHelper>::deserialize(deserializer)?
.into_iter()
.map(Into::into)
.collect())
}
}

pub mod vec_field_as_pubkey {
use super::*;

pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Pubkey>, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct Helper(#[serde(with = "field_as_string")] Pubkey);

Ok(Vec::<Helper>::deserialize(deserializer)?
.into_iter()
.map(|v| v.0)
.collect())
}
}
141 changes: 17 additions & 124 deletions jupiter-swap-api-client/src/swap.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
use crate::{
quote::QuoteResponse, serde_helpers::field_as_string, transaction_config::TransactionConfig,
quote::QuoteResponse,
serde_helpers::{
field_as_base64, field_as_string, vec_field_as_pubkey, vec_field_as_instruction,
option_field_as_instruction, field_as_instruction
},
transaction_config::TransactionConfig,
};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use solana_sdk::{
instruction::{AccountMeta, Instruction},
instruction::Instruction,
pubkey::Pubkey,
};

Expand Down Expand Up @@ -50,7 +55,7 @@ pub struct UiSimulationError {
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SwapResponse {
#[serde(with = "base64_serialize_deserialize")]
#[serde(with = "field_as_base64")]
pub swap_transaction: Vec<u8>,
pub last_valid_block_height: u64,
pub prioritization_fee_lamports: u64,
Expand All @@ -60,141 +65,29 @@ pub struct SwapResponse {
pub simulation_error: Option<UiSimulationError>,
}

pub mod base64_serialize_deserialize {
use base64::{engine::general_purpose::STANDARD, Engine};
use serde::{de, Deserializer, Serializer};

use super::*;
pub fn serialize<S: Serializer>(v: &Vec<u8>, s: S) -> Result<S::Ok, S::Error> {
let base58 = STANDARD.encode(v);
String::serialize(&base58, s)
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where
D: Deserializer<'de>,
{
let field_string = String::deserialize(deserializer)?;
STANDARD
.decode(field_string)
.map_err(|e| de::Error::custom(format!("base64 decoding error: {:?}", e)))
}
}

#[derive(Debug, Clone)]
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SwapInstructionsResponse {
#[serde(with = "option_field_as_instruction")]
pub token_ledger_instruction: Option<Instruction>,
#[serde(with = "vec_field_as_instruction")]
pub compute_budget_instructions: Vec<Instruction>,
#[serde(with = "vec_field_as_instruction")]
pub setup_instructions: Vec<Instruction>,
/// Instruction performing the action of swapping
#[serde(with = "field_as_instruction")]
pub swap_instruction: Instruction,
#[serde(with = "option_field_as_instruction")]
pub cleanup_instruction: Option<Instruction>,
/// Other instructions that should be included in the transaction.
/// Now, it should only have the Jito tip instruction.
#[serde(with = "vec_field_as_instruction")]
pub other_instructions: Vec<Instruction>,
#[serde(with = "vec_field_as_pubkey")]
pub address_lookup_table_addresses: Vec<Pubkey>,
pub prioritization_fee_lamports: u64,
pub compute_unit_limit: u32,
pub prioritization_type: Option<PrioritizationType>,
pub dynamic_slippage_report: Option<DynamicSlippageReport>,
pub simulation_error: Option<UiSimulationError>,
}

// Duplicate for deserialization
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SwapInstructionsResponseInternal {
token_ledger_instruction: Option<InstructionInternal>,
compute_budget_instructions: Vec<InstructionInternal>,
setup_instructions: Vec<InstructionInternal>,
/// Instruction performing the action of swapping
swap_instruction: InstructionInternal,
cleanup_instruction: Option<InstructionInternal>,
/// Other instructions that should be included in the transaction.
/// Now, it should only have the Jito tip instruction.
other_instructions: Vec<InstructionInternal>,
address_lookup_table_addresses: Vec<PubkeyInternal>,
prioritization_fee_lamports: u64,
compute_unit_limit: u32,
prioritization_type: Option<PrioritizationType>,
dynamic_slippage_report: Option<DynamicSlippageReport>,
simulation_error: Option<UiSimulationError>,
}

#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
struct InstructionInternal {
#[serde(with = "field_as_string")]
pub program_id: Pubkey,
pub accounts: Vec<AccountMetaInternal>,
#[serde(with = "base64_serialize_deserialize")]
pub data: Vec<u8>,
}

#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct AccountMetaInternal {
#[serde(with = "field_as_string")]
pub pubkey: Pubkey,
pub is_signer: bool,
pub is_writable: bool,
}

impl From<AccountMetaInternal> for AccountMeta {
fn from(val: AccountMetaInternal) -> Self {
AccountMeta {
pubkey: val.pubkey,
is_signer: val.is_signer,
is_writable: val.is_writable,
}
}
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
struct PubkeyInternal(#[serde(with = "field_as_string")] Pubkey);

impl From<InstructionInternal> for Instruction {
fn from(val: InstructionInternal) -> Self {
Instruction {
program_id: val.program_id,
accounts: val.accounts.into_iter().map(Into::into).collect(),
data: val.data,
}
}
}

impl From<SwapInstructionsResponseInternal> for SwapInstructionsResponse {
fn from(value: SwapInstructionsResponseInternal) -> Self {
Self {
token_ledger_instruction: value.token_ledger_instruction.map(Into::into),
compute_budget_instructions: value
.compute_budget_instructions
.into_iter()
.map(Into::into)
.collect(),
setup_instructions: value
.setup_instructions
.into_iter()
.map(Into::into)
.collect(),
swap_instruction: value.swap_instruction.into(),
cleanup_instruction: value.cleanup_instruction.map(Into::into),
other_instructions: value
.other_instructions
.into_iter()
.map(Into::into)
.collect(),
address_lookup_table_addresses: value
.address_lookup_table_addresses
.into_iter()
.map(|p| p.0)
.collect(),
prioritization_fee_lamports: value.prioritization_fee_lamports,
compute_unit_limit: value.compute_unit_limit,
prioritization_type: value.prioritization_type,
dynamic_slippage_report: value.dynamic_slippage_report,
simulation_error: value.simulation_error,
}
}
}