-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathoracle.rs
200 lines (186 loc) · 5.87 KB
/
oracle.rs
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
//! Oracle
//!
//! The Oracle service is respoinsible for reacting to all remote/on-chain events.
use {
crate::agent::{
solana::{
key_store::KeyStore,
network::{
Config,
Network,
},
},
state::oracle::Oracle,
},
anyhow::Result,
solana_account_decoder::UiAccountEncoding,
solana_client::{
nonblocking::{
pubsub_client::PubsubClient,
rpc_client::RpcClient,
},
rpc_config::{
RpcAccountInfoConfig,
RpcProgramAccountsConfig,
},
},
solana_sdk::{
account::Account,
commitment_config::CommitmentConfig,
pubkey::Pubkey,
signature::Keypair,
},
std::{
sync::Arc,
time::Instant,
},
tokio::task::JoinHandle,
tokio_stream::StreamExt,
tracing::instrument,
};
#[instrument(skip(config, state))]
pub fn oracle<S>(config: Config, network: Network, state: Arc<S>) -> Vec<JoinHandle<()>>
where
S: Oracle,
S: Send + Sync + 'static,
{
let mut handles = Vec::new();
let Ok(key_store) = KeyStore::new(config.key_store.clone()) else {
tracing::warn!("Key store not available, Oracle won't start.");
return handles;
};
handles.push(tokio::spawn(poller(
config.clone(),
network,
state.clone(),
key_store.pyth_oracle_program_key,
key_store.publish_keypair,
key_store.pyth_price_store_program_key,
config.oracle.max_lookup_batch_size,
)));
if config.oracle.subscriber_enabled {
let min_elapsed_time = config.oracle.subscriber_finished_min_time;
let sleep_time = config.oracle.subscriber_finished_sleep_time;
handles.push(tokio::spawn(async move {
loop {
let current_time = Instant::now();
if let Err(ref err) = subscriber(
config.clone(),
network,
state.clone(),
key_store.pyth_oracle_program_key,
)
.await
{
tracing::error!(?err, "Subscriber exited unexpectedly");
if current_time.elapsed() < min_elapsed_time {
tracing::warn!(?sleep_time, "Subscriber restarting too quickly. Sleeping");
tokio::time::sleep(sleep_time).await;
}
}
}
}));
}
handles
}
/// When an account RPC Subscription update is receiveed.
///
/// We check if the account is one we're aware of and tracking, and if so, spawn
/// a small background task that handles that update. We only do this for price
/// accounts, all other accounts are handled below in the poller.
#[instrument(skip(config, state))]
async fn subscriber<S>(
config: Config,
network: Network,
state: Arc<S>,
program_key: Pubkey,
) -> Result<()>
where
S: Oracle,
S: Send + Sync + 'static,
{
// Setup PubsubClient to listen for account changes on the Oracle program.
let client = PubsubClient::new(config.wss_url.as_str()).await?;
let (mut notifier, _unsub) = {
let commitment = config.oracle.commitment;
let config = RpcProgramAccountsConfig {
account_config: RpcAccountInfoConfig {
commitment: Some(CommitmentConfig { commitment }),
encoding: Some(UiAccountEncoding::Base64Zstd),
..Default::default()
},
filters: None,
with_context: Some(true),
};
client.program_subscribe(&program_key, Some(config)).await
}?;
while let Some(update) = notifier.next().await {
match update.value.account.decode::<Account>() {
Some(account) => {
let pubkey: Pubkey = update.value.pubkey.as_str().try_into()?;
let state = state.clone();
tokio::spawn(async move {
if let Err(err) =
Oracle::handle_price_account_update(&*state, network, &pubkey, &account)
.await
{
tracing::error!(?err, "Failed to handle account update");
}
});
}
None => {
tracing::error!(
update = ?update,
"Failed to decode account from update.",
);
}
}
}
tracing::debug!("Subscriber closed connection.");
Ok(())
}
/// On poll lookup all Pyth Product/Price accounts and sync.
#[instrument(skip(config, publish_keypair, state))]
async fn poller<S>(
config: Config,
network: Network,
state: Arc<S>,
oracle_program_key: Pubkey,
publish_keypair: Option<Keypair>,
pyth_price_store_program_key: Option<Pubkey>,
max_lookup_batch_size: usize,
) where
S: Oracle,
S: Send + Sync + 'static,
{
// Setup an RpcClient for manual polling.
let mut tick = tokio::time::interval(config.oracle.poll_interval_duration);
let client = Arc::new(RpcClient::new_with_timeout_and_commitment(
config.rpc_url,
config.rpc_timeout,
CommitmentConfig {
commitment: config.oracle.commitment,
},
));
loop {
if let Err(err) = async {
tick.tick().await;
tracing::debug!("Polling for updates.");
Oracle::poll_updates(
&*state,
network,
oracle_program_key,
publish_keypair.as_ref(),
pyth_price_store_program_key,
&client,
max_lookup_batch_size,
)
.await?;
Oracle::sync_global_store(&*state, network).await
}
.await
{
tracing::error!(err = ?err, "Failed to handle poll updates.");
}
}
}