Skip to content

Commit

Permalink
Merge pull request #64 from Vovke/api-specs
Browse files Browse the repository at this point in the history
fix: order responses
  • Loading branch information
Slesarew authored Oct 7, 2024
2 parents 10d616e + f296103 commit 632d19b
Show file tree
Hide file tree
Showing 11 changed files with 213 additions and 96 deletions.
71 changes: 0 additions & 71 deletions .github/workflows/rust-check-version.yml

This file was deleted.

24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Kalatori Changelog

All notable changes to this project will be documented in this file.

## [2.1.2] - 2024-10-07

Making the order request work according to specs in the [specs](https://alzymologist.github.io/kalatori-api/#/).
Using the tests from [kalatori-api-test-suite]() in order to validate.
Added git cliff and configuration for it to generate CHANGELOG like this one, see [CONTRIBUTING.md](CONTRIBUTING.md)

### 🐛 Bug Fixes

- API specs Balances->Native
- Not having currency in the request responds with Fatal
- Validate missing order parameters
- Get order handler functionality part
- Get order and update order
- Removed version check for PRs

### ⚙️ Miscellaneous Tasks

- Resolve conflicts


30 changes: 30 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
## Version Bumping and Release Process

When you make changes that require a new version of the project, follow these steps to bump the version:

1. **Update the Version Number**:
- Update version in `Cargo.toml`

2. **Update the Changelog**:
- Run `git cliff <range> --tag <new-version>` to generate the changelog for the new version.
```bash
# For example in my case the origin of main repository marked as main,
# som main/main is the main branch of the main repository.
# 2.1.2 is version example.
git cliff main/main..HEAD --tag 2.1.2 -p CHANGELOG.md
```
- Review the changelog to ensure that the description is meaningful

3. **Add version related changes to commit**:
```bash
git add CHANGELOG.md Cargo.toml Cargo.lock
git commit -m "chore: bump version to 2.1.2"
git push origin <branch-name>
```

4. **Tag the version**:
```bash
git tag -a v2.1.2 -m "Release version 2.1.2"
git push origin v2.1.2
```

84 changes: 84 additions & 0 deletions cliff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# git-cliff ~ default configuration file
# https://git-cliff.org/docs/configuration
#
# Lines starting with "#" are comments.
# Configuration options are organized into tables and keys.
# See documentation for more information on available options.

[changelog]
# template for the changelog header
initial_tag="0.2.1"
header = """
# Kalatori Changelog\n
All notable changes to this project will be documented in this file.\n
"""
# template for the changelog body
# https://keats.github.io/tera/docs/#introduction
body = """
{% if version %}\
## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }}
{% else %}\
## [unreleased]
{% endif %}\
{% for group, commits in commits | group_by(attribute="group") %}
### {{ group | striptags | trim | upper_first }}
{% for commit in commits %}
- {% if commit.scope %}*({{ commit.scope }})* {% endif %}\
{% if commit.breaking %}[**breaking**] {% endif %}\
{{ commit.message | upper_first }}\
{% endfor %}
{% endfor %}\n
"""
# template for the changelog footer
footer = """
"""
# remove the leading and trailing s
trim = true
# postprocessors
postprocessors = [
# { pattern = '<REPO>', replace = "https://github.com/orhun/git-cliff" }, # replace repository URL
]
# render body even when there are no releases to process
# render_always = true
# output file path
# output = "test.md"

[git]
# parse the commits based on https://www.conventionalcommits.org
conventional_commits = true
# filter out the commits that are not conventional
filter_unconventional = true
# process each line of a commit as an individual commit
split_commits = false
# regex for preprocessing the commit messages
commit_preprocessors = [
# Replace issue numbers
#{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](<REPO>/issues/${2}))"},
# Check spelling of the commit with https://github.com/crate-ci/typos
# If the spelling is incorrect, it will be automatically fixed.
#{ pattern = '.*', replace_command = 'typos --write-changes -' },
]
# regex for parsing and grouping commits
commit_parsers = [
{ message = "^feat", group = "<!-- 0 -->🚀 Features" },
{ message = "^fix", group = "<!-- 1 -->🐛 Bug Fixes" },
{ message = "^doc", group = "<!-- 3 -->📚 Documentation" },
{ message = "^perf", group = "<!-- 4 -->⚡ Performance" },
{ message = "^refactor", group = "<!-- 2 -->🚜 Refactor" },
{ message = "^style", group = "<!-- 5 -->🎨 Styling" },
{ message = "^test", group = "<!-- 6 -->🧪 Testing" },
{ message = "^chore\\(release\\): prepare for", skip = true },
{ message = "^chore\\(deps.*\\)", skip = true },
{ message = "^chore\\(pr\\)", skip = true },
{ message = "^chore\\(pull\\)", skip = true },
{ message = "^chore|^ci", group = "<!-- 7 -->⚙️ Miscellaneous Tasks" },
{ body = ".*security", group = "<!-- 8 -->🛡️ Security" },
{ message = "^revert", group = "<!-- 9 -->◀️ Revert" },
]
# filter out the commits that are not matched by commit parsers
filter_commits = false
# sort the tags topologically
topo_order = false
# sort the commits inside sections by oldest/newest order
sort_commits = "oldest"
2 changes: 1 addition & 1 deletion src/chain/payout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub async fn payout(
// Payout operation logic
let transactions = match balance.0 - order.amount.0 {
a if (0..=loss_tolerance).contains(&a) => match currency.kind {
TokenKind::Balances => {
TokenKind::Native => {
let balance_transfer_constructor = BalanceTransferConstructor {
amount: order.amount.0,
to_account: &order.recipient,
Expand Down
2 changes: 1 addition & 1 deletion src/chain/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ pub async fn assets_set_at_block(
specs.unit,
CurrencyProperties {
chain_name: chain_name.clone(),
kind: TokenKind::Balances,
kind: TokenKind::Native,
decimals: specs.decimals,
rpc_url: rpc_url.to_owned(),
asset_id: None,
Expand Down
12 changes: 8 additions & 4 deletions src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,15 +365,18 @@ fn create_order(
orders: &sled::Tree,
account_lifetime: Timestamp,
) -> Result<OrderCreateResponse, DbError> {
Ok(if let Some(record) = orders.get(&order)? {
let order_key = order.encode();
Ok(if let Some(record) = orders.get(&order_key)? {
let mut old_order_info = OrderInfo::decode(&mut &record[..])?;
match old_order_info.payment_status {
PaymentStatus::Pending => {
let death = calculate_death_ts(account_lifetime);

old_order_info.death = death;
old_order_info.currency = currency;
old_order_info.amount = query.amount;

drop(orders.insert(order.encode(), old_order_info.encode())?);
orders.insert(&order_key, old_order_info.encode())?;
OrderCreateResponse::Modified(old_order_info)
}
PaymentStatus::Paid => OrderCreateResponse::Collision(old_order_info),
Expand All @@ -382,13 +385,14 @@ fn create_order(
let death = calculate_death_ts(account_lifetime);
let order_info_new = OrderInfo::new(query, currency, payment_account, death);

orders.insert(order.encode(), order_info_new.encode())?;
orders.insert(&order_key, order_info_new.encode())?;
OrderCreateResponse::New(order_info_new)
})
}

fn read_order(order: String, orders: &sled::Tree) -> Result<Option<OrderInfo>, DbError> {
if let Some(order) = orders.get(order)? {
let order_key = order.encode();
if let Some(order) = orders.get(order_key)? {
Ok(Some(OrderInfo::decode(&mut &order[..])?))
} else {
Ok(None)
Expand Down
2 changes: 1 addition & 1 deletion src/definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ pub mod api_v2 {
#[serde(rename_all = "lowercase")]
pub enum TokenKind {
Asset,
Balances,
Native,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
Expand Down
58 changes: 42 additions & 16 deletions src/handlers/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,38 +13,64 @@ use axum::{
};
use serde::Deserialize;

const EXISTENTIAL_DEPOSIT: f64 = 0.07;
#[derive(Debug, Deserialize)]
pub struct OrderPayload {
pub amount: f64,
pub currency: String,
pub amount: Option<f64>,
pub currency: Option<String>,
pub callback: Option<String>,
}

pub async fn process_order(
state: State,
order_id: String,
payload: OrderPayload,
payload: Option<OrderPayload>,
) -> Result<OrderResponse, OrderError> {
if payload.amount < 0.07 {
return Err(OrderError::LessThanExistentialDeposit(0.07));
}
if let Some(payload) = payload {
// AMOUNT validation
if payload.amount.is_none() {
return Err(OrderError::MissingParameter(AMOUNT.to_string()));
} else if payload.amount.unwrap() < EXISTENTIAL_DEPOSIT {
return Err(OrderError::LessThanExistentialDeposit(EXISTENTIAL_DEPOSIT));
}

state
.create_order(OrderQuery {
order: order_id,
amount: payload.amount,
callback: payload.callback.unwrap_or_default(),
currency: payload.currency,
})
.await
.map_err(|_| OrderError::InternalError)
// CURRENCY validation
if payload.currency.is_none() {
return Err(OrderError::MissingParameter(CURRENCY.to_string()));
} else {
let currency = payload.currency.clone().unwrap();
if !state
.is_currency_supported(&currency)
.await
.map_err(|_| OrderError::InternalError)?
{
return Err(OrderError::UnknownCurrency);
}
}

state
.create_order(OrderQuery {
order: order_id,
amount: payload.amount.unwrap(),
callback: payload.callback.unwrap_or_default(),
currency: payload.currency.unwrap(),
})
.await
.map_err(|_| OrderError::InternalError)
} else {
return state
.order_status(&order_id)
.await
.map_err(|_| OrderError::InternalError);
}
}

pub async fn order(
ExtractState(state): ExtractState<State>,
Path(order_id): Path<String>,
Json(payload): Json<OrderPayload>,
payload: Option<Json<OrderPayload>>,
) -> Response {
let payload = payload.map(|p| p.0);
match process_order(state, order_id, payload).await {
Ok(order) => match order {
OrderResponse::NewOrder(order_status) => (StatusCode::CREATED, Json(order_status)).into_response(),
Expand Down
Loading

0 comments on commit 632d19b

Please sign in to comment.