0.9.3.6: Complete Banking, Viewer Economy, Land Commerce and NexCommerce

Complete Roadmap 10.3 through 10.6 with banking workflows, Viewer commerce integration, land settlement/leases, NexCommerce, ledger schema v4, OpenAPI/docs and regression coverage.
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-10-06 01:14:02 +02:00
1 parent 598bf104c4
commit c28ce59d4a
21 files changed
+6810 -75

No files matched your search

+20 -1
View File
@@ -221,6 +221,10 @@ jobs:
shell: bash
run: python3 tools/ci/verify_economy_api_viewer.py
- name: Verify NV dollar banking, commerce and land flows
shell: bash
run: python3 tools/ci/verify_banking_commerce.py
- name: Verify NV dollar live database matrix contract
shell: bash
run: python3 tools/ci/verify_ledger_db_matrix.py
@@ -309,12 +313,17 @@ jobs:
"ogl_ledger_account_state",
"ogl_ledger_account_events",
"ogl_ledger_virtual_accounts",
"ogl_economy_transfer_policies",
"ogl_economy_payment_requests",
"ogl_economy_commerce_orders",
"ogl_economy_land_listings",
"ogl_economy_land_leases",
}
assert required.issubset(tables), (required, tables)
version = con.execute(
"SELECT MAX(version) FROM ogl_ledger_schema"
).fetchone()[0]
assert version == 3, version
assert version == 4, version
assert con.execute(
"SELECT COUNT(*) FROM ogl_ledger_accounts"
).fetchone()[0] == 0
@@ -333,6 +342,16 @@ jobs:
assert con.execute(
"SELECT COUNT(*) FROM ogl_ledger_virtual_accounts"
).fetchone()[0] == 0
for table in (
"ogl_economy_transfer_policies",
"ogl_economy_payment_requests",
"ogl_economy_commerce_orders",
"ogl_economy_land_listings",
"ogl_economy_land_leases",
):
assert con.execute(
"SELECT COUNT(*) FROM " + table
).fetchone()[0] == 0
finally:
con.close()
PY
File diff suppressed because it is too large. Load diff
+485
View File
@@ -0,0 +1,485 @@
// SPDX-License-Identifier: MPL-2.0
using System;
using System.Collections.Generic;
namespace NexVerse.Core.Economy
{
public enum NexPaymentRequestStatus
{
Pending = 1,
Paid = 2,
Cancelled = 3,
Expired = 4
}
public sealed class NexPaymentRequest
{
public const int ReferenceLengthLimit = 255;
public NexPaymentRequest(
Guid requestId,
Guid payeeAccountId,
Guid payerAccountId,
long amountMinor,
string reference,
NexPaymentRequestStatus status = NexPaymentRequestStatus.Pending,
DateTimeOffset? createdAt = null,
DateTimeOffset? expiresAt = null,
Guid? paymentTransactionId = null)
{
if (requestId == Guid.Empty)
throw new ArgumentException("Payment request ID is required.", nameof(requestId));
if (payeeAccountId == Guid.Empty)
throw new ArgumentException("Payee account ID is required.", nameof(payeeAccountId));
if (payerAccountId == Guid.Empty)
throw new ArgumentException("Payer account ID is required.", nameof(payerAccountId));
if (payeeAccountId == payerAccountId)
throw new ArgumentException("Payer and payee must differ.");
if (amountMinor <= 0)
throw new ArgumentOutOfRangeException(nameof(amountMinor));
if (!Enum.IsDefined(typeof(NexPaymentRequestStatus), status))
throw new ArgumentOutOfRangeException(nameof(status));
string normalized =
(reference ?? string.Empty).Trim();
if (normalized.Length == 0)
throw new ArgumentException("Payment request reference is required.", nameof(reference));
if (normalized.Length > ReferenceLengthLimit)
throw new ArgumentOutOfRangeException(nameof(reference));
DateTimeOffset created =
createdAt ?? DateTimeOffset.UtcNow;
DateTimeOffset expires =
expiresAt ?? created.AddDays(30);
if (expires <= created)
throw new ArgumentOutOfRangeException(nameof(expiresAt));
RequestId = requestId;
PayeeAccountId = payeeAccountId;
PayerAccountId = payerAccountId;
AmountMinor = amountMinor;
Reference = normalized;
Status = status;
CreatedAt = created;
ExpiresAt = expires;
PaymentTransactionId = paymentTransactionId ?? Guid.Empty;
}
public Guid RequestId { get; }
public Guid PayeeAccountId { get; }
public Guid PayerAccountId { get; }
public long AmountMinor { get; }
public string Reference { get; }
public NexPaymentRequestStatus Status { get; }
public DateTimeOffset CreatedAt { get; }
public DateTimeOffset ExpiresAt { get; }
public Guid PaymentTransactionId { get; }
public NexPaymentRequest WithStatus(
NexPaymentRequestStatus status,
Guid paymentTransactionId = default) =>
new NexPaymentRequest(
RequestId,
PayeeAccountId,
PayerAccountId,
AmountMinor,
Reference,
status,
CreatedAt,
ExpiresAt,
paymentTransactionId);
}
public sealed class NexAccountTransferPolicy
{
public NexAccountTransferPolicy(
Guid accountId,
long maxPerTransferMinor = 0,
long dailyOutgoingLimitMinor = 0,
long flatFeeMinor = 0,
Guid feeAccountId = default)
{
if (accountId == Guid.Empty)
throw new ArgumentException("Account ID is required.", nameof(accountId));
if (maxPerTransferMinor < 0)
throw new ArgumentOutOfRangeException(nameof(maxPerTransferMinor));
if (dailyOutgoingLimitMinor < 0)
throw new ArgumentOutOfRangeException(nameof(dailyOutgoingLimitMinor));
if (flatFeeMinor < 0)
throw new ArgumentOutOfRangeException(nameof(flatFeeMinor));
if (flatFeeMinor > 0 && feeAccountId == Guid.Empty)
throw new ArgumentException("Fee account is required when a flat fee is configured.", nameof(feeAccountId));
AccountId = accountId;
MaxPerTransferMinor = maxPerTransferMinor;
DailyOutgoingLimitMinor = dailyOutgoingLimitMinor;
FlatFeeMinor = flatFeeMinor;
FeeAccountId = feeAccountId;
}
public Guid AccountId { get; }
public long MaxPerTransferMinor { get; }
public long DailyOutgoingLimitMinor { get; }
public long FlatFeeMinor { get; }
public Guid FeeAccountId { get; }
}
public enum NexCommerceKind
{
VendorPayment = 1,
ObjectSale = 2,
MarketplacePurchase = 3,
LandPurchase = 4,
EventTicket = 5,
Rental = 6,
MerchantRefund = 7
}
public enum NexCommerceOrderStatus
{
Pending = 1,
Completed = 2,
Refunded = 3,
Cancelled = 4
}
public sealed class NexCommerceOrder
{
public const int ReferenceLengthLimit = 255;
public const int ExternalReferenceLengthLimit = 255;
public NexCommerceOrder(
Guid orderId,
NexCommerceKind kind,
Guid buyerAccountId,
Guid sellerAccountId,
long amountMinor,
string reference,
string externalReference = "",
NexCommerceOrderStatus status = NexCommerceOrderStatus.Pending,
Guid paymentTransactionId = default,
Guid refundTransactionId = default,
DateTimeOffset? createdAt = null,
DateTimeOffset? completedAt = null)
{
if (orderId == Guid.Empty)
throw new ArgumentException("Commerce order ID is required.", nameof(orderId));
if (!Enum.IsDefined(typeof(NexCommerceKind), kind))
throw new ArgumentOutOfRangeException(nameof(kind));
if (!Enum.IsDefined(typeof(NexCommerceOrderStatus), status))
throw new ArgumentOutOfRangeException(nameof(status));
if (buyerAccountId == Guid.Empty)
throw new ArgumentException("Buyer account ID is required.", nameof(buyerAccountId));
if (sellerAccountId == Guid.Empty)
throw new ArgumentException("Seller account ID is required.", nameof(sellerAccountId));
if (buyerAccountId == sellerAccountId)
throw new ArgumentException("Buyer and seller must differ.");
if (amountMinor <= 0)
throw new ArgumentOutOfRangeException(nameof(amountMinor));
string normalizedReference =
(reference ?? string.Empty).Trim();
string normalizedExternal =
(externalReference ?? string.Empty).Trim();
if (normalizedReference.Length == 0)
throw new ArgumentException("Commerce reference is required.", nameof(reference));
if (normalizedReference.Length > ReferenceLengthLimit)
throw new ArgumentOutOfRangeException(nameof(reference));
if (normalizedExternal.Length > ExternalReferenceLengthLimit)
throw new ArgumentOutOfRangeException(nameof(externalReference));
OrderId = orderId;
Kind = kind;
BuyerAccountId = buyerAccountId;
SellerAccountId = sellerAccountId;
AmountMinor = amountMinor;
Reference = normalizedReference;
ExternalReference = normalizedExternal;
Status = status;
PaymentTransactionId = paymentTransactionId;
RefundTransactionId = refundTransactionId;
CreatedAt = createdAt ?? DateTimeOffset.UtcNow;
CompletedAt = completedAt;
}
public Guid OrderId { get; }
public NexCommerceKind Kind { get; }
public Guid BuyerAccountId { get; }
public Guid SellerAccountId { get; }
public long AmountMinor { get; }
public string Reference { get; }
public string ExternalReference { get; }
public NexCommerceOrderStatus Status { get; }
public Guid PaymentTransactionId { get; }
public Guid RefundTransactionId { get; }
public DateTimeOffset CreatedAt { get; }
public DateTimeOffset? CompletedAt { get; }
public NexCommerceOrder Complete(Guid transactionId) =>
new NexCommerceOrder(
OrderId,
Kind,
BuyerAccountId,
SellerAccountId,
AmountMinor,
Reference,
ExternalReference,
NexCommerceOrderStatus.Completed,
transactionId,
RefundTransactionId,
CreatedAt,
DateTimeOffset.UtcNow);
public NexCommerceOrder Refund(Guid transactionId) =>
new NexCommerceOrder(
OrderId,
Kind,
BuyerAccountId,
SellerAccountId,
AmountMinor,
Reference,
ExternalReference,
NexCommerceOrderStatus.Refunded,
PaymentTransactionId,
transactionId,
CreatedAt,
CompletedAt);
}
public enum NexLandListingType
{
Sale = 1,
Rental = 2
}
public sealed class NexLandListing
{
public NexLandListing(
Guid listingId,
NexLandListingType listingType,
Guid regionId,
string regionName,
Guid parcelId,
int parcelLocalId,
string parcelName,
Guid sellerAccountId,
Guid estateId,
int area,
long priceMinor,
int rentalPeriodDays = 0,
bool active = true,
DateTimeOffset? createdAt = null)
{
if (listingId == Guid.Empty)
throw new ArgumentException("Listing ID is required.", nameof(listingId));
if (!Enum.IsDefined(typeof(NexLandListingType), listingType))
throw new ArgumentOutOfRangeException(nameof(listingType));
if (regionId == Guid.Empty)
throw new ArgumentException("Region ID is required.", nameof(regionId));
if (parcelId == Guid.Empty)
throw new ArgumentException("Parcel ID is required.", nameof(parcelId));
if (parcelLocalId <= 0)
throw new ArgumentOutOfRangeException(nameof(parcelLocalId));
if (sellerAccountId == Guid.Empty)
throw new ArgumentException("Seller account ID is required.", nameof(sellerAccountId));
if (area <= 0)
throw new ArgumentOutOfRangeException(nameof(area));
if (priceMinor <= 0)
throw new ArgumentOutOfRangeException(nameof(priceMinor));
if (listingType == NexLandListingType.Rental && rentalPeriodDays <= 0)
throw new ArgumentOutOfRangeException(nameof(rentalPeriodDays));
ListingId = listingId;
ListingType = listingType;
RegionId = regionId;
RegionName = (regionName ?? string.Empty).Trim();
ParcelId = parcelId;
ParcelLocalId = parcelLocalId;
ParcelName = (parcelName ?? string.Empty).Trim();
SellerAccountId = sellerAccountId;
EstateId = estateId;
Area = area;
PriceMinor = priceMinor;
RentalPeriodDays = rentalPeriodDays;
Active = active;
CreatedAt = createdAt ?? DateTimeOffset.UtcNow;
}
public Guid ListingId { get; }
public NexLandListingType ListingType { get; }
public Guid RegionId { get; }
public string RegionName { get; }
public Guid ParcelId { get; }
public int ParcelLocalId { get; }
public string ParcelName { get; }
public Guid SellerAccountId { get; }
public Guid EstateId { get; }
public int Area { get; }
public long PriceMinor { get; }
public int RentalPeriodDays { get; }
public bool Active { get; }
public DateTimeOffset CreatedAt { get; }
public NexLandListing Deactivate() =>
new NexLandListing(
ListingId,
ListingType,
RegionId,
RegionName,
ParcelId,
ParcelLocalId,
ParcelName,
SellerAccountId,
EstateId,
Area,
PriceMinor,
RentalPeriodDays,
false,
CreatedAt);
}
public sealed class NexLandLease
{
public NexLandLease(
Guid leaseId,
Guid listingId,
Guid tenantAccountId,
Guid landlordAccountId,
long rentMinor,
int periodDays,
DateTimeOffset startsAt,
DateTimeOffset endsAt,
DateTimeOffset nextDueAt,
bool active = true,
Guid lastPaymentTransactionId = default)
{
if (leaseId == Guid.Empty)
throw new ArgumentException("Lease ID is required.", nameof(leaseId));
if (listingId == Guid.Empty)
throw new ArgumentException("Listing ID is required.", nameof(listingId));
if (tenantAccountId == Guid.Empty || landlordAccountId == Guid.Empty)
throw new ArgumentException("Lease accounts are required.");
if (rentMinor <= 0)
throw new ArgumentOutOfRangeException(nameof(rentMinor));
if (periodDays <= 0)
throw new ArgumentOutOfRangeException(nameof(periodDays));
if (endsAt <= startsAt)
throw new ArgumentOutOfRangeException(nameof(endsAt));
LeaseId = leaseId;
ListingId = listingId;
TenantAccountId = tenantAccountId;
LandlordAccountId = landlordAccountId;
RentMinor = rentMinor;
PeriodDays = periodDays;
StartsAt = startsAt;
EndsAt = endsAt;
NextDueAt = nextDueAt;
Active = active;
LastPaymentTransactionId = lastPaymentTransactionId;
}
public Guid LeaseId { get; }
public Guid ListingId { get; }
public Guid TenantAccountId { get; }
public Guid LandlordAccountId { get; }
public long RentMinor { get; }
public int PeriodDays { get; }
public DateTimeOffset StartsAt { get; }
public DateTimeOffset EndsAt { get; }
public DateTimeOffset NextDueAt { get; }
public bool Active { get; }
public Guid LastPaymentTransactionId { get; }
public NexLandLease Advance(Guid transactionId, DateTimeOffset nextDueAt, bool active) =>
new NexLandLease(
LeaseId,
ListingId,
TenantAccountId,
LandlordAccountId,
RentMinor,
PeriodDays,
StartsAt,
EndsAt,
nextDueAt,
active,
transactionId);
}
public sealed class NexBankStatement
{
public NexBankStatement(
Guid accountId,
DateTimeOffset from,
DateTimeOffset to,
long openingBalance,
long closingBalance,
IReadOnlyList<NexLedgerTransaction> transactions)
{
AccountId = accountId;
From = from;
To = to;
OpeningBalance = openingBalance;
ClosingBalance = closingBalance;
Transactions = transactions ?? Array.Empty<NexLedgerTransaction>();
}
public Guid AccountId { get; }
public DateTimeOffset From { get; }
public DateTimeOffset To { get; }
public long OpeningBalance { get; }
public long ClosingBalance { get; }
public IReadOnlyList<NexLedgerTransaction> Transactions { get; }
}
public sealed class NexReconciliationReport
{
public NexReconciliationReport(
Guid accountId,
long derivedBalance,
long recomputedBalance,
int transactionCount,
bool balanced)
{
AccountId = accountId;
DerivedBalance = derivedBalance;
RecomputedBalance = recomputedBalance;
TransactionCount = transactionCount;
Balanced = balanced;
}
public Guid AccountId { get; }
public long DerivedBalance { get; }
public long RecomputedBalance { get; }
public int TransactionCount { get; }
public bool Balanced { get; }
}
public interface INexEconomyWorkflowStore
{
NexAccountTransferPolicy GetTransferPolicy(Guid accountId);
NexAccountTransferPolicy SetTransferPolicy(NexAccountTransferPolicy policy);
long GetOutgoingTotal(Guid accountId, DateTimeOffset fromInclusive, DateTimeOffset toExclusive);
NexPaymentRequest CreatePaymentRequest(NexPaymentRequest request);
NexPaymentRequest GetPaymentRequest(Guid requestId);
IReadOnlyList<NexPaymentRequest> ListPaymentRequests(Guid accountId, int offset, int limit);
NexPaymentRequest UpdatePaymentRequest(NexPaymentRequest request);
NexCommerceOrder CreateCommerceOrder(NexCommerceOrder order);
NexCommerceOrder GetCommerceOrder(Guid orderId);
IReadOnlyList<NexCommerceOrder> ListCommerceOrders(Guid accountId, int offset, int limit);
NexCommerceOrder UpdateCommerceOrder(NexCommerceOrder order);
NexLandListing CreateLandListing(NexLandListing listing);
NexLandListing GetLandListing(Guid listingId);
IReadOnlyList<NexLandListing> SearchLandListings(string query, NexLandListingType? type, int offset, int limit);
NexLandListing UpdateLandListing(NexLandListing listing);
NexLandLease CreateLandLease(NexLandLease lease);
NexLandLease GetLandLease(Guid leaseId);
IReadOnlyList<NexLandLease> ListLandLeases(Guid accountId, int offset, int limit);
NexLandLease UpdateLandLease(NexLandLease lease);
}
}
File diff suppressed because it is too large. Load diff
+438 -1
View File
@@ -37,10 +37,17 @@ namespace NexVerse.Core.Economy
NexLedgerAppendResult Append(NexLedgerTransaction transaction);
NexLedgerTransaction GetTransaction(Guid transactionId);
long GetBalance(Guid accountId);
long GetBalanceAt(Guid accountId, DateTimeOffset atOrBefore);
IReadOnlyList<NexLedgerPosting> ListPostings(
Guid accountId,
int offset,
int limit);
IReadOnlyList<NexLedgerTransaction> ListTransactions(
Guid accountId,
DateTimeOffset? from,
DateTimeOffset? to,
int offset,
int limit);
}
/// <summary>
@@ -51,7 +58,8 @@ namespace NexVerse.Core.Economy
public sealed class InMemoryNexLedgerStore :
INexLedgerStore,
INexLedgerAccountStateStore,
INexVirtualBankAccountStore
INexVirtualBankAccountStore,
INexEconomyWorkflowStore
{
private readonly object m_Sync =
new object();
@@ -73,6 +81,16 @@ namespace NexVerse.Core.Economy
new Dictionary<Guid, NexVirtualBankAccount>();
private readonly Dictionary<string, NexVirtualBankAccount> m_VirtualBankAccountsByIdentifier =
new Dictionary<string, NexVirtualBankAccount>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<Guid, NexAccountTransferPolicy> m_TransferPolicies =
new Dictionary<Guid, NexAccountTransferPolicy>();
private readonly Dictionary<Guid, NexPaymentRequest> m_PaymentRequests =
new Dictionary<Guid, NexPaymentRequest>();
private readonly Dictionary<Guid, NexCommerceOrder> m_CommerceOrders =
new Dictionary<Guid, NexCommerceOrder>();
private readonly Dictionary<Guid, NexLandListing> m_LandListings =
new Dictionary<Guid, NexLandListing>();
private readonly Dictionary<Guid, NexLandLease> m_LandLeases =
new Dictionary<Guid, NexLandLease>();
public bool TryCreateAccount(
NexLedgerAccount account)
@@ -361,6 +379,405 @@ namespace NexVerse.Core.Economy
}
}
public long GetBalanceAt(
Guid accountId,
DateTimeOffset atOrBefore)
{
lock (m_Sync)
{
if (!m_Accounts.TryGetValue(
accountId,
out NexLedgerAccount account))
{
throw new NexLedgerValidationException(
$"Unknown ledger account {accountId}.");
}
long balance = 0;
foreach (NexLedgerTransaction transaction in
m_Transactions.Values
.Where(x => x.OccurredAt <= atOrBefore)
.OrderBy(x => x.OccurredAt)
.ThenBy(x => x.TransactionId))
{
foreach (NexLedgerPosting posting in
transaction.Postings.Where(x => x.AccountId == accountId))
{
checked
{
long delta =
posting.Side == account.NormalSide
? posting.AmountMinor
: -posting.AmountMinor;
balance += delta;
}
}
}
return balance;
}
}
public IReadOnlyList<NexLedgerTransaction> ListTransactions(
Guid accountId,
DateTimeOffset? from,
DateTimeOffset? to,
int offset,
int limit)
{
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (limit < 1 || limit > 1000)
throw new ArgumentOutOfRangeException(nameof(limit));
lock (m_Sync)
{
if (!m_Accounts.ContainsKey(accountId))
throw new NexLedgerValidationException(
$"Unknown ledger account {accountId}.");
IEnumerable<NexLedgerTransaction> query =
m_Transactions.Values
.Where(x => x.Postings.Any(p => p.AccountId == accountId));
if (from.HasValue)
query = query.Where(x => x.OccurredAt >= from.Value);
if (to.HasValue)
query = query.Where(x => x.OccurredAt <= to.Value);
return query
.OrderByDescending(x => x.OccurredAt)
.ThenByDescending(x => x.TransactionId)
.Skip(offset)
.Take(limit)
.ToArray();
}
}
public NexAccountTransferPolicy GetTransferPolicy(Guid accountId)
{
lock (m_Sync)
{
m_TransferPolicies.TryGetValue(
accountId,
out NexAccountTransferPolicy policy);
return policy;
}
}
public NexAccountTransferPolicy SetTransferPolicy(
NexAccountTransferPolicy policy)
{
if (policy == null)
throw new ArgumentNullException(nameof(policy));
lock (m_Sync)
{
if (!m_Accounts.ContainsKey(policy.AccountId))
throw new NexLedgerValidationException(
$"Unknown ledger account {policy.AccountId}.");
m_TransferPolicies[policy.AccountId] = policy;
return policy;
}
}
public long GetOutgoingTotal(
Guid accountId,
DateTimeOffset fromInclusive,
DateTimeOffset toExclusive)
{
lock (m_Sync)
{
if (!m_Accounts.ContainsKey(accountId))
throw new NexLedgerValidationException(
$"Unknown ledger account {accountId}.");
long total = 0;
checked
{
foreach (NexLedgerTransaction transaction in
m_Transactions.Values.Where(x =>
x.OccurredAt >= fromInclusive &&
x.OccurredAt < toExclusive))
{
foreach (NexLedgerPosting posting in transaction.Postings)
{
if (posting.AccountId == accountId &&
posting.Side == NexLedgerSide.Debit)
{
total += posting.AmountMinor;
}
}
}
}
return total;
}
}
public NexPaymentRequest CreatePaymentRequest(NexPaymentRequest request)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
lock (m_Sync)
{
if (m_PaymentRequests.TryGetValue(request.RequestId, out NexPaymentRequest existing))
return existing;
m_PaymentRequests.Add(request.RequestId, request);
return request;
}
}
public NexPaymentRequest GetPaymentRequest(Guid requestId)
{
lock (m_Sync)
{
m_PaymentRequests.TryGetValue(requestId, out NexPaymentRequest request);
return request;
}
}
public IReadOnlyList<NexPaymentRequest> ListPaymentRequests(
Guid accountId,
int offset,
int limit)
{
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (limit < 1 || limit > 1000)
throw new ArgumentOutOfRangeException(nameof(limit));
lock (m_Sync)
{
return m_PaymentRequests.Values
.Where(x => x.PayeeAccountId == accountId || x.PayerAccountId == accountId)
.OrderByDescending(x => x.CreatedAt)
.ThenByDescending(x => x.RequestId)
.Skip(offset)
.Take(limit)
.ToArray();
}
}
public NexPaymentRequest UpdatePaymentRequest(NexPaymentRequest request)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
lock (m_Sync)
{
if (!m_PaymentRequests.ContainsKey(request.RequestId))
throw new NexLedgerValidationException("Payment request was not found.");
m_PaymentRequests[request.RequestId] = request;
return request;
}
}
public NexCommerceOrder CreateCommerceOrder(NexCommerceOrder order)
{
if (order == null)
throw new ArgumentNullException(nameof(order));
lock (m_Sync)
{
if (m_CommerceOrders.TryGetValue(order.OrderId, out NexCommerceOrder existing))
return existing;
m_CommerceOrders.Add(order.OrderId, order);
return order;
}
}
public NexCommerceOrder GetCommerceOrder(Guid orderId)
{
lock (m_Sync)
{
m_CommerceOrders.TryGetValue(orderId, out NexCommerceOrder order);
return order;
}
}
public IReadOnlyList<NexCommerceOrder> ListCommerceOrders(
Guid accountId,
int offset,
int limit)
{
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (limit < 1 || limit > 1000)
throw new ArgumentOutOfRangeException(nameof(limit));
lock (m_Sync)
{
return m_CommerceOrders.Values
.Where(x => x.BuyerAccountId == accountId || x.SellerAccountId == accountId)
.OrderByDescending(x => x.CreatedAt)
.ThenByDescending(x => x.OrderId)
.Skip(offset)
.Take(limit)
.ToArray();
}
}
public NexCommerceOrder UpdateCommerceOrder(NexCommerceOrder order)
{
if (order == null)
throw new ArgumentNullException(nameof(order));
lock (m_Sync)
{
if (!m_CommerceOrders.ContainsKey(order.OrderId))
throw new NexLedgerValidationException("Commerce order was not found.");
m_CommerceOrders[order.OrderId] = order;
return order;
}
}
public NexLandListing CreateLandListing(NexLandListing listing)
{
if (listing == null)
throw new ArgumentNullException(nameof(listing));
lock (m_Sync)
{
if (m_LandListings.TryGetValue(listing.ListingId, out NexLandListing existing))
return existing;
m_LandListings.Add(listing.ListingId, listing);
return listing;
}
}
public NexLandListing GetLandListing(Guid listingId)
{
lock (m_Sync)
{
m_LandListings.TryGetValue(listingId, out NexLandListing listing);
return listing;
}
}
public IReadOnlyList<NexLandListing> SearchLandListings(
string query,
NexLandListingType? type,
int offset,
int limit)
{
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (limit < 1 || limit > 1000)
throw new ArgumentOutOfRangeException(nameof(limit));
string normalized = (query ?? string.Empty).Trim();
lock (m_Sync)
{
IEnumerable<NexLandListing> result =
m_LandListings.Values.Where(x => x.Active);
if (type.HasValue)
result = result.Where(x => x.ListingType == type.Value);
if (normalized.Length > 0)
{
result = result.Where(x =>
x.RegionName.IndexOf(normalized, StringComparison.OrdinalIgnoreCase) >= 0 ||
x.ParcelName.IndexOf(normalized, StringComparison.OrdinalIgnoreCase) >= 0);
}
return result
.OrderByDescending(x => x.CreatedAt)
.ThenByDescending(x => x.ListingId)
.Skip(offset)
.Take(limit)
.ToArray();
}
}
public NexLandListing UpdateLandListing(NexLandListing listing)
{
if (listing == null)
throw new ArgumentNullException(nameof(listing));
lock (m_Sync)
{
if (!m_LandListings.ContainsKey(listing.ListingId))
throw new NexLedgerValidationException("Land listing was not found.");
m_LandListings[listing.ListingId] = listing;
return listing;
}
}
public NexLandLease CreateLandLease(NexLandLease lease)
{
if (lease == null)
throw new ArgumentNullException(nameof(lease));
lock (m_Sync)
{
if (m_LandLeases.TryGetValue(lease.LeaseId, out NexLandLease existing))
return existing;
m_LandLeases.Add(lease.LeaseId, lease);
return lease;
}
}
public NexLandLease GetLandLease(Guid leaseId)
{
lock (m_Sync)
{
m_LandLeases.TryGetValue(leaseId, out NexLandLease lease);
return lease;
}
}
public IReadOnlyList<NexLandLease> ListLandLeases(
Guid accountId,
int offset,
int limit)
{
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (limit < 1 || limit > 1000)
throw new ArgumentOutOfRangeException(nameof(limit));
lock (m_Sync)
{
return m_LandLeases.Values
.Where(x => x.TenantAccountId == accountId || x.LandlordAccountId == accountId)
.OrderByDescending(x => x.StartsAt)
.ThenByDescending(x => x.LeaseId)
.Skip(offset)
.Take(limit)
.ToArray();
}
}
public NexLandLease UpdateLandLease(NexLandLease lease)
{
if (lease == null)
throw new ArgumentNullException(nameof(lease));
lock (m_Sync)
{
if (!m_LandLeases.ContainsKey(lease.LeaseId))
throw new NexLedgerValidationException("Land lease was not found.");
m_LandLeases[lease.LeaseId] = lease;
return lease;
}
}
public NexLedgerAccountState GetAccountState(
Guid accountId)
{
@@ -549,6 +966,13 @@ namespace NexVerse.Core.Economy
Guid accountId) =>
m_Store.GetBalance(accountId);
public long GetBalanceAt(
Guid accountId,
DateTimeOffset atOrBefore) =>
m_Store.GetBalanceAt(
accountId,
atOrBefore);
public IReadOnlyList<NexLedgerPosting> ListPostings(
Guid accountId,
int offset = 0,
@@ -557,5 +981,18 @@ namespace NexVerse.Core.Economy
accountId,
offset,
limit);
public IReadOnlyList<NexLedgerTransaction> ListTransactions(
Guid accountId,
DateTimeOffset? from = null,
DateTimeOffset? to = null,
int offset = 0,
int limit = 100) =>
m_Store.ListTransactions(
accountId,
from,
to,
offset,
limit);
}
}
@@ -356,17 +356,37 @@ namespace NexVerse.RegionModules.Economy
UUID toUser,
int amount,
MoneyTransactionType type,
string text) =>
MoveMoneyInternal(
string text)
{
string reference =
string.IsNullOrWhiteSpace(text)
? type.ToString()
: text;
if (reference.StartsWith(
"Land purchase:",
StringComparison.OrdinalIgnoreCase))
{
return CommercePaymentInternal(
fromUser,
toUser,
amount,
"LandPurchase",
reference,
"viewer-land-purchase",
Guid.NewGuid(),
out _);
}
return MoveMoneyInternal(
fromUser,
toUser,
amount,
string.IsNullOrWhiteSpace(text)
? type.ToString()
: text,
reference,
"viewer-" +
Guid.NewGuid().ToString("N"),
out _);
}
public bool ObjectGiveMoney(
UUID objectID,
@@ -407,6 +427,164 @@ namespace NexVerse.RegionModules.Economy
EconomyDataRequestHandler;
client.OnMoneyBalanceRequest +=
SendMoneyBalance;
client.OnObjectBuy +=
ObjectBuy;
}
private void ObjectBuy(
IClientAPI remoteClient,
UUID agentID,
UUID sessionID,
UUID groupID,
UUID categoryID,
uint localID,
byte saleType,
int salePrice)
{
if (remoteClient == null ||
remoteClient.AgentId != agentID ||
remoteClient.SessionId != sessionID ||
remoteClient.Scene is not Scene scene)
{
return;
}
SceneObjectPart part =
scene.GetSceneObjectPart(
localID);
if (part == null ||
part.ParentGroup == null ||
part.ParentGroup.IsDeleted)
{
remoteClient.SendAgentAlertMessage(
"Unable to buy now. The object was not found.",
false);
return;
}
SceneObjectGroup group =
part.ParentGroup;
SceneObjectPart root =
group.RootPart;
if (root.ObjectSaleType == (byte)SaleType.Not ||
root.ObjectSaleType != saleType ||
root.SalePrice != salePrice)
{
remoteClient.SendAgentAlertMessage(
"Object sale data changed. Please refresh the object properties and try again.",
false);
return;
}
IBuySellModule buySell =
scene.RequestModuleInterface<IBuySellModule>();
if (buySell == null)
{
remoteClient.SendAgentAlertMessage(
"Object buying is unavailable in this region.",
false);
return;
}
UUID seller =
group.OwnerID;
if (seller.IsZero() ||
seller == agentID)
{
remoteClient.SendAgentAlertMessage(
"This object cannot be purchased from its current owner.",
false);
return;
}
Guid orderId =
Guid.NewGuid();
string paymentError =
string.Empty;
bool paid =
salePrice <= 0 ||
CommercePaymentInternal(
agentID,
seller,
salePrice,
"ObjectSale",
"Object purchase: " +
root.Name,
"object:" +
group.UUID.ToString(),
orderId,
out paymentError);
if (!paid)
{
remoteClient.SendAgentAlertMessage(
string.IsNullOrWhiteSpace(paymentError)
? "NV$ object purchase payment failed."
: paymentError,
false);
return;
}
bool delivered =
buySell.BuyObject(
remoteClient,
categoryID,
localID,
saleType,
salePrice);
if (!delivered)
{
bool refunded =
salePrice <= 0;
string refundError =
string.Empty;
if (salePrice > 0)
{
refunded =
RefundCommerceInternal(
orderId,
"Object delivery failed",
out refundError);
}
if (!refunded)
{
m_Log.ErrorFormat(
"[NEX-ECONOMY-VIEWER]: Object delivery failed and NexCommerce refund {0} also failed: {1}",
orderId,
refundError);
}
remoteClient.SendAgentAlertMessage(
refunded
? "Object delivery failed. The completed NV$ payment was refunded."
: "Object delivery failed and the automatic NV$ refund could not be confirmed. Please contact an administrator with order " +
orderId.ToString("D") +
".",
false);
return;
}
SendBalanceRefresh(agentID);
SendBalanceRefresh(seller);
remoteClient.SendAgentAlertMessage(
salePrice > 0
? "Object purchased for " +
salePrice +
" NV$."
: "Object purchased.",
false);
}
private void ClientClosed(
@@ -484,15 +662,50 @@ namespace NexVerse.RegionModules.Economy
return;
}
bool success =
MoveMoneyInternal(
e.sender,
UUID paymentReceiver =
e.receiver;
bool objectPayment =
TryResolveLocalObjectOwner(
e.receiver,
e.amount,
e.description,
"viewer-event-" +
Guid.NewGuid().ToString("N"),
out string reason);
out UUID objectOwner);
if (objectPayment)
paymentReceiver = objectOwner;
Guid commerceOrderId =
Guid.NewGuid();
string reason;
bool success;
if (objectPayment)
{
success =
CommercePaymentInternal(
e.sender,
paymentReceiver,
e.amount,
"VendorPayment",
string.IsNullOrWhiteSpace(e.description)
? "Inworld object payment"
: e.description,
"object:" +
e.receiver.ToString(),
commerceOrderId,
out reason);
}
else
{
success =
MoveMoneyInternal(
e.sender,
paymentReceiver,
e.amount,
e.description,
"viewer-event-" +
Guid.NewGuid().ToString("N"),
out reason);
}
if (!success)
{
@@ -512,10 +725,31 @@ namespace NexVerse.RegionModules.Economy
SendBalanceRefresh(
e.sender);
SendBalanceRefresh(
e.receiver);
paymentReceiver);
if (IsLocalObject(
e.receiver))
LocateClient(
e.sender)
?.SendAgentAlertMessage(
"NV$ transfer completed: " +
e.amount +
" NV$.",
false);
IClientAPI receiverClient =
LocateClient(
paymentReceiver);
if (receiverClient != null &&
paymentReceiver != e.sender)
{
receiverClient.SendAgentAlertMessage(
"NV$ received: " +
e.amount +
" NV$.",
false);
}
if (objectPayment)
{
try
{
@@ -563,6 +797,160 @@ namespace NexVerse.RegionModules.Economy
}
}
private bool CommercePaymentInternal(
UUID buyer,
UUID seller,
int amount,
string kind,
string reference,
string externalReference,
Guid orderId,
out string reason)
{
reason =
string.Empty;
if (!m_Enabled ||
buyer.IsZero() ||
seller.IsZero() ||
buyer == seller ||
amount <= 0 ||
orderId == Guid.Empty)
{
reason =
"Invalid NV$ commerce payment.";
return false;
}
try
{
if (!EnsureLocalServiceWallet(
buyer,
out reason) ||
!EnsureLocalServiceWallet(
seller,
out reason))
{
return false;
}
byte[] payload =
JsonSerializer.SerializeToUtf8Bytes(
new
{
order_id =
orderId.ToString(),
kind,
buyer_account_id =
buyer.ToString(),
seller_account_id =
seller.ToString(),
amount,
reference =
string.IsNullOrWhiteSpace(reference)
? "NexCommerce payment"
: reference,
external_reference =
externalReference ??
string.Empty
});
using HttpRequestMessage request =
CreateRequest(
HttpMethod.Post,
"/api/v1/commerce/orders");
request.Content =
new ByteArrayContent(
payload);
request.Content.Headers.ContentType =
new MediaTypeHeaderValue(
"application/json");
using HttpResponseMessage response =
m_Http.Send(request);
if (response.IsSuccessStatusCode)
return true;
reason =
ReadErrorMessage(
response);
return false;
}
catch (Exception e)
{
reason =
"NexCommerce service unavailable.";
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Commerce payment {0}->{1} failed: {2}",
buyer,
seller,
e.Message);
return false;
}
}
private bool RefundCommerceInternal(
Guid orderId,
string reasonText,
out string reason)
{
reason =
string.Empty;
try
{
byte[] payload =
JsonSerializer.SerializeToUtf8Bytes(
new
{
reason =
string.IsNullOrWhiteSpace(reasonText)
? "Commerce rollback"
: reasonText
});
using HttpRequestMessage request =
CreateRequest(
HttpMethod.Post,
"/api/v1/commerce/orders/" +
orderId.ToString("D") +
"/refund");
request.Content =
new ByteArrayContent(
payload);
request.Content.Headers.ContentType =
new MediaTypeHeaderValue(
"application/json");
using HttpResponseMessage response =
m_Http.Send(request);
if (response.IsSuccessStatusCode)
return true;
reason =
ReadErrorMessage(
response);
return false;
}
catch (Exception e)
{
reason =
"NexCommerce refund service unavailable.";
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Commerce refund {0} failed: {1}",
orderId,
e.Message);
return false;
}
}
private bool MoveMoneyInternal(
UUID fromUser,
UUID toUser,
@@ -587,6 +975,16 @@ namespace NexVerse.RegionModules.Economy
try
{
if (!EnsureLocalServiceWallet(
fromUser,
out reason) ||
!EnsureLocalServiceWallet(
toUser,
out reason))
{
return false;
}
byte[] payload =
JsonSerializer.SerializeToUtf8Bytes(
new
@@ -749,6 +1147,144 @@ namespace NexVerse.RegionModules.Economy
string.Empty);
}
private bool EnsureLocalServiceWallet(
UUID accountId,
out string reason)
{
reason =
string.Empty;
if (!TryResolveLocalGroup(
accountId,
out string groupName))
{
return true;
}
try
{
byte[] payload =
JsonSerializer.SerializeToUtf8Bytes(
new
{
account_id =
accountId.ToString(),
account_class =
"group",
display_name =
string.IsNullOrWhiteSpace(groupName)
? accountId.ToString()
: groupName
});
using HttpRequestMessage request =
CreateRequest(
HttpMethod.Post,
"/api/v1/economy/accounts/ensure");
request.Content =
new ByteArrayContent(
payload);
request.Content.Headers.ContentType =
new MediaTypeHeaderValue(
"application/json");
using HttpResponseMessage response =
m_Http.Send(request);
if (response.IsSuccessStatusCode)
return true;
reason =
ReadErrorMessage(
response);
return false;
}
catch (Exception e)
{
reason =
"NV$ group wallet provisioning failed.";
m_Log.WarnFormat(
"[NEX-ECONOMY-VIEWER]: Group wallet {0} provisioning failed: {1}",
accountId,
e.Message);
return false;
}
}
private bool TryResolveLocalGroup(
UUID groupId,
out string groupName)
{
groupName =
string.Empty;
if (groupId.IsZero())
return false;
lock (m_Sync)
{
foreach (Scene scene in
m_Scenes.Values)
{
IGroupsModule groups =
scene.RequestModuleInterface<IGroupsModule>();
GroupRecord record =
groups?.GetGroupRecord(
groupId);
if (record == null)
continue;
groupName =
record.GroupName ??
string.Empty;
return true;
}
}
return false;
}
private bool TryResolveLocalObjectOwner(
UUID objectId,
out UUID ownerId)
{
ownerId =
UUID.Zero;
lock (m_Sync)
{
foreach (Scene scene in
m_Scenes.Values)
{
SceneObjectPart part =
scene.GetSceneObjectPart(
objectId);
if (part?.ParentGroup == null ||
part.ParentGroup.IsDeleted)
{
continue;
}
ownerId =
part.ParentGroup.OwnerID;
return !ownerId.IsZero();
}
}
return false;
}
private bool IsLocalObject(
UUID objectId)
{
File diff suppressed because it is too large. Load diff
+149
View File
@@ -146,6 +146,45 @@ namespace NexVerse.Server.Api
return;
}
if (string.Equals(
path,
"/api/v1/economy/accounts/ensure",
StringComparison.OrdinalIgnoreCase))
{
if (!method.Equals("POST", StringComparison.OrdinalIgnoreCase))
{
MethodNotAllowed(response, "POST");
return;
}
if (!Authenticate(
request,
response,
NexScopes.EconomyTransfer,
out NexPrincipal principal,
out UserAccount account))
{
return;
}
if (account != null &&
!principal.HasScope(NexScopes.AdminAll))
{
WriteError(
response,
HttpStatusCode.Forbidden,
"economy_wallet_provision_forbidden",
"Wallet provisioning is restricted to trusted services and administrators.");
return;
}
HandleEnsureWallet(
request,
response,
principal);
return;
}
const string transactionPrefix =
"/api/v1/economy/transactions/";
@@ -619,6 +658,116 @@ namespace NexVerse.Server.Api
}
}
private void HandleEnsureWallet(
IOSHttpRequest request,
IOSHttpResponse response,
NexPrincipal principal)
{
NexEconomyService economy =
RequireEconomy(response);
if (economy == null)
return;
if (!TryBody(
request,
response,
out JsonElement body))
{
return;
}
if (!TryGuid(
body,
"account_id",
out Guid accountId))
{
WriteError(
response,
HttpStatusCode.BadRequest,
"account_id_required",
"account_id is required.");
return;
}
string rawClass =
GetOptionalString(
body,
"account_class")
.Replace("-", string.Empty)
.Replace("_", string.Empty);
NexLedgerAccountClass accountClass;
if (rawClass.Equals("group", StringComparison.OrdinalIgnoreCase))
accountClass = NexLedgerAccountClass.Group;
else if (rawClass.Equals("business", StringComparison.OrdinalIgnoreCase) ||
rawClass.Equals("merchant", StringComparison.OrdinalIgnoreCase))
accountClass = NexLedgerAccountClass.Business;
else if (rawClass.Equals("estate", StringComparison.OrdinalIgnoreCase))
accountClass = NexLedgerAccountClass.Estate;
else if (rawClass.Equals("objectmerchantendpoint", StringComparison.OrdinalIgnoreCase) ||
rawClass.Equals("object", StringComparison.OrdinalIgnoreCase))
accountClass = NexLedgerAccountClass.ObjectMerchantEndpoint;
else
{
WriteError(
response,
HttpStatusCode.BadRequest,
"invalid_account_class",
"account_class must be group, business, estate or object_merchant_endpoint.");
return;
}
try
{
NexLedgerAccount account =
economy.EnsureWalletAccount(
accountId,
accountClass,
GetOptionalString(
body,
"display_name"));
NexLedgerAccountState state =
economy.GetAccountState(
account.AccountId);
m_Audit.Record(
new NexAuditEvent(
principal.Subject,
"economy.wallet.ensure",
"ledger-account:" +
account.AccountId.ToString("D"),
Correlation(response),
new Dictionary<string, string>
{
["account_class"] =
account.AccountClass.ToString()
}));
WriteJson(
response,
new
{
account =
AccountPayload(
account,
economy.GetBalance(account.AccountId),
state),
correlation_id =
Correlation(response)
},
HttpStatusCode.OK);
}
catch (Exception e)
{
WriteEconomyFailure(
response,
e);
}
}
private void HandleTransaction(
IOSHttpResponse response,
Guid transactionId,
@@ -413,6 +413,35 @@ namespace NexVerse.Server.Api
"OpenGenesisLINK NV$ Economy API"),
true);
NexBankingCommerceApi bankingCommerceApi =
new NexBankingCommerceApi(
authenticator,
userAccounts,
auditSink,
() =>
NexEconomyConnector.Current?.Enabled == true
? NexEconomyConnector.Current.Economy
: null);
server.AddSimpleStreamHandler(
new SimpleStreamHandler(
"/api/v1/banking",
apiGate.Wrap(bankingCommerceApi.HandleBanking),
"OpenGenesisLINK NV$ Banking API"),
true);
server.AddSimpleStreamHandler(
new SimpleStreamHandler(
"/api/v1/commerce",
apiGate.Wrap(bankingCommerceApi.HandleCommerce),
"OpenGenesisLINK NexCommerce API"),
true);
server.AddSimpleStreamHandler(
new SimpleStreamHandler(
"/api/v1/land-commerce",
apiGate.Wrap(bankingCommerceApi.HandleLandCommerce),
"OpenGenesisLINK Land Commerce API"),
true);
NexInventoryApi inventoryApi =
new NexInventoryApi(
inventory,
@@ -188,6 +188,50 @@ namespace NexVerse.Server.Api
("post", "NV$-Transaktion als neue Gegenbuchung reversieren", "admin:*", "201")),
["/api/v1/economy/accounts/{accountId}/status"] = AuthenticatedOperations(
("post", "NV$-Konto sperren, freigeben oder schließen", "admin:*", "200")),
["/api/v1/economy/accounts/ensure"] = AuthenticatedOperations(
("post", "Vertrauenswürdiges Gruppen-, Business-, Estate- oder Objekt-Wallet provisionieren", "economy:transfer (service/admin)", "200")),
["/api/v1/banking/transactions"] = AuthenticatedOperations(
("get", "NV$-Transaktionshistorie des eigenen oder autorisierten Kontos lesen", "economy:read", "200")),
["/api/v1/banking/statements"] = AuthenticatedOperations(
("get", "NV$-Kontoauszug mit Anfangs-/Endsaldo erzeugen", "economy:read", "200")),
["/api/v1/banking/reconciliation"] = AuthenticatedOperations(
("get", "Ledger-Saldo aus unveränderlichen Buchungen abgleichen", "economy:read", "200")),
["/api/v1/banking/transfers"] = AuthenticatedOperations(
("post", "NV$-Bankingtransfer per Konto-ID oder NVBAN mit Limits/Gebühren ausführen", "economy:transfer", "201")),
["/api/v1/banking/payment-requests"] = AuthenticatedOperations(
("get", "Zahlungsanforderungen des Kontos lesen", "economy:read", "200"),
("post", "Zahlungsanforderung erstellen", "economy:transfer", "201")),
["/api/v1/banking/payment-requests/{requestId}/pay"] = AuthenticatedOperations(
("post", "Zahlungsanforderung bezahlen", "economy:transfer", "200")),
["/api/v1/banking/payment-requests/{requestId}/cancel"] = AuthenticatedOperations(
("post", "Eigene Zahlungsanforderung stornieren", "economy:transfer", "200")),
["/api/v1/banking/accounts/{accountId}/policy"] = AuthenticatedOperations(
("get", "Transferlimits und Gebührenpolicy lesen", "economy:read", "200"),
("put", "Transferlimits und Gebührenpolicy administrativ setzen", "admin:*", "200")),
["/api/v1/banking/escrow/{escrowId}/fund"] = AuthenticatedOperations(
("post", "NV$ in Escrow einzahlen", "economy:transfer", "201")),
["/api/v1/banking/escrow/{escrowId}/release"] = AuthenticatedOperations(
("post", "NV$ aus Escrow freigeben", "economy:transfer (service/admin)", "201")),
["/api/v1/commerce/orders"] = AuthenticatedOperations(
("get", "NexCommerce-Kaufhistorie lesen", "economy:read", "200"),
("post", "NexCommerce-Auftrag ausführen", "economy:transfer", "201")),
["/api/v1/commerce/orders/{orderId}"] = AuthenticatedOperations(
("get", "NexCommerce-Auftrag lesen", "economy:read", "200")),
["/api/v1/commerce/orders/{orderId}/refund"] = AuthenticatedOperations(
("post", "Commerce-Auftrag als Ledger-Gegenbuchung erstatten", "economy:transfer (service/admin)", "200")),
["/api/v1/land-commerce/listings"] = AuthenticatedOperations(
("get", "Landangebote durchsuchen", "economy:read", "200"),
("post", "Land-/Mietangebot administrativ anlegen", "admin:*", "201")),
["/api/v1/land-commerce/listings/{listingId}/deactivate"] = AuthenticatedOperations(
("post", "Landangebot deaktivieren", "admin:*", "200")),
["/api/v1/land-commerce/listings/{listingId}/purchase"] = AuthenticatedOperations(
("post", "Landangebot über NexCommerce kaufen", "economy:transfer", "201")),
["/api/v1/land-commerce/listings/{listingId}/lease"] = AuthenticatedOperations(
("post", "Mietvertrag anlegen und erste Miete begleichen", "economy:transfer", "201")),
["/api/v1/land-commerce/leases"] = AuthenticatedOperations(
("get", "Mietverträge des Kontos lesen", "economy:read", "200")),
["/api/v1/land-commerce/leases/{leaseId}/pay"] = AuthenticatedOperations(
("post", "Fällige wiederkehrende Landmiete begleichen", "economy:transfer", "200")),
["/api/v1/regions"] = AuthenticatedOperations(
("get", "Auswählbare Home-/Startregionen durchsuchen", "regions:read", "200"),
("post", "NexVerse-verwaltete Region auf einem Simulator-Node erstellen", "regions:manage", "202")),
@@ -377,6 +421,30 @@ namespace NexVerse.Server.Api
"EconomyAccountStatusRequest",
"EconomyAccountStateResponse",
"200");
ApplyJsonContract(paths, "/api/v1/economy/accounts/ensure", "post", "EconomyWalletEnsureRequest", "EconomyBalanceResponse", "200");
ApplyJsonContract(paths, "/api/v1/banking/transactions", "get", null, "BankingTransactionsResponse", "200");
ApplyJsonContract(paths, "/api/v1/banking/statements", "get", null, "BankingStatementResponse", "200");
ApplyJsonContract(paths, "/api/v1/banking/reconciliation", "get", null, "BankingReconciliationResponse", "200");
ApplyJsonContract(paths, "/api/v1/banking/transfers", "post", "BankingTransferRequest", "EconomyTransferResponse", "201");
ApplyJsonContract(paths, "/api/v1/banking/payment-requests", "get", null, "PaymentRequestListResponse", "200");
ApplyJsonContract(paths, "/api/v1/banking/payment-requests", "post", "PaymentRequestCreateRequest", "PaymentRequestResponse", "201");
ApplyJsonContract(paths, "/api/v1/banking/payment-requests/{requestId}/pay", "post", null, "PaymentRequestResponse", "200");
ApplyJsonContract(paths, "/api/v1/banking/payment-requests/{requestId}/cancel", "post", null, "PaymentRequestResponse", "200");
ApplyJsonContract(paths, "/api/v1/banking/accounts/{accountId}/policy", "get", null, "BankingPolicyResponse", "200");
ApplyJsonContract(paths, "/api/v1/banking/accounts/{accountId}/policy", "put", "BankingPolicyRequest", "BankingPolicyResponse", "200");
ApplyJsonContract(paths, "/api/v1/banking/escrow/{escrowId}/fund", "post", "EscrowTransferRequest", "EconomyTransactionResponse", "201");
ApplyJsonContract(paths, "/api/v1/banking/escrow/{escrowId}/release", "post", "EscrowTransferRequest", "EconomyTransactionResponse", "201");
ApplyJsonContract(paths, "/api/v1/commerce/orders", "get", null, "CommerceOrderListResponse", "200");
ApplyJsonContract(paths, "/api/v1/commerce/orders", "post", "CommerceOrderRequest", "CommerceOrderResponse", "201");
ApplyJsonContract(paths, "/api/v1/commerce/orders/{orderId}", "get", null, "CommerceOrderResponse", "200");
ApplyJsonContract(paths, "/api/v1/commerce/orders/{orderId}/refund", "post", "EconomyReverseRequest", "CommerceOrderResponse", "200");
ApplyJsonContract(paths, "/api/v1/land-commerce/listings", "get", null, "LandListingListResponse", "200");
ApplyJsonContract(paths, "/api/v1/land-commerce/listings", "post", "LandListingRequest", "LandListingResponse", "201");
ApplyJsonContract(paths, "/api/v1/land-commerce/listings/{listingId}/deactivate", "post", "LandSellerRequest", "LandListingResponse", "200");
ApplyJsonContract(paths, "/api/v1/land-commerce/listings/{listingId}/purchase", "post", "LandPurchaseRequest", "CommerceOrderResponse", "201");
ApplyJsonContract(paths, "/api/v1/land-commerce/listings/{listingId}/lease", "post", "LandLeaseCreateRequest", "LandLeaseResponse", "201");
ApplyJsonContract(paths, "/api/v1/land-commerce/leases", "get", null, "LandLeaseListResponse", "200");
ApplyJsonContract(paths, "/api/v1/land-commerce/leases/{leaseId}/pay", "post", "LandRentPayRequest", "LandLeaseResponse", "200");
ApplyJsonContract(
paths,
@@ -2222,6 +2290,150 @@ namespace NexVerse.Server.Api
["correlation_id"] = new { type = "string" }
}
},
["EconomyWalletEnsureRequest"] = new
{
type = "object",
required = new[] { "account_id", "account_class" },
properties = new Dictionary<string, object>
{
["account_id"] = new { type = "string", format = "uuid" },
["account_class"] = new { type = "string", @enum = new[] { "group", "business", "estate", "object_merchant_endpoint" } },
["display_name"] = new { type = "string", maxLength = 255 }
}
},
["BankingTransferRequest"] = new
{
type = "object",
required = new[] { "amount" },
properties = new Dictionary<string, object>
{
["from_account_id"] = new { type = "string", format = "uuid" },
["to_account_id"] = new { type = "string", format = "uuid" },
["to_nvban"] = new { type = "string", pattern = "^NVBAN-" },
["amount"] = new { type = "integer", format = "int64", minimum = 1 },
["reference"] = new { type = "string", maxLength = 255 }
}
},
["PaymentRequestCreateRequest"] = new
{
type = "object",
required = new[] { "payer_account_id", "amount", "reference" },
properties = new Dictionary<string, object>
{
["payee_account_id"] = new { type = "string", format = "uuid" },
["payer_account_id"] = new { type = "string", format = "uuid" },
["amount"] = new { type = "integer", format = "int64", minimum = 1 },
["reference"] = new { type = "string", maxLength = 255 },
["expires_at"] = new { type = "string", format = "date-time" }
}
},
["BankingPolicyRequest"] = new
{
type = "object",
properties = new Dictionary<string, object>
{
["max_per_transfer"] = new { type = "integer", format = "int64", minimum = 0 },
["daily_outgoing_limit"] = new { type = "integer", format = "int64", minimum = 0 },
["flat_fee"] = new { type = "integer", format = "int64", minimum = 0 },
["fee_account_id"] = new { type = "string", format = "uuid" }
}
},
["EscrowTransferRequest"] = new
{
type = "object",
required = new[] { "amount" },
properties = new Dictionary<string, object>
{
["from_account_id"] = new { type = "string", format = "uuid" },
["to_account_id"] = new { type = "string", format = "uuid" },
["amount"] = new { type = "integer", format = "int64", minimum = 1 },
["reference"] = new { type = "string", maxLength = 255 }
}
},
["CommerceOrderRequest"] = new
{
type = "object",
required = new[] { "kind", "seller_account_id", "amount", "reference" },
properties = new Dictionary<string, object>
{
["order_id"] = new { type = "string", format = "uuid" },
["kind"] = new { type = "string", @enum = new[] { "VendorPayment", "ObjectSale", "MarketplacePurchase", "LandPurchase", "EventTicket", "Rental", "MerchantRefund" } },
["buyer_account_id"] = new { type = "string", format = "uuid" },
["seller_account_id"] = new { type = "string", format = "uuid" },
["amount"] = new { type = "integer", format = "int64", minimum = 1 },
["reference"] = new { type = "string", maxLength = 255 },
["external_reference"] = new { type = "string", maxLength = 255 }
}
},
["LandListingRequest"] = new
{
type = "object",
required = new[] { "type", "region_id", "parcel_id", "parcel_local_id", "seller_account_id", "area", "price" },
properties = new Dictionary<string, object>
{
["listing_id"] = new { type = "string", format = "uuid" },
["type"] = new { type = "string", @enum = new[] { "Sale", "Rental" } },
["region_id"] = new { type = "string", format = "uuid" },
["region_name"] = new { type = "string" },
["parcel_id"] = new { type = "string", format = "uuid" },
["parcel_local_id"] = new { type = "integer", minimum = 1 },
["parcel_name"] = new { type = "string" },
["seller_account_id"] = new { type = "string", format = "uuid" },
["estate_id"] = new { type = "string", format = "uuid" },
["area"] = new { type = "integer", minimum = 1 },
["price"] = new { type = "integer", format = "int64", minimum = 1 },
["rental_period_days"] = new { type = "integer", minimum = 0 }
}
},
["LandSellerRequest"] = new
{
type = "object",
required = new[] { "seller_account_id" },
properties = new Dictionary<string, object>
{
["seller_account_id"] = new { type = "string", format = "uuid" }
}
},
["LandPurchaseRequest"] = new
{
type = "object",
properties = new Dictionary<string, object>
{
["buyer_account_id"] = new { type = "string", format = "uuid" },
["order_id"] = new { type = "string", format = "uuid" }
}
},
["LandLeaseCreateRequest"] = new
{
type = "object",
required = new[] { "periods" },
properties = new Dictionary<string, object>
{
["tenant_account_id"] = new { type = "string", format = "uuid" },
["periods"] = new { type = "integer", minimum = 1, maximum = 120 },
["order_id"] = new { type = "string", format = "uuid" }
}
},
["LandRentPayRequest"] = new
{
type = "object",
properties = new Dictionary<string, object>
{
["order_id"] = new { type = "string", format = "uuid" }
}
},
["BankingTransactionsResponse"] = new { type = "object" },
["BankingStatementResponse"] = new { type = "object" },
["BankingReconciliationResponse"] = new { type = "object" },
["PaymentRequestListResponse"] = new { type = "object" },
["PaymentRequestResponse"] = new { type = "object" },
["BankingPolicyResponse"] = new { type = "object" },
["CommerceOrderListResponse"] = new { type = "object" },
["CommerceOrderResponse"] = new { type = "object" },
["LandListingListResponse"] = new { type = "object" },
["LandListingResponse"] = new { type = "object" },
["LandLeaseListResponse"] = new { type = "object" },
["LandLeaseResponse"] = new { type = "object" },
["EconomyTransferRequest"] = new
{
type = "object",
@@ -1735,19 +1735,85 @@ namespace OpenSim.Region.CoreModules.World.Land
public void EventManagerOnLandBuy(Object o, EventManager.LandBuyArgs e)
{
if (e.economyValidated && e.landValidated)
if (e == null ||
!e.landValidated)
{
ILandObject land;
lock (m_landList)
{
if (!m_landList.TryGetValue(e.parcelLocalID, out land) || land is null)
return;
}
land.UpdateLandSold(e.agentId, e.groupId, e.groupOwned, (uint)e.transactionID, e.parcelPrice, e.parcelArea);
m_scene.ForEachClient(SendParcelOverlay);
land.SendLandUpdateToAvatars();
return;
}
ILandObject land;
lock (m_landList)
{
if (!m_landList.TryGetValue(e.parcelLocalID, out land) || land is null)
return;
}
if (!e.economyValidated)
{
if (e.parcelPrice <= 0)
{
e.economyValidated = true;
}
else
{
IMoneyModule money =
m_scene.RequestModuleInterface<IMoneyModule>();
string description =
String.Format(
"Land purchase: {0} in {1}",
land.LandData.Name,
m_scene.RegionInfo.RegionName);
bool paid =
money != null &&
money.AmountCovered(
e.agentId,
e.parcelPrice) &&
money.MoveMoney(
e.agentId,
e.parcelOwnerID,
e.parcelPrice,
default(MoneyTransactionType),
description);
if (!paid)
{
ScenePresence buyer =
m_scene.GetScenePresence(
e.agentId);
buyer?.ControllingClient
?.SendAgentAlertMessage(
"Land purchase failed because the NV$ payment could not be completed.",
true);
return;
}
e.amountDebited =
e.parcelPrice;
e.transactionID =
e.agentId.GetHashCode();
e.economyValidated =
true;
}
}
if (!e.economyValidated)
return;
land.UpdateLandSold(
e.agentId,
e.groupId,
e.groupOwned,
(uint)e.transactionID,
e.parcelPrice,
e.parcelArea);
m_scene.ForEachClient(
SendParcelOverlay);
land.SendLandUpdateToAvatars();
}
// After receiving a land buy packet, first the data needs to
+11
View File
@@ -93,3 +93,14 @@ OpenGenesisLINK verwendet fuer virtuelle Kontokennungen das eigene Schema `NVBAN
Die Kennung wird deterministisch aus der unveraenderlichen Ledger-Konto-UUID abgeleitet und anschliessend dauerhaft 1:1 in `ogl_ledger_virtual_accounts` gespeichert. Ledger-Schema v3 erzwingt Eindeutigkeit sowohl fuer die Konto-UUID als auch fuer die virtuelle Kennung. Die Kennung ist ein Alias fuer ein bestehendes NV$-Wallet; sie erzeugt kein zweites Saldo- oder Buchungssystem.
`NexEconomyService.EnsureVirtualBankAccount()` bleibt die Policy-Grenze. World API und spaetere Banking-Funktionen greifen nicht direkt auf die SQL-Tabelle zu. `GET /api/v1/economy/virtual-account` liefert die eigene bzw. autorisiert ausgewaehlte NVBAN-Kennung mit `economy:read` und enthaelt einen ausdruecklichen Hinweis, dass es sich nicht um ein reales Bankkonto oder eine IBAN handelt.
## Banking, NexCommerce und Landhandel (Roadmap 10.3–10.6)
Ledger-Schema v4 ergaenzt ausschliesslich Workflow-Zustaende neben dem unveraenderlichen Journal: Transfer-Policies, Zahlungsanforderungen, Commerce-Auftraege, Landangebote und Mietvertraege. Die Tabellen `ogl_ledger_transactions` und `ogl_ledger_postings` bleiben append-only.
`BankingTransfer` erzwingt Kontostatus, Deckung, optionales Transaktionslimit, Tageslimit und eine optionale feste Gebuehr. Statements und Reconciliation werden aus den unveraenderlichen Buchungen abgeleitet. Refunds erzeugen Gegenbuchungen; es gibt weiterhin keinen produktiven Pfad, der historische Journalzeilen editiert.
NexCommerce vereinheitlicht Vendor-Zahlungen, Objektverkaeufe, Marketplace, Landkauf, Eventtickets, Mieten und Merchant-Refunds ueber persistente Orders, die auf ihre Ledger-Transaktionen zeigen. Der Viewer und Simulator behalten keine eigene Geld-Datenbank.
Der Landhandel trennt Katalog und Weltzustand: Listings/Leases sind OpenGenesisLINK-Workflowdaten; die eigentlichen Parcel-Rechte bleiben im nativen LandManagementModule. Beim Viewer-Landkauf wird der Eigentumswechsel erst nach erfolgreichem NV$-Settlement ausgefuehrt.
+46 -40
View File
@@ -957,7 +957,7 @@ These identifiers must never be represented as real-world bank accounts.
- [x] dedicated non-IBAN `NVBAN` scheme with an unmistakable `NVBAN-` prefix and restricted human-readable alphabet;
- [x] deterministic collision-resistant identifier derivation bound to the immutable ledger account UUID;
- [x] one-to-one persistent mapping in ledger schema v3 for SQLite, MariaDB/MySQL and PostgreSQL;
- [x] one-to-one persistent mapping introduced in ledger schema v3 and retained in current schema v4 for SQLite, MariaDB/MySQL and PostgreSQL;
- [x] in-memory reference-store support and regression coverage for assignment, idempotency, reverse lookup and SQL persistence;
- [x] policy-bound `NexEconomyService` access; API code never writes the mapping table directly;
- [x] authenticated `GET /api/v1/economy/virtual-account` World API contract using `economy:read`;
@@ -966,57 +966,63 @@ These identifiers must never be represented as real-world bank accounts.
### 10.3 Banking functions
- balances;
- transaction history;
- statements;
- transfers;
- payment requests;
- refunds;
- escrow;
- limits;
- fees;
- recurring payments later;
- account locking;
- reconciliation;
- audit trails.
**Status: completed on the 0.9.3.6 development line.** Generic scheduled/recurring payments remain the explicitly deferred post-foundation item; recurring land rent has a persistent due-date model in 10.5.
- [x] balances through the immutable ledger;
- [x] bounded transaction history with account authorization;
- [x] date-bounded statements with opening/closing balances;
- [x] idempotent banking transfers by ledger UUID or OpenGenesisLINK `NVBAN`;
- [x] persistent payment requests with pay/cancel/expiry state;
- [x] refunds as append-only reversals;
- [x] dedicated escrow accounts with controlled fund/release flows;
- [x] per-transfer and daily outgoing limits;
- [x] optional flat transfer fees routed to an explicit fee wallet;
- [x] account locking from the 10.1 lifecycle remains enforced by every banking transfer;
- [x] reconciliation recomputes account balance from immutable postings;
- [x] World API banking mutations emit persistent audit events through the existing audit sink;
- [x] generic recurring payments remain intentionally deferred as originally specified; the storage/service design does not fake a scheduler.
### 10.4 Viewer economy compatibility
Support Firestorm-visible flows including:
- balance;
- pay resident;
- pay object;
- buy object;
- buy contents;
- land purchase;
- group accounting where applicable;
- transaction notifications.
- [x] balance through the central World API;
- [x] pay resident;
- [x] pay object, resolving the local object owner while still raising `OnObjectPaid`;
- [x] buy object with price/sale-type validation and compensating refund when object delivery fails;
- [x] buy contents through the authoritative `IBuySellModule` sale-type path after NV$ settlement;
- [x] land purchase: the native parcel ownership commit runs only after successful NV$ settlement;
- [x] group accounting: local groups are provisioned as central NV$ group wallets on demand;
- [x] transaction notifications through balance refreshes and explicit purchase/payment failure/success messages;
- [x] simulator remains database-isolated; all money/commerce operations cross the authenticated World API.
### 10.5 Land commerce
- parcel for sale;
- buy land;
- abandon land;
- transfer land;
- rent/lease model;
- recurring rent;
- land listing;
- land search;
- purchase history;
- estate restrictions.
- [x] native parcel-for-sale state remains authoritative in `LandManagementModule`;
- [x] buy land is settlement-gated before `UpdateLandSold`;
- [x] native abandon-land flow remains authoritative and unchanged by the economy layer;
- [x] native parcel transfer/deed flow remains authoritative and unchanged by the economy layer;
- [x] persistent sale/rental listing model;
- [x] persistent lease model with tenant, landlord, term, rent, next due date and last payment;
- [x] recurring rent settlement is represented as explicit NexCommerce rental transactions at each due date;
- [x] land listing creation/deactivation;
- [x] bounded land search by region/parcel name and listing type;
- [x] land purchase/rental history is available through NexCommerce orders;
- [x] native parcel/estate permissions remain the authority for actual parcel sale/ownership changes; the catalog cannot bypass them.
### 10.6 NexCommerce
Unify:
**Status: completed as the common transaction/order layer.**
- inworld vendor payments;
- object sales;
- marketplace purchases;
- land purchases;
- event tickets;
- rentals;
- merchant refunds.
- [x] inworld vendor/object payments;
- [x] object sales;
- [x] marketplace purchases;
- [x] land purchases;
- [x] event-ticket orders;
- [x] rentals;
- [x] merchant refunds as immutable ledger reversals;
- [x] common persistent order state links every completed/refunded commerce operation to its ledger transaction;
- [x] service remains policy-bound through `NexEconomyService`; no commerce endpoint can append arbitrary journal entries.
---
+40
View File
@@ -658,3 +658,43 @@ RequestTimeoutMilliseconds = 3000
```
The API key should contain only the scopes required by the simulator, normally `economy:read` and `economy:transfer`. The region process never receives the SQL connection string and never opens the ledger database. `IMoneyModule` balance and transfer calls are translated into the World API contract.
## NV$ Banking API — Roadmap 10.3
The banking surface is hosted below `/api/v1/banking` and remains a policy adapter over `NexEconomyService`; it has no SQL or raw journal-append access.
- `GET /api/v1/banking/transactions` — bounded account transaction history.
- `GET /api/v1/banking/statements` — date-bounded statement with opening/closing balances and ledger transactions.
- `GET /api/v1/banking/reconciliation` — recompute and compare the immutable-posting balance.
- `POST /api/v1/banking/transfers` — idempotent transfer to `to_account_id` or OpenGenesisLINK-only `to_nvban`; transfer policy/limits/fees are applied centrally.
- `GET|POST /api/v1/banking/payment-requests` and `POST .../{id}/pay|cancel` — persistent payment-request lifecycle.
- `GET|PUT /api/v1/banking/accounts/{accountId}/policy` — transfer limits and optional fee wallet; writes require `admin:*`.
- `POST /api/v1/banking/escrow/{escrowId}/fund|release` — controlled escrow movement.
Generic scheduled recurring payments remain intentionally deferred by the original roadmap. Land leases provide the first persisted due-date/recurring-payment use case without introducing a background scheduler into the ledger.
## NexCommerce API — Roadmap 10.6
`/api/v1/commerce/orders` is the common order/transaction layer for vendor payments, object sales, marketplace purchases, land purchases, event tickets and rentals. Every completed order references its immutable ledger payment transaction. A merchant refund creates a ledger reversal and moves the order into `refunded`; historical payment journal rows are never edited or deleted.
Trusted simulator/service principals can create commerce orders with `economy:transfer`. Resident bearer tokens are restricted to their own buyer wallet. Refunds require a trusted service principal or administrator.
## Land Commerce API — Roadmap 10.5
The catalog/workflow API is hosted at `/api/v1/land-commerce`:
- `GET|POST /listings` — search or administratively create sale/rental listings.
- `POST /listings/{id}/deactivate` — retire a listing.
- `POST /listings/{id}/purchase` — settle a sale through NexCommerce.
- `POST /listings/{id}/lease` — create a fixed-term rental and settle its first rent period.
- `GET /leases` — account lease history.
- `POST /leases/{id}/pay` — settle a due recurring rent period.
The API catalog does not replace the simulator's parcel authority. Native parcel-for-sale flags, authorized buyer checks, abandon/deed/transfer behavior and estate/parcel permissions remain authoritative. The simulator land-buy path now refuses to call `UpdateLandSold` until the active money module confirms successful NV$ settlement.
## Firestorm / Viewer commerce — Roadmap 10.4
`NexVerseMoneyModule` remains the database-isolated `IMoneyModule` adapter. Resident payments use the World API; local object payments resolve the object owner and are recorded as NexCommerce vendor orders while preserving `OnObjectPaid`. Viewer object purchases validate current sale type/price, settle an `ObjectSale` order and then call the authoritative `IBuySellModule`; failed delivery triggers a compensating NexCommerce refund. SaleType Contents therefore uses the native contents-delivery implementation after settlement.
Local groups are provisioned on demand as central NV$ `Group` wallets through the trusted `POST /api/v1/economy/accounts/ensure` service endpoint. Native parcel purchases route their payment through NexCommerce before ownership is changed.
@@ -20,6 +20,7 @@
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerModel.cs" Link="NexLedgerModel.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerAccountState.cs" Link="NexLedgerAccountState.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexVirtualBankAccount.cs" Link="NexVirtualBankAccount.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexEconomyWorkflow.cs" Link="NexEconomyWorkflow.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerStore.cs" Link="NexLedgerStore.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerSqlStore.cs" Link="NexLedgerSqlStore.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerSqlRuntime.cs" Link="NexLedgerSqlRuntime.cs" />
+365 -1
View File
@@ -316,6 +316,336 @@ internal static class Program
label + ": long-reason adjustment roundtrip mismatch");
}
private static void RunBankingCommerceRegression(
INexLedgerStore store,
INexLedgerAccountStateStore stateStore,
string label)
{
NexDoubleEntryLedger ledger =
new NexDoubleEntryLedger(store);
NexEconomyService economy =
new NexEconomyService(
ledger,
stateStore);
Guid systemId = Guid.NewGuid();
Guid payerId = Guid.NewGuid();
Guid merchantId = Guid.NewGuid();
Guid feeId = Guid.NewGuid();
Guid escrowId = Guid.NewGuid();
Require(
ledger.TryCreateAccount(
new NexLedgerAccount(
systemId,
NexLedgerAccountClass.System,
NexLedgerSide.Debit,
"system:banking:" + label + ":" + systemId.ToString("N"),
label + " banking issuance")),
label + ": banking system account not created");
economy.EnsureResidentAccount(
payerId,
label + " banking payer");
economy.EnsureWalletAccount(
merchantId,
NexLedgerAccountClass.Business,
label + " merchant");
economy.EnsureWalletAccount(
feeId,
NexLedgerAccountClass.Business,
label + " fee wallet");
economy.AdministrativeAdjustment(
payerId,
systemId,
5000,
"ci-admin",
"banking regression funding");
economy.SetTransferPolicy(
new NexAccountTransferPolicy(
payerId,
1000,
5000,
5,
feeId));
Guid bankingTransactionId =
Guid.NewGuid();
NexLedgerAppendResult banking =
economy.BankingTransfer(
payerId,
merchantId,
100,
"BANK-TRANSFER",
label,
bankingTransactionId);
Require(
banking.Created &&
economy.GetBalance(payerId) == 4895 &&
economy.GetBalance(merchantId) == 100 &&
economy.GetBalance(feeId) == 5,
label + ": banking transfer/fee balances mismatch");
Require(
economy.BankingTransfer(
payerId,
merchantId,
100,
"BANK-TRANSFER",
label,
bankingTransactionId).Status ==
NexLedgerAppendStatus.Duplicate &&
economy.GetBalance(payerId) == 4895,
label + ": banking transfer retry was not idempotent");
RequireThrows<NexLedgerPolicyException>(
() => economy.BankingTransfer(
payerId,
merchantId,
1001,
"LIMIT-REJECT"),
label + ": per-transfer limit was not enforced");
NexPaymentRequest request =
economy.CreatePaymentRequest(
merchantId,
payerId,
200,
"PAYMENT-REQUEST");
NexPaymentRequest paid =
economy.PayPaymentRequest(
request.RequestId,
payerId,
label);
Require(
paid.Status == NexPaymentRequestStatus.Paid &&
paid.PaymentTransactionId != Guid.Empty &&
economy.GetBalance(payerId) == 4690 &&
economy.GetBalance(merchantId) == 300 &&
economy.GetBalance(feeId) == 10,
label + ": payment request settlement mismatch");
NexBankStatement statement =
economy.GetStatement(
payerId,
DateTimeOffset.UtcNow.AddDays(-1),
DateTimeOffset.UtcNow.AddDays(1));
Require(
statement.OpeningBalance == 0 &&
statement.ClosingBalance == 4690 &&
statement.Transactions.Count >= 3,
label + ": statement balances/history mismatch");
NexReconciliationReport reconciliation =
economy.ReconcileAccount(
payerId);
Require(
reconciliation.Balanced &&
reconciliation.DerivedBalance ==
reconciliation.RecomputedBalance,
label + ": reconciliation failed");
economy.FundEscrow(
payerId,
escrowId,
300,
"ESCROW-FUND",
label,
Guid.NewGuid());
economy.ReleaseEscrow(
escrowId,
merchantId,
100,
"ESCROW-RELEASE",
label,
Guid.NewGuid());
Require(
economy.GetBalance(escrowId) == 200 &&
economy.GetBalance(payerId) == 4390 &&
economy.GetBalance(merchantId) == 400,
label + ": escrow balances mismatch");
Guid commerceOrderId =
Guid.NewGuid();
NexCommerceOrder commerce =
economy.ExecuteCommerceOrder(
commerceOrderId,
NexCommerceKind.MarketplacePurchase,
payerId,
merchantId,
150,
"MARKETPLACE",
"ci-marketplace",
label);
Require(
commerce.Status == NexCommerceOrderStatus.Completed &&
commerce.PaymentTransactionId != Guid.Empty &&
economy.GetBalance(payerId) == 4235 &&
economy.GetBalance(merchantId) == 550 &&
economy.GetBalance(feeId) == 15,
label + ": commerce settlement mismatch");
NexCommerceOrder refunded =
economy.RefundCommerceOrder(
commerceOrderId,
"ci-admin",
"merchant refund");
Require(
refunded.Status == NexCommerceOrderStatus.Refunded &&
refunded.RefundTransactionId != Guid.Empty &&
economy.GetBalance(payerId) == 4390 &&
economy.GetBalance(merchantId) == 400 &&
economy.GetBalance(feeId) == 10,
label + ": commerce refund mismatch");
Guid saleListingId =
Guid.NewGuid();
NexLandListing sale =
economy.CreateLandListing(
new NexLandListing(
saleListingId,
NexLandListingType.Sale,
Guid.NewGuid(),
label + " region",
Guid.NewGuid(),
101,
label + " parcel sale",
merchantId,
Guid.NewGuid(),
1024,
250));
Guid landOrderId =
Guid.NewGuid();
NexCommerceOrder landPurchase =
economy.PurchaseLandListing(
sale.ListingId,
payerId,
landOrderId,
label);
Require(
landPurchase.Kind == NexCommerceKind.LandPurchase &&
landPurchase.Status == NexCommerceOrderStatus.Completed &&
economy.GetLandListing(sale.ListingId)?.Active == false &&
economy.GetBalance(payerId) == 4135 &&
economy.GetBalance(merchantId) == 650 &&
economy.GetBalance(feeId) == 15,
label + ": land purchase mismatch");
Require(
economy.PurchaseLandListing(
sale.ListingId,
payerId,
landOrderId,
label).PaymentTransactionId ==
landPurchase.PaymentTransactionId &&
economy.GetBalance(payerId) == 4135,
label + ": land purchase retry was not idempotent");
NexLandListing rental =
economy.CreateLandListing(
new NexLandListing(
Guid.NewGuid(),
NexLandListingType.Rental,
Guid.NewGuid(),
label + " rental region",
Guid.NewGuid(),
202,
label + " rental parcel",
merchantId,
Guid.NewGuid(),
512,
50,
7));
Guid leaseOrderId =
Guid.NewGuid();
NexLandLease lease =
economy.CreateLandLease(
rental.ListingId,
payerId,
2,
leaseOrderId,
label);
Require(
lease.Active &&
lease.TenantAccountId == payerId &&
lease.LandlordAccountId == merchantId &&
lease.RentMinor == 50 &&
economy.GetLandLease(lease.LeaseId) != null &&
economy.GetBalance(payerId) == 4080 &&
economy.GetBalance(merchantId) == 700 &&
economy.GetBalance(feeId) == 20,
label + ": land lease initial settlement mismatch");
Require(
economy.CreateLandLease(
rental.ListingId,
payerId,
2,
leaseOrderId,
label).LeaseId ==
lease.LeaseId &&
economy.GetBalance(payerId) == 4080,
label + ": land lease retry was not idempotent");
Require(
economy.SearchLandListings(
label + " rental",
NexLandListingType.Rental,
0,
10).Count == 1,
label + ": land listing search mismatch");
NexCommerceOrder ticket =
economy.ExecuteCommerceOrder(
Guid.NewGuid(),
NexCommerceKind.EventTicket,
payerId,
merchantId,
25,
"EVENT-TICKET",
"ci-event",
label);
Require(
ticket.Status == NexCommerceOrderStatus.Completed &&
ticket.Kind == NexCommerceKind.EventTicket,
label + ": event ticket commerce mismatch");
Require(
economy.ListCommerceOrders(
payerId,
0,
20).Count >= 4,
label + ": commerce purchase history mismatch");
Require(
economy.ListLandLeases(
payerId,
0,
10).Count == 1,
label + ": land lease history mismatch");
}
private static void RunSqlitePersistence()
{
string path =
@@ -342,6 +672,11 @@ internal static class Program
store,
"sqlite");
RunBankingCommerceRegression(
store,
store,
"sqlite-banking");
using DbConnection connection =
runtime.CreateConnection();
connection.Open();
@@ -377,6 +712,30 @@ internal static class Program
virtualAccounts.ExecuteScalar()) >= 2,
"sqlite: NVBAN mappings were not persisted");
string[] workflowTables =
{
"ogl_economy_transfer_policies",
"ogl_economy_payment_requests",
"ogl_economy_commerce_orders",
"ogl_economy_land_listings",
"ogl_economy_land_leases"
};
foreach (string table in workflowTables)
{
using DbCommand count =
connection.CreateCommand();
count.CommandText =
"SELECT COUNT(*) FROM " +
table;
Require(
Convert.ToInt64(
count.ExecuteScalar()) > 0,
"sqlite: workflow rows missing from " +
table);
}
NexLedgerSqlStore reopened =
runtime.CreateStore();
@@ -418,10 +777,15 @@ internal static class Program
memory,
"memory");
RunBankingCommerceRegression(
memory,
memory,
"memory-banking");
RunSqlitePersistence();
Console.WriteLine(
"OpenGenesisLINK NV$ lifecycle, NVBAN and policy regression: OK");
"OpenGenesisLINK NV$ banking, commerce, land and policy regression: OK");
return 0;
}
@@ -16,6 +16,7 @@
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerModel.cs" Link="NexLedgerModel.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerAccountState.cs" Link="NexLedgerAccountState.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexVirtualBankAccount.cs" Link="NexVirtualBankAccount.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexEconomyWorkflow.cs" Link="NexEconomyWorkflow.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerStore.cs" Link="NexLedgerStore.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerSqlStore.cs" Link="NexLedgerSqlStore.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerSqlRuntime.cs" Link="NexLedgerSqlRuntime.cs" />
@@ -24,6 +24,7 @@
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerModel.cs" Link="NexLedgerModel.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerAccountState.cs" Link="NexLedgerAccountState.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexVirtualBankAccount.cs" Link="NexVirtualBankAccount.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexEconomyWorkflow.cs" Link="NexEconomyWorkflow.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerStore.cs" Link="NexLedgerStore.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerSqlStore.cs" Link="NexLedgerSqlStore.cs" />
<Compile Include="../../../NexVerse/Core/Economy/NexLedgerSqlRuntime.cs" Link="NexLedgerSqlRuntime.cs" />
+221
View File
@@ -0,0 +1,221 @@
#!/usr/bin/env python3
from pathlib import Path
workflow = Path("NexVerse/Core/Economy/NexEconomyWorkflow.cs").read_text(encoding="utf-8")
service = Path("NexVerse/Core/Economy/NexEconomyService.cs").read_text(encoding="utf-8")
store = Path("NexVerse/Core/Economy/NexLedgerStore.cs").read_text(encoding="utf-8")
sql = Path("NexVerse/Core/Economy/NexLedgerSqlStore.cs").read_text(encoding="utf-8")
api = Path("NexVerse/Server/Api/NexBankingCommerceApi.cs").read_text(encoding="utf-8")
economy_api = Path("NexVerse/Server/Api/NexEconomyApi.cs").read_text(encoding="utf-8")
connector = Path("NexVerse/Server/Api/NexVerseWorldApiConnector.cs").read_text(encoding="utf-8")
openapi = Path("NexVerse/Server/Api/NexVerseWorldApiHandlers.cs").read_text(encoding="utf-8")
viewer = Path("NexVerse/RegionModules/Economy/NexVerseMoneyModule.cs").read_text(encoding="utf-8")
land = Path("OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs").read_text(encoding="utf-8")
regression = Path("tools/ci/NexEconomyPolicyRegression/Program.cs").read_text(encoding="utf-8")
roadmap = Path("doc/NexVerse/ROADMAP.md").read_text(encoding="utf-8")
world_api = Path("doc/NexVerse/WORLD_API.md").read_text(encoding="utf-8")
for marker in (
"NexPaymentRequestStatus",
"NexPaymentRequest",
"NexAccountTransferPolicy",
"NexCommerceKind",
"VendorPayment",
"ObjectSale",
"MarketplacePurchase",
"LandPurchase",
"EventTicket",
"Rental",
"MerchantRefund",
"NexCommerceOrder",
"NexLandListing",
"NexLandLease",
"NexBankStatement",
"NexReconciliationReport",
"INexEconomyWorkflowStore",
):
assert marker in workflow, f"missing workflow model marker: {marker}"
for marker in (
"BankingTransfer(",
"GetStatement(",
"ReconcileAccount(",
"SetTransferPolicy(",
"CreatePaymentRequest(",
"PayPaymentRequest(",
"CancelPaymentRequest(",
"Refund(",
"FundEscrow(",
"ReleaseEscrow(",
"ExecuteCommerceOrder(",
"RefundCommerceOrder(",
"CreateLandListing(",
"SearchLandListings(",
"PurchaseLandListing(",
"CreateLandLease(",
"PayLandRent(",
"EnsureWalletAccount(",
"EnsureEscrowAccount(",
):
assert marker in service, f"missing banking/commerce service marker: {marker}"
for marker in (
"GetBalanceAt(",
"ListTransactions(",
"INexEconomyWorkflowStore",
"m_TransferPolicies",
"m_PaymentRequests",
"m_CommerceOrders",
"m_LandListings",
"m_LandLeases",
):
assert marker in store, f"missing workflow store marker: {marker}"
for marker in (
"CurrentSchemaVersion = 4",
"ApplySchemaVersion4(",
"ogl_economy_transfer_policies",
"ogl_economy_payment_requests",
"ogl_economy_commerce_orders",
"ogl_economy_land_listings",
"ogl_economy_land_leases",
"GetBalanceAt(",
"ListTransactions(",
):
assert marker in sql, f"missing SQL workflow marker: {marker}"
for forbidden in (
"UPDATE ogl_ledger_transactions",
"DELETE FROM ogl_ledger_transactions",
"UPDATE ogl_ledger_postings",
"DELETE FROM ogl_ledger_postings",
):
assert forbidden not in sql, f"immutable journal violation: {forbidden}"
for marker in (
"/api/v1/banking/transactions",
"/api/v1/banking/statements",
"/api/v1/banking/reconciliation",
"/api/v1/banking/transfers",
"/api/v1/banking/payment-requests",
"/api/v1/banking/accounts/",
"/api/v1/banking/escrow/",
"/api/v1/commerce/orders",
"/api/v1/land-commerce/listings",
"/api/v1/land-commerce/leases",
"economy.BankingTransfer(",
"economy.CreatePaymentRequest(",
"economy.PayPaymentRequest(",
"economy.ExecuteCommerceOrder(",
"economy.RefundCommerceOrder(",
"economy.PurchaseLandListing(",
"economy.CreateLandLease(",
"economy.PayLandRent(",
):
assert marker in api, f"missing World API banking/commerce marker: {marker}"
for forbidden in (
"INexLedgerStore",
"NexLedgerSqlStore",
"DbConnection",
".Append(",
"AdministrativeAdjustment(",
):
assert forbidden not in api, f"banking/commerce API bypasses policy boundary: {forbidden}"
for marker in (
'"/api/v1/banking"',
'"/api/v1/commerce"',
'"/api/v1/land-commerce"',
"new NexBankingCommerceApi(",
):
assert marker in connector, f"missing API registration marker: {marker}"
for marker in (
'["/api/v1/banking/transactions"]',
'["/api/v1/banking/statements"]',
'["/api/v1/banking/transfers"]',
'["/api/v1/banking/payment-requests"]',
'["/api/v1/commerce/orders"]',
'["/api/v1/land-commerce/listings"]',
'["/api/v1/land-commerce/leases"]',
'["BankingTransferRequest"]',
'["PaymentRequestCreateRequest"]',
'["CommerceOrderRequest"]',
'["LandListingRequest"]',
):
assert marker in openapi, f"missing OpenAPI banking/commerce marker: {marker}"
for marker in (
'"/api/v1/economy/accounts/ensure"',
"EnsureWalletAccount(",
"economy.wallet.ensure",
):
assert marker in economy_api, f"missing trusted wallet provisioning marker: {marker}"
for marker in (
"client.OnObjectBuy +=",
"private void ObjectBuy(",
"CommercePaymentInternal(",
"RefundCommerceInternal(",
'"ObjectSale"',
'"VendorPayment"',
'"LandPurchase"',
'"/api/v1/commerce/orders"',
'"/api/v1/economy/accounts/ensure"',
"TryResolveLocalGroup(",
"TryResolveLocalObjectOwner(",
):
assert marker in viewer, f"missing Viewer commerce marker: {marker}"
for forbidden in (
"DbConnection",
"NexLedgerSqlStore",
"ConnectionString",
"MySql",
"Npgsql",
):
assert forbidden not in viewer, f"Viewer adapter bypasses World API: {forbidden}"
for marker in (
"if (!e.economyValidated)",
"money.AmountCovered(",
"money.MoveMoney(",
"Land purchase:",
"land.UpdateLandSold(",
):
assert marker in land, f"missing native land settlement marker: {marker}"
assert land.index("money.MoveMoney(") < land.index("land.UpdateLandSold("), "land ownership transfer occurs before economy settlement"
for marker in (
"banking transfer/fee balances mismatch",
"banking transfer retry was not idempotent",
"payment request settlement mismatch",
"statement balances/history mismatch",
"reconciliation failed",
"escrow balances mismatch",
"commerce refund mismatch",
"land purchase mismatch",
"land purchase retry was not idempotent",
"land lease initial settlement mismatch",
"land lease retry was not idempotent",
):
assert marker in regression, f"missing banking/commerce regression marker: {marker}"
for heading in (
"### 10.3 Banking functions",
"### 10.4 Viewer economy compatibility",
"### 10.5 Land commerce",
"### 10.6 NexCommerce",
):
assert heading in roadmap, f"missing roadmap section: {heading}"
for marker in (
"/api/v1/banking",
"/api/v1/commerce",
"/api/v1/land-commerce",
):
assert marker in world_api, f"missing World API documentation marker: {marker}"
print("NV$ banking, Viewer commerce, land commerce and NexCommerce contract: OK")
+46 -2
View File
@@ -3,6 +3,7 @@ from pathlib import Path
model = Path("NexVerse/Core/Economy/NexLedgerAccountState.cs").read_text(encoding="utf-8")
virtual = Path("NexVerse/Core/Economy/NexVirtualBankAccount.cs").read_text(encoding="utf-8")
workflow = Path("NexVerse/Core/Economy/NexEconomyWorkflow.cs").read_text(encoding="utf-8")
service = Path("NexVerse/Core/Economy/NexEconomyService.cs").read_text(encoding="utf-8")
memory = Path("NexVerse/Core/Economy/NexLedgerStore.cs").read_text(encoding="utf-8")
sql = Path("NexVerse/Core/Economy/NexLedgerSqlStore.cs").read_text(encoding="utf-8")
@@ -27,6 +28,18 @@ for marker in (
):
assert marker in virtual, f"missing virtual account marker: {marker}"
for marker in (
"NexPaymentRequest",
"NexAccountTransferPolicy",
"NexCommerceOrder",
"NexLandListing",
"NexLandLease",
"NexBankStatement",
"NexReconciliationReport",
"INexEconomyWorkflowStore",
):
assert marker in workflow, f"missing banking/commerce model marker: {marker}"
for marker in (
"public sealed class NexEconomyService",
"EnsureResidentAccount(",
@@ -35,6 +48,18 @@ for marker in (
"SetAccountStatus(",
"EnsureVirtualBankAccount(",
"ResolveVirtualBankAccount(",
"BankingTransfer(",
"CreatePaymentRequest(",
"PayPaymentRequest(",
"RefundCommerceOrder(",
"FundEscrow(",
"ReleaseEscrow(",
"GetStatement(",
"ReconcileAccount(",
"PurchaseLandListing(",
"CreateLandLease(",
"PayLandRent(",
"ExecuteCommerceOrder(",
"Insufficient NV$ balance",
"Closed ledger accounts cannot be reopened",
"A ledger account can be closed only with zero balance",
@@ -49,16 +74,28 @@ for marker in (
"m_AccountStateEvents",
"m_VirtualBankAccountsByAccount",
"GetOrCreateVirtualBankAccount(",
"INexEconomyWorkflowStore",
"m_TransferPolicies",
"m_PaymentRequests",
"m_CommerceOrders",
"m_LandListings",
"m_LandLeases",
):
assert marker in memory, f"missing in-memory lifecycle marker: {marker}"
for marker in (
"CurrentSchemaVersion = 3",
"CurrentSchemaVersion = 4",
"ogl_ledger_account_state",
"ogl_ledger_account_events",
"ApplySchemaVersion2(",
"ApplySchemaVersion3(",
"ApplySchemaVersion4(",
"ogl_ledger_virtual_accounts",
"ogl_economy_transfer_policies",
"ogl_economy_payment_requests",
"ogl_economy_commerce_orders",
"ogl_economy_land_listings",
"ogl_economy_land_leases",
"GetOrCreateVirtualBankAccount(",
"SetAccountStatus(",
"ListAccountStateEvents(",
@@ -84,7 +121,14 @@ for marker in (
"schema version mismatch",
"resident NVBAN mapping mismatch",
"NVBAN mappings were not persisted",
"banking transfer/fee balances mismatch",
"payment request settlement mismatch",
"reconciliation failed",
"escrow balances mismatch",
"commerce refund mismatch",
"land purchase mismatch",
"land lease initial settlement mismatch",
):
assert marker in regression, f"missing policy regression marker: {marker}"
print("NV$ account lifecycle, NVBAN and policy contract: OK")
print("NV$ banking, commerce, land and policy contract: OK")
+9 -1
View File
@@ -11,7 +11,8 @@ for marker in (
"INexLedgerStore",
"INexLedgerAccountStateStore",
"INexVirtualBankAccountStore",
"public const int CurrentSchemaVersion = 3",
"INexEconomyWorkflowStore",
"public const int CurrentSchemaVersion = 4",
"Func<DbConnection>",
"IsolationLevel.Serializable",
"ogl_ledger_accounts",
@@ -22,6 +23,12 @@ for marker in (
"ogl_ledger_virtual_accounts",
"ApplySchemaVersion2(",
"ApplySchemaVersion3(",
"ApplySchemaVersion4(",
"ogl_economy_transfer_policies",
"ogl_economy_payment_requests",
"ogl_economy_commerce_orders",
"ogl_economy_land_listings",
"ogl_economy_land_leases",
"UNIQUE (account_id, state_version)",
"UNIQUE (transaction_id, sequence_no)",
"UNIQUE (account_id, posting_id)",
@@ -84,5 +91,6 @@ assert "Mono.Data.Sqlite.dll" in project
assert "NexLedgerSqlStore.cs" in project
assert "NexLedgerSqlRuntime.cs" in project
assert "NexVirtualBankAccount.cs" in project
assert "NexEconomyWorkflow.cs" in project
print("NV$ durable SQL ledger contract: OK")