Skip to content

Commit

Permalink
chore: replace pending nft with fetched token id
Browse files Browse the repository at this point in the history
  • Loading branch information
rpalakkal committed Jun 21, 2024
1 parent 53761c9 commit 7fade56
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 54 deletions.
38 changes: 24 additions & 14 deletions src/actions/nft.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,20 +61,20 @@ pub async fn subscribe_to_nft_events<A: TeleportDB>(
}
}
}
NFTEvents::NewTokenData(new_token_data) => {
let mut db = db.lock().await;
db.promote_pending_nft(
log.transaction_hash.unwrap().encode_hex_with_prefix(),
new_token_data.tokenId.to_string(),
)
.await?;
drop(db);
log::info!(
"NFT minted with id {} to address {}",
new_token_data.tokenId.to_string(),
new_token_data.to.to_string()
);
}
// NFTEvents::NewTokenData(new_token_data) => {
// let mut db = db.lock().await;
// db.promote_pending_nft(
// log.transaction_hash.unwrap().encode_hex_with_prefix(),
// new_token_data.tokenId.to_string(),
// )
// .await?;
// drop(db);
// log::info!(
// "NFT minted with id {} to address {}",
// new_token_data.tokenId.to_string(),
// new_token_data.to.to_string()
// );
// }
_ => continue,
}
}
Expand Down Expand Up @@ -133,6 +133,16 @@ pub async fn send_eth(
Ok(())
}

pub async fn get_curr_token_id(rpc_url: String) -> eyre::Result<u64> {
let rpc_url = rpc_url.parse()?;
let provider = ProviderBuilder::new().on_http(rpc_url);
let nft = NFT::new(NFT_ADDRESS, provider);
let curr_token_id = nft.currentTokenId().call().await?._0;
let curr_token_id: u64 = curr_token_id.to::<u64>();
Ok(curr_token_id)
// Ok(curr_token_id.to_string())
}

#[cfg(test)]
mod tests {
use alloy::signers::local::{coins_bip39::English, MnemonicBuilder};
Expand Down
41 changes: 23 additions & 18 deletions src/db/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use super::{PendingNFT, TeleportDB, User, NFT};
use super::{TeleportDB, User, NFT};

#[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct InMemoryDB {
pub x_id_to_teleport_id: BTreeMap<String, String>,
pub users: BTreeMap<String, User>,
pub pending_nfts: BTreeMap<String, PendingNFT>,
// pub pending_nfts: BTreeMap<String, PendingNFT>,
pub nfts: BTreeMap<String, NFT>,
pub tweets: BTreeMap<String, String>,
}
Expand Down Expand Up @@ -51,22 +51,27 @@ impl TeleportDB for InMemoryDB {
Ok(serialized)
}

async fn add_pending_nft(
&mut self,
tx_hash: String,
pending_nft: PendingNFT,
) -> eyre::Result<()> {
self.pending_nfts.insert(tx_hash, pending_nft);
Ok(())
}

async fn promote_pending_nft(&mut self, tx_hash: String, token_id: String) -> eyre::Result<()> {
let pending_nft = self
.pending_nfts
.remove(&tx_hash)
.ok_or_else(|| eyre::eyre!("Pending NFT not found"))?;
let nft = NFT { teleport_id: pending_nft.teleport_id, token_id };
self.nfts.insert(pending_nft.nft_id, nft);
// async fn add_pending_nft(
// &mut self,
// tx_hash: String,
// pending_nft: PendingNFT,
// ) -> eyre::Result<()> {
// self.pending_nfts.insert(tx_hash, pending_nft);
// Ok(())
// }

// async fn promote_pending_nft(&mut self, tx_hash: String, token_id: String) ->
// eyre::Result<()> { let pending_nft = self
// .pending_nfts
// .remove(&tx_hash)
// .ok_or_else(|| eyre::eyre!("Pending NFT not found"))?;
// let nft = NFT { teleport_id: pending_nft.teleport_id, token_id };
// self.nfts.insert(pending_nft.nft_id, nft);
// Ok(())
// }

async fn add_nft(&mut self, nft_id: String, nft: NFT) -> eyre::Result<()> {
self.nfts.insert(nft_id, nft);
Ok(())
}

Expand Down
23 changes: 12 additions & 11 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ pub struct NFT {
pub token_id: String,
}

#[derive(Debug, Serialize, Deserialize, Clone, FromRow, PartialEq, Eq)]
pub struct PendingNFT {
pub teleport_id: String,
pub nft_id: String,
}
// #[derive(Debug, Serialize, Deserialize, Clone, FromRow, PartialEq, Eq)]
// pub struct PendingNFT {
// pub teleport_id: String,
// pub nft_id: String,
// }

impl User {
pub fn signer(&self) -> eyre::Result<PrivateKeySigner> {
Expand All @@ -49,12 +49,13 @@ pub trait TeleportDB {
async fn add_user(&mut self, teleport_id: String, user: User) -> eyre::Result<()>;
async fn get_user_by_teleport_id(&self, teleport_id: String) -> eyre::Result<User>;
async fn get_user_by_x_id(&self, x_id: String) -> eyre::Result<User>;
async fn add_pending_nft(
&mut self,
tx_hash: String,
pending_nft: PendingNFT,
) -> eyre::Result<()>;
async fn promote_pending_nft(&mut self, tx_hash: String, token_id: String) -> eyre::Result<()>;
// async fn add_pending_nft(
// &mut self,
// tx_hash: String,
// pending_nft: PendingNFT,
// ) -> eyre::Result<()>;
// async fn promote_pending_nft(&mut self, tx_hash: String, token_id: String) -> eyre::Result<()>;
async fn add_nft(&mut self, nft_id: String, nft: NFT) -> eyre::Result<()>;
async fn get_nft(&self, nft_id: String) -> eyre::Result<NFT>;
async fn add_tweet(&mut self, token_id: String, tweet_id: String) -> eyre::Result<()>;
async fn get_tweet(&self, token_id: String) -> eyre::Result<String>;
Expand Down
26 changes: 17 additions & 9 deletions src/endpoints.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::sync::Arc;
use tokio::fs;
use std::sync::{
atomic::{AtomicU64, Ordering},
Arc,
};

use axum::{
extract::{Query, State},
Expand All @@ -14,7 +16,7 @@ use crate::{
nft::{mint_nft, redeem_nft, send_eth},
wallet::{gen_sk, WalletProvider},
},
db::{PendingNFT, TeleportDB, User},
db::{TeleportDB, User, NFT},
twitter::{authorize_token, get_user_x_info, request_oauth_token},
};

Expand Down Expand Up @@ -69,6 +71,7 @@ pub struct SharedState<A: TeleportDB> {
pub db: Arc<Mutex<A>>,
pub rpc_url: String,
pub provider: WalletProvider,
pub curr_nft_id: Arc<AtomicU64>,
}

pub async fn new_user<A: TeleportDB>(
Expand All @@ -81,6 +84,7 @@ pub async fn new_user<A: TeleportDB>(
let existing_user = db_lock.get_user_by_teleport_id(teleport_id.clone()).await.ok();
if let Some(user) = existing_user {
if user.x_id.is_some() {
log::info!("User already created");
let x_info = get_user_x_info(user.access_token, user.access_secret).await;
let encoded_x_info = serde_urlencoded::to_string(&x_info)
.expect("Failed to encode x_info as query params");
Expand Down Expand Up @@ -170,10 +174,13 @@ pub async fn mint<A: TeleportDB>(
.await
.expect("Failed to mint NFT");

let curr_nft_id = shared_state.curr_nft_id.clone();
let new_value = curr_nft_id.fetch_add(1, Ordering::SeqCst) + 1;

let mut db = shared_state.db.lock().await;
db.add_pending_nft(
tx_hash.clone(),
PendingNFT { teleport_id: query.teleport_id.clone(), nft_id: query.nft_id.clone() },
db.add_nft(
query.nft_id.clone(),
NFT { teleport_id: query.teleport_id.clone(), token_id: new_value.to_string() },
)
.await
.expect("Failed to add pending NFT");
Expand Down Expand Up @@ -219,9 +226,10 @@ pub async fn get_tweet_id<A: TeleportDB>(
pub async fn get_ratls_cert<A: TeleportDB>(
State(shared_state): State<SharedState<A>>,
) -> Json<AttestationResponse> {
let cert = fs::read_to_string(std::env::var("TLS_CERT_PATH").expect("TLS_CERT_PATH not set"))
.await
.expect("gramine ratls rootCA.crt not found");
let cert =
tokio::fs::read_to_string(std::env::var("TLS_CERT_PATH").expect("TLS_CERT_PATH not set"))
.await
.expect("gramine ratls rootCA.crt not found");
Json(AttestationResponse { cert })
}

Expand Down
11 changes: 9 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use std::{net::SocketAddr, sync::Arc};
use std::{
net::SocketAddr,
sync::{atomic::AtomicU64, Arc},
};

use actions::nft::get_curr_token_id;
use alloy::{
providers::ProviderBuilder,
signers::local::{coins_bip39::English, MnemonicBuilder},
Expand Down Expand Up @@ -43,7 +47,10 @@ async fn main() {

let db = db::in_memory::InMemoryDB::new();
let db = Arc::new(Mutex::new(db));
let shared_state = SharedState { db: db.clone(), rpc_url, provider };

let curr_nft_id = get_curr_token_id(rpc_url.clone()).await.unwrap();
let curr_nft_id = Arc::new(AtomicU64::new(curr_nft_id));
let shared_state = SharedState { db: db.clone(), rpc_url, provider, curr_nft_id };

let eph = fs::read(tls_key_path).await.expect("gramine ratls rootCA.key not found");

Expand Down

0 comments on commit 7fade56

Please sign in to comment.