generated from switchboard-xyz/solana-functions-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binance.rs
208 lines (183 loc) · 6.07 KB
/
binance.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
201
202
203
204
205
206
207
208
// Note: Binance API requires a non-US IP address
use crate::*;
pub use switchboard_utils::reqwest;
use basic_oracle::{OracleDataBorsh, TradingSymbol};
use serde::Deserialize;
const ONE: i128 = 1000000000;
pub fn ix_discriminator(name: &str) -> [u8; 8] {
let preimage = format!("global:{}", name);
let mut sighash = [0u8; 8];
sighash.copy_from_slice(
&anchor_lang::solana_program::hash::hash(preimage.as_bytes()).to_bytes()[..8],
);
sighash
}
#[allow(non_snake_case)]
#[derive(Deserialize, Default, Clone, Debug)]
pub struct Ticker {
pub symbol: String, // BTCUSDT
pub priceChange: String,
pub priceChangePercent: String,
pub weightedAvgPrice: String,
pub openPrice: String,
pub highPrice: String,
pub lowPrice: String,
pub lastPrice: String,
pub volume: String,
pub quoteVolume: String,
pub openTime: u64, // ms
pub closeTime: u64, // ms
}
#[derive(Clone, Debug)]
pub struct IndexData {
pub symbol: String,
pub hr: Ticker,
pub d: Ticker,
}
impl Into<OracleDataBorsh> for IndexData {
fn into(self) -> OracleDataBorsh {
let oracle_timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
.try_into()
.unwrap_or_default();
let price = parse_string_value(self.hr.lastPrice.as_str());
let volume_1hr = parse_string_value(self.hr.volume.as_str());
let volume_24hr = parse_string_value(self.d.volume.as_str());
let twap_1hr = parse_string_value(self.hr.weightedAvgPrice.as_str());
let twap_24hr = parse_string_value(self.d.weightedAvgPrice.as_str());
OracleDataBorsh {
oracle_timestamp,
price,
volume_1hr,
volume_24hr,
twap_1hr,
twap_24hr,
}
}
}
pub struct Binance {
btc_usdt: IndexData,
usdc_usdt: IndexData,
eth_usdt: IndexData,
sol_usdt: IndexData,
doge_usdt: IndexData,
}
impl Binance {
// Fetch data from the Binance API
pub async fn fetch() -> std::result::Result<Binance, SwitchboardClientError> {
let symbols = ["BTCUSDT", "USDCUSDT", "ETHUSDT", "SOLUSDT", "DOGEUSDT"];
let tickers_1hr = reqwest::get(format!(
"https://api.binance.com/api/v3/ticker?symbols=[{}]&windowSize=1h",
symbols
.iter()
.map(|x| format!("\"{}\"", x))
.collect::<Vec<String>>()
.join(",")
))
.await
.unwrap()
.json::<Vec<Ticker>>()
.await
.unwrap();
let tickers_1d = reqwest::get(format!(
"https://api.binance.com/api/v3/ticker?symbols=[{}]&windowSize=1d",
symbols
.iter()
.map(|x| format!("\"{}\"", x))
.collect::<Vec<String>>()
.join(",")
))
.await
.unwrap()
.json::<Vec<Ticker>>()
.await
.unwrap();
assert!(
tickers_1d.len() == symbols.len(),
"ticker (1d) length mismatch"
);
assert!(
tickers_1hr.len() == symbols.len(),
"ticker (1hr) length mismatch"
);
let data: Vec<IndexData> = symbols
.iter()
.enumerate()
.map(|(i, s)| IndexData {
symbol: s.to_string(),
d: tickers_1d.get(i).unwrap().clone(),
hr: tickers_1hr.get(i).unwrap().clone(),
})
.collect();
Ok(Binance {
btc_usdt: data.get(0).unwrap().clone(),
usdc_usdt: data.get(1).unwrap().clone(),
eth_usdt: data.get(2).unwrap().clone(),
sol_usdt: data.get(3).unwrap().clone(),
doge_usdt: data.get(4).unwrap().clone(),
})
}
pub fn to_ixns(&self, runner: &FunctionRunner) -> Vec<Instruction> {
let rows: Vec<OracleDataWithTradingSymbol> = vec![
OracleDataWithTradingSymbol {
symbol: TradingSymbol::Btc,
data: self.btc_usdt.clone().into(),
},
OracleDataWithTradingSymbol {
symbol: TradingSymbol::Usdc,
data: self.usdc_usdt.clone().into(),
},
OracleDataWithTradingSymbol {
symbol: TradingSymbol::Eth,
data: self.eth_usdt.clone().into(),
},
// OracleDataWithTradingSymbol {
// symbol: TradingSymbol::Sol,
// data: self.sol_usdt.clone().into(),
// },
// OracleDataWithTradingSymbol {
// symbol: TradingSymbol::Doge,
// data: self.doge_usdt.clone().into(),
// },
];
let params = RefreshPricesParams { rows };
let (program_state_pubkey, _state_bump) =
Pubkey::find_program_address(&[b"BASICORACLE"], &PROGRAM_ID);
let (oracle_pubkey, _oracle_bump) =
Pubkey::find_program_address(&[b"ORACLE_V1_SEED"], &PROGRAM_ID);
let ixn = Instruction {
program_id: basic_oracle::ID,
accounts: vec![
AccountMeta {
pubkey: oracle_pubkey,
is_signer: false,
is_writable: true,
},
AccountMeta {
pubkey: runner.function,
is_signer: false,
is_writable: false,
},
AccountMeta {
pubkey: runner.signer,
is_signer: true,
is_writable: false,
},
],
data: [
ix_discriminator("refresh_oracles").to_vec(),
params.try_to_vec().unwrap(),
]
.concat(),
};
vec![ixn]
}
}
// Convert a string to an i128 scaled to 9 decimal places
pub fn parse_string_value(value: &str) -> i128 {
let f64_value = value.parse::<f64>().unwrap();
let sb_decimal = SwitchboardDecimal::from_f64(f64_value);
sb_decimal.scale_to(9)
}