offchain_utils/
offchain_api_key.rs1use sp_io::offchain::{local_storage_get, local_storage_set};
2
3use sp_core::offchain::StorageKind::PERSISTENT;
4
5use scale_info::prelude::string::String;
6
7pub trait OffchainApiKey {
9 fn fetch_api_key_for_request(key: &str) -> Result<String, &'static str> {
11 Self::do_fetch_local(key).ok_or("Missing or invalid API key")
12 }
13
14 fn do_fetch_local(key: &str) -> Option<String> {
16 if let Some(api_key_bytes) = local_storage_get(PERSISTENT, key.as_bytes()) {
17 let api_key = String::from_utf8(api_key_bytes).expect("Invalid UTF-8");
18 Some(api_key)
19 } else {
20 log::error!("API key not found in offchain storage");
21 None
22 }
23 }
24
25 fn store_api_key(key: &str, value: &str) {
27 local_storage_set(PERSISTENT, key.as_bytes(), value.as_bytes());
28 }
29}
30
31pub struct DefaultOffchainApiKey;
33
34impl OffchainApiKey for DefaultOffchainApiKey {}