NAC_Blockchain/charter-std/acc/acc20_enhanced.ch

734 lines
19 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

///! ACC-20 Enhanced - GNACS增强版可替代资产协议
///!
///! 这是NAC原生的ACC-20增强版集成了GNACS编码、主权管理和合规检查。
///!
///! 与标准ACC-20的区别
///! - 集成GNACS 48位编码系统
///! - 支持7种主权类型A0-G5
///! - 内置KYC/AML合规检查
///! - 支持资产冻结和估值管理
///! - 完整的审计追踪
module acc20_enhanced;
use asset::gnacs::{GNACSCode, AssetCategory, Jurisdiction, ComplianceLevel, RiskLevel};
use sovereignty::types::{SovereigntyType};
use sovereignty::rules::{SovereigntyRules, TransferRules};
use utils::crypto::{Hash, sha3_384_hash};
/// ACC-20增强版资产
contract ACC20Enhanced {
// ========== 基础信息 ==========
/// 资产名称
name: string;
/// 资产符号
symbol: string;
/// 小数位数
decimals: u8;
/// 总供应量
total_supply: u128;
// ========== GNACS集成 ==========
/// GNACS编码48位数字基因
gnacs_code: GNACSCode;
// ========== 主权管理 ==========
/// 主权类型
sovereignty_type: SovereigntyType;
/// 主权规则
sovereignty_rules: SovereigntyRules;
// ========== 持有量管理 ==========
/// 持有量映射使用Holdings而不是balance
holdings: map<Address, u128>;
/// 授权映射
allowances: map<Address, map<Address, u128>>;
// ========== 合规管理 ==========
/// KYC级别映射
kyc_levels: map<Address, KYCLevel>;
/// AML状态映射
aml_status: map<Address, AMLStatus>;
/// 合规状态
compliance_status: ComplianceStatus;
/// 白名单
whitelist: map<Address, bool>;
/// 黑名单
blacklist: map<Address, bool>;
// ========== 冻结管理 ==========
/// 全局冻结标志
globally_frozen: bool;
/// 账户冻结映射
frozen_accounts: map<Address, bool>;
// ========== RWA扩展 ==========
/// 估值信息
valuation: AssetValuation;
/// 审计追踪
audit_trail: vec<AuditEntry>;
/// 碎片化支持
fragmentable: bool;
/// 跨链支持
cross_chain_enabled: bool;
// ========== 贸易金融扩展 ==========
/// 信用证集成
letter_of_credit: Option<LetterOfCredit>;
/// 保函支持
bank_guarantee: Option<BankGuarantee>;
/// 应收账款
accounts_receivable: Option<AccountsReceivable>;
// ========== 管理员 ==========
/// 所有者
owner: Address;
/// 合规官
compliance_officer: Address;
/// 估值师
valuator: Address;
// ========== 构造函数 ==========
public fn new(
name: string,
symbol: string,
decimals: u8,
gnacs_code: GNACSCode,
sovereignty_type: SovereigntyType,
) -> Result<Self, Error> {
// 验证GNACS编码
if !gnacs_code.is_valid() {
return Err(Error::InvalidGNACS);
}
// 创建默认主权规则
let sovereignty_rules = SovereigntyRules::default_for_type(sovereignty_type);
return Ok(Self {
name,
symbol,
decimals,
total_supply: 0,
gnacs_code,
sovereignty_type,
sovereignty_rules,
holdings: map::new(),
allowances: map::new(),
kyc_levels: map::new(),
aml_status: map::new(),
compliance_status: ComplianceStatus::Pending,
whitelist: map::new(),
blacklist: map::new(),
globally_frozen: false,
frozen_accounts: map::new(),
valuation: AssetValuation::new(),
audit_trail: vec::new(),
fragmentable: false,
cross_chain_enabled: false,
letter_of_credit: None,
bank_guarantee: None,
accounts_receivable: None,
owner: msg::sender(),
compliance_officer: msg::sender(),
valuator: msg::sender(),
});
}
// ========== 查询函数 ==========
/// 获取资产名称
public fn get_name() -> string {
return self.name;
}
/// 获取资产符号
public fn get_symbol() -> string {
return self.symbol;
}
/// 获取小数位数
public fn get_decimals() -> u8 {
return self.decimals;
}
/// 获取总供应量
public fn get_total_supply() -> u128 {
return self.total_supply;
}
/// 获取GNACS编码
public fn get_gnacs_code() -> GNACSCode {
return self.gnacs_code;
}
/// 获取主权类型
public fn get_sovereignty_type() -> SovereigntyType {
return self.sovereignty_type;
}
/// 获取持有量
public fn holdings_of(owner: Address) -> u128 {
return self.holdings.get(owner).unwrap_or(0);
}
/// 获取授权额度
public fn allowance(owner: Address, spender: Address) -> u128 {
return self.allowances
.get(owner)
.and_then(|inner| inner.get(spender))
.unwrap_or(0);
}
/// 检查账户是否冻结
public fn is_frozen(account: Address) -> bool {
return self.globally_frozen || self.frozen_accounts.get(account).unwrap_or(false);
}
/// 获取合规状态
public fn get_compliance_status() -> ComplianceStatus {
return self.compliance_status;
}
/// 获取KYC级别
public fn get_kyc_level(account: Address) -> KYCLevel {
return self.kyc_levels.get(account).unwrap_or(KYCLevel::None);
}
/// 获取AML状态
public fn get_aml_status(account: Address) -> AMLStatus {
return self.aml_status.get(account).unwrap_or(AMLStatus::Unknown);
}
// ========== 转账函数 ==========
/// 转账
public fn transfer(to: Address, amount: u128) -> Result<bool, Error> {
let from = msg::sender();
return self._transfer(from, to, amount);
}
/// 从授权转账
public fn transfer_from(from: Address, to: Address, amount: u128) -> Result<bool, Error> {
let spender = msg::sender();
// 检查授权额度
let current_allowance = self.allowance(from, spender);
if current_allowance < amount {
return Err(Error::InsufficientAllowance);
}
// 执行转账
self._transfer(from, to, amount)?;
// 减少授权额度
let new_allowance = current_allowance - amount;
self.allowances.get_mut(from).unwrap().insert(spender, new_allowance);
return Ok(true);
}
/// 内部转账函数
fn _transfer(from: Address, to: Address, amount: u128) -> Result<bool, Error> {
// 1. 基础检查
if from == Address::zero() {
return Err(Error::TransferFromZeroAddress);
}
if to == Address::zero() {
return Err(Error::TransferToZeroAddress);
}
if amount == 0 {
return Err(Error::ZeroAmount);
}
// 2. 冻结检查
if self.is_frozen(from) {
return Err(Error::AccountFrozen);
}
if self.is_frozen(to) {
return Err(Error::AccountFrozen);
}
// 3. 合规检查
self._check_compliance(from)?;
self._check_compliance(to)?;
// 4. 主权规则验证
self._validate_sovereignty_transfer(from, to, amount)?;
// 5. 余额检查
let from_holdings = self.holdings_of(from);
if from_holdings < amount {
return Err(Error::InsufficientHoldings);
}
// 6. 执行转账
let new_from_holdings = from_holdings - amount;
let to_holdings = self.holdings_of(to);
let new_to_holdings = to_holdings + amount;
self.holdings.insert(from, new_from_holdings);
self.holdings.insert(to, new_to_holdings);
// 7. 记录审计追踪
self._record_audit(
AuditAction::Transfer,
from,
Some(to),
amount,
"Transfer executed".to_string(),
);
// 8. 触发事件
emit Transfer(from, to, amount);
return Ok(true);
}
// ========== 授权函数 ==========
/// 授权
public fn approve(spender: Address, amount: u128) -> Result<bool, Error> {
let owner = msg::sender();
if spender == Address::zero() {
return Err(Error::ApproveToZeroAddress);
}
if !self.allowances.contains_key(owner) {
self.allowances.insert(owner, map::new());
}
self.allowances.get_mut(owner).unwrap().insert(spender, amount);
emit Approval(owner, spender, amount);
return Ok(true);
}
/// 增加授权
public fn increase_allowance(spender: Address, added_value: u128) -> Result<bool, Error> {
let owner = msg::sender();
let current_allowance = self.allowance(owner, spender);
let new_allowance = current_allowance + added_value;
return self.approve(spender, new_allowance);
}
/// 减少授权
public fn decrease_allowance(spender: Address, subtracted_value: u128) -> Result<bool, Error> {
let owner = msg::sender();
let current_allowance = self.allowance(owner, spender);
if current_allowance < subtracted_value {
return Err(Error::AllowanceBelowZero);
}
let new_allowance = current_allowance - subtracted_value;
return self.approve(spender, new_allowance);
}
// ========== 管理函数 ==========
/// 铸造
public fn mint(to: Address, amount: u128) -> Result<bool, Error> {
self._only_owner()?;
if to == Address::zero() {
return Err(Error::MintToZeroAddress);
}
// 检查合规状态
if self.compliance_status != ComplianceStatus::Approved {
return Err(Error::NotCompliant);
}
// 增加总供应量
self.total_supply = self.total_supply + amount;
// 增加持有量
let current_holdings = self.holdings_of(to);
self.holdings.insert(to, current_holdings + amount);
// 记录审计
self._record_audit(
AuditAction::Mint,
Address::zero(),
Some(to),
amount,
"Minted new assets".to_string(),
);
emit Mint(to, amount);
emit Transfer(Address::zero(), to, amount);
return Ok(true);
}
/// 销毁
public fn burn(amount: u128) -> Result<bool, Error> {
let from = msg::sender();
let current_holdings = self.holdings_of(from);
if current_holdings < amount {
return Err(Error::InsufficientHoldings);
}
// 减少总供应量
self.total_supply = self.total_supply - amount;
// 减少持有量
self.holdings.insert(from, current_holdings - amount);
// 记录审计
self._record_audit(
AuditAction::Burn,
from,
None,
amount,
"Burned assets".to_string(),
);
emit Burn(from, amount);
emit Transfer(from, Address::zero(), amount);
return Ok(true);
}
/// 冻结账户
public fn freeze_account(account: Address) -> Result<bool, Error> {
self._only_compliance_officer()?;
self.frozen_accounts.insert(account, true);
emit AccountFrozen(account);
return Ok(true);
}
/// 解冻账户
public fn unfreeze_account(account: Address) -> Result<bool, Error> {
self._only_compliance_officer()?;
self.frozen_accounts.insert(account, false);
emit AccountUnfrozen(account);
return Ok(true);
}
/// 全局冻结
public fn global_freeze() -> Result<bool, Error> {
self._only_owner()?;
self.globally_frozen = true;
emit GlobalFreeze();
return Ok(true);
}
/// 全局解冻
public fn global_unfreeze() -> Result<bool, Error> {
self._only_owner()?;
self.globally_frozen = false;
emit GlobalUnfreeze();
return Ok(true);
}
/// 设置KYC级别
public fn set_kyc_level(account: Address, level: KYCLevel) -> Result<bool, Error> {
self._only_compliance_officer()?;
self.kyc_levels.insert(account, level);
emit KYCLevelUpdated(account, level);
return Ok(true);
}
/// 设置AML状态
public fn set_aml_status(account: Address, status: AMLStatus) -> Result<bool, Error> {
self._only_compliance_officer()?;
self.aml_status.insert(account, status);
emit AMLStatusUpdated(account, status);
return Ok(true);
}
/// 更新估值
public fn update_valuation(
value_xtzh: u128,
valuator: Address,
report_hash: Hash,
) -> Result<bool, Error> {
self._only_valuator()?;
self.valuation.value_xtzh = value_xtzh;
self.valuation.last_valuation_time = block::timestamp();
self.valuation.valuator = valuator;
self.valuation.valuation_report_hash = report_hash;
emit ValuationUpdated(value_xtzh, valuator, report_hash);
return Ok(true);
}
// ========== 内部辅助函数 ==========
/// 检查合规性
fn _check_compliance(account: Address) -> Result<(), Error> {
// 检查黑名单
if self.blacklist.get(account).unwrap_or(false) {
return Err(Error::Blacklisted);
}
// 检查KYC
let kyc_level = self.get_kyc_level(account);
if kyc_level == KYCLevel::None {
return Err(Error::KYCRequired);
}
// 检查AML
let aml_status = self.get_aml_status(account);
if aml_status == AMLStatus::HighRisk || aml_status == AMLStatus::Blocked {
return Err(Error::AMLCheckFailed);
}
return Ok(());
}
/// 验证主权规则
fn _validate_sovereignty_transfer(
from: Address,
to: Address,
amount: u128,
) -> Result<(), Error> {
// 使用主权规则验证器
let result = self.sovereignty_rules.validate_transfer(
from,
to,
amount,
block::timestamp(),
);
if result.is_err() {
return Err(Error::SovereigntyRuleViolation);
}
return Ok(());
}
/// 记录审计追踪
fn _record_audit(
action: AuditAction,
from: Address,
to: Option<Address>,
amount: u128,
note: string,
) {
let entry = AuditEntry {
timestamp: block::timestamp(),
action,
from,
to,
amount,
note,
tx_hash: tx::hash(),
};
self.audit_trail.push(entry);
}
/// 仅所有者
fn _only_owner() -> Result<(), Error> {
if msg::sender() != self.owner {
return Err(Error::OnlyOwner);
}
return Ok(());
}
/// 仅合规官
fn _only_compliance_officer() -> Result<(), Error> {
if msg::sender() != self.compliance_officer {
return Err(Error::OnlyComplianceOfficer);
}
return Ok(());
}
/// 仅估值师
fn _only_valuator() -> Result<(), Error> {
if msg::sender() != self.valuator {
return Err(Error::OnlyValuator);
}
return Ok(());
}
}
// ========== 辅助结构体 ==========
/// KYC级别
enum KYCLevel {
None, // 未验证
Basic, // 基础验证
Intermediate, // 中级验证
Advanced, // 高级验证
Institutional, // 机构验证
}
/// AML状态
enum AMLStatus {
Unknown, // 未知
Clear, // 清白
LowRisk, // 低风险
MediumRisk, // 中等风险
HighRisk, // 高风险
Blocked, // 已阻止
}
/// 合规状态
enum ComplianceStatus {
Pending, // 待审核
Approved, // 已批准
Rejected, // 已拒绝
Suspended, // 已暂停
Revoked, // 已撤销
}
/// 资产估值
struct AssetValuation {
value_xtzh: u128, // XTZH计价
last_valuation_time: Timestamp, // 最后估值时间
valuator: Address, // 估值师
valuation_report_hash: Hash, // 估值报告哈希
}
impl AssetValuation {
fn new() -> Self {
return Self {
value_xtzh: 0,
last_valuation_time: Timestamp::zero(),
valuator: Address::zero(),
valuation_report_hash: Hash::zero(),
};
}
}
/// 审计条目
struct AuditEntry {
timestamp: Timestamp,
action: AuditAction,
from: Address,
to: Option<Address>,
amount: u128,
note: string,
tx_hash: Hash,
}
/// 审计动作
enum AuditAction {
Transfer,
Mint,
Burn,
Freeze,
Unfreeze,
Approve,
KYCUpdate,
AMLUpdate,
ValuationUpdate,
}
/// 信用证
struct LetterOfCredit {
issuing_bank: Address,
beneficiary: Address,
amount: u128,
expiry_date: Timestamp,
document_hash: Hash,
}
/// 保函
struct BankGuarantee {
guarantor_bank: Address,
beneficiary: Address,
amount: u128,
expiry_date: Timestamp,
terms_hash: Hash,
}
/// 应收账款
struct AccountsReceivable {
debtor: Address,
amount: u128,
due_date: Timestamp,
invoice_hash: Hash,
}
// ========== 错误类型 ==========
enum Error {
InvalidGNACS,
TransferFromZeroAddress,
TransferToZeroAddress,
ZeroAmount,
AccountFrozen,
InsufficientHoldings,
InsufficientAllowance,
ApproveToZeroAddress,
AllowanceBelowZero,
MintToZeroAddress,
NotCompliant,
Blacklisted,
KYCRequired,
AMLCheckFailed,
SovereigntyRuleViolation,
OnlyOwner,
OnlyComplianceOfficer,
OnlyValuator,
}
// ========== 事件 ==========
event Transfer(from: Address, to: Address, amount: u128);
event Approval(owner: Address, spender: Address, amount: u128);
event Mint(to: Address, amount: u128);
event Burn(from: Address, amount: u128);
event AccountFrozen(account: Address);
event AccountUnfrozen(account: Address);
event GlobalFreeze();
event GlobalUnfreeze();
event KYCLevelUpdated(account: Address, level: KYCLevel);
event AMLStatusUpdated(account: Address, status: AMLStatus);
event ValuationUpdated(value_xtzh: u128, valuator: Address, report_hash: Hash);