Skip to content

Commit

Permalink
添加创建钱包,更新钱包积分接口
Browse files Browse the repository at this point in the history
  • Loading branch information
ouyangkang committed Feb 23, 2024
1 parent 150478b commit 07d230e
Show file tree
Hide file tree
Showing 6 changed files with 93 additions and 39 deletions.
5 changes: 2 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ edition = "2021"

loco-rs = { version = "0.3.1" }
migration = { path = "migration" }

rand = "0.8.4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
eyre = "0.6"
Expand All @@ -21,8 +21,7 @@ tracing = "0.1.40"
chrono = "0.4"
validator = { version = "0.16" }
sea-orm = { version = "1.0.0-rc.1", features = [
"sqlx-sqlite",
"sqlx-postgres",
"sqlx-mysql",
"runtime-tokio-rustls",
"macros",
] }
Expand Down
32 changes: 0 additions & 32 deletions config/development.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -59,30 +59,6 @@ server:
# Set the value of the [`Access-Control-Max-Age`][mdn] header in seconds
# max_age: 3600

# Worker Configuration
workers:
# specifies the worker mode. Options:
# - BackgroundQueue - Workers operate asynchronously in the background, processing queued.
# - ForegroundBlocking - Workers operate in the foreground and block until tasks are completed.
# - BackgroundAsync - Workers operate asynchronously in the background, processing tasks with async capabilities.
mode: BackgroundQueue

# Mailer Configuration.
mailer:
# SMTP mailer configuration.
smtp:
# Enable/Disable smtp mailer.
enable: true
# SMTP server host. e.x localhost, smtp.gmail.com
host: {{ get_env(name="MAILER_HOST", default="localhost") }}
# SMTP server port
port: 1025
# Use secure connection (SSL/TLS).
secure: false
# auth:
# user:
# password:

# Database Configuration
database:
# Database connection URI
Expand Down Expand Up @@ -111,12 +87,4 @@ redis:
# Dangerously flush all data in Redis on startup. dangerous operation, make sure that you using this flag only on dev environments or test mode
dangerously_flush: false

# Authentication Configuration
auth:
# JWT authentication
jwt:
# Secret key for token generation and verification
secret: 6m0Zspduvb2gozN49CP6
# Token expiration time in seconds
expiration: 604800 # 7 days

62 changes: 59 additions & 3 deletions src/controllers/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,79 @@
#![allow(clippy::unused_async)]
use crate::models::_entities::prelude::*;
use crate::models::_entities::wallets;
use crate::views::response::ModelResp;
use crate::views::wallets::UpdateWallet;
use crate::views::wallets::WalletResponse;
use loco_rs::prelude::*;
use sea_orm::prelude::Decimal;
use sea_orm::{ColumnTrait, QueryFilter};

// 获取钱包信息
pub async fn get_one(
Path(addr): Path<String>,
State(ctx): State<AppContext>,
) -> Result<Json<WalletResponse>> {
) -> Result<Json<ModelResp<WalletResponse>>> {
let base = Wallets::find()
.filter(wallets::Column::Addr.eq(&addr))
.one(&ctx.db)
.await?
.ok_or_else(|| Error::NotFound)?;
format::json(WalletResponse::new(&base))
format::json(success(&base))
}

// 创建钱包
pub async fn create_addr(State(ctx): State<AppContext>) -> Result<Json<ModelResp<WalletResponse>>> {
let active_model = wallets::ActiveModel {
addr: Set(get_addr()),
balance: Set(Decimal::new(0, 2)),
status: Set(1),
..Default::default()
};
let base = active_model.insert(&ctx.db).await?;
format::json(success(&base))
}

// 更新钱包积分
pub async fn update_balance(
State(ctx): State<AppContext>,
Json(params): Json<UpdateWallet>,
) -> Result<Json<ModelResp<WalletResponse>>> {
let mut base: wallets::Model = Wallets::find()
.filter(wallets::Column::Addr.eq(&params.addr))
.one(&ctx.db)
.await?
.ok_or_else(|| Error::NotFound)?;
let mut active_model = base.into_active_model();
params.update_balance(&mut active_model);
tracing::info!("active---- info {:?}", &active_model);
base = active_model.update(&ctx.db).await?;
format::json(success(&base))
}

fn success(base: &wallets::Model) -> ModelResp<WalletResponse> {
ModelResp::success(WalletResponse::new(base))
}

/*
生成一个随机钱包地址
0x开头 长度为42位的字符串
示例: 0xed761902880a3ce647c472c8d32c5fda13c0d235
*/
fn get_addr() -> String {
let mut addr = "0x".to_string();
let chars = "abcdef0123456789";
for _ in 0..40 {
let idx = rand::random::<usize>() % 16;
addr.push(chars.chars().nth(idx).unwrap());
}
tracing::info!("生成的地址: {}", addr);
addr
}

pub fn routes() -> Routes {
Routes::new().prefix("wallet").add("/:addr", get(get_one))
Routes::new()
.prefix("wallet")
.add("/update_balance", post(update_balance))
.add("/", post(create_addr))
.add("/:addr", get(get_one))
}
2 changes: 2 additions & 0 deletions src/views/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
pub mod wallets;

pub mod response;
18 changes: 18 additions & 0 deletions src/views/response.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
pub struct ModelResp<T> {
pub data: T,
pub code: i8,
pub msg: String,
}

impl<T> ModelResp<T> {
pub fn success(data: T) -> Self {
ModelResp {
data: data,
code: 0,
msg: "success".to_string(),
}
}
}
13 changes: 12 additions & 1 deletion src/views/wallets.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use sea_orm::prelude::Decimal;
use sea_orm::{prelude::Decimal, Set};
use serde::{Deserialize, Serialize};

use crate::models::_entities::wallets;
Expand All @@ -18,3 +18,14 @@ impl WalletResponse {
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct UpdateWallet {
pub addr: String,
pub balance: Decimal,
}

impl UpdateWallet {
pub fn update_balance(&self, model: &mut wallets::ActiveModel) {
model.balance = Set(self.balance.clone());
}
}

0 comments on commit 07d230e

Please sign in to comment.