solana_central/central_context/
insert_pool.rs

1use crate::central_context::central_context::CentralContext;
2use crate::constants::SOLANA_PROGRAMS;
3use crate::types::pool::PoolTrait;
4use std::collections::HashMap;
5use std::sync::{Arc, RwLock};
6
7impl CentralContext {
8  /// Insert a pool into the central context
9  ///
10  /// Adds the pool to both the bidirectional market graph and the pools map.
11  /// Pools can then be queried by token pairs or by account addresses (pool address or vault addresses).
12  /// Invalid pools (with system program addresses or duplicate tokens) are silently ignored.
13  pub fn insert_pool(&self, pool: Arc<RwLock<dyn PoolTrait>>) {
14    let result_unlocked = pool.read().unwrap();
15    let token_a_address: &solana_sdk::pubkey::Pubkey = result_unlocked.token_a_address();
16    let token_b_address = result_unlocked.token_b_address();
17    // Token addresses are all 0/garbage, throw this pool away
18    if *token_a_address == SOLANA_PROGRAMS.system_program
19      || *token_b_address == SOLANA_PROGRAMS.system_program
20    {
21      return;
22    }
23    // Token addresses are the same, throw this pool away
24    if token_a_address == token_b_address {
25      return;
26    }
27    // println!("load_pools: processing pool {}", result_unlocked.pool_address());
28    // Aquire a write lock on markets
29    let mut markets = self.markets.write().unwrap();
30
31    // Ensure both tokens exist in the markets map
32    markets
33      .entry(token_a_address.clone())
34      .or_insert_with(|| HashMap::new());
35    markets
36      .entry(token_b_address.clone())
37      .or_insert_with(|| HashMap::new());
38
39    // Get references to both market maps
40    let markets_a = markets.get_mut(token_a_address).unwrap();
41
42    // Check if market pair already exists
43    if let Some(existing_markets) = markets_a.get(token_b_address) {
44      existing_markets.write().unwrap().push(pool.clone());
45    } else {
46      // Create new market pair
47      let a_b_markets = Arc::new(RwLock::new(vec![pool.clone()]));
48      // Insert bidirectional mapping
49      markets_a.insert(token_b_address.clone(), a_b_markets.clone());
50      let markets_b = markets.get_mut(token_b_address).unwrap();
51      markets_b.insert(token_a_address.clone(), a_b_markets);
52    }
53
54    // Get a write lock for the token accounts and insert this pool there
55    let mut token_accounts_map = self.pools_map.write().unwrap();
56    token_accounts_map.insert(*result_unlocked.token_a_vault_address(), pool.clone());
57    token_accounts_map.insert(*result_unlocked.token_b_vault_address(), pool.clone());
58    token_accounts_map.insert(*result_unlocked.pool_address(), pool.clone());
59  }
60}