Skip to main content

fogo_paymaster/
swap.rs

1use anyhow::Context;
2use futures::future::join_all;
3use rand::distr::{Bernoulli, Distribution};
4use reqwest::Client;
5use serde::{Deserialize, Serialize};
6use serde_with::{serde_as, DisplayFromStr};
7use solana_client::{nonblocking::rpc_client::RpcClient, rpc_config::RpcSendTransactionConfig};
8use solana_commitment_config::CommitmentLevel;
9use solana_keypair::Keypair;
10use solana_pubkey::Pubkey;
11use solana_signer::Signer;
12use solana_transaction::versioned::VersionedTransaction;
13use std::str::FromStr;
14use url::{form_urlencoded, Url};
15
16use crate::{
17    api::{PubsubClientWithReconnect, ValiantClient},
18    cli::NetworkEnvironment,
19    constraint::MintSwapRate,
20    parse::parse_transaction_from_base64,
21    rpc::{
22        get_spl_ata_balance, send_and_confirm_transaction, ConfirmationResultInternal,
23        SignedVersionedTransaction,
24    },
25    serde::{deserialize_pubkey_vec, serialize_pubkey_vec},
26};
27
28pub const VALIANT_URL_MAINNET: &str = "https://mainnet-pro-api.valiant.trade";
29pub const VALIANT_URL_TESTNET: &str = "https://api.valiant.trade";
30pub const MAX_SLIPPAGE_BPS: u64 = 50;
31pub const PERCENTAGE_TO_SWAP_BPS: u64 = 9900;
32
33// NOTE: the params and response types below are manually defined for an external API.
34// This external API could change in the future, which could break our integration.
35// Additionally note that we leave out certain fields that are not relevant to our use case.
36// For reference, please see the Valiant API docs at https://mainnet-api.valiant.trade/docs.
37
38#[serde_as]
39#[derive(Serialize)]
40#[serde(rename_all = "camelCase")]
41struct TwoHopQuoteParams {
42    #[serde_as(as = "DisplayFromStr")]
43    input_mint: Pubkey,
44    #[serde_as(as = "DisplayFromStr")]
45    output_mint: Pubkey,
46    input_amount: u64,
47    is_exact_in: bool,
48    direct_only: bool,
49}
50
51#[serde_as]
52#[derive(Deserialize)]
53#[serde(rename_all = "camelCase")]
54struct TwoHopQuoteResponse {
55    #[serde_as(as = "DisplayFromStr")]
56    token_est_out: u64,
57    quote: TwoHopQuote,
58}
59
60#[serde_as]
61#[derive(Deserialize)]
62#[serde(rename_all = "camelCase")]
63struct TwoHopQuote {
64    #[serde(deserialize_with = "deserialize_pubkey_vec")]
65    route: Vec<Pubkey>,
66    #[serde(deserialize_with = "deserialize_pubkey_vec")]
67    pools: Vec<Pubkey>,
68}
69
70#[serde_as]
71#[derive(Serialize)]
72#[serde(rename_all = "camelCase")]
73struct TwoHopSwapParams {
74    #[serde_as(as = "DisplayFromStr")]
75    user_address: Pubkey,
76    #[serde(serialize_with = "serialize_pubkey_vec")]
77    route: Vec<Pubkey>,
78    #[serde(serialize_with = "serialize_pubkey_vec")]
79    pools: Vec<Pubkey>,
80    is_exact_in: bool,
81    input_amount: u64,
82    output_amount: u64,
83    use_alt: bool,
84    include_fee: bool,
85}
86
87#[derive(Deserialize)]
88#[serde(rename_all = "camelCase")]
89struct TwoHopSwapResponse {
90    serialized_tx: String,
91}
92
93/// Builds the query string for the twoHopSwap request from the params object.
94/// We build the query string manually here because reqwest/serde currently
95/// don't support serialization of Vec<T> into depth-0 params with the same name.
96fn build_swap_query_string(params: &TwoHopSwapParams) -> String {
97    let mut serializer = form_urlencoded::Serializer::new(String::new());
98    serializer.append_pair("userAddress", &params.user_address.to_string());
99    serializer.append_pair("inputAmount", &params.input_amount.to_string());
100    serializer.append_pair("outputAmount", &params.output_amount.to_string());
101    for pubkey in &params.route {
102        serializer.append_pair("route", &pubkey.to_string());
103    }
104    for pubkey in &params.pools {
105        serializer.append_pair("pools", &pubkey.to_string());
106    }
107    serializer.append_pair("isExactIn", &params.is_exact_in.to_string());
108    serializer.append_pair("useAlt", &params.use_alt.to_string());
109    serializer.append_pair("includeFee", &params.include_fee.to_string());
110    serializer.finish()
111}
112
113pub struct SwapConfirmationResult {
114    pub mint: Pubkey,
115    pub confirmation: ConfirmationResultInternal,
116}
117
118impl ValiantClient {
119    /// Creates a new ValiantClient from the given parameters.
120    pub fn from_params(
121        api_key: &str,
122        network_environment: NetworkEnvironment,
123        valiant_url_override: Option<String>,
124    ) -> anyhow::Result<Self> {
125        let mut headers = reqwest::header::HeaderMap::new();
126        headers.insert(
127            "X-API-KEY",
128            reqwest::header::HeaderValue::from_str(api_key)?,
129        );
130        let client = Client::builder().default_headers(headers).build()?;
131        let base_url = if let Some(override_url) = valiant_url_override {
132            Url::from_str(&override_url)
133        } else {
134            match network_environment {
135                NetworkEnvironment::Mainnet => Url::from_str(VALIANT_URL_MAINNET),
136                NetworkEnvironment::Testnet => Url::from_str(VALIANT_URL_TESTNET),
137                NetworkEnvironment::Localnet => {
138                    return Err(anyhow::anyhow!("Localnet Valiant is not supported"))
139                }
140            }
141        }?;
142        Ok(ValiantClient { client, base_url })
143    }
144
145    /// Swaps tokens into FOGO based on sampling using the provided mint swap rates.
146    /// If the sample is successful, constructs and submits a swap transaction.
147    /// Returns a vector of confirmation results, one per attempted swap.
148    /// Note this could return a smaller vector than the number of input mint swap rates.
149    pub async fn swap_tokens_probabilistic(
150        &self,
151        mint_swap_rates: &[MintSwapRate],
152        transaction_sponsor: &Keypair,
153        rpc: &RpcClient,
154        pubsub: &PubsubClientWithReconnect,
155    ) -> Vec<anyhow::Result<SwapConfirmationResult>> {
156        let futures = mint_swap_rates.iter().filter_map(|mint_swap_rate| {
157            if mint_swap_rate.sample() {
158                Some(self.swap_token(mint_swap_rate.mint(), transaction_sponsor, rpc, pubsub))
159            } else {
160                None
161            }
162        });
163        join_all(futures).await
164    }
165
166    async fn swap_token(
167        &self,
168        mint: Pubkey,
169        transaction_sponsor: &Keypair,
170        rpc: &RpcClient,
171        pubsub: &PubsubClientWithReconnect,
172    ) -> anyhow::Result<SwapConfirmationResult> {
173        let paymaster_wallet_key = transaction_sponsor.pubkey();
174        let spl_balance = get_spl_ata_balance(rpc, &paymaster_wallet_key, &mint).await?;
175        // TODO: this is necessary for mainnet bc include_fee needs to be set to true for now
176        // As a result, the Valiant paymaster takes a small fee from the swap, in the input token for USDC/FISH/FOGO.
177        // Eventually, if we are supporting other tokens, the Valiant fee will be charged in WFOGO, so this patch
178        // WILL NOT WORK. But we expect the Valiant API to be fixed shortly.
179        let amount_to_swap = spl_balance * PERCENTAGE_TO_SWAP_BPS / 10_000;
180        let swap_transaction = self
181            .get_valiant_swap_transaction(mint, amount_to_swap, &paymaster_wallet_key)
182            .await?;
183
184        let signature = transaction_sponsor.sign_message(&swap_transaction.message.serialize());
185        let signed_transaction = SignedVersionedTransaction::new(swap_transaction, signature)
186            .map_err(|e| anyhow::anyhow!("Failed to sign swap transaction: {}", e))?;
187
188        let rpc_config = RpcSendTransactionConfig {
189            skip_preflight: true,
190            preflight_commitment: Some(CommitmentLevel::Processed),
191            ..RpcSendTransactionConfig::default()
192        };
193        let confirmation_result =
194            send_and_confirm_transaction(rpc, pubsub, &signed_transaction, rpc_config)
195                .await
196                .map_err(|e| {
197                    anyhow::anyhow!(
198                        "Failed to send and confirm swap transaction for mint {}: {:?}",
199                        mint,
200                        e
201                    )
202                })?;
203        Ok(SwapConfirmationResult {
204            mint,
205            confirmation: confirmation_result,
206        })
207    }
208
209    async fn get_valiant_swap_transaction(
210        &self,
211        mint_in: Pubkey,
212        amount_in: u64,
213        transaction_sponsor_pubkey: &Pubkey,
214    ) -> anyhow::Result<VersionedTransaction> {
215        let quote_response = self.get_two_hop_quote(mint_in, amount_in).await?;
216        let amount_out_min = quote_response
217            .token_est_out
218            .checked_mul(10_000 - MAX_SLIPPAGE_BPS)
219            .context("Overflow on minimum output amount calculation")?
220            / 10_000;
221
222        let swap_response = self
223            .get_two_hop_swap(
224                transaction_sponsor_pubkey,
225                amount_in,
226                amount_out_min,
227                quote_response.quote.route.clone(),
228                quote_response.quote.pools,
229            )
230            .await?;
231
232        parse_transaction_from_base64(&swap_response.serialized_tx)
233    }
234
235    /// Queries the /dex/twoHopQuote Valiant endpoint to retrieve quote details.
236    /// These quote details will inform the swap transaction construction.
237    async fn get_two_hop_quote(
238        &self,
239        mint_in: Pubkey,
240        amount_in: u64,
241    ) -> anyhow::Result<TwoHopQuoteResponse> {
242        let params = TwoHopQuoteParams {
243            input_mint: mint_in,
244            output_mint: spl_token::native_mint::ID,
245            input_amount: amount_in,
246            is_exact_in: true,
247            direct_only: false,
248        };
249
250        let response = self
251            .client
252            .get(self.base_url.join("/dex/twoHopQuote")?)
253            .query(&params)
254            .send()
255            .await?
256            .error_for_status()?
257            .json()
258            .await?;
259
260        Ok(response)
261    }
262
263    /// Queries the /dex/txs/twoHopSwap endpoint to retrieve a swap transaction.
264    async fn get_two_hop_swap(
265        &self,
266        pubkey: &Pubkey,
267        amount_in: u64,
268        amount_out_min: u64,
269        route: Vec<Pubkey>,
270        pools: Vec<Pubkey>,
271    ) -> anyhow::Result<TwoHopSwapResponse> {
272        let params = TwoHopSwapParams {
273            user_address: *pubkey,
274            input_amount: amount_in,
275            output_amount: amount_out_min,
276            route,
277            pools,
278            is_exact_in: true,
279            use_alt: true,
280            // Valiant's API is being improved, once it returns a valid tx with all the createIdempotents necessary, we can disable this flag.
281            // We should also swap the full balance once this is reverted to false.
282            include_fee: true,
283        };
284
285        let query_string = build_swap_query_string(&params);
286
287        let mut url = self.base_url.join("/dex/txs/twoHopSwap")?;
288        url.set_query(Some(&query_string));
289
290        let response = self
291            .client
292            .get(url)
293            .send()
294            .await?
295            .error_for_status()?
296            .json()
297            .await?;
298
299        Ok(response)
300    }
301}
302
303impl MintSwapRate {
304    fn sample(&self) -> bool {
305        let rv = Bernoulli::new(self.rate());
306        // this should always be okay, since 0 <= rate <= 1
307        if let Ok(bern) = rv {
308            return bern.sample(&mut rand::rng());
309        }
310        false
311    }
312}