用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/tomevault-io/skills-registry --skill rust-fintech命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
基于 SOC 职业分类
正在显示 SKILL.md
| name | rust-fintech |
| description | | Use when this capability is needed. |
Best practices for building accurate, compliant, and deterministic financial systems in Rust.
Never use floats (f32, f64) to represent monetary values due to rounding errors and precision loss. Instead, use rust_decimal::Decimal.
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
// Bad: f64 is subject to rounding inaccuracies
let price: f64 = 19.99;
// Good: Exact fixed-point precision
let price: Decimal = dec!(19.99);
Encapsulate currency and amount into a single type-safe domain boundary. Prevent addition or arithmetic operations between mismatched currencies.
use rust_decimal::Decimal;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Currency {
USD,
EUR,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Money {
amount: Decimal,
currency: Currency,
}
impl Money {
pub fn new(amount: Decimal, currency: Currency) -> Self {
Self { amount, currency }
}
pub fn add(&self, other: &Money) -> Result<Money, &'static str> {
if self.currency != other.currency {
return Err("Currency mismatch");
}
let new_amount = self.amount.checked_add(other.amount)
.ok_or("Arithmetic overflow")?;
Ok(Money::new(new_amount, self.currency.clone()))
}
}
Ensure that entries balance exactly: the sum of debits must equal the sum of credits.
pub struct LedgerEntry {
pub account_id: String,
pub amount: Decimal, // Positive for debit, negative for credit
}
pub struct Transaction {
pub id: uuid::Uuid,
pub entries: Vec<LedgerEntry>,
}
impl Transaction {
pub fn validate(&self) -> Result<(), &'static str> {
let sum: Decimal = self.entries.iter().map(|e| e.amount).sum();
if sum.is_zero() {
Ok(())
} else {
Err("Transaction is unbalanced: total sum of entries must equal zero")
}
}
}
Ledger entries must be append-only and immutable. Rather than modifying states in-place, record discrete event entries over time.
pub enum AccountEvent {
Deposited { amount: Decimal, timestamp: chrono::DateTime<chrono::Utc> },
Withdrawn { amount: Decimal, timestamp: chrono::DateTime<chrono::Utc> },
}
pub struct Account {
id: String,
balance: Decimal,
}
impl Account {
pub fn apply(&mut self, event: &AccountEvent) {
match event {
AccountEvent::Deposited { amount, .. } => self.balance += amount,
AccountEvent::Withdrawn { amount, .. } => self.balance -= amount,
}
}
}
Always use checked, wrapping, or saturating arithmetic methods rather than standard operators if there's any chance of input overflow.
checked_add / checked_subsaturating_add / saturating_subPrefer integer minor units for ledgers and settlement. Use decimal types for pricing, rates, tax, and calculations where scale must be preserved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AmountMinor(i64);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Currency { Usd, Eur, Gbp }
Every posted transaction must be:
pub struct IdempotencyKey(String);
pub async fn post_payment(req: PaymentRequest, key: IdempotencyKey) -> Result<Receipt, Error> {
// 1. reserve key in transaction
// 2. if existing response, return it
// 3. validate and post ledger entries
// 4. persist response tied to key
// 5. commit
todo_domain_example()
}
pub struct FxRate {
pub base: Currency,
pub quote: Currency,
pub rate: Decimal,
pub source: &'static str,
pub fetched_at: chrono::DateTime<chrono::Utc>,
}
impl FxRate {
pub fn convert(&self, amount: Decimal) -> Result<Decimal, &'static str> {
(amount * self.rate).round_dp(4).checked_sub(Decimal::ZERO)
.ok_or("FX conversion overflow")
}
}
pub struct FxProvider {
rates: HashMap<(Currency, Currency), FxRate>,
}
impl FxProvider {
pub fn convert(&self, from: Currency, to: Currency, amount: Decimal) -> Result<Money, FxError> {
if from == to {
return Ok(Money::new(amount, from));
}
let rate = self.rates.get(&(from, to))
.ok_or(FxError::RateNotFound { from, to })?;
if rate.fetched_at + chrono::Duration::() < chrono::Utc::() {
(FxError::StaleRate);
}
= amount * rate.rate;
(Money::(converted.(), to))
}
}
pub enum FeeStructure {
Flat { amount: Decimal },
Percentage { rate: Decimal, min: Option<Decimal>, max: Option<Decimal> },
Tiered { tiers: Vec<(Decimal, Decimal)> },
}
impl FeeStructure {
pub fn calculate(&self, amount: Decimal) -> Result<Decimal, FeeError> {
match self {
FeeStructure::Flat { amount: fee } => Ok(*fee),
FeeStructure::Percentage { rate, min, max } => {
let raw = (amount * rate).round_dp(2);
let bounded = match (min, max) {
(Some(lo), _) if raw < *lo => *lo,
(_, Some(hi)) if raw > *hi => *hi,
_ => raw,
};
Ok(bounded)
}
FeeStructure::Tiered { tiers } => {
for (threshold, rate) in tiers.iter().rev() {
if amount >= *threshold {
return Ok((amount * rate).round_dp(2));
}
}
Ok(Decimal::ZERO)
}
}
}
}
pub fn compound_interest(
principal: Decimal,
annual_rate: Decimal,
periods: u32,
compounds_per_year: u32,
) -> Result<Decimal, &'static str> {
let rate_per_period = annual_rate / Decimal::from(compounds_per_year);
let total_periods = periods * compounds_per_year;
let mut balance = principal;
for _ in 0..total_periods {
let interest = (balance * rate_per_period).round_dp(2);
balance = balance.checked_add(interest)
.ok_or("Interest calculation overflow")?;
}
Ok(balance - principal) // total interest earned
}
use hmac::{Hmac, Mac};
use sha2::Sha256;
type HmacSha256 = Hmac<Sha256>;
pub fn verify_webhook_signature(
payload: &[u8],
signature: &str,
secret: &[u8],
) -> Result<(), WebhookError> {
let expected = hex::decode(signature)
.map_err(|_| WebhookError::InvalidSignature)?;
let mut mac = HmacSha256::new_from_slice(secret)
.map_err(|_| WebhookError::InvalidSecret)?;
mac.update(payload);
mac.verify_slice(&expected)
.map_err(|_| WebhookError::SignatureMismatch)
}
For fintech Rust, verify numeric representation, ledger immutability, idempotency, audit trail completeness, database constraints, and property tests for invariants.
Source: adxptived/Rust-Skills — distributed by TomeVault.