MC/website/node/game-exchange-service.mjs
2026-11-27 23:43:05 +00:00

68 lines
7.4 KiB
JavaScript
Raw Permalink 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.

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?['id<?']:[])],rows=await bank.query('SELECT * FROM '+listings+(where.length?' WHERE '+where.join(' AND '):'')+' ORDER BY id DESC LIMIT 128',[...(mine?[player]:[]),...(cursor?[cursor]:[])]);
for(const row of rows){let offer;try{offer=exchangeListing(row);}catch{continue;}const world=minecraftItemOrigin(row.payload,row.material),rule=policy[world];if(!mine&&rule?.embargoUntil>clock())continue;if(eligible++<page*12)continue;offers.push({...offer,creationWorld:world,levyPercent:rule?.percent||0});if(offers.length===13)break;}
if(offers.length===13||rows.length<128){complete=true;break;}cursor=String(rows.at(-1).id);
}
if(!complete)throw new BankError('This page is too far into the Exchange. Refine your selection.',409);
return {listings:offers.slice(0,12),page,hasNext:offers.length>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<input.amount)throw new BankError('The price or available quantity changed.',409);
const current=await revalidate(actor,player);if(!current||current.id!==actor.id)throw new BankError('Your current Exchange authority is unavailable.',403);
const seller=await resolveSeller(offer.sellerUuid);if(!seller||seller.id===actor.id)throw new BankError('The seller is not linked to an eligible personal account.',409);
const order={id:input.requestId,buyer_uuid:player,buyer_account_id:actor.id,seller_uuid:offer.sellerUuid,listing_id:offer.id,quantity:input.amount,unit_minor:offer.priceMinor,payload_hash:createHash('sha256').update(row.material+'\n'+(row.payload||'')).digest('hex'),display_name:offer.title};
const settlement=await payments.post(tx,current,seller,order,rule?{...rule,requestId:rule.taxRequestId}:null,incentives?{service:incentives,world}:null);
if(offer.quantity===input.amount)await tx.query('DELETE FROM '+listings+' WHERE id=?',[offer.id]);
else await tx.query('UPDATE '+listings+' SET quantity=quantity-? WHERE id=?',[input.amount,offer.id]);
await tx.query('INSERT INTO '+deliveries+'(id,buyer_uuid,buyer_account_id,seller_uuid,listing_id,quantity,unit_minor,material,payload,payload_hash,display_name,origin,state,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,\'queued\',?)',[order.id,player,actor.id,offer.sellerUuid,offer.id,input.amount,offer.priceMinor,offer.material,offer.payload,order.payload_hash,offer.title,offer.origin,clock()]);
await tx.query('INSERT INTO '+sales+'(listing_id,seller,seller_name,buyer,buyer_name,material,display_name,quantity,unit_price,total_price,origin) VALUES(?,?,?,?,?,?,?,?,?,?,?)',[offer.id,offer.sellerUuid,offer.seller,player,actor.username,offer.material,offer.title,input.amount,(offer.priceMinor/100).toFixed(2),(offer.priceMinor*input.amount/100).toFixed(2),offer.origin]);
return {id:order.id,state:'queued',quantity:input.amount,totalMinor:offer.priceMinor*input.amount,taxMinor:settlement.taxMinor,sellerNetMinor:settlement.sellerNetMinor,...(incentives?{rebateMinor:settlement.rebateMinor}:{}),replayed:false};
});
}
});
}