import {createHash} from 'node:crypto'; import {createGameExchangePayments,exchangeFingerprint} from './game-exchange-payments.mjs'; import {BankError} from './postbank-service.mjs'; import {minecraftItemOrigin} from './minecraft-item-payload.mjs'; export function exchangeMinor(value){ const match=/^(\d{1,7})(?:\.(\d{1,2}))?$/.exec(String(value)); if(!match)throw new BankError('This listing has an invalid price.',409); const amount=Number(match[1])*100+Number((match[2]||'').padEnd(2,'0')); if(!Number.isSafeInteger(amount)||amount<1||amount>100000000)throw new BankError('This listing has an unsupported price.',409); return amount; } export function exchangeListing(row){ if(!/^[1-9]\d{0,17}$/.test(String(row.id))||!Number.isSafeInteger(Number(row.quantity))||Number(row.quantity)<1||!/^\w{1,80}$/.test(row.material)||row.payload!==null&&(typeof row.payload!=='string'||row.payload.length>65536))throw new BankError('This listing is not supported.',409); return {id:String(row.id),sellerUuid:row.seller,seller:String(row.seller_name||'Seller').slice(0,32),title:String(row.display_name||row.material).slice(0,120),material:row.material,payload:row.payload,quantity:Number(row.quantity),priceMinor:exchangeMinor(row.price),origin:String(row.origin).slice(0,48)}; } export function createGameExchangeService(bank,{gameSchema,authority,resolveSeller,revalidate=async actor=>actor,clock=Date.now,tradePolicy=async()=>({}),incentives=null}={}){ if(!/^[a-z][a-z0-9_]{2,63}$/.test(gameSchema||''))throw Error('A verified game schema is required.'); const table=name=>'`'+gameSchema+'`.`'+name+'`',listings=table('dune_exchange_listings'),deliveries=table('dune_exchange_deliveries'),sales=table('dune_exchange_sales'); const payments=createGameExchangePayments(bank,authority,{clock}); const receipt=row=>({id:row.id,state:row.delivered_at===null?'queued':'delivered',quantity:Number(row.quantity),totalMinor:Number(row.unit_minor)*Number(row.quantity)}); return Object.freeze({ async list(actor,player,{mine=false,page=0}={}){ const policy=await tradePolicy(bank,clock()),offers=[];let cursor=null,eligible=0,complete=false; // Filter before pagination. Keyset scanning preserves page sizes even when // many consecutive offers are suspended; no listing is deleted or rewritten. for(let scanned=0;scanned<200000;scanned+=128){ const where=[...(mine?['seller=?']:[]),...(cursor?['idclock())continue;if(eligible++12,mine}; }, async prepareSale(actor){await payments.canReceive(actor);return {allowed:true};}, async pending(actor,player){const rows=await bank.query('SELECT id FROM '+deliveries+" WHERE buyer_uuid=? AND state='queued' ORDER BY created_at,id LIMIT 16",[player]);return {pending:rows.map(r=>r.id)};}, async buy(actor,player,input){ // Bank entries, stock, sales history and the native delivery receipt commit on // the same MySQL server. No cross-database compensation or wallet mirror. return bank.transaction(async tx=>{ const prior=await tx.first('SELECT * FROM '+deliveries+' WHERE id=? FOR UPDATE',[input.requestId]); if(prior){ if(prior.buyer_uuid!==player||prior.buyer_account_id!==actor.id||String(prior.listing_id)!==input.listingId||Number(prior.quantity)!==input.amount||Number(prior.unit_minor)!==input.priceMinor)throw new BankError('This purchase reference was already used.',409); const paid=await tx.first('SELECT state,fingerprint FROM pb_orders WHERE id=?',[input.requestId]); if(paid?.state!=='posted'||paid.fingerprint!==exchangeFingerprint(prior))throw new BankError('The purchase requires reconciliation.',503); const levy=await tx.first('SELECT tax_minor,net_minor FROM pb_exchange_levies WHERE purchase_id=?',[input.requestId]); return {...receipt(prior),...(incentives?{rebateMinor:await incentives.replay(tx,input.requestId)}:{}),taxMinor:Number(levy?.tax_minor||0),sellerNetMinor:levy?Number(levy.net_minor):Number(prior.unit_minor)*Number(prior.quantity),replayed:true}; } const row=await tx.first('SELECT * FROM '+listings+' WHERE id=? FOR UPDATE',[input.listingId]); if(!row)throw new BankError('That listing was sold or withdrawn. Refresh the Exchange.',409); const offer=exchangeListing(row); const policy=await tradePolicy(tx,clock(),true),world=minecraftItemOrigin(row.payload,row.material),rule=policy[world]; if(rule?.embargoUntil>clock())throw new BankError('The Spacing Guild has suspended trade with this item’s origin world. Your funds were not taken.',409); if(offer.sellerUuid===player)throw new BankError('Use Sell to withdraw your own listing.',409); if(offer.priceMinor!==input.priceMinor||offer.quantity