Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(onramp): adding onramp buy options endpoint #499

Merged
merged 4 commits into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions integration/onramp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { getTestSetup } from './init';

describe('OnRamp', () => {
const { baseUrl, projectId, httpClient } = getTestSetup();
const onRampPath = `${baseUrl}/v1/onramp`;

it('buy options', async () => {
let resp: any = await httpClient.get(
`${onRampPath}/buy/options?projectId=${projectId}&country=US&subdivision=NY`,
)
expect(resp.status).toBe(200)

const firstPayment = resp.data.paymentCurrencies[0]
expect(typeof firstPayment.id).toBe('string')
const firstPaymentLimits = firstPayment.limits[0]
expect(typeof firstPaymentLimits.id).toBe('string')
expect(typeof firstPaymentLimits.min).toBe('string')
expect(typeof firstPaymentLimits.max).toBe('string')

const firstPurchase = resp.data.purchaseCurrencies[0]
expect(typeof firstPurchase.id).toBe('string')
expect(typeof firstPurchase.name).toBe('string')
expect(typeof firstPurchase.symbol).toBe('string')
const firstPurchaseNetworks = firstPurchase.networks[0]
expect(typeof firstPurchaseNetworks.name).toBe('string')
expect(typeof firstPurchaseNetworks.displayName).toBe('string')
expect(typeof firstPurchaseNetworks.contractAddress).toBe('string')
expect(typeof firstPurchaseNetworks.chainId).toBe('string')
})
})
3 changes: 3 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ pub enum RpcError {
#[error("Failed to reach the portfolio provider")]
PortfolioProviderError,

#[error("Failed to parse onramp provider url")]
OnRampParseURLError,

#[error("Failed to reach the onramp provider")]
OnRampProviderError,

Expand Down
1 change: 1 addition & 0 deletions src/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub mod health;
pub mod history;
pub mod identity;
pub mod metrics;
pub mod onramp;
pub mod portfolio;
pub mod profile;
pub mod proxy;
Expand Down
1 change: 1 addition & 0 deletions src/handlers/onramp/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod options;
99 changes: 99 additions & 0 deletions src/handlers/onramp/options.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
use {
crate::{error::RpcError, handlers::HANDLER_TASK_METRICS, state::AppState},
axum::{
extract::{ConnectInfo, Query, State},
response::{IntoResponse, Response},
Json,
},
hyper::HeaderMap,
serde::{Deserialize, Serialize},
std::{net::SocketAddr, sync::Arc},
tap::TapFallible,
tracing::log::error,
validator::Validate,
wc::future::FutureExt,
};

#[derive(Debug, Deserialize, Clone, Validate)]
#[serde(rename_all = "camelCase")]
pub struct OnRampBuyOptionsParams {
pub project_id: String,
#[validate(length(equal = 2))]
pub country: String,
#[validate(length(equal = 2))]
pub subdivision: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct OnRampBuyOptionsResponse {
#[serde(rename(serialize = "paymentCurrencies"))]
pub payment_currencies: Vec<PaymentCurrenciesLimits>,
#[serde(rename(serialize = "purchaseCurrencies"))]
pub purchase_currencies: Vec<PurchaseCurrencies>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PaymentCurrenciesLimits {
pub id: String,
pub limits: Vec<PaymentCurrenciesLimit>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PaymentCurrenciesLimit {
pub id: String,
pub min: String,
pub max: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PurchaseCurrencies {
pub id: String,
pub name: String,
pub symbol: String,
pub networks: Vec<PurchaseCurrencyNetwork>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PurchaseCurrencyNetwork {
pub name: String,
#[serde(rename(serialize = "displayName"))]
pub display_name: String,
#[serde(rename(serialize = "contractAddress"))]
pub contract_address: String,
#[serde(rename(serialize = "chainId"))]
pub chain_id: String,
}

pub async fn handler(
state: State<Arc<AppState>>,
connect_info: ConnectInfo<SocketAddr>,
query: Query<OnRampBuyOptionsParams>,
headers: HeaderMap,
) -> Result<Response, RpcError> {
handler_internal(state, connect_info, query, headers)
.with_metrics(HANDLER_TASK_METRICS.with_name("onrmap_buy_options"))
.await
}

#[tracing::instrument(skip_all)]
async fn handler_internal(
state: State<Arc<AppState>>,
_connect_info: ConnectInfo<SocketAddr>,
query: Query<OnRampBuyOptionsParams>,
_headers: HeaderMap,
) -> Result<Response, RpcError> {
state
.validate_project_access_and_quota(&query.project_id)
.await?;

let buy_options = state
.providers
.onramp_provider
.get_buy_options(query.0, state.http_client.clone())
.await
.tap_err(|e| {
error!("Failed to call coinbase buy options with {}", e);
})?;

Ok(Json(buy_options).into_response())
}
5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,11 @@ pub async fn bootstrap(config: Config) -> RpcResult<()> {
"/v1/generators/onrampurl",
post(handlers::generators::onrampurl::handler),
)
// OnRamp
.route(
"/v1/onramp/buy/options",
get(handlers::onramp::options::handler),
)
.route_layer(tracing_and_metrics_layer)
.route("/health", get(handlers::health::handler))
.layer(cors);
Expand Down
67 changes: 53 additions & 14 deletions src/providers/coinbase.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
use {
super::HistoryProvider,
super::{HistoryProvider, OnRampProvider},
crate::{
error::{RpcError, RpcResult},
handlers::history::{
HistoryQueryParams,
HistoryResponseBody,
HistoryTransaction,
HistoryTransactionFungibleInfo,
HistoryTransactionMetadata,
HistoryTransactionTransfer,
HistoryTransactionTransferQuantity,
handlers::{
history::{
HistoryQueryParams,
HistoryResponseBody,
HistoryTransaction,
HistoryTransactionFungibleInfo,
HistoryTransactionMetadata,
HistoryTransactionTransfer,
HistoryTransactionTransferQuantity,
},
onramp::options::{OnRampBuyOptionsParams, OnRampBuyOptionsResponse},
},
utils::crypto::string_chain_id_to_caip2_format,
},
Expand All @@ -26,15 +29,17 @@ pub struct CoinbaseProvider {
pub api_key: String,
pub app_id: String,
pub http_client: Client<HttpsConnector<hyper::client::HttpConnector>>,
pub base_api_url: String,
}

impl CoinbaseProvider {
pub fn new(api_key: String, app_id: String) -> Self {
pub fn new(api_key: String, app_id: String, base_api_url: String) -> Self {
let http_client = Client::builder().build::<_, hyper::Body>(HttpsConnector::new());
Self {
api_key,
app_id,
http_client,
base_api_url,
}
}
}
Expand Down Expand Up @@ -71,10 +76,7 @@ impl HistoryProvider for CoinbaseProvider {
params: HistoryQueryParams,
http_client: reqwest::Client,
) -> RpcResult<HistoryResponseBody> {
let base = format!(
"https://pay.coinbase.com/api/v1/buy/user/{}/transactions",
&address
);
let base = format!("{}/buy/user/{}/transactions", &self.base_api_url, &address);

let mut url = Url::parse(&base).map_err(|_| RpcError::HistoryParseCursorError)?;
url.query_pairs_mut().append_pair("page_size", "50");
Expand Down Expand Up @@ -140,3 +142,40 @@ impl HistoryProvider for CoinbaseProvider {
})
}
}

#[async_trait]
impl OnRampProvider for CoinbaseProvider {
#[tracing::instrument(skip(self), fields(provider = "Coinbase"))]
async fn get_buy_options(
&self,
params: OnRampBuyOptionsParams,
http_client: reqwest::Client,
) -> RpcResult<OnRampBuyOptionsResponse> {
let base = format!("{}/buy/options", &self.base_api_url);
let mut url = Url::parse(&base).map_err(|_| RpcError::OnRampParseURLError)?;
url.query_pairs_mut()
.append_pair("country", &params.country);
if let Some(subdivision) = params.subdivision {
url.query_pairs_mut()
.append_pair("subdivision", &subdivision);
}

let response = http_client
.get(url)
.header("Content-Type", "application/json")
.header("CBPAY-APP-ID", self.app_id.clone())
.header("CBPAY-API-KEY", self.api_key.clone())
.send()
.await?;

if response.status() != reqwest::StatusCode::OK {
error!(
"Error on CoinBase buy options response. Status is not OK: {:?}",
response.status(),
);
return Err(RpcError::OnRampProviderError);
}

Ok(response.json::<OnRampBuyOptionsResponse>().await?)
}
}
21 changes: 18 additions & 3 deletions src/providers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use {
error::{RpcError, RpcResult},
handlers::{
history::{HistoryQueryParams, HistoryResponseBody},
onramp::options::{OnRampBuyOptionsParams, OnRampBuyOptionsResponse},
portfolio::{PortfolioQueryParams, PortfolioResponseBody},
RpcQueryParams,
},
Expand Down Expand Up @@ -82,6 +83,7 @@ pub struct ProviderRepository {
pub history_provider: Arc<dyn HistoryProvider>,
pub portfolio_provider: Arc<dyn PortfolioProvider>,
pub coinbase_pay_provider: Arc<dyn HistoryProvider>,
pub onramp_provider: Arc<dyn OnRampProvider>,
}

impl ProviderRepository {
Expand Down Expand Up @@ -125,8 +127,11 @@ impl ProviderRepository {

let history_provider = Arc::new(ZerionProvider::new(zerion_api_key));
let portfolio_provider = history_provider.clone();
let coinbase_pay_provider =
Arc::new(CoinbaseProvider::new(coinbase_api_key, coinbase_app_id));
let coinbase_pay_provider = Arc::new(CoinbaseProvider::new(
coinbase_api_key,
coinbase_app_id,
"https://pay.coinbase.com/api/v1".into(),
));

Self {
providers: HashMap::new(),
Expand All @@ -137,7 +142,8 @@ impl ProviderRepository {
prometheus_workspace_header,
history_provider,
portfolio_provider,
coinbase_pay_provider,
coinbase_pay_provider: coinbase_pay_provider.clone(),
onramp_provider: coinbase_pay_provider,
}
}

Expand Down Expand Up @@ -484,3 +490,12 @@ pub trait PortfolioProvider: Send + Sync + Debug {
params: PortfolioQueryParams,
) -> RpcResult<PortfolioResponseBody>;
}

#[async_trait]
pub trait OnRampProvider: Send + Sync + Debug {
async fn get_buy_options(
&self,
params: OnRampBuyOptionsParams,
http_client: reqwest::Client,
) -> RpcResult<OnRampBuyOptionsResponse>;
}
Loading