Skip to content

Commit

Permalink
Merge upstream/main
Browse files Browse the repository at this point in the history
  • Loading branch information
davidcaseria committed Nov 11, 2024
2 parents 7ccdb49 + 4e2c013 commit b1f11ab
Show file tree
Hide file tree
Showing 81 changed files with 2,957 additions and 937 deletions.
1 change: 0 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,6 @@ jobs:
-p cdk --no-default-features,
-p cdk --no-default-features --features wallet,
-p cdk --no-default-features --features mint,
-p cdk --no-default-features --features "mint swagger",
-p cdk-axum,
-p cdk-strike,
-p cdk-lnbits,
Expand Down
2 changes: 1 addition & 1 deletion .helix/languages.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[language-server.rust-analyzer.config]
cargo = { features = ["wallet", "mint"] }
cargo = { features = ["wallet", "mint", "swagger"] }
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
- cdk: Move unit conversion util fn to amount module ([davidcaseria]).
- cdk: Remove spent proofs from db when check state is called ([mubarak23]).
- cdk: Use `MintUrl` directly in wallet client ([ok300]).
- cdk-cli: Change cdk-cli pay command to melt ([mubarak23]).
- cdk-cli: Change cdk-cli pay command to melt ([mubarak23]).
- cdk: Rename `Wallet::get_proofs` to `Wallet::get_unspent_proofs` ([ok300]).


### Added
Expand All @@ -49,6 +50,7 @@
- cdk: Wallet verifiys keyset id when first fetching keys ([thesimplekid]).
- cdk-mind: Add swagger docs ([ok300]).
- cdk: NUT18 payment request support ([thesimplekid]).
- cdk: Add `Wallet::get_proofs_with` ([ok300]).

### Removed
- cdk: Remove `MintMeltSettings` since it is no longer used ([lollerfirst]).
Expand Down
152 changes: 152 additions & 0 deletions DEVELOPMENT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
# Development Guide

This guide will help you set up your development environment for working with the CDK repository.

## Prerequisites

Before you begin, ensure you have:
- Git installed on your system
- GitHub account
- Basic familiarity with command line operations

## Initial Setup

### 1. Fork and Clone the Repository

1. Navigate to the CDK repository on GitHub
2. Click the "Fork" button in the top-right corner
3. Clone your forked repository:
```bash
git clone https://github.com/YOUR-USERNAME/cdk.git
cd cdk
```

### 2. Install Nix

<!--
MIT License
Copyright (c) 2021 elsirion
https://github.com/fedimint/fedimint/blob/master/docs/dev-env.md
-->

CDK uses [Nix](https://nixos.org/explore.html) for building, CI, and managing dev environment.
Note: only `Nix` (the language & package manager) and not the NixOS (the Linux distribution) is needed.
Nix can be installed on any Linux distribution and macOS.

While it is technically possible to not use Nix, it is highly recommended as
it ensures consistent and reproducible environment for all developers.

### Install Nix

You have 2 options to install nix:

* **RECOMMENDED:** The [Determinate Nix Installer](https://github.com/DeterminateSystems/nix-installer)
* [The official installer](https://nixos.org/download.html)

Example:

```
> nix --version
nix (Nix) 2.9.1
```

The exact version might be different.

### Enable nix flakes

If you installed Nix using the "determinate installer" you can skip this step. If you used the "official installer", edit either `~/.config/nix/nix.conf` or `/etc/nix/nix.conf` and add:

```
experimental-features = nix-command flakes
```

If the Nix installation is in multi-user mode, don’t forget to restart the nix-daemon.

## Use Nix Shell

```sh
nix develop -c $SHELL
```

## Common Development Tasks

### Building the Project
```sh
just build
```

### Running Unit Tests
```bash
just test
```

### Running Integration Tests
```bash
just itest REDB/SQLITE/MEMEORY
```

### Running Format
```bash
just format
```


### Running Clippy
```bash
just clippy
```

### Running final check before commit
```sh
just final-check
```


## Best Practices

1. **Branch Management**
- Create feature branches from `main`
- Use descriptive branch names: `feature/new-feature` or `fix/bug-description`

2. **Commit Messages**
- Follow conventional commits format
- Begin with type: `feat:`, `fix:`, `docs:`, `chore:`, etc.
- Provide clear, concise descriptions

3. **Testing**
- Write tests for new features
- Ensure all tests pass before submitting PR
- Include integration tests where applicable

## Troubleshooting

### Common Issues

1. **Development Shell Issues**
- Clean Nix store: `nix-collect-garbage -d`
- Remove and recreate development shell

### Getting Help

- Open an issue on GitHub
- Check existing issues for similar problems
- Include relevant error messages and system information
- Reach out in Discord [Invite link](https://discord.gg/tUxMKd5YjN)

## Contributing

1. Create a feature branch
2. Make your changes
3. Run tests and formatting
4. Submit a pull request
5. Wait for review and address feedback

## Additional Resources

- [Nix Documentation](https://nixos.org/manual/nix/stable/)
- [Contributing Guidelines](CONTRIBUTING.md)

## License

Refer to the LICENSE file in the repository for terms of use and distribution.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ The project is split up into several crates in the `crates/` directory:
| [16][16] | Animated QR codes | :x: |
| [17][17] | WebSocket subscriptions | :construction: |

MSRV

## Bindings

Expand All @@ -75,6 +74,9 @@ All contributions welcome.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, shall be licensed as above, without any additional terms or conditions.

Please see the [development guide](DEVELOPMENT.md).


[00]: https://github.com/cashubtc/nuts/blob/main/00.md
[01]: https://github.com/cashubtc/nuts/blob/main/01.md
[02]: https://github.com/cashubtc/nuts/blob/main/02.md
Expand Down
2 changes: 2 additions & 0 deletions bindings/cdk-js/src/nuts/nut06.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ impl JsMintInfo {
contact: Option<Vec<JsContactInfo>>,
nuts: JsValue,
icon_url: Option<String>,
urls: Option<Vec<String>>,
motd: Option<String>,
time: Option<u64>,
) -> Result<JsMintInfo> {
Expand All @@ -92,6 +93,7 @@ impl JsMintInfo {
.map(|contacts| contacts.iter().map(|c| c.deref().clone()).collect()),
nuts: serde_wasm_bindgen::from_value(nuts).map_err(into_err)?,
icon_url,
urls,
motd,
time,
},
Expand Down
2 changes: 1 addition & 1 deletion bindings/cdk-js/src/types/melt_quote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl JsMeltQuote {

#[wasm_bindgen(getter)]
pub fn unit(&self) -> JsCurrencyUnit {
self.inner.unit.into()
self.inner.unit.clone().into()
}

#[wasm_bindgen(getter)]
Expand Down
2 changes: 1 addition & 1 deletion bindings/cdk-js/src/types/mint_quote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl JsMintQuote {

#[wasm_bindgen(getter)]
pub fn unit(&self) -> JsCurrencyUnit {
self.inner.unit.into()
self.inner.unit.clone().into()
}

#[wasm_bindgen(getter)]
Expand Down
25 changes: 17 additions & 8 deletions crates/cdk-axum/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,30 @@ edition = "2021"
license = "MIT"
homepage = "https://github.com/cashubtc/cdk"
repository = "https://github.com/cashubtc/cdk.git"
rust-version = "1.63.0" # MSRV
rust-version = "1.63.0" # MSRV
description = "Cashu CDK axum webserver"

[dependencies]
anyhow = "1"
async-trait = "0.1"
axum = "0.6.20"
cdk = { path = "../cdk", version = "0.4.0", default-features = false, features = ["mint"] }
tokio = { version = "1", default-features = false }
tracing = { version = "0.1", default-features = false, features = ["attributes", "log"] }
utoipa = { version = "4", features = ["preserve_order", "preserve_path_order"], optional = true }
async-trait = "0.1.83"
axum = { version = "0.6.20", features = ["ws"] }
cdk = { path = "../cdk", version = "0.4.0", default-features = false, features = [
"mint",
] }
tokio = { version = "1", default-features = false, features = ["io-util"] }
tracing = { version = "0.1", default-features = false, features = [
"attributes",
"log",
] }
utoipa = { version = "4", features = [
"preserve_order",
"preserve_path_order",
], optional = true }
futures = { version = "0.3.28", default-features = false }
moka = { version = "0.11.1", features = ["future"] }
serde_json = "1"
paste = "1.0.15"
serde = { version = "1.0.210", features = ["derive"] }

[features]
swagger = ["cdk/swagger", "dep:utoipa"]
swagger = ["cdk/swagger", "dep:utoipa"]
10 changes: 6 additions & 4 deletions crates/cdk-axum/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use moka::future::Cache;
use router_handlers::*;

mod router_handlers;
mod ws;

#[cfg(feature = "swagger")]
mod swagger_imports {
Expand Down Expand Up @@ -117,10 +118,10 @@ pub struct MintState {
get_keyset_pubkeys,
get_keysets,
get_mint_info,
get_mint_bolt11_quote,
post_mint_bolt11_quote,
get_check_mint_bolt11_quote,
post_mint_bolt11,
get_melt_bolt11_quote,
post_melt_bolt11_quote,
get_check_melt_bolt11_quote,
post_melt_bolt11,
post_swap,
Expand All @@ -147,13 +148,14 @@ pub async fn create_mint_router(mint: Arc<Mint>, cache_ttl: u64, cache_tti: u64)
.route("/keysets", get(get_keysets))
.route("/keys/:keyset_id", get(get_keyset_pubkeys))
.route("/swap", post(cache_post_swap))
.route("/mint/quote/bolt11", post(get_mint_bolt11_quote))
.route("/mint/quote/bolt11", post(post_mint_bolt11_quote))
.route(
"/mint/quote/bolt11/:quote_id",
get(get_check_mint_bolt11_quote),
)
.route("/mint/bolt11", post(cache_post_mint_bolt11))
.route("/melt/quote/bolt11", post(get_melt_bolt11_quote))
.route("/melt/quote/bolt11", post(post_melt_bolt11_quote))
.route("/ws", get(ws_handler))
.route(
"/melt/quote/bolt11/:quote_id",
get(get_check_melt_bolt11_quote),
Expand Down
22 changes: 13 additions & 9 deletions crates/cdk-axum/src/router_handlers.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use anyhow::Result;
use axum::extract::{Json, Path, State};
use axum::extract::{ws::WebSocketUpgrade, Json, Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use cdk::error::ErrorResponse;
Expand All @@ -13,7 +13,7 @@ use cdk::util::unix_time;
use cdk::Error;
use paste::paste;

use crate::MintState;
use crate::{ws::main_websocket, MintState};

macro_rules! post_cache_wrapper {
($handler:ident, $request_type:ty, $response_type:ty) => {
Expand Down Expand Up @@ -130,7 +130,7 @@ pub async fn get_keysets(State(state): State<MintState>) -> Result<Json<KeysetRe
/// Request a quote for minting of new tokens
///
/// Request minting of new tokens. The mint responds with a Lightning invoice. This endpoint can be used for a Lightning invoice UX flow.
pub async fn get_mint_bolt11_quote(
pub async fn post_mint_bolt11_quote(
State(state): State<MintState>,
Json(payload): Json<MintQuoteBolt11Request>,
) -> Result<Json<MintQuoteBolt11Response>, Response> {
Expand Down Expand Up @@ -174,6 +174,15 @@ pub async fn get_check_mint_bolt11_quote(
Ok(Json(quote))
}

pub async fn ws_handler(State(state): State<MintState>, ws: WebSocketUpgrade) -> impl IntoResponse {
ws.on_upgrade(|ws| main_websocket(ws, state))
}

/// Mint tokens by paying a BOLT11 Lightning invoice.
///
/// Requests the minting of tokens belonging to a paid payment request.
///
/// Call this endpoint after `POST /v1/mint/quote`.
#[cfg_attr(feature = "swagger", utoipa::path(
post,
context_path = "/v1",
Expand All @@ -184,11 +193,6 @@ pub async fn get_check_mint_bolt11_quote(
(status = 500, description = "Server error", body = ErrorResponse, content_type = "application/json")
)
))]
/// Mint tokens by paying a BOLT11 Lightning invoice.
///
/// Requests the minting of tokens belonging to a paid payment request.
///
/// Call this endpoint after `POST /v1/mint/quote`.
pub async fn post_mint_bolt11(
State(state): State<MintState>,
Json(payload): Json<MintBolt11Request>,
Expand Down Expand Up @@ -216,7 +220,7 @@ pub async fn post_mint_bolt11(
)
))]
/// Request a quote for melting tokens
pub async fn get_melt_bolt11_quote(
pub async fn post_melt_bolt11_quote(
State(state): State<MintState>,
Json(payload): Json<MeltQuoteBolt11Request>,
) -> Result<Json<MeltQuoteBolt11Response>, Response> {
Expand Down
19 changes: 19 additions & 0 deletions crates/cdk-axum/src/ws/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Source: https://www.jsonrpc.org/specification#error_object
pub enum WsError {
/// Invalid JSON was received by the server.
/// An error occurred on the server while parsing the JSON text.
ParseError,
/// The JSON sent is not a valid Request object.
InvalidRequest,
/// The method does not exist / is not available.
MethodNotFound,
/// Invalid method parameter(s).
InvalidParams,
/// Internal JSON-RPC error.
InternalError,
/// Custom error
ServerError(i32, String),
}
Loading

0 comments on commit b1f11ab

Please sign in to comment.