riftenlabs-indexer/src/rpc/bcmr.rs

66 lines
2.4 KiB
Rust
Raw Normal View History

// Copyright (C) 2024 Riften Labs AS
//
// This software is licensed under the GNU Affero General Public License (AGPL), version 3.0 or later.
// A copy of the license can be found in the LICENSE file or at https://www.gnu.org/licenses/agpl-3.0.html
use anyhow::Context;
use bitcoin_hashes::hex::{FromHex, ToHex};
use bitcoincash::TokenID;
use rocket::{get, http::Status, response::status::Custom, serde::json::Json, State};
use serde_json::json;
use serde_json::Value;
use crate::db::bcmr::get_well_known_bcmr;
use crate::db::{bcmr::get_token_bcmr, DB};
/// Fetches BCMR data from on-chain registry
#[get("/token/<category>")]
pub fn token_bcmr(category: Option<&str>, db: &State<DB>) -> Result<Json<Value>, Custom<String>> {
let token_id_hex = category
.context("category missing")
.map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?;
// validate input by parsing it into TokenID
let token_id = TokenID::from_hex(token_id_hex)
.map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?;
let conn = db
.bcmr_r
.get()
.map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?;
let bcmr = get_token_bcmr(&conn, &token_id.to_hex())
.map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?;
Ok(Json(json!(bcmr)))
}
/// Fetches BCMR data for token from all registries
#[get("/token/<category>/all")]
pub fn token_bcmr_all(
category: Option<&str>,
db: &State<DB>,
) -> Result<Json<Value>, Custom<String>> {
let token_id_hex = category
.context("category missing")
.map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?;
// validate input by parsing it into TokenID
let token_id = TokenID::from_hex(token_id_hex)
.map_err(|e| Custom(Status::BadRequest, format!("Error: {}", e)))?;
let conn = db
.bcmr_r
.get()
.map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?;
let onchain_bcmr = get_token_bcmr(&conn, &token_id.to_hex())
.map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?;
let mut bcmr_entries = get_well_known_bcmr(&conn, &token_id.to_hex())
.map_err(|e| Custom(Status::InternalServerError, format!("Error: {}", e)))?;
if let Some(bcmr) = onchain_bcmr {
bcmr_entries.push(bcmr)
}
Ok(Json(json!(bcmr_entries)))
}