1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
//! providers helper functions for parsing Orca's configuration api
//! and generating rust types corresponding to the emitted JSON

use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

pub const ORCA_CONFIGS_API: &str = "https://api.orca.so/configs";

/// the resposne body from orca's configuration api
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OrcaConfigsApiResponse {
    pub aquafarms: HashMap<String, AquaFarm>,
    pub collectibles: HashMap<String, Collectible>,
    pub double_dips: HashMap<String, DoubleDip>,
    pub pools: HashMap<String, Pool>,
    pub program_ids: ProgramIds,
    pub tokens: HashMap<String, Token>,
    pub coingecko_ids: HashMap<String, String>,
    pub ftx_ids: HashMap<String, String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AquaFarm {
    pub account: String,
    pub nonce: u8,
    pub token_program_id: String,
    pub emissions_authority: String,
    pub remove_rewards_authority: String,
    pub base_token_mint: String,
    pub base_token_vault: String,
    pub reward_token_mint: String,
    pub reward_token_vault: String,
    pub farm_token_mint: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DoubleDip {
    pub account: String,
    pub nonce: u8,
    pub token_program_id: String,
    pub emissions_authority: String,
    pub remove_rewards_authority: String,
    pub base_token_mint: String,
    pub base_token_vault: String,
    pub reward_token_mint: String,
    pub reward_token_vault: String,
    pub farm_token_mint: String,
    pub date_start: String,
    pub date_end: String,
    pub total_emissions: String,
    pub custom_gradient_start_color: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Collectible {
    pub mint: String,
    pub decimals: u8,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Pool {
    pub account: String,
    pub authority: String,
    pub nonce: u8,
    pub pool_token_mint: String,
    pub token_account_a: String,
    pub token_account_b: String,
    pub fee_account: String,
    pub fee_numerator: u64,
    pub fee_denominator: u64,
    pub owner_trade_fee_numerator: u64,
    pub owner_trade_fee_denominator: u64,
    pub owner_withdraw_fee_numerator: u64,
    pub host_fee_numerator: u64,
    pub token_a_name: String,
    pub token_b_name: String,
    pub curve_type: String,
    pub deprecated: Option<bool>,
    pub program_version: Option<u64>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProgramIds {
    pub serum_token_swap: String,
    pub token_swap_v2: String,
    pub token_swap: String,
    pub token: String,
    pub aquafarm: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Token {
    pub mint: String,
    pub name: String,
    pub decimals: u8,
    pub fetch_price: Option<bool>,
}

impl OrcaConfigsApiResponse {
    pub async fn fetch_orca_config() -> Result<Self> {
        let client = reqwest::Client::builder().build()?;
        let res = client.get(ORCA_CONFIGS_API).send().await?;
        let data = res.json::<Self>().await?;
        Ok(data)
    }
    /// used to lookup pool information for the given pool matching `name`
    /// if aquafarm is true, search query becomes `name[aquafarm]`
    /// if stable is true, search query becomes `name[stable]`
    /// if stable & aquafarm is true, search query becomes `name[stable][aquafarm]`
    pub fn find_pool(&self, name: &str, stable: bool, aquafarm: bool) -> Result<Pool> {
        let name = format_orca_amm_name(name, stable, aquafarm);
        for pool in self.pools.iter() {
            if pool.0.eq(&name) {
                return Ok(pool.1.clone());
            }
        }
        Err(anyhow!("failed to find pool for {}", name))
    }
    /// used to lookup information for an aquafarm, returning a tuple of the
    /// pool and aquafarm config
    pub fn find_aquafarm(&self, name: &str, stable: bool) -> Result<(Pool, AquaFarm)> {
        let pool = self.find_pool(name, stable, true)?;
        for farm in self.aquafarms.iter() {
            if farm.0.eq(&pool.account) {
                return Ok((pool, farm.1.clone()));
            }
        }
        Err(anyhow!("failed to find aquafarm for {}", name))
    }
    /// used to lookup information for a double dip
    pub fn find_double_dip(&self, name: &str, stable: bool) -> Result<(Pool, DoubleDip, AquaFarm)> {
        let pool = self.find_pool(name, stable, true)?;
        for doubledip in self.double_dips.iter() {
            if doubledip.0.eq(&pool.account) {
                for aquafarm in self.aquafarms.iter() {
                    if aquafarm.0.eq(&pool.account) {
                        return Ok((pool, doubledip.1.clone(), aquafarm.1.clone()));
                    }
                }
            }
        }
        Err(anyhow!("failed to find doubledip for {}", name))
    }
}

pub fn format_orca_amm_name(name: &str, stable: bool, aquafarm: bool) -> String {
    // orca uses a platform specifier for pairs with names that would conflict
    // with other vaults
    let name = if name.split('-').count() == 3 {
        let lp_name_str = name.to_string();
        let parts: Vec<_> = lp_name_str.split('-').collect();
        let mut lp_name_parsed = String::with_capacity(name.len() - 5); // 5 for '-ORCA'
        for (idx, part) in parts.iter().enumerate() {
            if idx == parts.len() - 1 {
                break;
            }
            lp_name_parsed.push_str(*part);
            if idx != parts.len() - 2 {
                lp_name_parsed.push('/');
            }
        }
        lp_name_parsed
    } else {
        name.replace("-", "/")
    };
    // scnSOL previously used to be labeled as SOCN
    // so handle that edgecase, todo(bonedaddy): test
    let name = name.replace("SOCN", "scnSOL");
    let name = if stable && !name.contains("[stable]") {
        format!("{}[stable]", name)
    } else {
        name
    };
    let name = if aquafarm && !name.contains("[aquafarm]") {
        format!("{}[aquafarm]", name)
    } else {
        name
    };
    name
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn test_format_orca_amm_name() {
        let name_one = "SAMO-USDC[stable][aquafarm]".to_string();
        let name_two = "SAMO-USDC".to_string();
        assert_eq!(
            format_orca_amm_name(&name_one, true, true),
            "SAMO/USDC[stable][aquafarm]"
        );
        assert_eq!(
            format_orca_amm_name(&name_two, false, true),
            "SAMO/USDC[aquafarm]"
        );
        assert_eq!(
            format_orca_amm_name(&name_two, true, false),
            "SAMO/USDC[stable]"
        );
    }
    #[tokio::test]
    async fn test_orca_config() {
        let orca_config = OrcaConfigsApiResponse::fetch_orca_config().await.unwrap();

        let pool_config = orca_config
            .find_pool(&"SOL/USDC".to_string(), false, false)
            .unwrap();
        assert_eq!(
            pool_config.account,
            "6fTRDD7sYxCN7oyoSQaN1AWC3P2m8A6gVZzGrpej9DvL".to_string()
        );

        let pool_config = orca_config
            .find_pool(&"SOL/USDC".to_string(), false, true)
            .unwrap();
        assert_eq!(
            pool_config.account,
            "EGZ7tiLeH62TPV1gL8WwbXGzEPa9zmcpVnnkPKKnrE2U".to_string()
        );

        let aquafarm_config = orca_config
            .find_aquafarm(&"SOL/USDC".to_string(), false)
            .unwrap();
        assert_eq!(aquafarm_config.0, pool_config);
        println!(
            "sol/usdc aquafarm information\npool {:#?}\nfarm {:#?}",
            aquafarm_config.0, aquafarm_config.1
        );

        let pool_config = orca_config
            .find_pool(&"LIQ/USDC".to_string(), false, true)
            .unwrap();
        let doubledip_config = orca_config
            .find_double_dip(&"LIQ/USDC".to_string(), false)
            .unwrap();
        assert_eq!(doubledip_config.0, pool_config);
        println!(
            "liq/usdc doubledip information\npool {:#?}\nfarm {:#?}\ndouble dip {:#?}",
            doubledip_config.0, doubledip_config.1, doubledip_config.0,
        );
    }
}