feat(acc-protocols): 完成所有 ACC 协议族 SDK 层实现

- 修复 nac-sdk 中 acc1410/1400/1594/1643/1644 空函数体问题
- 重写 10 个新增 RWA/稳定币协议的 SDK 客户端文件
- 修复 protocols/mod.rs 中的类型导出错误
- 修复 adapters/mod.rs 中的自引用类型别名
- 全局修复含空格的非法标识符(NAC Lens4Client -> NacLensClient)
- nac-sdk 编译通过(0 errors)

ACC 协议族完整清单(19个协议,三层全覆盖):
基础代币: ACC-20, ACC-20Enhanced, ACC-721, ACC-1155, ACC-20C
RWA专用: ACC-RWA, ACC-Compliance, ACC-Valuation, ACC-Custody,
         ACC-Collateral, ACC-Redemption, ACC-Insurance, ACC-Governance
稳定币:   ACC-XTZH, ACC-Reserve
证券代币: ACC-1410, ACC-1400, ACC-1594, ACC-1643, ACC-1644

三层架构:
L1 nac-udm: 协议定义层(Rust 完整实现)
L2 charter-std: Charter 标准库(.ch 接口文件)
L3 nac-sdk: 开发者 SDK(NRPC4.0 客户端)
This commit is contained in:
NAC Admin 2026-03-06 16:19:56 +08:00
parent 29544afec4
commit 023a1b7926
30 changed files with 1753 additions and 1529 deletions

View File

@ -37,7 +37,7 @@ use super::{
CollateralProof, Decimal, CollateralProof, Decimal,
}; };
use nac_udm::l1_protocol::gnacs::GNACSCode; use nac_udm::l1_protocol::gnacs::GNACSCode;
use super::NAC Lens4Client; use super::NacLensClient;
use std::time::Duration; use std::time::Duration;
/// L1协议层适配器 /// L1协议层适配器
@ -46,7 +46,7 @@ use std::time::Duration;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct L1ProtocolAdapter { pub struct L1ProtocolAdapter {
/// NAC Lens4客户端 /// NAC Lens4客户端
client: NAC Lens4Client, client: NacLensClient,
/// 链ID /// 链ID
chain_id: u32, chain_id: u32,
/// 超时时间 /// 超时时间
@ -64,7 +64,7 @@ impl L1ProtocolAdapter {
/// ///
/// 返回初始化完成的L1适配器实例 /// 返回初始化完成的L1适配器实例
pub async fn new(config: &L1Config) -> Result<Self> { pub async fn new(config: &L1Config) -> Result<Self> {
let client = NAC Lens4Client::new(&config.nac_lens_url, config.timeout) let client = NacLensClient::new(&config.nac_lens_url, config.timeout)
.map_err(|e| NACError::NetworkError(format!("Failed to create NAC Lens4 client: {}", e)))?; .map_err(|e| NACError::NetworkError(format!("Failed to create NAC Lens4 client: {}", e)))?;
Ok(Self { Ok(Self {

View File

@ -35,7 +35,7 @@ use super::{
Amendment, AmendmentStatus, Proposal, ProposalDetails, Amendment, AmendmentStatus, Proposal, ProposalDetails,
Vote, ComplianceResult, PeerInfo, Vote, ComplianceResult, PeerInfo,
}; };
use super::NAC Lens4Client; use super::NacLensClient;
use super::CSNPNetwork; use super::CSNPNetwork;
use super::Decimal; use super::Decimal;
@ -50,9 +50,9 @@ pub type ProposalId = u64;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct L2Adapter { pub struct L2Adapter {
/// 宪政层客户端 /// 宪政层客户端
constitutional_client: NAC Lens4Client, constitutional_client: NacLensClient,
/// 治理层客户端 /// 治理层客户端
governance_client: NAC Lens4Client, governance_client: NacLensClient,
/// CSNP网络 /// CSNP网络
network: Arc<CSNPNetwork>, network: Arc<CSNPNetwork>,
} }
@ -68,10 +68,10 @@ impl L2Adapter {
/// ///
/// 返回初始化完成的L2适配器实例 /// 返回初始化完成的L2适配器实例
pub async fn new(config: &L2Config) -> Result<Self> { pub async fn new(config: &L2Config) -> Result<Self> {
let constitutional_client = NAC Lens4Client::new(&config.constitutional_url, std::time::Duration::from_secs(30)) let constitutional_client = NacLensClient::new(&config.constitutional_url, std::time::Duration::from_secs(30))
.map_err(|e| NACError::NetworkError(format!("Failed to create constitutional client: {}", e)))?; .map_err(|e| NACError::NetworkError(format!("Failed to create constitutional client: {}", e)))?;
let governance_client = NAC Lens4Client::new(&config.governance_url, std::time::Duration::from_secs(30)) let governance_client = NacLensClient::new(&config.governance_url, std::time::Duration::from_secs(30))
.map_err(|e| NACError::NetworkError(format!("Failed to create governance client: {}", e)))?; .map_err(|e| NACError::NetworkError(format!("Failed to create governance client: {}", e)))?;
let network = Arc::new(CSNPNetwork::new(&config.network_peers).await let network = Arc::new(CSNPNetwork::new(&config.network_peers).await

View File

@ -33,7 +33,7 @@ use crate::error::{NACError, Result};
use super::config::L4Config; use super::config::L4Config;
use nac_udm::primitives::Address; use nac_udm::primitives::Address;
use super::{NacLensClient as NAC Lens4Client, use super::{NacLensClient as NacLensClient,
Transaction, ComplianceData, ComplianceResult, ComplianceReport, Transaction, ComplianceData, ComplianceResult, ComplianceReport,
ZKProof, Asset, ValuationResult, MarketData, RiskScore, ZKProof, Asset, ValuationResult, MarketData, RiskScore,
UserBehavior, AnomalyReport, RiskReport, Reserves, ReserveStrategy, UserBehavior, AnomalyReport, RiskReport, Reserves, ReserveStrategy,
@ -48,13 +48,13 @@ use std::time::Duration;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct L4AIAdapter { pub struct L4AIAdapter {
/// AI合规客户端 /// AI合规客户端
compliance_client: NAC Lens4Client, compliance_client: NacLensClient,
/// AI估值客户端 /// AI估值客户端
valuation_client: NAC Lens4Client, valuation_client: NacLensClient,
/// AI风险客户端 /// AI风险客户端
risk_client: NAC Lens4Client, risk_client: NacLensClient,
/// XTZH AI客户端 /// XTZH AI客户端
xtzh_ai_client: NAC Lens4Client, xtzh_ai_client: NacLensClient,
} }
impl L4AIAdapter { impl L4AIAdapter {
@ -68,16 +68,16 @@ impl L4AIAdapter {
/// ///
/// 返回初始化完成的L4适配器实例 /// 返回初始化完成的L4适配器实例
pub async fn new(config: &L4Config) -> Result<Self> { pub async fn new(config: &L4Config) -> Result<Self> {
let compliance_client = NAC Lens4Client::new(&config.compliance_url, Duration::from_secs(30)) let compliance_client = NacLensClient::new(&config.compliance_url, Duration::from_secs(30))
.map_err(|e| NACError::NetworkError(format!("Failed to create compliance client: {}", e)))?; .map_err(|e| NACError::NetworkError(format!("Failed to create compliance client: {}", e)))?;
let valuation_client = NAC Lens4Client::new(&config.valuation_url, Duration::from_secs(30)) let valuation_client = NacLensClient::new(&config.valuation_url, Duration::from_secs(30))
.map_err(|e| NACError::NetworkError(format!("Failed to create valuation client: {}", e)))?; .map_err(|e| NACError::NetworkError(format!("Failed to create valuation client: {}", e)))?;
let risk_client = NAC Lens4Client::new(&config.risk_url, Duration::from_secs(30)) let risk_client = NacLensClient::new(&config.risk_url, Duration::from_secs(30))
.map_err(|e| NACError::NetworkError(format!("Failed to create risk client: {}", e)))?; .map_err(|e| NACError::NetworkError(format!("Failed to create risk client: {}", e)))?;
let xtzh_ai_client = NAC Lens4Client::new(&config.xtzh_ai_url, Duration::from_secs(30)) let xtzh_ai_client = NacLensClient::new(&config.xtzh_ai_url, Duration::from_secs(30))
.map_err(|e| NACError::NetworkError(format!("Failed to create XTZH AI client: {}", e)))?; .map_err(|e| NACError::NetworkError(format!("Failed to create XTZH AI client: {}", e)))?;
Ok(Self { Ok(Self {

View File

@ -33,7 +33,7 @@ use crate::error::{NACError, Result};
use super::config::L5Config; use super::config::L5Config;
use nac_udm::primitives::{Address, Hash}; use nac_udm::primitives::{Address, Hash};
use super::{ use super::{
Wallet, BalanceInfo, TransactionInfo, TransactionReceipt, NacLensClient as NAC Lens4Client, Decimal, Wallet, BalanceInfo, TransactionInfo, TransactionReceipt, NacLensClient as NacLensClient, Decimal,
ChainStatistics, AddressInfo, TokenMetadata, TradingPair, ChainStatistics, AddressInfo, TokenMetadata, TradingPair,
OrderBook, Value, ContractCall, OrderBook, Value, ContractCall,
}; };
@ -55,13 +55,13 @@ pub struct EventStream {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct L5ApplicationAdapter { pub struct L5ApplicationAdapter {
/// 钱包客户端 /// 钱包客户端
wallet_client: NAC Lens4Client, wallet_client: NacLensClient,
/// DApp客户端 /// DApp客户端
dapp_client: NAC Lens4Client, dapp_client: NacLensClient,
/// 浏览器客户端 /// 浏览器客户端
explorer_client: NAC Lens4Client, explorer_client: NacLensClient,
/// 交易所客户端 /// 交易所客户端
exchange_client: NAC Lens4Client, exchange_client: NacLensClient,
} }
impl L5ApplicationAdapter { impl L5ApplicationAdapter {
@ -75,16 +75,16 @@ impl L5ApplicationAdapter {
/// ///
/// 返回初始化完成的L5适配器实例 /// 返回初始化完成的L5适配器实例
pub async fn new(config: &L5Config) -> Result<Self> { pub async fn new(config: &L5Config) -> Result<Self> {
let wallet_client = NAC Lens4Client::new(&config.wallet_url, Duration::from_secs(30)) let wallet_client = NacLensClient::new(&config.wallet_url, Duration::from_secs(30))
.map_err(|e| NACError::NetworkError(format!("Failed to create wallet client: {}", e)))?; .map_err(|e| NACError::NetworkError(format!("Failed to create wallet client: {}", e)))?;
let dapp_client = NAC Lens4Client::new(&config.dapp_url, Duration::from_secs(30)) let dapp_client = NacLensClient::new(&config.dapp_url, Duration::from_secs(30))
.map_err(|e| NACError::NetworkError(format!("Failed to create dapp client: {}", e)))?; .map_err(|e| NACError::NetworkError(format!("Failed to create dapp client: {}", e)))?;
let explorer_client = NAC Lens4Client::new(&config.explorer_url, Duration::from_secs(30)) let explorer_client = NacLensClient::new(&config.explorer_url, Duration::from_secs(30))
.map_err(|e| NACError::NetworkError(format!("Failed to create explorer client: {}", e)))?; .map_err(|e| NACError::NetworkError(format!("Failed to create explorer client: {}", e)))?;
let exchange_client = NAC Lens4Client::new(&config.exchange_url, Duration::from_secs(30)) let exchange_client = NacLensClient::new(&config.exchange_url, Duration::from_secs(30))
.map_err(|e| NACError::NetworkError(format!("Failed to create exchange client: {}", e)))?; .map_err(|e| NACError::NetworkError(format!("Failed to create exchange client: {}", e)))?;
Ok(Self { Ok(Self {

View File

@ -1444,10 +1444,6 @@ impl NacLensClient {
} }
} }
/// NAC Lens4Client 类型别名(向后兼容)
pub type NAC Lens4Client = NacLensClient;
/// NacLensClient 类型别名(向后兼容,已更名为 NAC Lens
pub type NacLensClient = NacLensClient;
/// Decimal 类型(代币数量,精度由协议层处理) /// Decimal 类型(代币数量,精度由协议层处理)
/// 使用 u128 表示,最小单位为 1e-18 /// 使用 u128 表示,最小单位为 1e-18

View File

@ -17,7 +17,7 @@ use thiserror::Error;
pub enum NACError { pub enum NACError {
/// NAC Lens协议错误 /// NAC Lens协议错误
#[error("NAC Lens protocol error: {0}")] #[error("NAC Lens protocol error: {0}")]
NAC Lens3Error(String), NacLensProtocolError(String),
/// 网络错误 /// 网络错误
#[error("Network error: {0}")] #[error("Network error: {0}")]
@ -179,7 +179,7 @@ mod tests {
#[test] #[test]
fn test_error_display() { fn test_error_display() {
let err = NACError::NAC Lens3Error("test error".to_string()); let err = NACError::NacLensProtocolError("test error".to_string());
assert_eq!(err.to_string(), "NAC Lens protocol error: test error"); assert_eq!(err.to_string(), "NAC Lens protocol error: test error");
} }

View File

@ -1,42 +1,98 @@
//! NAC SDK - ACC-1400 证券代币协议接口 //! NAC SDK - ACC-1400 证券代币协议接口
//! //!
//! ACC-1400 继承 ACC-1410专门用于证券型资产Security Token //! ACC-1400 是 NAC 原生的证券代币协议,支持合规证券发行、股息分配和转让限制
//! 增加了股息分配、投票权管理、转让限制、合规验证等功能
use crate::types::*; use crate::adapters::NacLensClient;
use crate::error::NacError; use crate::error::{NACError, Result};
use super::acc1410::{Acc1410Client, PartitionType, ExtendedGNACS}; use nac_udm::primitives::{Address, Hash};
use serde_json::json;
/// ACC-1400 证券代币协议客户端 /// ACC-1400 证券代币协议客户端
pub struct Acc1400Client { pub struct Acc1400Client {
pub base: Acc1410Client, pub client: NacLensClient,
pub contract_address: Address,
} }
impl Acc1400Client { impl Acc1400Client {
pub fn new(certificate_address: Address) -> Self { pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { base: Acc1410Client::new(certificate_address) } Self { client, contract_address }
} }
/// 发行证券 /// 发行证券代币
pub fn issue_security( pub async fn issue_security(
&self, &self,
security_id: &Hash, recipient: &Address,
to: &Address,
amount: u128, amount: u128,
) -> Result<Hash, NacError> { gnacs_code: &str,
jurisdiction: &str,
constitutional_receipt: &Hash,
) -> Result<Hash> {
let params = json!({
"contract": self.contract_address.to_hex(),
"recipient": recipient.to_hex(),
"amount": amount.to_string(),
"gnacs_code": gnacs_code,
"jurisdiction": jurisdiction,
"constitutional_receipt": constitutional_receipt.to_hex(),
});
let response = self.client.call("acc1400.issue_security", params).await?;
let tx_hash = response["result"].as_str()
.ok_or(NACError::InvalidResponse("Missing tx_hash".to_string()))?;
Hash::from_hex(tx_hash).map_err(|e| NACError::InvalidAddress(format!("Invalid hash: {}", e)))
} }
/// 证券转让(含合规检查) /// 合规转让
pub fn transfer_security( pub async fn transfer_with_data(
&self, &self,
from: &Address, from: &Address,
to: &Address, to: &Address,
amount: u128, amount: u128,
security_id: &Hash, compliance_data: &Hash,
) -> Result<Hash, NacError> { ) -> Result<Hash> {
let params = json!({
"contract": self.contract_address.to_hex(),
"from": from.to_hex(),
"to": to.to_hex(),
"amount": amount.to_string(),
"compliance_data": compliance_data.to_hex(),
});
let response = self.client.call("acc1400.transfer_with_data", params).await?;
let tx_hash = response["result"].as_str()
.ok_or(NACError::InvalidResponse("Missing tx_hash".to_string()))?;
Hash::from_hex(tx_hash).map_err(|e| NACError::InvalidAddress(format!("Invalid hash: {}", e)))
} }
/// 添加白名单 /// 查询合规状态
pub fn add_to_whitelist(&self, account: &Address) -> Result<(), NacError> { pub async fn can_transfer(
&self,
from: &Address,
to: &Address,
amount: u128,
) -> Result<bool> {
let params = json!({
"contract": self.contract_address.to_hex(),
"from": from.to_hex(),
"to": to.to_hex(),
"amount": amount.to_string(),
});
let response = self.client.call("acc1400.can_transfer", params).await?;
Ok(response["result"].as_bool().unwrap_or(false))
}
/// 分配股息
pub async fn distribute_dividend(
&self,
total_amount: u128,
constitutional_receipt: &Hash,
) -> Result<Hash> {
let params = json!({
"contract": self.contract_address.to_hex(),
"total_amount": total_amount.to_string(),
"constitutional_receipt": constitutional_receipt.to_hex(),
});
let response = self.client.call("acc1400.distribute_dividend", params).await?;
let tx_hash = response["result"].as_str()
.ok_or(NACError::InvalidResponse("Missing tx_hash".to_string()))?;
Hash::from_hex(tx_hash).map_err(|e| NACError::InvalidAddress(format!("Invalid hash: {}", e)))
} }
} }

View File

@ -3,42 +3,102 @@
//! ACC-1410 是 NAC 原生的分区代币协议,支持将代币分割为多个分区 //! ACC-1410 是 NAC 原生的分区代币协议,支持将代币分割为多个分区
//! (普通股、优先股、限制股、员工期权、收益权、投票权等) //! (普通股、优先股、限制股、员工期权、收益权、投票权等)
use crate::types::*; use crate::adapters::NacLensClient;
use crate::error::NacError; use crate::error::{NACError, Result};
use nac_udm::primitives::{Address, Hash};
use serde_json::json;
/// ACC-1410 分区代币协议客户端 /// ACC-1410 分区代币协议客户端
pub struct Acc1410Client { pub struct Acc1410Client {
/// 证书地址Charter 合约地址) pub client: NacLensClient,
pub certificate_address: Address, pub contract_address: Address,
} }
impl Acc1410Client { impl Acc1410Client {
/// 创建新的 ACC-1410 客户端 pub fn new(client: NacLensClient, contract_address: Address) -> Self {
pub fn new(certificate_address: Address) -> Self { Self { client, contract_address }
Self { certificate_address }
} }
/// 查询分区余额 /// 查询分区余额
pub fn balance_of_by_partition( pub async fn balance_of_by_partition(
&self, &self,
partition_id: &Hash, partition_id: &Hash,
account: &Address, account: &Address,
) -> Result<u128, NacError> { ) -> Result<u128> {
// 通过 NRPC4.0 调用链上合约 let params = json!({
"contract": self.contract_address.to_hex(),
"partition_id": partition_id.to_hex(),
"account": account.to_hex(),
});
let response = self.client.call("acc1410.balance_of_by_partition", params).await?;
let balance = response["result"].as_str()
.ok_or(NACError::InvalidResponse("Missing balance".to_string()))?
.parse::<u128>()
.map_err(|e| NACError::InvalidResponse(format!("Invalid balance: {}", e)))?;
Ok(balance)
} }
/// 查询账户持有的所有分区 /// 查询账户持有的所有分区
pub fn partitions_of(&self, account: &Address) -> Result<Vec<Hash>, NacError> { pub async fn partitions_of(&self, account: &Address) -> Result<Vec<Hash>> {
let params = json!({
"contract": self.contract_address.to_hex(),
"account": account.to_hex(),
});
let response = self.client.call("acc1410.partitions_of", params).await?;
let partitions = response["result"].as_array()
.ok_or(NACError::InvalidResponse("Missing partitions".to_string()))?
.iter()
.filter_map(|v| v.as_str())
.filter_map(|s| Hash::from_hex(s).ok())
.collect();
Ok(partitions)
} }
/// 分区间转账 /// 分区间转账
pub fn transfer_by_partition( pub async fn transfer_by_partition(
&self, &self,
from: &Address, from: &Address,
to: &Address, to: &Address,
amount: u128, amount: u128,
partition_id: &Hash, partition_id: &Hash,
) -> Result<Hash, NacError> { ) -> Result<Hash> {
let params = json!({
"contract": self.contract_address.to_hex(),
"from": from.to_hex(),
"to": to.to_hex(),
"amount": amount.to_string(),
"partition_id": partition_id.to_hex(),
});
let response = self.client.call("acc1410.transfer_by_partition", params).await?;
let tx_hash = response["result"].as_str()
.ok_or(NACError::InvalidResponse("Missing tx_hash".to_string()))?;
Hash::from_hex(tx_hash).map_err(|e| NACError::InvalidAddress(format!("Invalid hash: {}", e)))
}
/// 创建新分区
pub async fn create_partition(
&self,
partition_id: &Hash,
partition_type: u8,
constitutional_receipt: &Hash,
) -> Result<()> {
let params = json!({
"contract": self.contract_address.to_hex(),
"partition_id": partition_id.to_hex(),
"partition_type": partition_type,
"constitutional_receipt": constitutional_receipt.to_hex(),
});
self.client.call("acc1410.create_partition", params).await?;
Ok(())
}
/// 查询分区信息
pub async fn get_partition_info(&self, partition_id: &Hash) -> Result<serde_json::Value> {
let params = json!({
"contract": self.contract_address.to_hex(),
"partition_id": partition_id.to_hex(),
});
self.client.call("acc1410.get_partition_info", params).await
} }
} }

View File

@ -1,63 +1,63 @@
//! NAC SDK - ACC-1594 收益分配协议接口 //! NAC SDK - ACC-1594 收益分配协议接口
//!
//! ACC-1594 基于 GNACS 数字基因的核心收益与资产操作协议
//! 增加了资产发行/赎回、收益分配、分红领取等功能
use crate::types::*; use crate::adapters::NacLensClient;
use crate::error::NacError; use crate::error::{NACError, Result};
use nac_udm::primitives::{Address, Hash};
use serde_json::json;
/// ACC-1594 收益分配协议客户端 /// ACC-1594 收益分配协议客户端
pub struct Acc1594Client { pub struct Acc1594Client {
pub certificate_address: Address, pub client: NacLensClient,
pub contract_address: Address,
} }
impl Acc1594Client { impl Acc1594Client {
pub fn new(certificate_address: Address) -> Self { pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { certificate_address } Self { client, contract_address }
} }
/// 发行资产 /// 分配收益
pub fn issue( pub async fn distribute_yield(
&self, &self,
to: &Address, total_yield: u128,
amount: u128, period_id: u64,
partition_id: &Hash, constitutional_receipt: &Hash,
receipt: &Hash, ) -> Result<Hash> {
) -> Result<Hash, NacError> { let params = json!({
"contract": self.contract_address.to_hex(),
"total_yield": total_yield.to_string(),
"period_id": period_id,
"constitutional_receipt": constitutional_receipt.to_hex(),
});
let response = self.client.call("acc1594.distribute_yield", params).await?;
let tx_hash = response["result"].as_str()
.ok_or(NACError::InvalidResponse("Missing tx_hash".to_string()))?;
Hash::from_hex(tx_hash).map_err(|e| NACError::InvalidAddress(format!("Invalid hash: {}", e)))
} }
/// 赎回资产 /// 查询待领取收益
pub fn redeem( pub async fn claimable_yield(&self, account: &Address) -> Result<u128> {
&self, let params = json!({
amount: u128, "contract": self.contract_address.to_hex(),
partition_id: &Hash, "account": account.to_hex(),
receipt: &Hash, });
) -> Result<Hash, NacError> { let response = self.client.call("acc1594.claimable_yield", params).await?;
let amount = response["result"].as_str()
.ok_or(NACError::InvalidResponse("Missing amount".to_string()))?
.parse::<u128>()
.map_err(|e| NACError::InvalidResponse(format!("Invalid amount: {}", e)))?;
Ok(amount)
} }
/// 分配收益(分红) /// 领取收益
pub fn distribute_dividend( pub async fn claim_yield(&self, account: &Address) -> Result<Hash> {
&self, let params = json!({
partition_id: &Hash, "contract": self.contract_address.to_hex(),
total_amount: u128, "account": account.to_hex(),
period: u64, });
receipt: &Hash, let response = self.client.call("acc1594.claim_yield", params).await?;
) -> Result<Hash, NacError> { let tx_hash = response["result"].as_str()
} .ok_or(NACError::InvalidResponse("Missing tx_hash".to_string()))?;
Hash::from_hex(tx_hash).map_err(|e| NACError::InvalidAddress(format!("Invalid hash: {}", e)))
/// 查询可领取分红
pub fn claimable_dividend(
&self,
account: &Address,
partition_id: &Hash,
) -> Result<u128, NacError> {
}
/// 领取分红
pub fn claim_dividend(
&self,
partition_id: &Hash,
receipt: &Hash,
) -> Result<Hash, NacError> {
} }
} }

View File

@ -1,53 +1,69 @@
//! NAC SDK - ACC-1643 文档管理协议接口 //! NAC SDK - ACC-1643 文档管理协议接口
//!
//! ACC-1643 提供链上文档存储、版本控制、完整性验证功能
use crate::types::*; use crate::adapters::NacLensClient;
use crate::error::NacError; use crate::error::{NACError, Result};
use nac_udm::primitives::{Address, Hash};
use serde_json::json;
/// ACC-1643 文档管理协议客户端 /// ACC-1643 文档管理协议客户端
pub struct Acc1643Client { pub struct Acc1643Client {
pub certificate_address: Address, pub client: NacLensClient,
pub contract_address: Address,
} }
impl Acc1643Client { impl Acc1643Client {
pub fn new(certificate_address: Address) -> Self { pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { certificate_address } Self { client, contract_address }
} }
/// 存储/更新文档 /// 设置文档
pub fn set_document( pub async fn set_document(
&self, &self,
doc_type: &str, doc_name: &str,
uri: &str, doc_uri: &str,
content_hash: &Hash, doc_hash: &Hash,
supersedes: &Hash, constitutional_receipt: &Hash,
receipt: &Hash, ) -> Result<()> {
) -> Result<Hash, NacError> { let params = json!({
"contract": self.contract_address.to_hex(),
"doc_name": doc_name,
"doc_uri": doc_uri,
"doc_hash": doc_hash.to_hex(),
"constitutional_receipt": constitutional_receipt.to_hex(),
});
self.client.call("acc1643.set_document", params).await?;
Ok(())
} }
/// 获取文档 /// 查询文档
pub fn get_document(&self, doc_id: &Hash) -> Result<AssetDocument, NacError> { pub async fn get_document(&self, doc_name: &str) -> Result<serde_json::Value> {
let params = json!({
"contract": self.contract_address.to_hex(),
"doc_name": doc_name,
});
self.client.call("acc1643.get_document", params).await
} }
/// 验证文档完整性 /// 列出所有文档
pub fn verify_document( pub async fn get_all_documents(&self) -> Result<serde_json::Value> {
let params = json!({
"contract": self.contract_address.to_hex(),
});
self.client.call("acc1643.get_all_documents", params).await
}
/// 删除文档
pub async fn remove_document(
&self, &self,
doc_id: &Hash, doc_name: &str,
uri: &str, constitutional_receipt: &Hash,
content_hash: &Hash, ) -> Result<()> {
) -> Result<bool, NacError> { let params = json!({
"contract": self.contract_address.to_hex(),
"doc_name": doc_name,
"constitutional_receipt": constitutional_receipt.to_hex(),
});
self.client.call("acc1643.remove_document", params).await?;
Ok(())
} }
} }
/// 文档结构
#[derive(Debug, Clone)]
pub struct AssetDocument {
pub doc_id: Hash,
pub doc_type: String,
pub uri: String,
pub content_hash: Hash,
pub version: u32,
pub is_active: bool,
pub created_at: u64,
}

View File

@ -1,54 +1,81 @@
//! NAC SDK - ACC-1644 监管控制协议接口 //! NAC SDK - ACC-1644 监管控制协议接口
//!
//! ACC-1644 宪法授权控制器操作协议
//! 提供监管机构对资产的强制操作能力(需要宪法授权)
use crate::types::*; use crate::adapters::NacLensClient;
use crate::error::NacError; use crate::error::{NACError, Result};
use nac_udm::primitives::{Address, Hash};
use serde_json::json;
/// ACC-1644 监管控制协议客户端 /// ACC-1644 监管控制协议客户端
pub struct Acc1644Client { pub struct Acc1644Client {
pub certificate_address: Address, pub client: NacLensClient,
pub contract_address: Address,
} }
impl Acc1644Client { impl Acc1644Client {
pub fn new(certificate_address: Address) -> Self { pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { certificate_address } Self { client, contract_address }
} }
/// 冻结分区(监管机构操作) /// 冻结账户
pub fn freeze( pub async fn freeze_account(
&self, &self,
partition_id: &Hash, account: &Address,
reason: &[u8], reason: &str,
evidence: &[u8], constitutional_receipt: &Hash,
receipt: &Hash, ) -> Result<()> {
) -> Result<Hash, NacError> { let params = json!({
"contract": self.contract_address.to_hex(),
"account": account.to_hex(),
"reason": reason,
"constitutional_receipt": constitutional_receipt.to_hex(),
});
self.client.call("acc1644.freeze_account", params).await?;
Ok(())
} }
/// 解冻分区 /// 解冻账户
pub fn unfreeze( pub async fn unfreeze_account(
&self, &self,
partition_id: &Hash, account: &Address,
reason: &[u8], constitutional_receipt: &Hash,
evidence: &[u8], ) -> Result<()> {
receipt: &Hash, let params = json!({
) -> Result<Hash, NacError> { "contract": self.contract_address.to_hex(),
"account": account.to_hex(),
"constitutional_receipt": constitutional_receipt.to_hex(),
});
self.client.call("acc1644.unfreeze_account", params).await?;
Ok(())
} }
/// 强制转移(法院命令) /// 强制转移(监管命令)
pub fn force_transfer( pub async fn forced_transfer(
&self, &self,
partition_id: &Hash,
from: &Address, from: &Address,
to: &Address, to: &Address,
amount: u128, amount: u128,
legal_basis: &Hash, constitutional_receipt: &Hash,
receipt: &Hash, ) -> Result<Hash> {
) -> Result<Hash, NacError> { let params = json!({
"contract": self.contract_address.to_hex(),
"from": from.to_hex(),
"to": to.to_hex(),
"amount": amount.to_string(),
"constitutional_receipt": constitutional_receipt.to_hex(),
});
let response = self.client.call("acc1644.forced_transfer", params).await?;
let tx_hash = response["result"].as_str()
.ok_or(NACError::InvalidResponse("Missing tx_hash".to_string()))?;
Hash::from_hex(tx_hash).map_err(|e| NACError::InvalidAddress(format!("Invalid hash: {}", e)))
} }
/// 查询分区冻结状态 /// 查询账户冻结状态
pub fn is_partition_frozen(&self, partition_id: &Hash) -> Result<bool, NacError> { pub async fn is_frozen(&self, account: &Address) -> Result<bool> {
let params = json!({
"contract": self.contract_address.to_hex(),
"account": account.to_hex(),
});
let response = self.client.call("acc1644.is_frozen", params).await?;
Ok(response["result"].as_bool().unwrap_or(false))
} }
} }

View File

@ -1,42 +1,48 @@
//! ACC-Collateral 抵押协议客户端接口 //! AccCollateral 协议客户端接口
//! NAC 原生 SDK - 通过 NRPC4.0 与链交互
use crate::types::{Address, Hash, NRPCClient, NRPCError}; use crate::error::{NACError, Result};
use crate::adapters::NacLensClient;
use nac_udm::primitives::{Address, Hash};
use serde_json::{json, Value};
#[derive(Debug, Clone)] /// AccCollateral 协议客户端
pub struct CollateralRecord { pub struct AccCollateralClient {
pub collateral_id: Hash, pub client: NacLensClient,
pub asset_id: Hash, pub contract_address: Address,
pub borrower: Address,
pub lender: Address,
pub collateral_value_xtzh: u128,
pub loan_amount_xtzh: u128,
pub is_liquidated: bool,
} }
pub struct AccCollateralClient { rpc: NRPCClient }
impl AccCollateralClient { impl AccCollateralClient {
pub fn new(rpc: NRPCClient) -> Self { Self { rpc } } pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { client, contract_address }
pub async fn create_collateral(
&self, asset_id: Hash, borrower: Address, lender: Address,
collateral_value_xtzh: u128, loan_amount_xtzh: u128,
maturity_secs: u64, constitutional_receipt: Hash,
) -> Result<Hash, NRPCError> {
self.rpc.call("acc_collateral.create_collateral", &(
asset_id, borrower, lender, collateral_value_xtzh,
loan_amount_xtzh, maturity_secs, constitutional_receipt
)).await
} }
pub async fn liquidate( /// 锁定抵押品
&self, collateral_id: Hash, liquidator: Address, current_value: u128, pub async fn lock_collateral(&self, params: Value) -> Result<Value> {
constitutional_receipt: Hash, let mut p = params;
) -> Result<u128, NRPCError> { p["contract"] = json!(self.contract_address.to_hex());
self.rpc.call("acc_collateral.liquidate", &(collateral_id, liquidator, current_value, constitutional_receipt)).await self.client.call("acc_collateral.lock_collateral", p).await
} }
pub async fn get_collateral(&self, collateral_id: Hash) -> Result<Option<CollateralRecord>, NRPCError> { /// 查询抵押品详情
self.rpc.call("acc_collateral.get_collateral", &collateral_id).await pub async fn get_collateral(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_collateral.get_collateral", p).await
} }
/// 释放抵押品
pub async fn release_collateral(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_collateral.release_collateral", p).await
}
/// 清算抵押品
pub async fn liquidate_collateral(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_collateral.liquidate_collateral", p).await
}
} }

View File

@ -1,66 +1,48 @@
//! ACC-Compliance 七层合规验证协议客户端接口 //! AccCompliance 协议客户端接口
//! NAC 原生 SDK - 通过 NRPC4.0 与链交互
use crate::types::{Address, Hash, NRPCClient, NRPCError}; use crate::error::{NACError, Result};
use crate::adapters::NacLensClient;
use nac_udm::primitives::{Address, Hash};
use serde_json::{json, Value};
/// 七层合规验证结果 /// AccCompliance 协议客户端
#[derive(Debug, Clone)]
pub struct SevenLayerComplianceResult {
pub layer1_kyc: bool,
pub layer2_aml: bool,
pub layer3_jurisdiction: bool,
pub layer4_ai_risk: bool,
pub layer5_constitutional: bool,
pub layer6_gnacs: bool,
pub layer7_cbpp: bool,
pub overall_compliant: bool,
pub ai_risk_score: u8,
}
/// 合规记录
#[derive(Debug, Clone)]
pub struct ComplianceRecord {
pub entity: Address,
pub kyc_verified: bool,
pub aml_cleared: bool,
pub is_blacklisted: bool,
pub ai_risk_score: u8,
pub allowed_jurisdictions: Vec<String>,
}
/// ACC-Compliance 协议客户端
pub struct AccComplianceClient { pub struct AccComplianceClient {
rpc: NRPCClient, pub client: NacLensClient,
pub contract_address: Address,
} }
impl AccComplianceClient { impl AccComplianceClient {
pub fn new(rpc: NRPCClient) -> Self { Self { rpc } } pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { client, contract_address }
/// 注册合规实体
pub async fn register_entity(
&self, entity: Address, kyc_verified: bool, aml_cleared: bool,
allowed_jurisdictions: Vec<String>, ai_risk_score: u8,
constitutional_receipt: Hash,
) -> Result<(), NRPCError> {
self.rpc.call("acc_compliance.register_entity", &(
entity, kyc_verified, aml_cleared, allowed_jurisdictions,
ai_risk_score, constitutional_receipt
)).await
} }
/// 执行七层合规验证 /// 七层合规验证
pub async fn run_seven_layer_check( pub async fn verify(&self, params: Value) -> Result<Value> {
&self, entity: Address, jurisdiction: &str, constitutional_receipt: Hash, let mut p = params;
) -> Result<SevenLayerComplianceResult, NRPCError> { p["contract"] = json!(self.contract_address.to_hex());
self.rpc.call("acc_compliance.run_seven_layer_check", &(entity, jurisdiction, constitutional_receipt)).await self.client.call("acc_compliance.verify", p).await
} }
/// 查询合规状态 /// 查询合规记录
pub async fn is_compliant(&self, entity: Address) -> Result<bool, NRPCError> { pub async fn get_record(&self, params: Value) -> Result<Value> {
self.rpc.call("acc_compliance.is_compliant", &entity).await let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_compliance.get_record", p).await
} }
/// 获取合规记录 /// 更新合规记录
pub async fn get_record(&self, entity: Address) -> Result<Option<ComplianceRecord>, NRPCError> { pub async fn update_record(&self, params: Value) -> Result<Value> {
self.rpc.call("acc_compliance.get_record", &entity).await let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_compliance.update_record", p).await
} }
/// 查询司法管辖区规则
pub async fn get_jurisdiction_rules(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_compliance.get_jurisdiction_rules", p).await
}
} }

View File

@ -1,43 +1,48 @@
//! ACC-Custody 资产托管协议客户端接口 //! AccCustody 协议客户端接口
//! NAC 原生 SDK - 通过 NRPC4.0 与链交互
use crate::types::{Address, Hash, NRPCClient, NRPCError}; use crate::error::{NACError, Result};
use crate::adapters::NacLensClient;
use nac_udm::primitives::{Address, Hash};
use serde_json::{json, Value};
#[derive(Debug, Clone)] /// AccCustody 协议客户端
pub enum CustodyType { Primary, Secondary, Escrow, Regulatory } pub struct AccCustodyClient {
pub client: NacLensClient,
#[derive(Debug, Clone)] pub contract_address: Address,
pub struct CustodyRecord {
pub custody_id: Hash,
pub asset_id: Hash,
pub owner: Address,
pub custodian: Address,
pub custody_type: CustodyType,
pub is_active: bool,
} }
pub struct AccCustodyClient { rpc: NRPCClient }
impl AccCustodyClient { impl AccCustodyClient {
pub fn new(rpc: NRPCClient) -> Self { Self { rpc } } pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { client, contract_address }
pub async fn create_custody(
&self, asset_id: Hash, owner: Address, custodian: Address,
custody_type: CustodyType, constitutional_receipt: Hash,
) -> Result<Hash, NRPCError> {
self.rpc.call("acc_custody.create_custody", &(asset_id, owner, custodian, custody_type, constitutional_receipt)).await
} }
pub async fn transfer_custody( /// 创建托管记录
&self, custody_id: Hash, new_custodian: Address, constitutional_receipt: Hash, pub async fn create_custody(&self, params: Value) -> Result<Value> {
) -> Result<(), NRPCError> { let mut p = params;
self.rpc.call("acc_custody.transfer_custody", &(custody_id, new_custodian, constitutional_receipt)).await p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_custody.create_custody", p).await
} }
pub async fn release_custody(&self, custody_id: Hash, constitutional_receipt: Hash) -> Result<(), NRPCError> { /// 查询托管详情
self.rpc.call("acc_custody.release_custody", &(custody_id, constitutional_receipt)).await pub async fn get_custody(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_custody.get_custody", p).await
} }
pub async fn get_custody(&self, custody_id: Hash) -> Result<Option<CustodyRecord>, NRPCError> { /// 释放托管
self.rpc.call("acc_custody.get_custody", &custody_id).await pub async fn release_custody(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_custody.release_custody", p).await
} }
/// 转移托管权
pub async fn transfer_custody(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_custody.transfer_custody", p).await
}
} }

View File

@ -1,30 +1,48 @@
//! ACC-Governance 治理协议客户端接口 //! AccGovernance 协议客户端接口
//! NAC 原生 SDK - 通过 NRPC4.0 与链交互
use crate::types::{Address, Hash, NRPCClient, NRPCError}; use crate::error::{NACError, Result};
use crate::adapters::NacLensClient;
use nac_udm::primitives::{Address, Hash};
use serde_json::{json, Value};
#[derive(Debug, Clone)] /// AccGovernance 协议客户端
pub enum VoteChoice { For, Against, Abstain } pub struct AccGovernanceClient {
pub client: NacLensClient,
#[derive(Debug, Clone)] pub contract_address: Address,
pub enum ProposalType { ParameterChange, ProtocolUpgrade, EmergencyAction, FundAllocation } }
pub struct AccGovernanceClient { rpc: NRPCClient }
impl AccGovernanceClient { impl AccGovernanceClient {
pub fn new(rpc: NRPCClient) -> Self { Self { rpc } } pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { client, contract_address }
pub async fn create_proposal(
&self, proposer: Address, proposal_type: ProposalType,
description: &str, voting_duration_secs: u64, constitutional_receipt: Hash,
) -> Result<Hash, NRPCError> {
self.rpc.call("acc_governance.create_proposal", &(proposer, proposal_type, description, voting_duration_secs, constitutional_receipt)).await
} }
pub async fn cast_vote(&self, proposal_id: Hash, voter: Address, choice: VoteChoice) -> Result<(), NRPCError> { /// 创建治理提案
self.rpc.call("acc_governance.cast_vote", &(proposal_id, voter, choice)).await pub async fn create_proposal(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_governance.create_proposal", p).await
} }
pub async fn finalize_proposal(&self, proposal_id: Hash, constitutional_receipt: Hash) -> Result<bool, NRPCError> { /// 投票
self.rpc.call("acc_governance.finalize_proposal", &(proposal_id, constitutional_receipt)).await pub async fn vote(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_governance.vote", p).await
} }
/// 执行提案
pub async fn execute_proposal(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_governance.execute_proposal", p).await
}
/// 查询提案详情
pub async fn get_proposal(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_governance.get_proposal", p).await
}
} }

View File

@ -1,34 +1,48 @@
//! ACC-Insurance 资产保险协议客户端接口 //! AccInsurance 协议客户端接口
//! NAC 原生 SDK - 通过 NRPC4.0 与链交互
use crate::types::{Address, Hash, NRPCClient, NRPCError}; use crate::error::{NACError, Result};
use crate::adapters::NacLensClient;
use nac_udm::primitives::{Address, Hash};
use serde_json::{json, Value};
#[derive(Debug, Clone)] /// AccInsurance 协议客户端
pub enum InsuranceType { AssetLoss, PriceVolatility, CustodyRisk, LegalRisk, NaturalDisaster } pub struct AccInsuranceClient {
pub client: NacLensClient,
pub struct AccInsuranceClient { rpc: NRPCClient } pub contract_address: Address,
}
impl AccInsuranceClient { impl AccInsuranceClient {
pub fn new(rpc: NRPCClient) -> Self { Self { rpc } } pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { client, contract_address }
pub async fn issue_policy(
&self, asset_id: Hash, insured: Address, insurer: Address,
insurance_type: InsuranceType, coverage_amount: u128,
premium_rate_bps: u16, duration_secs: u64, constitutional_receipt: Hash,
) -> Result<Hash, NRPCError> {
self.rpc.call("acc_insurance.issue_policy", &(
asset_id, insured, insurer, insurance_type,
coverage_amount, premium_rate_bps, duration_secs, constitutional_receipt
)).await
} }
pub async fn submit_claim( /// 创建保险策略
&self, policy_id: Hash, claimant: Address, claim_amount: u128, pub async fn create_policy(&self, params: Value) -> Result<Value> {
reason: &str, evidence_hash: Hash, constitutional_receipt: Hash, let mut p = params;
) -> Result<Hash, NRPCError> { p["contract"] = json!(self.contract_address.to_hex());
self.rpc.call("acc_insurance.submit_claim", &(policy_id, claimant, claim_amount, reason, evidence_hash, constitutional_receipt)).await self.client.call("acc_insurance.create_policy", p).await
} }
pub async fn pay_claim(&self, claim_id: Hash, constitutional_receipt: Hash) -> Result<u128, NRPCError> { /// 查询保险策略
self.rpc.call("acc_insurance.pay_claim", &(claim_id, constitutional_receipt)).await pub async fn get_policy(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_insurance.get_policy", p).await
} }
/// 提交理赔申请
pub async fn file_claim(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_insurance.file_claim", p).await
}
/// 处理理赔
pub async fn process_claim(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_insurance.process_claim", p).await
}
} }

View File

@ -1,24 +1,48 @@
//! ACC-Redemption 赎回协议客户端接口 //! AccRedemption 协议客户端接口
//! NAC 原生 SDK - 通过 NRPC4.0 与链交互
use crate::types::{Address, Hash, NRPCClient, NRPCError}; use crate::error::{NACError, Result};
use crate::adapters::NacLensClient;
use nac_udm::primitives::{Address, Hash};
use serde_json::{json, Value};
pub struct AccRedemptionClient { rpc: NRPCClient } /// AccRedemption 协议客户端
pub struct AccRedemptionClient {
pub client: NacLensClient,
pub contract_address: Address,
}
impl AccRedemptionClient { impl AccRedemptionClient {
pub fn new(rpc: NRPCClient) -> Self { Self { rpc } } pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { client, contract_address }
pub async fn fund_pool(&self, asset_id: Hash, amount_xtzh: u128, constitutional_receipt: Hash) -> Result<(), NRPCError> {
self.rpc.call("acc_redemption.fund_redemption_pool", &(asset_id, amount_xtzh, constitutional_receipt)).await
} }
pub async fn request_redemption( /// 申请赎回
&self, asset_id: Hash, redeemer: Address, amount: u128, pub async fn request_redemption(&self, params: Value) -> Result<Value> {
price_xtzh: u128, constitutional_receipt: Hash, let mut p = params;
) -> Result<Hash, NRPCError> { p["contract"] = json!(self.contract_address.to_hex());
self.rpc.call("acc_redemption.request_redemption", &(asset_id, redeemer, amount, price_xtzh, constitutional_receipt)).await self.client.call("acc_redemption.request_redemption", p).await
} }
pub async fn complete_redemption(&self, redemption_id: Hash, constitutional_receipt: Hash) -> Result<u128, NRPCError> { /// 批准赎回
self.rpc.call("acc_redemption.complete_redemption", &(redemption_id, constitutional_receipt)).await pub async fn approve_redemption(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_redemption.approve_redemption", p).await
} }
/// 查询赎回详情
pub async fn get_redemption(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_redemption.get_redemption", p).await
}
/// 取消赎回
pub async fn cancel_redemption(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_redemption.cancel_redemption", p).await
}
} }

View File

@ -1,39 +1,48 @@
//! ACC-Reserve 多资产储备协议客户端接口 //! AccReserve 协议客户端接口
//! NAC 原生 SDK - 通过 NRPC4.0 与链交互
use crate::types::{Address, Hash, NRPCClient, NRPCError}; use crate::error::{NACError, Result};
use crate::adapters::NacLensClient;
use nac_udm::primitives::{Address, Hash};
use serde_json::{json, Value};
#[derive(Debug, Clone)] /// AccReserve 协议客户端
pub struct ReserveEntry { pub struct AccReserveClient {
pub asset_symbol: String, pub client: NacLensClient,
pub amount: u128, pub contract_address: Address,
pub custodian: Address,
pub last_audit_hash: Option<Hash>,
} }
pub struct AccReserveClient { rpc: NRPCClient }
impl AccReserveClient { impl AccReserveClient {
pub fn new(rpc: NRPCClient) -> Self { Self { rpc } } pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { client, contract_address }
pub async fn deposit(
&self, asset_symbol: &str, amount: u128, custodian: Address,
constitutional_receipt: Hash,
) -> Result<(), NRPCError> {
self.rpc.call("acc_reserve.deposit", &(asset_symbol, amount, custodian, constitutional_receipt)).await
} }
pub async fn withdraw( /// 查询储备信息
&self, asset_symbol: &str, amount: u128, recipient: Address, pub async fn get_reserve_info(&self, params: Value) -> Result<Value> {
constitutional_receipt: Hash, let mut p = params;
) -> Result<(), NRPCError> { p["contract"] = json!(self.contract_address.to_hex());
self.rpc.call("acc_reserve.withdraw", &(asset_symbol, amount, recipient, constitutional_receipt)).await self.client.call("acc_reserve.get_reserve_info", p).await
} }
pub async fn audit(&self, asset_symbol: &str, audit_hash: Hash) -> Result<(), NRPCError> { /// 增加储备
self.rpc.call("acc_reserve.audit", &(asset_symbol, audit_hash)).await pub async fn add_reserve(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_reserve.add_reserve", p).await
} }
pub async fn get_reserve(&self, asset_symbol: &str) -> Result<Option<ReserveEntry>, NRPCError> { /// 提取储备
self.rpc.call("acc_reserve.get_reserve", &asset_symbol).await pub async fn withdraw_reserve(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_reserve.withdraw_reserve", p).await
} }
/// 查询储备构成
pub async fn get_reserve_composition(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_reserve.get_reserve_composition", p).await
}
} }

View File

@ -1,70 +1,58 @@
//! ACC-RWA 协议客户端接口 //! ACC-RWA 协议客户端接口
//! NAC 原生 SDK - 通过 NRPC4.0 与链交互 //! NAC 原生 SDK - 通过 NRPC4.0 与链交互
use crate::types::{Address, Hash, NRPCClient, NRPCError}; use crate::error::{NACError, Result};
use crate::adapters::NacLensClient;
use nac_udm::primitives::{Address, Hash};
use serde_json::{json, Value};
/// RWA 资产类型 /// ACC-RWA 真实世界资产协议客户端
#[derive(Debug, Clone)]
pub enum RWAAssetType {
RealEstate, Infrastructure, CommodityFund, PrivateEquity,
CarbonCredit, IntellectualProperty, ArtAndCollectibles, Other(String),
}
/// RWA 资产记录
#[derive(Debug, Clone)]
pub struct RWAAssetRecord {
pub asset_id: Hash,
pub gnacs_code: String,
pub asset_type: RWAAssetType,
pub owner: Address,
pub total_supply: u128,
pub valuation_xtzh: u128,
pub jurisdiction: String,
pub is_frozen: bool,
}
/// ACC-RWA 协议客户端
pub struct AccRwaClient { pub struct AccRwaClient {
rpc: NRPCClient, pub client: NacLensClient,
pub contract_address: Address,
} }
impl AccRwaClient { impl AccRwaClient {
pub fn new(rpc: NRPCClient) -> Self { Self { rpc } } pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { client, contract_address }
}
/// 注册 RWA 资产 /// 注册 RWA 资产
pub async fn register_asset( pub async fn register_asset(&self, params: Value) -> Result<Value> {
&self, gnacs_code: &str, asset_type: RWAAssetType, owner: Address, let mut p = params;
total_supply: u128, initial_valuation_xtzh: u128, jurisdiction: &str, p["contract"] = json!(self.contract_address.to_hex());
legal_document_hash: Hash, ai_compliance_score: u8, self.client.call("acc_rwa.register_asset", p).await
constitutional_receipt: Hash,
) -> Result<Hash, NRPCError> {
self.rpc.call("acc_rwa.register_asset", &(
gnacs_code, asset_type, owner, total_supply, initial_valuation_xtzh,
jurisdiction, legal_document_hash, ai_compliance_score, constitutional_receipt
)).await
} }
/// 转移 RWA 资产 /// 转移 RWA 资产
pub async fn transfer_asset( pub async fn transfer_asset(&self, params: Value) -> Result<Value> {
&self, asset_id: Hash, from: Address, to: Address, amount: u128, let mut p = params;
) -> Result<(), NRPCError> { p["contract"] = json!(self.contract_address.to_hex());
self.rpc.call("acc_rwa.transfer_asset", &(asset_id, from, to, amount)).await self.client.call("acc_rwa.transfer_asset", p).await
} }
/// 冻结资产 /// 冻结 RWA 资产
pub async fn freeze_asset( pub async fn freeze_asset(&self, params: Value) -> Result<Value> {
&self, asset_id: Hash, reason: &str, constitutional_receipt: Hash, let mut p = params;
) -> Result<(), NRPCError> { p["contract"] = json!(self.contract_address.to_hex());
self.rpc.call("acc_rwa.freeze_asset", &(asset_id, reason, constitutional_receipt)).await self.client.call("acc_rwa.freeze_asset", p).await
} }
/// 查询资产持仓 /// 查询 RWA 资产详情
pub async fn balance_of(&self, asset_id: Hash, holder: Address) -> Result<u128, NRPCError> { pub async fn get_asset(&self, asset_id: &Hash) -> Result<Value> {
self.rpc.call("acc_rwa.balance_of", &(asset_id, holder)).await let params = json!({
"contract": self.contract_address.to_hex(),
"asset_id": asset_id.to_hex(),
});
self.client.call("acc_rwa.get_asset", params).await
} }
/// 查询资产详情 /// 查询地址持有的 RWA 资产列表
pub async fn get_asset(&self, asset_id: Hash) -> Result<Option<RWAAssetRecord>, NRPCError> { pub async fn get_holdings(&self, owner: &Address) -> Result<Value> {
self.rpc.call("acc_rwa.get_asset", &asset_id).await let params = json!({
"contract": self.contract_address.to_hex(),
"owner": owner.to_hex(),
});
self.client.call("acc_rwa.get_holdings", params).await
} }
} }

View File

@ -1,40 +1,48 @@
//! ACC-Valuation AI 驱动资产估值协议客户端接口 //! AccValuation 协议客户端接口
//! NAC 原生 SDK - 通过 NRPC4.0 与链交互
use crate::types::{Address, Hash, NRPCClient, NRPCError}; use crate::error::{NACError, Result};
use crate::adapters::NacLensClient;
use nac_udm::primitives::{Address, Hash};
use serde_json::{json, Value};
/// 估值结果 /// AccValuation 协议客户端
#[derive(Debug, Clone)]
pub struct ValuationResult {
pub asset_id: Hash,
pub value_xtzh: u128,
pub ai_confidence: u8,
pub timestamp: u64,
pub method: String,
}
/// ACC-Valuation 协议客户端
pub struct AccValuationClient { pub struct AccValuationClient {
rpc: NRPCClient, pub client: NacLensClient,
pub contract_address: Address,
} }
impl AccValuationClient { impl AccValuationClient {
pub fn new(rpc: NRPCClient) -> Self { Self { rpc } } pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { client, contract_address }
/// 提交估值请求
pub async fn request_valuation(
&self, asset_id: Hash, gnacs_code: &str, asset_data: Vec<u8>,
constitutional_receipt: Hash,
) -> Result<Hash, NRPCError> {
self.rpc.call("acc_valuation.request_valuation", &(asset_id, gnacs_code, asset_data, constitutional_receipt)).await
} }
/// 获取最新估值 /// 查询资产估值
pub async fn get_valuation(&self, asset_id: Hash) -> Result<Option<ValuationResult>, NRPCError> { pub async fn get_valuation(&self, params: Value) -> Result<Value> {
self.rpc.call("acc_valuation.get_valuation", &asset_id).await let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_valuation.get_valuation", p).await
} }
/// 获取估值历史 /// 更新资产估值
pub async fn get_history(&self, asset_id: Hash) -> Result<Vec<ValuationResult>, NRPCError> { pub async fn update_valuation(&self, params: Value) -> Result<Value> {
self.rpc.call("acc_valuation.get_valuation_history", &asset_id).await let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_valuation.update_valuation", p).await
} }
/// 查询估值历史
pub async fn get_history(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_valuation.get_history", p).await
}
/// 请求 AI 估值
pub async fn request_ai_valuation(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_valuation.request_ai_valuation", p).await
}
} }

View File

@ -1,33 +1,48 @@
//! ACC-XTZH 稳定币协议客户端接口SDR锚定+黄金储备) //! AccXtzh 协议客户端接口
//! NAC 原生 SDK - 通过 NRPC4.0 与链交互
use crate::types::{Address, Hash, NRPCClient, NRPCError}; use crate::error::{NACError, Result};
use crate::adapters::NacLensClient;
use nac_udm::primitives::{Address, Hash};
use serde_json::{json, Value};
pub struct AccXtzhClient { rpc: NRPCClient } /// AccXtzh 协议客户端
pub struct AccXtzhClient {
pub client: NacLensClient,
pub contract_address: Address,
}
impl AccXtzhClient { impl AccXtzhClient {
pub fn new(rpc: NRPCClient) -> Self { Self { rpc } } pub fn new(client: NacLensClient, contract_address: Address) -> Self {
Self { client, contract_address }
pub async fn mint(&self, recipient: Address, amount: u128, constitutional_receipt: Hash) -> Result<(), NRPCError> {
self.rpc.call("acc_xtzh.mint", &(recipient, amount, constitutional_receipt)).await
} }
pub async fn burn(&self, holder: Address, amount: u128, constitutional_receipt: Hash) -> Result<(), NRPCError> { /// 查询 XTZH 汇率
self.rpc.call("acc_xtzh.burn", &(holder, amount, constitutional_receipt)).await pub async fn get_rate(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_xtzh.get_rate", p).await
} }
pub async fn transfer(&self, from: Address, to: Address, amount: u128) -> Result<(), NRPCError> { /// 铸造 XTZH 稳定币
self.rpc.call("acc_xtzh.transfer", &(from, to, amount)).await pub async fn mint_xtzh(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_xtzh.mint_xtzh", p).await
} }
pub async fn balance_of(&self, address: Address) -> Result<u128, NRPCError> { /// 赎回 XTZH 稳定币
self.rpc.call("acc_xtzh.balance_of", &address).await pub async fn redeem_xtzh(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_xtzh.redeem_xtzh", p).await
} }
pub async fn total_supply(&self) -> Result<u128, NRPCError> { /// 查询储备率
self.rpc.call("acc_xtzh.total_supply", &()).await pub async fn get_reserve_ratio(&self, params: Value) -> Result<Value> {
let mut p = params;
p["contract"] = json!(self.contract_address.to_hex());
self.client.call("acc_xtzh.get_reserve_ratio", p).await
} }
pub async fn update_sdr_rate(&self, new_rate: u128, constitutional_receipt: Hash) -> Result<(), NRPCError> {
self.rpc.call("acc_xtzh.update_sdr_rate", &(new_rate, constitutional_receipt)).await
}
} }

View File

@ -62,20 +62,20 @@ mod acc_collateral;
mod acc_redemption; mod acc_redemption;
mod acc_insurance; mod acc_insurance;
mod acc_governance; mod acc_governance;
pub use acc_rwa::{AccRwaClient, RWAAssetType, RWAAssetRecord}; pub use acc_rwa::AccRwaClient;
pub use acc_compliance::{AccComplianceClient, SevenLayerComplianceResult, ComplianceRecord}; pub use acc_compliance::AccComplianceClient;
pub use acc_valuation::{AccValuationClient, ValuationResult}; pub use acc_valuation::AccValuationClient;
pub use acc_custody::{AccCustodyClient, CustodyType, CustodyRecord}; pub use acc_custody::AccCustodyClient;
pub use acc_collateral::{AccCollateralClient, CollateralRecord}; pub use acc_collateral::AccCollateralClient;
pub use acc_redemption::AccRedemptionClient; pub use acc_redemption::AccRedemptionClient;
pub use acc_insurance::{AccInsuranceClient, InsuranceType}; pub use acc_insurance::AccInsuranceClient;
pub use acc_governance::{AccGovernanceClient, VoteChoice, ProposalType}; pub use acc_governance::AccGovernanceClient;
// === 稳定币与储备协议 === // === 稳定币与储备协议 ===
mod acc_xtzh; mod acc_xtzh;
mod acc_reserve; mod acc_reserve;
pub use acc_xtzh::AccXtzhClient; pub use acc_xtzh::AccXtzhClient;
pub use acc_reserve::{AccReserveClient, ReserveEntry}; pub use acc_reserve::AccReserveClient;
// === 证券代币协议族 === // === 证券代币协议族 ===
mod acc1410; mod acc1410;
@ -86,5 +86,5 @@ mod acc1644;
pub use acc1410::{Acc1410Client, PartitionType, ExtendedGNACS}; pub use acc1410::{Acc1410Client, PartitionType, ExtendedGNACS};
pub use acc1400::Acc1400Client; pub use acc1400::Acc1400Client;
pub use acc1594::Acc1594Client; pub use acc1594::Acc1594Client;
pub use acc1643::{Acc1643Client, AssetDocument}; pub use acc1643::Acc1643Client;
pub use acc1644::Acc1644Client; pub use acc1644::Acc1644Client;

View File

@ -67,7 +67,7 @@ pub struct NacLensResponse {
/// 错误(失败时) /// 错误(失败时)
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<NAC Lens3Error>, pub error: Option<NacLensProtocolError>,
/// 宪法收据(可选,某些操作会返回) /// 宪法收据(可选,某些操作会返回)
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@ -76,7 +76,7 @@ pub struct NacLensResponse {
/// NAC Lens错误 /// NAC Lens错误
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NAC Lens3Error { pub struct NacLensProtocolError {
/// 错误代码 /// 错误代码
pub code: i32, pub code: i32,

View File

@ -1,19 +1,19 @@
//! acc_compliance - NAC 原生协议实现 //! acc_compliance - NAC 原生协议实现
//! 从 acc_remaining_protocols.rs 提取 //! 从 acc_remaining_protocols.rs 提取
use crate::primitives::{Address, Hash, Timestamp}; use crate::primitives::{Address, Hash, Timestamp};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ACCComplianceError { pub enum ACCComplianceError {
EntityNotFound(Address), EntityNotFound(Address),
ComplianceCheckFailed { layer: u8, reason: String }, ComplianceCheckFailed { layer: u8, reason: String },
InvalidConstitutionalReceipt, InvalidConstitutionalReceipt,
Unauthorized(Address), Unauthorized(Address),
BlacklistedEntity(Address), BlacklistedEntity(Address),
JurisdictionRestricted { entity: Address, jurisdiction: String }, JurisdictionRestricted { entity: Address, jurisdiction: String },
} }
impl std::fmt::Display for ACCComplianceError { impl std::fmt::Display for ACCComplianceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Self::EntityNotFound(a) => write!(f, "实体不存在: {}", a.to_hex()), Self::EntityNotFound(a) => write!(f, "实体不存在: {}", a.to_hex()),
@ -24,11 +24,11 @@ use crate::primitives::{Address, Hash, Timestamp};
Self::JurisdictionRestricted { entity, jurisdiction } => write!(f, "司法管辖区限制 {} 在 {}", entity.to_hex(), jurisdiction), Self::JurisdictionRestricted { entity, jurisdiction } => write!(f, "司法管辖区限制 {} 在 {}", entity.to_hex(), jurisdiction),
} }
} }
} }
/// 七层合规验证结果 /// 七层合规验证结果
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SevenLayerComplianceResult { pub struct SevenLayerComplianceResult {
pub entity: Address, pub entity: Address,
/// L1: 身份验证 /// L1: 身份验证
pub l1_identity: bool, pub l1_identity: bool,
@ -47,17 +47,17 @@ use crate::primitives::{Address, Hash, Timestamp};
pub overall_pass: bool, pub overall_pass: bool,
pub checked_at: Timestamp, pub checked_at: Timestamp,
pub constitutional_receipt: Hash, pub constitutional_receipt: Hash,
} }
impl SevenLayerComplianceResult { impl SevenLayerComplianceResult {
pub fn is_fully_compliant(&self) -> bool { pub fn is_fully_compliant(&self) -> bool {
self.l1_identity && self.l2_kyc_aml && self.l3_jurisdiction self.l1_identity && self.l2_kyc_aml && self.l3_jurisdiction
&& self.l4_asset && self.l5_transaction && self.l4_asset && self.l5_transaction
&& self.l6_ai_score >= 70 && self.l7_constitutional && self.l6_ai_score >= 70 && self.l7_constitutional
} }
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceRecord { pub struct ComplianceRecord {
pub entity: Address, pub entity: Address,
pub kyc_verified: bool, pub kyc_verified: bool,
pub aml_cleared: bool, pub aml_cleared: bool,
@ -66,20 +66,20 @@ use crate::primitives::{Address, Hash, Timestamp};
pub ai_risk_score: u8, pub ai_risk_score: u8,
pub last_checked: Timestamp, pub last_checked: Timestamp,
pub compliance_hash: Hash, pub compliance_hash: Hash,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ComplianceProtocolEvent { pub enum ComplianceProtocolEvent {
EntityRegistered { entity: Address, timestamp: Timestamp }, EntityRegistered { entity: Address, timestamp: Timestamp },
ComplianceChecked { entity: Address, result: bool, timestamp: Timestamp }, ComplianceChecked { entity: Address, result: bool, timestamp: Timestamp },
EntityBlacklisted { entity: Address, reason: String, timestamp: Timestamp, constitutional_receipt: Hash }, EntityBlacklisted { entity: Address, reason: String, timestamp: Timestamp, constitutional_receipt: Hash },
EntityWhitelisted { entity: Address, timestamp: Timestamp, constitutional_receipt: Hash }, EntityWhitelisted { entity: Address, timestamp: Timestamp, constitutional_receipt: Hash },
} }
/// ACC-Compliance 七层合规验证协议 /// ACC-Compliance 七层合规验证协议
/// UID: nac.acc.ACCComplianceProtocol.v1 /// UID: nac.acc.ACCComplianceProtocol.v1
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ACCComplianceProtocol { pub struct ACCComplianceProtocol {
pub protocol_uid: String, pub protocol_uid: String,
pub lens_protocol_vector: String, pub lens_protocol_vector: String,
pub compliance_records: HashMap<Address, ComplianceRecord>, pub compliance_records: HashMap<Address, ComplianceRecord>,
@ -88,8 +88,8 @@ use crate::primitives::{Address, Hash, Timestamp};
pub pending_events: Vec<ComplianceProtocolEvent>, pub pending_events: Vec<ComplianceProtocolEvent>,
pub created_at: Timestamp, pub created_at: Timestamp,
pub updated_at: Timestamp, pub updated_at: Timestamp,
} }
impl ACCComplianceProtocol { impl ACCComplianceProtocol {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
protocol_uid: "nac.acc.ACCComplianceProtocol.v1".to_string(), protocol_uid: "nac.acc.ACCComplianceProtocol.v1".to_string(),
@ -174,4 +174,4 @@ use crate::primitives::{Address, Hash, Timestamp};
} }
pub fn get_record(&self, entity: &Address) -> Option<&ComplianceRecord> { self.compliance_records.get(entity) } pub fn get_record(&self, entity: &Address) -> Option<&ComplianceRecord> { self.compliance_records.get(entity) }
pub fn drain_pending_events(&mut self) -> Vec<ComplianceProtocolEvent> { std::mem::take(&mut self.pending_events) } pub fn drain_pending_events(&mut self) -> Vec<ComplianceProtocolEvent> { std::mem::take(&mut self.pending_events) }
} }

View File

@ -1,11 +1,11 @@
//! acc_governance - NAC 原生协议实现 //! acc_governance - NAC 原生协议实现
use crate::primitives::{Address, Hash, Timestamp}; use crate::primitives::{Address, Hash, Timestamp};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ACCGovernanceError { pub enum ACCGovernanceError {
ProposalNotFound(Hash), ProposalNotFound(Hash),
ProposalAlreadyExecuted(Hash), ProposalAlreadyExecuted(Hash),
VotingPeriodEnded(Hash), VotingPeriodEnded(Hash),
@ -14,8 +14,8 @@ use crate::primitives::{Address, Hash, Timestamp};
QuorumNotReached { required: u128, actual: u128 }, QuorumNotReached { required: u128, actual: u128 },
InvalidConstitutionalReceipt, InvalidConstitutionalReceipt,
Unauthorized(Address), Unauthorized(Address),
} }
impl std::fmt::Display for ACCGovernanceError { impl std::fmt::Display for ACCGovernanceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Self::ProposalNotFound(h) => write!(f, "提案不存在: {}", h.to_hex()), Self::ProposalNotFound(h) => write!(f, "提案不存在: {}", h.to_hex()),
@ -28,25 +28,25 @@ use crate::primitives::{Address, Hash, Timestamp};
Self::Unauthorized(a) => write!(f, "未授权: {}", a.to_hex()), Self::Unauthorized(a) => write!(f, "未授权: {}", a.to_hex()),
} }
} }
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ProposalType { pub enum ProposalType {
ParameterChange { parameter: String, new_value: Vec<u8> }, ParameterChange { parameter: String, new_value: Vec<u8> },
ProtocolUpgrade { new_version: String, upgrade_hash: Hash }, ProtocolUpgrade { new_version: String, upgrade_hash: Hash },
AssetPolicyChange { asset_id: Hash, policy_hash: Hash }, AssetPolicyChange { asset_id: Hash, policy_hash: Hash },
EmergencyPause { reason: String }, EmergencyPause { reason: String },
GovernanceMemberChange { member: Address, action: MemberAction }, GovernanceMemberChange { member: Address, action: MemberAction },
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MemberAction { Add, Remove } pub enum MemberAction { Add, Remove }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProposalStatus { Active, Passed, Rejected, Executed, Cancelled, Expired } pub enum ProposalStatus { Active, Passed, Rejected, Executed, Cancelled, Expired }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum VoteChoice { For, Against, Abstain } pub enum VoteChoice { For, Against, Abstain }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GovernanceProposal { pub struct GovernanceProposal {
pub proposal_id: Hash, pub proposal_id: Hash,
pub proposer: Address, pub proposer: Address,
pub proposal_type: ProposalType, pub proposal_type: ProposalType,
@ -63,19 +63,19 @@ use crate::primitives::{Address, Hash, Timestamp};
pub constitutional_receipt: Hash, pub constitutional_receipt: Hash,
pub created_at: Timestamp, pub created_at: Timestamp,
pub executed_at: Option<Timestamp>, pub executed_at: Option<Timestamp>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GovernanceProtocolEvent { pub enum GovernanceProtocolEvent {
ProposalCreated { proposal_id: Hash, proposer: Address, timestamp: Timestamp }, ProposalCreated { proposal_id: Hash, proposer: Address, timestamp: Timestamp },
VoteCast { proposal_id: Hash, voter: Address, choice: VoteChoice, voting_power: u128, timestamp: Timestamp }, VoteCast { proposal_id: Hash, voter: Address, choice: VoteChoice, voting_power: u128, timestamp: Timestamp },
ProposalPassed { proposal_id: Hash, votes_for: u128, votes_against: u128, timestamp: Timestamp }, ProposalPassed { proposal_id: Hash, votes_for: u128, votes_against: u128, timestamp: Timestamp },
ProposalRejected { proposal_id: Hash, reason: String, timestamp: Timestamp }, ProposalRejected { proposal_id: Hash, reason: String, timestamp: Timestamp },
ProposalExecuted { proposal_id: Hash, timestamp: Timestamp, constitutional_receipt: Hash }, ProposalExecuted { proposal_id: Hash, timestamp: Timestamp, constitutional_receipt: Hash },
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ACCGovernanceProtocol { pub struct ACCGovernanceProtocol {
pub protocol_uid: String, pub protocol_uid: String,
pub lens_protocol_vector: String, pub lens_protocol_vector: String,
pub proposals: HashMap<Hash, GovernanceProposal>, pub proposals: HashMap<Hash, GovernanceProposal>,
@ -86,8 +86,8 @@ use crate::primitives::{Address, Hash, Timestamp};
pub pending_events: Vec<GovernanceProtocolEvent>, pub pending_events: Vec<GovernanceProtocolEvent>,
pub created_at: Timestamp, pub created_at: Timestamp,
pub updated_at: Timestamp, pub updated_at: Timestamp,
} }
impl ACCGovernanceProtocol { impl ACCGovernanceProtocol {
pub fn new(default_quorum_bps: u32, default_pass_threshold_bps: u32) -> Self { pub fn new(default_quorum_bps: u32, default_pass_threshold_bps: u32) -> Self {
Self { Self {
protocol_uid: "nac.acc.ACCGovernanceProtocol.v1".to_string(), protocol_uid: "nac.acc.ACCGovernanceProtocol.v1".to_string(),
@ -189,4 +189,4 @@ use crate::primitives::{Address, Hash, Timestamp};
} }
pub fn get_proposal(&self, id: &Hash) -> Option<&GovernanceProposal> { self.proposals.get(id) } pub fn get_proposal(&self, id: &Hash) -> Option<&GovernanceProposal> { self.proposals.get(id) }
pub fn drain_pending_events(&mut self) -> Vec<GovernanceProtocolEvent> { std::mem::take(&mut self.pending_events) } pub fn drain_pending_events(&mut self) -> Vec<GovernanceProtocolEvent> { std::mem::take(&mut self.pending_events) }
} }

View File

@ -1,19 +1,19 @@
//! acc_insurance - NAC 原生协议实现 //! acc_insurance - NAC 原生协议实现
use crate::primitives::{Address, Hash, Timestamp}; use crate::primitives::{Address, Hash, Timestamp};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ACCInsuranceError { pub enum ACCInsuranceError {
PolicyNotFound(Hash), PolicyNotFound(Hash),
PolicyExpired(Hash), PolicyExpired(Hash),
ClaimAlreadyProcessed(Hash), ClaimAlreadyProcessed(Hash),
InvalidConstitutionalReceipt, InvalidConstitutionalReceipt,
Unauthorized(Address), Unauthorized(Address),
ClaimExceedsCoverage { coverage: u128, claim: u128 }, ClaimExceedsCoverage { coverage: u128, claim: u128 },
} }
impl std::fmt::Display for ACCInsuranceError { impl std::fmt::Display for ACCInsuranceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Self::PolicyNotFound(h) => write!(f, "保险单不存在: {}", h.to_hex()), Self::PolicyNotFound(h) => write!(f, "保险单不存在: {}", h.to_hex()),
@ -24,13 +24,13 @@ use crate::primitives::{Address, Hash, Timestamp};
Self::ClaimExceedsCoverage { coverage, claim } => write!(f, "理赔超额: 保额 {},理赔 {}", coverage, claim), Self::ClaimExceedsCoverage { coverage, claim } => write!(f, "理赔超额: 保额 {},理赔 {}", coverage, claim),
} }
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InsuranceType { AssetLoss, CustodyRisk, ComplianceRisk, MarketPrice, Comprehensive } pub enum InsuranceType { AssetLoss, CustodyRisk, ComplianceRisk, MarketPrice, Comprehensive }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InsurancePolicy { pub struct InsurancePolicy {
pub policy_id: Hash, pub policy_id: Hash,
pub asset_id: Hash, pub asset_id: Hash,
pub insured: Address, pub insured: Address,
@ -44,17 +44,17 @@ use crate::primitives::{Address, Hash, Timestamp};
pub is_active: bool, pub is_active: bool,
pub constitutional_receipt: Hash, pub constitutional_receipt: Hash,
pub created_at: Timestamp, pub created_at: Timestamp,
} }
impl InsurancePolicy { impl InsurancePolicy {
pub fn is_expired(&self) -> bool { self.end_time.is_expired(0) } pub fn is_expired(&self) -> bool { self.end_time.is_expired(0) }
pub fn remaining_coverage(&self) -> u128 { self.coverage_amount.saturating_sub(self.claimed_amount) } pub fn remaining_coverage(&self) -> u128 { self.coverage_amount.saturating_sub(self.claimed_amount) }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ClaimStatus { Pending, UnderReview, Approved, Rejected, Paid } pub enum ClaimStatus { Pending, UnderReview, Approved, Rejected, Paid }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InsuranceClaim { pub struct InsuranceClaim {
pub claim_id: Hash, pub claim_id: Hash,
pub policy_id: Hash, pub policy_id: Hash,
pub claimant: Address, pub claimant: Address,
@ -65,17 +65,17 @@ use crate::primitives::{Address, Hash, Timestamp};
pub submitted_at: Timestamp, pub submitted_at: Timestamp,
pub processed_at: Option<Timestamp>, pub processed_at: Option<Timestamp>,
pub constitutional_receipt: Hash, pub constitutional_receipt: Hash,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub enum InsuranceProtocolEvent { pub enum InsuranceProtocolEvent {
PolicyIssued { policy_id: Hash, asset_id: Hash, insured: Address, coverage: u128, timestamp: Timestamp }, PolicyIssued { policy_id: Hash, asset_id: Hash, insured: Address, coverage: u128, timestamp: Timestamp },
ClaimSubmitted { claim_id: Hash, policy_id: Hash, amount: u128, timestamp: Timestamp }, ClaimSubmitted { claim_id: Hash, policy_id: Hash, amount: u128, timestamp: Timestamp },
ClaimPaid { claim_id: Hash, amount: u128, timestamp: Timestamp, constitutional_receipt: Hash }, ClaimPaid { claim_id: Hash, amount: u128, timestamp: Timestamp, constitutional_receipt: Hash },
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ACCInsuranceProtocol { pub struct ACCInsuranceProtocol {
pub protocol_uid: String, pub protocol_uid: String,
pub lens_protocol_vector: String, pub lens_protocol_vector: String,
pub policies: HashMap<Hash, InsurancePolicy>, pub policies: HashMap<Hash, InsurancePolicy>,
@ -84,8 +84,8 @@ use crate::primitives::{Address, Hash, Timestamp};
pub pending_events: Vec<InsuranceProtocolEvent>, pub pending_events: Vec<InsuranceProtocolEvent>,
pub created_at: Timestamp, pub created_at: Timestamp,
pub updated_at: Timestamp, pub updated_at: Timestamp,
} }
impl ACCInsuranceProtocol { impl ACCInsuranceProtocol {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
protocol_uid: "nac.acc.ACCInsuranceProtocol.v1".to_string(), protocol_uid: "nac.acc.ACCInsuranceProtocol.v1".to_string(),
@ -165,4 +165,4 @@ use crate::primitives::{Address, Hash, Timestamp};
pub fn get_policy(&self, id: &Hash) -> Option<&InsurancePolicy> { self.policies.get(id) } pub fn get_policy(&self, id: &Hash) -> Option<&InsurancePolicy> { self.policies.get(id) }
pub fn get_claim(&self, id: &Hash) -> Option<&InsuranceClaim> { self.claims.get(id) } pub fn get_claim(&self, id: &Hash) -> Option<&InsuranceClaim> { self.claims.get(id) }
pub fn drain_pending_events(&mut self) -> Vec<InsuranceProtocolEvent> { std::mem::take(&mut self.pending_events) } pub fn drain_pending_events(&mut self) -> Vec<InsuranceProtocolEvent> { std::mem::take(&mut self.pending_events) }
} }

View File

@ -1,19 +1,19 @@
//! acc_redemption - NAC 原生协议实现 //! acc_redemption - NAC 原生协议实现
//! 从 acc_remaining_protocols.rs 提取 //! 从 acc_remaining_protocols.rs 提取
use crate::primitives::{Address, Hash, Timestamp}; use crate::primitives::{Address, Hash, Timestamp};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ACCRedemptionError { pub enum ACCRedemptionError {
RedemptionNotFound(Hash), RedemptionNotFound(Hash),
InsufficientRedemptionFund { available: u128, requested: u128 }, InsufficientRedemptionFund { available: u128, requested: u128 },
RedemptionWindowClosed, RedemptionWindowClosed,
InvalidConstitutionalReceipt, InvalidConstitutionalReceipt,
Unauthorized(Address), Unauthorized(Address),
RedemptionAlreadyProcessed(Hash), RedemptionAlreadyProcessed(Hash),
} }
impl std::fmt::Display for ACCRedemptionError { impl std::fmt::Display for ACCRedemptionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Self::RedemptionNotFound(h) => write!(f, "赎回请求不存在: {}", h.to_hex()), Self::RedemptionNotFound(h) => write!(f, "赎回请求不存在: {}", h.to_hex()),
@ -24,13 +24,13 @@ use crate::primitives::{Address, Hash, Timestamp};
Self::RedemptionAlreadyProcessed(h) => write!(f, "赎回请求已处理: {}", h.to_hex()), Self::RedemptionAlreadyProcessed(h) => write!(f, "赎回请求已处理: {}", h.to_hex()),
} }
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RedemptionStatus { Pending, Processing, Completed, Rejected, Cancelled } pub enum RedemptionStatus { Pending, Processing, Completed, Rejected, Cancelled }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RedemptionRequest { pub struct RedemptionRequest {
pub redemption_id: Hash, pub redemption_id: Hash,
pub asset_id: Hash, pub asset_id: Hash,
pub redeemer: Address, pub redeemer: Address,
@ -42,17 +42,17 @@ use crate::primitives::{Address, Hash, Timestamp};
pub processed_at: Option<Timestamp>, pub processed_at: Option<Timestamp>,
pub constitutional_receipt: Hash, pub constitutional_receipt: Hash,
pub rejection_reason: Option<String>, pub rejection_reason: Option<String>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RedemptionProtocolEvent { pub enum RedemptionProtocolEvent {
RedemptionRequested { redemption_id: Hash, asset_id: Hash, redeemer: Address, amount: u128, timestamp: Timestamp }, RedemptionRequested { redemption_id: Hash, asset_id: Hash, redeemer: Address, amount: u128, timestamp: Timestamp },
RedemptionCompleted { redemption_id: Hash, total_xtzh: u128, timestamp: Timestamp }, RedemptionCompleted { redemption_id: Hash, total_xtzh: u128, timestamp: Timestamp },
RedemptionRejected { redemption_id: Hash, reason: String, timestamp: Timestamp }, RedemptionRejected { redemption_id: Hash, reason: String, timestamp: Timestamp },
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ACCRedemptionProtocol { pub struct ACCRedemptionProtocol {
pub protocol_uid: String, pub protocol_uid: String,
pub lens_protocol_vector: String, pub lens_protocol_vector: String,
pub requests: HashMap<Hash, RedemptionRequest>, pub requests: HashMap<Hash, RedemptionRequest>,
@ -61,8 +61,8 @@ use crate::primitives::{Address, Hash, Timestamp};
pub pending_events: Vec<RedemptionProtocolEvent>, pub pending_events: Vec<RedemptionProtocolEvent>,
pub created_at: Timestamp, pub created_at: Timestamp,
pub updated_at: Timestamp, pub updated_at: Timestamp,
} }
impl ACCRedemptionProtocol { impl ACCRedemptionProtocol {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
protocol_uid: "nac.acc.ACCRedemptionProtocol.v1".to_string(), protocol_uid: "nac.acc.ACCRedemptionProtocol.v1".to_string(),
@ -116,4 +116,4 @@ use crate::primitives::{Address, Hash, Timestamp};
} }
pub fn get_request(&self, id: &Hash) -> Option<&RedemptionRequest> { self.requests.get(id) } pub fn get_request(&self, id: &Hash) -> Option<&RedemptionRequest> { self.requests.get(id) }
pub fn drain_pending_events(&mut self) -> Vec<RedemptionProtocolEvent> { std::mem::take(&mut self.pending_events) } pub fn drain_pending_events(&mut self) -> Vec<RedemptionProtocolEvent> { std::mem::take(&mut self.pending_events) }
} }

View File

@ -1,18 +1,18 @@
//! acc_reserve - NAC 原生协议实现 //! acc_reserve - NAC 原生协议实现
//! 从 acc_remaining_protocols.rs 提取 //! 从 acc_remaining_protocols.rs 提取
use crate::primitives::{Address, Hash, Timestamp}; use crate::primitives::{Address, Hash, Timestamp};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ACCReserveError { pub enum ACCReserveError {
ReserveNotFound(String), ReserveNotFound(String),
InsufficientReserve { asset: String, available: u128, requested: u128 }, InsufficientReserve { asset: String, available: u128, requested: u128 },
InvalidConstitutionalReceipt, InvalidConstitutionalReceipt,
Unauthorized(Address), Unauthorized(Address),
ReserveRatioViolation { required: u8, actual: u8 }, ReserveRatioViolation { required: u8, actual: u8 },
} }
impl std::fmt::Display for ACCReserveError { impl std::fmt::Display for ACCReserveError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Self::ReserveNotFound(s) => write!(f, "储备资产不存在: {}", s), Self::ReserveNotFound(s) => write!(f, "储备资产不存在: {}", s),
@ -22,28 +22,28 @@ use crate::primitives::{Address, Hash, Timestamp};
Self::ReserveRatioViolation { required, actual } => write!(f, "储备率违规: 要求 {}%,实际 {}%", required, actual), Self::ReserveRatioViolation { required, actual } => write!(f, "储备率违规: 要求 {}%,实际 {}%", required, actual),
} }
} }
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReserveEntry { pub struct ReserveEntry {
pub asset_symbol: String, pub asset_symbol: String,
pub amount: u128, pub amount: u128,
pub custodian: Address, pub custodian: Address,
pub last_audited: Timestamp, pub last_audited: Timestamp,
pub audit_hash: Hash, pub audit_hash: Hash,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ReserveProtocolEvent { pub enum ReserveProtocolEvent {
ReserveDeposited { asset: String, amount: u128, custodian: Address, timestamp: Timestamp }, ReserveDeposited { asset: String, amount: u128, custodian: Address, timestamp: Timestamp },
ReserveWithdrawn { asset: String, amount: u128, recipient: Address, constitutional_receipt: Hash, timestamp: Timestamp }, ReserveWithdrawn { asset: String, amount: u128, recipient: Address, constitutional_receipt: Hash, timestamp: Timestamp },
ReserveAudited { asset: String, audit_hash: Hash, timestamp: Timestamp }, ReserveAudited { asset: String, audit_hash: Hash, timestamp: Timestamp },
} }
/// ACC-Reserve 储备协议 /// ACC-Reserve 储备协议
/// UID: nac.acc.ACCReserveProtocol.v1 /// UID: nac.acc.ACCReserveProtocol.v1
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ACCReserveProtocol { pub struct ACCReserveProtocol {
pub protocol_uid: String, pub protocol_uid: String,
pub lens_protocol_vector: String, pub lens_protocol_vector: String,
pub reserves: HashMap<String, ReserveEntry>, pub reserves: HashMap<String, ReserveEntry>,
@ -52,8 +52,8 @@ use crate::primitives::{Address, Hash, Timestamp};
pub pending_events: Vec<ReserveProtocolEvent>, pub pending_events: Vec<ReserveProtocolEvent>,
pub created_at: Timestamp, pub created_at: Timestamp,
pub updated_at: Timestamp, pub updated_at: Timestamp,
} }
impl ACCReserveProtocol { impl ACCReserveProtocol {
pub fn new(min_reserve_ratio: u8) -> Self { pub fn new(min_reserve_ratio: u8) -> Self {
Self { Self {
protocol_uid: "nac.acc.ACCReserveProtocol.v1".to_string(), protocol_uid: "nac.acc.ACCReserveProtocol.v1".to_string(),
@ -109,4 +109,4 @@ use crate::primitives::{Address, Hash, Timestamp};
pub fn get_reserve(&self, asset: &str) -> Option<&ReserveEntry> { self.reserves.get(asset) } pub fn get_reserve(&self, asset: &str) -> Option<&ReserveEntry> { self.reserves.get(asset) }
pub fn total_reserve_count(&self) -> usize { self.reserves.len() } pub fn total_reserve_count(&self) -> usize { self.reserves.len() }
pub fn drain_pending_events(&mut self) -> Vec<ReserveProtocolEvent> { std::mem::take(&mut self.pending_events) } pub fn drain_pending_events(&mut self) -> Vec<ReserveProtocolEvent> { std::mem::take(&mut self.pending_events) }
} }

View File

@ -1,11 +1,11 @@
//! acc_rwa - NAC 原生协议实现 //! acc_rwa - NAC 原生协议实现
//! 从 acc_remaining_protocols.rs 提取 //! 从 acc_remaining_protocols.rs 提取
use crate::primitives::{Address, Hash, Timestamp}; use crate::primitives::{Address, Hash, Timestamp};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ACCRWAError { pub enum ACCRWAError {
AssetNotFound(Hash), AssetNotFound(Hash),
AssetAlreadyRegistered(Hash), AssetAlreadyRegistered(Hash),
InvalidConstitutionalReceipt, InvalidConstitutionalReceipt,
@ -13,8 +13,8 @@ use crate::primitives::{Address, Hash, Timestamp};
ComplianceCheckFailed(String), ComplianceCheckFailed(String),
ValuationExpired(Hash), ValuationExpired(Hash),
AssetFrozen(Hash), AssetFrozen(Hash),
} }
impl std::fmt::Display for ACCRWAError { impl std::fmt::Display for ACCRWAError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Self::AssetNotFound(h) => write!(f, "RWA 资产不存在: {}", h.to_hex()), Self::AssetNotFound(h) => write!(f, "RWA 资产不存在: {}", h.to_hex()),
@ -26,10 +26,10 @@ use crate::primitives::{Address, Hash, Timestamp};
Self::AssetFrozen(h) => write!(f, "资产已冻结: {}", h.to_hex()), Self::AssetFrozen(h) => write!(f, "资产已冻结: {}", h.to_hex()),
} }
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RWAAssetType { pub enum RWAAssetType {
RealEstate, RealEstate,
CorporateBond, CorporateBond,
GovernmentBond, GovernmentBond,
@ -39,15 +39,15 @@ use crate::primitives::{Address, Hash, Timestamp};
IntellectualProperty, IntellectualProperty,
NaturalResource, NaturalResource,
Other, Other,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RWAAssetStatus { Pending, Active, Frozen, Redeemed, Delisted } pub enum RWAAssetStatus { Pending, Active, Frozen, Redeemed, Delisted }
/// RWA 资产记录 /// RWA 资产记录
/// UID: nac.acc.RWAAssetRecord.v1 /// UID: nac.acc.RWAAssetRecord.v1
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RWAAssetRecord { pub struct RWAAssetRecord {
pub asset_id: Hash, pub asset_id: Hash,
pub gnacs_code: String, pub gnacs_code: String,
pub asset_type: RWAAssetType, pub asset_type: RWAAssetType,
@ -64,21 +64,21 @@ use crate::primitives::{Address, Hash, Timestamp};
pub constitutional_receipt: Hash, pub constitutional_receipt: Hash,
pub registered_at: Timestamp, pub registered_at: Timestamp,
pub updated_at: Timestamp, pub updated_at: Timestamp,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RWAProtocolEvent { pub enum RWAProtocolEvent {
AssetRegistered { asset_id: Hash, gnacs_code: String, owner: Address, valuation: u128, timestamp: Timestamp }, AssetRegistered { asset_id: Hash, gnacs_code: String, owner: Address, valuation: u128, timestamp: Timestamp },
AssetTransferred { asset_id: Hash, from: Address, to: Address, amount: u128, timestamp: Timestamp }, AssetTransferred { asset_id: Hash, from: Address, to: Address, amount: u128, timestamp: Timestamp },
AssetFrozen { asset_id: Hash, reason: String, timestamp: Timestamp, constitutional_receipt: Hash }, AssetFrozen { asset_id: Hash, reason: String, timestamp: Timestamp, constitutional_receipt: Hash },
AssetUnfrozen { asset_id: Hash, timestamp: Timestamp, constitutional_receipt: Hash }, AssetUnfrozen { asset_id: Hash, timestamp: Timestamp, constitutional_receipt: Hash },
ValuationUpdated { asset_id: Hash, old_value: u128, new_value: u128, timestamp: Timestamp }, ValuationUpdated { asset_id: Hash, old_value: u128, new_value: u128, timestamp: Timestamp },
} }
/// ACC-RWA 真实世界资产协议 /// ACC-RWA 真实世界资产协议
/// UID: nac.acc.ACCRWAProtocol.v1 /// UID: nac.acc.ACCRWAProtocol.v1
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ACCRWAProtocol { pub struct ACCRWAProtocol {
pub protocol_uid: String, pub protocol_uid: String,
pub lens_protocol_vector: String, pub lens_protocol_vector: String,
pub assets: HashMap<Hash, RWAAssetRecord>, pub assets: HashMap<Hash, RWAAssetRecord>,
@ -87,8 +87,8 @@ use crate::primitives::{Address, Hash, Timestamp};
pub pending_events: Vec<RWAProtocolEvent>, pub pending_events: Vec<RWAProtocolEvent>,
pub created_at: Timestamp, pub created_at: Timestamp,
pub updated_at: Timestamp, pub updated_at: Timestamp,
} }
impl ACCRWAProtocol { impl ACCRWAProtocol {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
protocol_uid: "nac.acc.ACCRWAProtocol.v1".to_string(), protocol_uid: "nac.acc.ACCRWAProtocol.v1".to_string(),
@ -174,4 +174,4 @@ use crate::primitives::{Address, Hash, Timestamp};
self.holdings.get(asset_id).and_then(|h| h.get(holder)).copied().unwrap_or(0) self.holdings.get(asset_id).and_then(|h| h.get(holder)).copied().unwrap_or(0)
} }
pub fn drain_pending_events(&mut self) -> Vec<RWAProtocolEvent> { std::mem::take(&mut self.pending_events) } pub fn drain_pending_events(&mut self) -> Vec<RWAProtocolEvent> { std::mem::take(&mut self.pending_events) }
} }

View File

@ -1,19 +1,19 @@
//! acc_xtzh - NAC 原生协议实现 //! acc_xtzh - NAC 原生协议实现
//! 从 acc_remaining_protocols.rs 提取 //! 从 acc_remaining_protocols.rs 提取
use crate::primitives::{Address, Hash, Timestamp}; use crate::primitives::{Address, Hash, Timestamp};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ACCXTZHError { pub enum ACCXTZHError {
InsufficientBalance { holder: Address, available: u128, requested: u128 }, InsufficientBalance { holder: Address, available: u128, requested: u128 },
InsufficientReserve { required: u128, available: u128 }, InsufficientReserve { required: u128, available: u128 },
InvalidConstitutionalReceipt, InvalidConstitutionalReceipt,
Unauthorized(Address), Unauthorized(Address),
SDRPegViolation { current_rate: u128, min_rate: u128, max_rate: u128 }, SDRPegViolation { current_rate: u128, min_rate: u128, max_rate: u128 },
GoldReserveInsufficient { required_ratio: u8, actual_ratio: u8 }, GoldReserveInsufficient { required_ratio: u8, actual_ratio: u8 },
} }
impl std::fmt::Display for ACCXTZHError { impl std::fmt::Display for ACCXTZHError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Self::InsufficientBalance { holder, available, requested } => write!(f, "余额不足 {}: 可用 {},请求 {}", holder.to_hex(), available, requested), Self::InsufficientBalance { holder, available, requested } => write!(f, "余额不足 {}: 可用 {},请求 {}", holder.to_hex(), available, requested),
@ -24,34 +24,34 @@ use crate::primitives::{Address, Hash, Timestamp};
Self::GoldReserveInsufficient { required_ratio, actual_ratio } => write!(f, "黄金储备不足: 要求 {}%,实际 {}%", required_ratio, actual_ratio), Self::GoldReserveInsufficient { required_ratio, actual_ratio } => write!(f, "黄金储备不足: 要求 {}%,实际 {}%", required_ratio, actual_ratio),
} }
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReserveAssetType { Gold, USD, EUR, GBP, JPY, CNY, NACNative } pub enum ReserveAssetType { Gold, USD, EUR, GBP, JPY, CNY, NACNative }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReserveAsset { pub struct ReserveAsset {
pub asset_type: ReserveAssetType, pub asset_type: ReserveAssetType,
pub amount: u128, pub amount: u128,
/// 权重基点10000=100% /// 权重基点10000=100%
pub weight_bps: u16, pub weight_bps: u16,
pub last_updated: Timestamp, pub last_updated: Timestamp,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub enum XTZHProtocolEvent { pub enum XTZHProtocolEvent {
Minted { recipient: Address, amount: u128, constitutional_receipt: Hash, timestamp: Timestamp }, Minted { recipient: Address, amount: u128, constitutional_receipt: Hash, timestamp: Timestamp },
Burned { holder: Address, amount: u128, constitutional_receipt: Hash, timestamp: Timestamp }, Burned { holder: Address, amount: u128, constitutional_receipt: Hash, timestamp: Timestamp },
Transferred { from: Address, to: Address, amount: u128, timestamp: Timestamp }, Transferred { from: Address, to: Address, amount: u128, timestamp: Timestamp },
ReserveRebalanced { old_gold_ratio: u8, new_gold_ratio: u8, timestamp: Timestamp }, ReserveRebalanced { old_gold_ratio: u8, new_gold_ratio: u8, timestamp: Timestamp },
SDRRateUpdated { old_rate: u128, new_rate: u128, timestamp: Timestamp }, SDRRateUpdated { old_rate: u128, new_rate: u128, timestamp: Timestamp },
} }
/// XTZH 稳定币协议 /// XTZH 稳定币协议
/// UID: nac.acc.XTZHStablecoinProtocol.v1 /// UID: nac.acc.XTZHStablecoinProtocol.v1
/// SDR 锚定 + 黄金储备保障 /// SDR 锚定 + 黄金储备保障
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct XTZHStablecoinProtocol { pub struct XTZHStablecoinProtocol {
pub protocol_uid: String, pub protocol_uid: String,
pub lens_protocol_vector: String, pub lens_protocol_vector: String,
pub total_supply: u128, pub total_supply: u128,
@ -70,8 +70,8 @@ use crate::primitives::{Address, Hash, Timestamp};
pub pending_events: Vec<XTZHProtocolEvent>, pub pending_events: Vec<XTZHProtocolEvent>,
pub created_at: Timestamp, pub created_at: Timestamp,
pub updated_at: Timestamp, pub updated_at: Timestamp,
} }
impl XTZHStablecoinProtocol { impl XTZHStablecoinProtocol {
pub fn new(sdr_peg_rate: u128, min_gold_reserve_ratio: u8) -> Self { pub fn new(sdr_peg_rate: u128, min_gold_reserve_ratio: u8) -> Self {
Self { Self {
protocol_uid: "nac.acc.XTZHStablecoinProtocol.v1".to_string(), protocol_uid: "nac.acc.XTZHStablecoinProtocol.v1".to_string(),
@ -169,4 +169,4 @@ use crate::primitives::{Address, Hash, Timestamp};
} }
pub fn balance_of(&self, address: &Address) -> u128 { self.holdings.get(address).copied().unwrap_or(0) } pub fn balance_of(&self, address: &Address) -> u128 { self.holdings.get(address).copied().unwrap_or(0) }
pub fn drain_pending_events(&mut self) -> Vec<XTZHProtocolEvent> { std::mem::take(&mut self.pending_events) } pub fn drain_pending_events(&mut self) -> Vec<XTZHProtocolEvent> { std::mem::take(&mut self.pending_events) }
} }