offchain_utils/
offchain_api_key.rs

1use sp_io::offchain::{local_storage_get, local_storage_set};
2
3use sp_core::offchain::StorageKind::PERSISTENT;
4
5use scale_info::prelude::string::String;
6
7/// A trait representing a way to fetch an API key for offchain calls.
8pub trait OffchainApiKey {
9	/// Fetch the API key for a given `key`.
10	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	/// Fetch the raw key string from local offchain storage.
15	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	/// Store an API key in local offchain storage for a given `key`.
26	fn store_api_key(key: &str, value: &str) {
27		local_storage_set(PERSISTENT, key.as_bytes(), value.as_bytes());
28	}
29}
30
31/// A default implementation of `OffchainApiKey` using local offchain storage.
32pub struct DefaultOffchainApiKey;
33
34impl OffchainApiKey for DefaultOffchainApiKey {}