From 2355aab0c4c1773e0383296208d7abe00759e85c Mon Sep 17 00:00:00 2001 From: unimatrix Date: Mon, 23 Nov 2026 20:15:12 +0000 Subject: [PATCH] Link paid spice sales to verified quest evidence and earned DM --- .../public/cp-v2/cp-v2-quest-guidance.mjs | 6 ++- .../public/jarvis-master-keys.mjs | 4 +- website/control-panel/server.mjs | 3 +- .../osticket/dev-jarvis-catalogue.json | 10 ++--- website/node/bank-quest-activities.mjs | 2 +- website/node/game-spice.mjs | 23 ++++++++--- website/node/spice-quest-receipts.mjs | 40 +++++++++++++++++++ website/scripts/spice-quest-migration.mjs | 4 ++ website/tests/bank-quest-activities.test.mjs | 5 ++- website/tests/game-spice.test.mjs | 15 +++++-- website/tests/spice-quest-receipts.test.mjs | 32 +++++++++++++++ 11 files changed, 123 insertions(+), 21 deletions(-) create mode 100644 website/node/spice-quest-receipts.mjs create mode 100644 website/scripts/spice-quest-migration.mjs create mode 100644 website/tests/spice-quest-receipts.test.mjs diff --git a/website/control-panel/public/cp-v2/cp-v2-quest-guidance.mjs b/website/control-panel/public/cp-v2/cp-v2-quest-guidance.mjs index f79e8e17..d097563a 100644 --- a/website/control-panel/public/cp-v2/cp-v2-quest-guidance.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-quest-guidance.mjs @@ -8,11 +8,13 @@ export const QUEST_GUIDANCE=Object.freeze({ profile:live('Set your display name and save a biography of at least 10 characters. Choosing a House alone does not complete your profile.','My Account → Profile','Saved display name and biography'), 'guild-travel':live('Book Spacing Guild passage in the lobby, remain online and arrive on your House world. The 100 DM fare is taken from your central personal bank account on arrival.','Lobby → Spacing Guild NPC / Imperial Codex → Spacing Guild','Confirmed destination arrival and settled passage payment'), 'citizen-introduction':live('Start this quest, then read the Imperial Citizen briefing and press I understand in your ingame mission journal. Refresh this quest after confirmation, then claim the reward. This is separate from choosing a House or completing your profile.','Imperial Codex → Mission journal → Personal Experience → Onboarding → Complete Imperial Citizen introduction → Read citizen briefing','Confirmed ingame Citizen briefing acknowledgement'), - 'earned-minor':live('Receive the stated cumulative amount in DM from posted incoming bank transfers, quest rewards, wages and Exchange sales during this season. Spending it later does not reduce your earned total. Transfers between your own accounts, refunds and pending payments do not count.','Central bank → Transactions; receive transfers, complete reward quests, earn wages or sell goods on the Exchange','Settled central-bank income, not your current balance'), + 'earned-minor':live('Receive the stated cumulative amount in DM from posted incoming bank transfers, quest rewards, wages, P&O spice payouts and Exchange sales during this season. Spending it later does not reduce your earned total. Transfers between your own accounts, refunds and pending payments do not count.','Central bank → Transactions; receive transfers, complete reward quests, earn wages or sell goods on the Exchange','Settled central-bank income, not your current balance'), 'bank-deposit':pending('Deposit physical cash into your personal central-bank account through the ingame ATM. A transfer between your own accounts is not a cash deposit.','Rihla / ATM ingame menu'), 'bank-transfer':live('Send a payment from an authorised personal bank account to another customer. Wait until it is posted; a queued payment or transfer between your own accounts does not count.','Website bank → Transfers','Posted standard or instant payment to another customer'), 'shop-purchase':live('Buy and pay for goods listed by another player on the Exchange. Browsing, publishing your own listing or withdrawing an unsold item does not count.','Ingame /exchange → Buy','Settled central-bank Exchange purchase'), - 'spice-harvest':live('Mine the stated number of spice units from real deposits on Arrakis in Survival or Adventure mode. Only native spice produced by successful mining counts; bought spice, inventory drops and creative items do not.','Arrakis → Spice deposits','Native spice production during an uncancelled mining action'), + 'spice-harvest':live('Harvest spice on Arrakis or sell normal raw spice through the Spacing Guild buyer. A paid Guild sale counts even when you bought the spice first. Compressed raw-spice blocks count as nine units; refined spice and contraband do not qualify for Guild sales. A quote or inventory drop does not count.','Arrakis → Spice deposits or /spice → Spacing Guild; /sellall sells normal spice','Verified native harvest or surrendered spice with a posted P&O Guild payment'), + 'pol-repeat-spice':live('Harvest the stated additional spice units or sell normal raw spice to the Spacing Guild on Arrakis. Blocks count as nine units. The sale must be surrendered ingame and paid by P&O. Claim this episode before beginning the next cooldown.','Arrakis → /spice → Spacing Guild, or /sellall','Verified harvest or paid Guild spice-sale receipt'), + 'pol-repeat-smuggling':live('Start an eligible Smuggler quest, then sell smuggled raw spice to Esmar Tuek on Arrakis. Smuggled blocks count as nine units. Normal, refined and contaminated spice do not count as raw contraband sales. Claim the current episode before the next cooldown.','Arrakis → /spice → Esmar Tuek, or /sellall smuggler','Surrendered contraband and posted P&O Smuggler payment'), 'arrakduin-visit':live('Enter Arrakis in Survival or Adventure mode. Merely selecting the world in a menu does not count.','Arrakis','Actual arrival in the Arrakis game world'), 'arrakduin-active-minutes':live('Spend the stated number of active minutes on Arrakis in Survival or Adventure mode. Move for at least 45 seconds per minute. AFK time, death screens and offline time do not count.','Arrakis','Active survival time recorded by the connector'), 'sietch-discovery':pending('Reach and interact with a registered sietch discovery marker on Arrakis. Entering an ordinary cave is not a verified discovery.','Arrakis → Registered sietch marker'), diff --git a/website/control-panel/public/jarvis-master-keys.mjs b/website/control-panel/public/jarvis-master-keys.mjs index 03dff127..a5eb5989 100644 --- a/website/control-panel/public/jarvis-master-keys.mjs +++ b/website/control-panel/public/jarvis-master-keys.mjs @@ -35,9 +35,9 @@ export const MASTER_KEY_TEMPLATES=[ action('progression.pol-funded-rewards','Funded Reputation reward delivery','quest',[],{webIssue:false,recordOnly:true,domainAdapter:'createPOLFundedRewards',executionStatus:'consumed-quest-outbox-only',effect:'Pay only explicitly configured and verified claim rewards from existing website treasury funds to the bound ordinary player bank account. Original QST identity prevents duplicate ledger entries; unfunded or invalid rewards remain queued.'}), action('progression.flight-policy','Elytra Reputation quest policy','progression-policy',[],{version:4,webIssue:false,recordOnly:true,domainAdapter:'ensureElytraQuestPolicy',executionStatus:'recorded-system-policy',effect:'Install the twelve Elytra quest reward configurations through their own policy:POL:S01:v4 instrument. Preserve existing quest settings, season dates and the separate v3 Mentat bonus instrument.'}), action('progression.game-observation','Native quest observation','quest-milestone',[field('eventId','Original native event UUID'),field('uuid','Linked Minecraft UUID'),field('kind','Fixed observation kind'),field('server','Native server'),field('occurredAt','Original event time','number',{min:1}),field('quantity','Native produced quantity','number',{min:1,max:64,required:false}),field('dimension','Native dimension','text',{required:false}),field('source','Fixed Elytra acquisition source','text',{required:false})],{version:4,webIssue:false,recordOnly:true,domainAdapter:'createGameQuestEventsAPI',executionStatus:'authenticated-game-service',effect:'Record confirmed Citizen briefing acknowledgements, real Arrakis visits, active survival minutes, durability-consuming equipment use and native spice drops from successful mining. Spice feeds the existing Personal and repeatable Reputation QSM adapters. Fixed world/dimension flight observations feed the Reputation Elytra branch. A committed paid delivery or natural End-ship acquisition completes only this branch, awarding its remaining rewards once. Preserve source UUID on retries. Creative/spectator gameplay and AFK/lobby movement supply no progress. A deliberate Citizen briefing acknowledgement is allowed in the lobby; other menu clicks never assert gameplay completion.'}), - action('commerce.spice-sale','Arrakis spice sale','entity-state',[field('uuid','Linked Minecraft UUID'),field('requestId','Original sale UUID'),field('channel','Buyer','select',{options:['guild','smuggler']}),field('amount','Surrendered spice','number',{min:1,max:21312})],{version:2,webIssue:false,recordOnly:true,domainAdapter:'createGameSpiceAPI + ExchangeInventory.sellSpice',executionStatus:'authenticated-arrakis-inventory-receipt',effect:'Arrakis only. Guild and Smuggler have separate server prices; Smuggler requires an active Smuggler quest. Native Core checkpoints all surrendered raw Melange Spice and compressed blocks (nine raw units each), retaining Guild versus contraband identity before the central bank pays its personal recipient from fixed P&O, with the existing Trust levy. Original request UUID binds quote, inventory receipt and balanced bank entries. Retry and reconnect recover an unpaid receipt without taking spice or paying twice. No Vault wallet or Exchange listing.'}), + action('commerce.spice-sale','Arrakis spice sale','entity-state',[field('uuid','Linked Minecraft UUID'),field('requestId','Original sale UUID'),field('channel','Buyer','select',{options:['guild','smuggler']}),field('amount','Surrendered spice','number',{min:1,max:21312})],{version:3,webIssue:false,recordOnly:true,domainAdapter:'createGameSpiceAPI + ExchangeInventory.sellSpice + createSpiceQuestReceipts',executionStatus:'authenticated-arrakis-inventory-receipt',effect:'Arrakis only. Guild and Smuggler have separate server prices; Smuggler requires an active Smuggler quest. Native Core checkpoints all surrendered raw Melange Spice and compressed blocks (nine raw units each), retaining Guild versus contraband identity before the central bank pays its personal recipient from fixed P&O, with the existing Trust levy. Original request UUID binds quote, inventory receipt and balanced bank entries. Retry and reconnect recover an unpaid receipt without taking spice or paying twice. Paid Guild sales supply Personal harvest and Reputation spice evidence; paid contraband sales supply separate Reputation smuggling evidence through existing ordinary quest-milestone keys. Pending quest reporting retries from the same stored sale without taking items or paying again. No Vault wallet or Exchange listing.'}), action('progression.spice-refining','NPC spice refinement','quest-milestone',[field('uuid','Linked player UUID'),field('requestId','Original turn-in UUID'),field('definitionId','Fixed refining quest'),field('npcUuid','Nearby Arrakis Smuggler UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createGameQuestsAPI.prepare_refine + SpiceRefiner + ExchangeInventory.refine',executionStatus:'authenticated-native-npc-turn-in',effect:'Revalidate the current player and quest prerequisites, then require the physical Arrakis NPC again before consuming two real raw spice, or two refined spice and two scraps. Core checkpoints inputs, two EI outputs and a recoverable receipt atomically. Existing QSM observations award no reward until verified by the Reputation quest engine.'}), - action('progression.earned-dm','Verified earned DM','quest-milestone',[],{webIssue:false,recordOnly:true,domainAdapter:'bankQuestIncome + progressionRuntime.collect',executionStatus:'committed-central-bank-source',effect:'Count posted wages, Exchange sale income, incoming bank transfers and verified quest treasury credits across the player’s personal central-bank accounts during the active season. Count each bank order once and preserve cumulative earnings after spending. Exclude own-account transfers, refunds, pending payments, unrelated system grants and organisation income; never use a legacy game wallet or current balance as an earnings counter.'}), + action('progression.earned-dm','Verified earned DM','quest-milestone',[],{version:2,webIssue:false,recordOnly:true,domainAdapter:'bankQuestIncome + progressionRuntime.collect',executionStatus:'committed-central-bank-source',effect:'Count posted wages, fixed-P&O spice-sale payouts, Exchange sale income, incoming bank transfers and verified quest treasury credits across the player’s personal central-bank accounts during the active season. Count each bank order once and preserve cumulative earnings after spending. Exclude own-account transfers, refunds, pending payments, unrelated system grants and organisation income; never use a legacy game wallet or current balance as an earnings counter.'}), action('progression.exchange-purchase','Committed Exchange quest evidence','quest-milestone',[],{webIssue:false,recordOnly:true,domainAdapter:'createBankQuestActivities',executionStatus:'committed-central-bank-source',effect:'Read the first settled Exchange purchase in the current season into existing Personal activity keys. Pending orders, self transfers, another customer and legacy wallets never count. Reuse the original order UUID without issuing a reward from the reader.'}), action('progression.personal-activity','Verified Personal activity','quest-milestone',[field('eventId','Unique domain event'),field('accountId','Current player account'),field('minecraftUuid','Current linked player UUID'),field('seasonId','Current Personal season'),field('metric','Registered Personal objective metric'),field('quantity','Verified quantity','number',{min:1}),field('reference','Original committed evidence reference')],{webIssue:false,recordOnly:true,domainAdapter:'personalActivityEvents.record',executionStatus:'trusted-domain-producer-only',effect:'Read current immutable QSM evidence through the existing Personal quest engine. Preserve dedicated bank, forum, acquisition and Q0 proof readers. Native observations and committed bank receipts feed their registered metrics. Other missing external events remain pending; browser counters never supply authority.'}), action('progression.pol-activity','Verified Reputation activity','quest-milestone',[field('eventId','Unique domain event'),field('accountId','Current player account'),field('minecraftUuid','Current linked player UUID'),field('seasonId','Current season'),field('metric','Registered objective metric'),field('quantity','Verified quantity','number',{min:1}),field('reference','Original evidence reference')],{webIssue:false,recordOnly:true,domainAdapter:'polActivityEvents.record',executionStatus:'trusted-domain-producer-only',effect:'Bind actual committed activity to the current player, season and quest-giver SID. Reuse existing QSM evidence and POL claims; a browser cannot assert progress. PvP, mob and death objectives require original production Minecraft ESK evidence instead.'}), diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index a915baec..d40e8a3f 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -1,4 +1,5 @@ import {createGameSpiceAPI} from '../node/game-spice.mjs'; +import {createSpiceQuestReceipts} from '../node/spice-quest-receipts.mjs'; import {POLITICAL_DECISION_SCHEMA,createPoliticalDecisions,createPoliticalDecisionAPI} from '../node/political-decisions.mjs'; import {createKitsetCommerce} from '../node/kitset-commerce.mjs'; import {createKitsetPurchaseAPI} from './kitset-purchase-api.mjs'; @@ -297,7 +298,7 @@ export function createPanel(db,settings={},dependencies={}){ const exchange=createExchange(db,pool); const kitsetCommerce=dependencies.kitsetCommerce||(dependencies.bankDatabase&&settings.DB_NAME&&settings.DUNE_INVENTORY_DATABASE_URL?createKitsetCommerce(db,dependencies.bankDatabase,settings,{gamePool:pool}):null); const kitsetPurchase=createKitsetPurchaseAPI(db,kitsetCommerce,settings); - const gameSpice=createGameSpiceAPI(db,dependencies.bankDatabase||null,pool,settings,{pol:polRuntime}); + const gameSpice=createGameSpiceAPI(db,dependencies.bankDatabase||null,pool,settings,{pol:polRuntime,recordSale:createSpiceQuestReceipts(db,dependencies.bankDatabase||null,dependencies.organisationKeys)}); const gameExchange=createGameExchangeAPI(db,dependencies.bankDatabase||null,pool,settings,{kitsetCommerce}); const gameKitGrants=createGameKitGrantsAPI(db,settings,{pool,commerce:kitsetCommerce,starter:gameStarter}); let clans,companyRecruitment;const jarvis=createJarvisServices(db,dependencies.bankDatabase||null,settings,{...dependencies.jarvis,organisationKeys:dependencies.organisationKeys,deedPurchases:dependencies.deedPurchases,promotionChannels:dependencies.promotionDelivery?.channels||[],invokeClans:request=>clans(request),invokeCompany:request=>companyRecruitment(request)});companyRecruitment=createCompanyRecruitment(db,{origin,requestIntegration:jarvis.companyRequests});clans=createClans(db,{origin,onClanCreated:async({id})=>{await dependencies.boardRuntime?.boards.refresh('clan',id).catch(()=>console.error('Clan board key remains pending reconciliation'));await syncClanMailRegistry(db);},onClanDeleted:()=>syncClanMailRegistry(db),requestIntegration:jarvis.requests});const gameTickets=createGameTickets(db,settings); diff --git a/website/integrations/osticket/dev-jarvis-catalogue.json b/website/integrations/osticket/dev-jarvis-catalogue.json index 3723596f..81b427ab 100644 --- a/website/integrations/osticket/dev-jarvis-catalogue.json +++ b/website/integrations/osticket/dev-jarvis-catalogue.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "sourceHash": "8ca2be330243474c7ce5643afc36a98db8da5d9bc4c4f8722cae8cc10f9ccf3a", + "sourceHash": "5fad98a571f599384c7d7c1f290fb807ca9e318f3521a72eb49cd318adc496dd", "actions": [ { "id": "clan.clear-protected-rosters", @@ -1306,7 +1306,7 @@ { "id": "commerce.spice-sale", "label": "Progression & XP · Arrakis spice sale", - "version": 2, + "version": 3, "keyType": "entity-state", "fields": [ { @@ -1347,7 +1347,7 @@ "max": 21312 } ], - "effect": "Arrakis only. Guild and Smuggler have separate server prices; Smuggler requires an active Smuggler quest. Native Core checkpoints all surrendered raw Melange Spice and compressed blocks (nine raw units each), retaining Guild versus contraband identity before the central bank pays its personal recipient from fixed P&O, with the existing Trust levy. Original request UUID binds quote, inventory receipt and balanced bank entries. Retry and reconnect recover an unpaid receipt without taking spice or paying twice. No Vault wallet or Exchange listing.", + "effect": "Arrakis only. Guild and Smuggler have separate server prices; Smuggler requires an active Smuggler quest. Native Core checkpoints all surrendered raw Melange Spice and compressed blocks (nine raw units each), retaining Guild versus contraband identity before the central bank pays its personal recipient from fixed P&O, with the existing Trust levy. Original request UUID binds quote, inventory receipt and balanced bank entries. Retry and reconnect recover an unpaid receipt without taking spice or paying twice. Paid Guild sales supply Personal harvest and Reputation spice evidence; paid contraband sales supply separate Reputation smuggling evidence through existing ordinary quest-milestone keys. Pending quest reporting retries from the same stored sale without taking items or paying again. No Vault wallet or Exchange listing.", "fixedTargets": [], "webIssue": false, "recordOnly": true @@ -1398,7 +1398,7 @@ { "id": "progression.earned-dm", "label": "Progression & XP · Verified earned DM", - "version": 1, + "version": 2, "keyType": "quest-milestone", "fields": [ { @@ -1409,7 +1409,7 @@ "maxLength": 80 } ], - "effect": "Count posted wages, Exchange sale income, incoming bank transfers and verified quest treasury credits across the player’s personal central-bank accounts during the active season. Count each bank order once and preserve cumulative earnings after spending. Exclude own-account transfers, refunds, pending payments, unrelated system grants and organisation income; never use a legacy game wallet or current balance as an earnings counter.", + "effect": "Count posted wages, fixed-P&O spice-sale payouts, Exchange sale income, incoming bank transfers and verified quest treasury credits across the player’s personal central-bank accounts during the active season. Count each bank order once and preserve cumulative earnings after spending. Exclude own-account transfers, refunds, pending payments, unrelated system grants and organisation income; never use a legacy game wallet or current balance as an earnings counter.", "fixedTargets": [], "webIssue": false, "recordOnly": true diff --git a/website/node/bank-quest-activities.mjs b/website/node/bank-quest-activities.mjs index 440a49b0..ece79384 100644 --- a/website/node/bank-quest-activities.mjs +++ b/website/node/bank-quest-activities.mjs @@ -12,7 +12,7 @@ export async function bankQuestIncome(bank,accountId,startsAt,now){ const rows=await bank.query(`SELECT COUNT(CASE WHEN o.mode='payroll' THEN 1 END) wages,COALESCE(SUM(o.amount_minor),0) earned FROM pb_orders o JOIN pb_accounts a ON a.id=o.target_id JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_accounts source ON source.id=o.source_id - WHERE e.kind='person' AND e.external_key=? AND o.state='posted' AND (o.mode IN ('payroll','exchange','standard','instant') OR (o.mode='system' AND source.system_key='sys_web_treasury' AND (o.memo=CONCAT('Reputation reward ',o.id) OR o.memo=CONCAT('Quest reward ',o.id)))) + WHERE e.kind='person' AND e.external_key=? AND o.state='posted' AND (o.mode IN ('payroll','exchange','standard','instant') OR (o.mode='spice' AND source.system_key='sys_payroll_po') OR (o.mode='system' AND source.system_key='sys_web_treasury' AND (o.memo=CONCAT('Reputation reward ',o.id) OR o.memo=CONCAT('Quest reward ',o.id)))) AND o.amount_minor>0 AND o.source_id<>o.target_id AND (source.client_number IS NULL OR source.client_number<>a.client_number) AND o.posted_at>=? AND o.posted_at<=?`,[accountId,startsAt,now]); const value={wages:Number(rows[0]?.wages||0),earned:Number(rows[0]?.earned||0)}; diff --git a/website/node/game-spice.mjs b/website/node/game-spice.mjs index 70d7eab5..213c971a 100644 --- a/website/node/game-spice.mjs +++ b/website/node/game-spice.mjs @@ -14,7 +14,12 @@ export function spiceQuote(channel,amount){ } export const activeSmugglerQuest=journal=>!!journal?.quests?.some(q=>q.state==='active'&&(q.branch==='smugglers'||q.id?.startsWith('RPT-CARGO-'))); const accounts=`SELECT a.*,e.active entity_active,p.state package_state FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id JOIN pb_packages p ON p.id=a.package_id WHERE e.kind='person' AND e.external_key=? AND a.type_code IN ('102','103','104','108') ORDER BY CASE WHEN a.type_code='102' THEN 0 ELSE 1 END,a.id`; -export function createGameSpiceAPI(db,bank,pool,settings,{pol,clock=Date.now,verifyStorage}={}){ +export async function ensureSpiceSaleStorage(bank){ + await bank.query(`CREATE TABLE IF NOT EXISTS pb_spice_sales (id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,player_uuid CHAR(36) NOT NULL,channel VARCHAR(16) NOT NULL,quantity INT NOT NULL,fingerprint CHAR(64) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,quest_reported_at BIGINT NULL,INDEX(player_uuid,created_at)) ENGINE=InnoDB`); + const found=await bank.first("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='pb_spice_sales' AND COLUMN_NAME='quest_reported_at'"); + if(!found)try{await bank.query('ALTER TABLE pb_spice_sales ADD COLUMN quest_reported_at BIGINT NULL');}catch(e){if(e.code!=='ER_DUP_FIELDNAME'&&e.errno!==1060)throw e;} +} +export function createGameSpiceAPI(db,bank,pool,settings,{pol,clock=Date.now,verifyStorage,recordSale}={}){ let storage,schema; const first=(s,q,a=[])=>s.first?s.first(q,a):s.query(q,a).then(rows=>rows[0]); async function ready(){if(!storage)storage=(async()=>{ @@ -25,7 +30,7 @@ export function createGameSpiceAPI(db,bank,pool,settings,{pol,clock=Date.now,ver if(!g||['host','port','server_id'].some(k=>String(b[k])!==String(g[k])))throw Error('Spice banking unavailable.'); const engine=await bank.first('SELECT ENGINE engine FROM information_schema.TABLES WHERE TABLE_SCHEMA=? AND TABLE_NAME=?',[schema,'dune_exchange_inventory_ops']); if(engine?.engine!=='InnoDB')throw Error('Spice inventory checkpoint unavailable.'); - await bank.query(`CREATE TABLE IF NOT EXISTS pb_spice_sales (id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,player_uuid CHAR(36) NOT NULL,channel VARCHAR(16) NOT NULL,quantity INT NOT NULL,fingerprint CHAR(64) NOT NULL,created_at BIGINT NOT NULL,expires_at BIGINT NOT NULL,INDEX(player_uuid,created_at)) ENGINE=InnoDB`); + await ensureSpiceSaleStorage(bank); })().catch(e=>{storage=null;throw e;});return storage;} async function actor(uuid){const rows=await db.query("SELECT a.id,a.username,a.role FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')",[uuid]);return rows.length===1?rows[0]:null;} async function smuggler(user){if(!pol?.quests)return false;return activeSmugglerQuest(await pol.quests.list({...user,revalidate:async()=>user}));} @@ -40,7 +45,7 @@ export function createGameSpiceAPI(db,bank,pool,settings,{pol,clock=Date.now,ver try{ await ready();const user=await actor(input.uuid);if(!user)return json({message:'Link your personal account first.'},403); if(input.action==='read')return json({ok:true,playerUuid:input.uuid,policy:SPICE_POLICY,smugglerEnabled:await smuggler(user),hasAccount:!!await recipient(bank,user)}); - if(input.action==='pending'){const rows=await bank.query('SELECT s.id FROM pb_spice_sales s JOIN `'+schema+'`.dune_exchange_inventory_ops r ON r.id=s.id LEFT JOIN pb_orders o ON o.id=s.id WHERE s.player_uuid=? AND s.actor_id=? AND o.id IS NULL ORDER BY s.created_at LIMIT 16',[input.uuid,user.id]);return json({ok:true,pending:rows.map(r=>r.id)});} + if(input.action==='pending'){const rows=await bank.query('SELECT s.id FROM pb_spice_sales s JOIN `'+schema+'`.dune_exchange_inventory_ops r ON r.id=s.id LEFT JOIN pb_orders o ON o.id=s.id WHERE s.player_uuid=? AND s.actor_id=? AND (o.id IS NULL'+(recordSale?' OR s.quest_reported_at IS NULL':'')+') ORDER BY s.created_at LIMIT 16',[input.uuid,user.id]);return json({ok:true,pending:rows.map(r=>r.id)});} if(input.action==='prepare'){ if(input.confirmed!==true)throw Error('Confirm the sale first.');const quote=spiceQuote(input.channel,input.amount); if(input.channel==='smuggler'&&!await smuggler(user))return json({message:'Start a Smuggler quest before selling to Esmar Tuek.'},403); @@ -49,7 +54,7 @@ export function createGameSpiceAPI(db,bank,pool,settings,{pol,clock=Date.now,ver const row=await bank.transaction(async tx=>{const prior=await tx.first('SELECT * FROM pb_spice_sales WHERE id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==user.id||prior.player_uuid!==input.uuid||prior.fingerprint!==fingerprint)throw Error('Sale reference conflict.');return prior;}await tx.query('INSERT INTO pb_spice_sales(id,actor_id,player_uuid,channel,quantity,fingerprint,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?)',[input.requestId,user.id,input.uuid,input.channel,input.amount,fingerprint,now,now+30000]);return {expires_at:now+30000};}); return json({ok:true,allowed:true,action:'prepare_spice',playerUuid:input.uuid,requestId:input.requestId,fingerprint,expiresAt:Number(row.expires_at),...quote}); } - return json(await bank.transaction(async tx=>{ + const paid=await bank.transaction(async tx=>{ const sale=await tx.first('SELECT * FROM pb_spice_sales WHERE id=? FOR UPDATE',[input.requestId]);if(!sale||sale.actor_id!==user.id||sale.player_uuid!==input.uuid)throw Error('Spice receipt unavailable.'); const quote=spiceQuote(sale.channel,Number(sale.quantity)); // Native receipts are append-only; the sale and bank-order locks serialize payment. @@ -67,7 +72,15 @@ export function createGameSpiceAPI(db,bank,pool,settings,{pol,clock=Date.now,ver await post(sale.id,destination,quote.netMinor,sale.fingerprint,'Spice sale · '+sale.channel+' · '+quote.amount); if(quote.taxMinor){const h=createHash('sha256').update('spice-tax:'+sale.id).digest('hex'),id=h.slice(0,8)+'-'+h.slice(8,12)+'-5'+h.slice(13,16)+'-a'+h.slice(17,20)+'-'+h.slice(20,32);await post(id,tax,quote.taxMinor,sale.fingerprint,'Spice sale · Trust levy');} return {ok:true,replayed:false,...quote}; - })); + }); + if(recordSale){ + const reported=await bank.first('SELECT quest_reported_at FROM pb_spice_sales WHERE id=?',[input.requestId]); + if(reported?.quest_reported_at==null)try{ + await recordSale(user,{requestId:input.requestId,uuid:input.uuid}); + await bank.query('UPDATE pb_spice_sales SET quest_reported_at=? WHERE id=? AND actor_id=? AND player_uuid=? AND quest_reported_at IS NULL',[clock(),input.requestId,user.id,input.uuid]); + }catch{return json({...paid,questProgressPending:true});} + } + return json(paid); }catch(error){return json({message:/^(Choose|Confirm|Start|An active|Your bank|Spice |Sale reference|P&O)/.test(error.message||'')?error.message:'Spice banking is temporarily unavailable. Committed sales remain payable.'},409);} }; } diff --git a/website/node/spice-quest-receipts.mjs b/website/node/spice-quest-receipts.mjs new file mode 100644 index 00000000..72e8b6ad --- /dev/null +++ b/website/node/spice-quest-receipts.mjs @@ -0,0 +1,40 @@ +import {createPersonalActivityEvents} from './personal-activity-events.mjs'; +import {createPOLActivityEvents} from './pol-activity-events.mjs'; + +// The ordinary activity-key adapter owns quest evidence; a quote never counts. +export function createSpiceQuestReceipts(db,bank,keys,{clock=Date.now}={}){ + if(!bank||!keys)return null; + async function paid(id){ + const sale=await bank.first('SELECT * FROM pb_spice_sales WHERE id=?',[id]); + const order=await bank.first('SELECT * FROM pb_orders WHERE id=?',[id]); + if(!sale||!order||order.state!=='posted'||order.mode!=='spice'||order.actor_id!==sale.actor_id||order.fingerprint!==sale.fingerprint||BigInt(order.amount_minor)<=0n||!['guild','smuggler'].includes(sale.channel))return null; + const source=await bank.first('SELECT system_key FROM pb_accounts WHERE id=?',[order.source_id]); + return source?.system_key==='sys_payroll_po'?{...sale,posted_at:Number(order.posted_at)}:null; + } + const authorize=(channel,metric)=>async(actor,p)=>{ + const sale=await paid(p.eventId); + return !!sale&&actor.id===p.accountId&&sale.actor_id===p.accountId&&sale.player_uuid===p.minecraftUuid&&sale.channel===channel&&p.metric===metric&&p.quantity===Number(sale.quantity)&&p.occurredAt===sale.posted_at&&p.reference==='spice-sale:'+channel+':'+sale.id; + }; + const personal=createPersonalActivityEvents(db,keys,{clock,authorizeProducer:authorize('guild','spice-harvest')}); + const official=db.polActivityEventsEnabled?createPOLActivityEvents(db,keys,{clock,authorizeProducer:authorize('guild','pol-repeat-spice')}):null; + const contraband=db.polActivityEventsEnabled?createPOLActivityEvents(db,keys,{clock,authorizeProducer:authorize('smuggler','pol-repeat-smuggling')}):null; + return async(user,{requestId,uuid})=>{ + const sale=await paid(requestId); + if(!sale||sale.actor_id!==user.id||sale.player_uuid!==uuid)throw Error('A posted native spice sale is required for quest progress.'); + const seasons=await db.query("SELECT season_id,starts_at,ends_at FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[clock(),clock()]); + if(seasons.length!==1||seasons[0].season_id!=='S01')throw Error('Spice quest season is unavailable.'); + const season=seasons[0]; + // Historical sales outside this season must not clog reconnect recovery. + if(sale.posted_at=Number(season.ends_at))return {skipped:true}; + const evidence={eventId:sale.id,accountId:user.id,minecraftUuid:uuid,seasonId:season.season_id,quantity:Number(sale.quantity),occurredAt:sale.posted_at,reference:'spice-sale:'+sale.channel+':'+sale.id}; + if(sale.channel==='guild'){ + await personal.record(user,{...evidence,metric:'spice-harvest'}); + if(!official)throw Error('Reputation spice evidence is unavailable.'); + await official.record(user,{...evidence,metric:'pol-repeat-spice'}); + }else{ + if(!contraband)throw Error('Reputation smuggling evidence is unavailable.'); + await contraband.record(user,{...evidence,metric:'pol-repeat-smuggling'}); + } + return {recorded:true}; + }; +} diff --git a/website/scripts/spice-quest-migration.mjs b/website/scripts/spice-quest-migration.mjs new file mode 100644 index 00000000..7aea338b --- /dev/null +++ b/website/scripts/spice-quest-migration.mjs @@ -0,0 +1,4 @@ +import {openPostbankDatabase} from '../node/postbank-db.mjs'; +import {ensureSpiceSaleStorage} from '../node/game-spice.mjs'; +const bank=await openPostbankDatabase(process.env); +try{await ensureSpiceSaleStorage(bank);console.log('Spice receipt quest tracking ready; no balances changed.');}finally{await bank.close();} diff --git a/website/tests/bank-quest-activities.test.mjs b/website/tests/bank-quest-activities.test.mjs index e1de54c2..75af17ea 100644 --- a/website/tests/bank-quest-activities.test.mjs +++ b/website/tests/bank-quest-activities.test.mjs @@ -21,9 +21,10 @@ test('earned DM is cumulative settled income across personal accounts, including insert(1,4,1,100000,'posted','payroll');insert(2,3,2,80000,'posted','exchange'); insert(3,1,2,9999999,'posted','exchange');insert(4,3,1,9999999,'queued','payroll');insert(5,3,1,40000,'posted','standard');insert(6,3,1,9999999,'posted','refund');insert(7,3,1,9999999,'posted','exchange',500);insert(8,3,1,9999999,'posted','exchange',3000);insert(9,3,5,9999999,'posted','exchange'); insert(10,3,1,20000,'posted','instant');insert(11,4,1,30000,'posted','system');db.prepare('UPDATE pb_orders SET memo=? WHERE id=11').run('Reputation reward 11');insert(12,4,1,9999999,'posted','system'); + db.exec("INSERT INTO pb_accounts VALUES(6,NULL,0,'sys_payroll_po')");insert(13,6,1,10000,'posted','spice');insert(14,3,1,9999999,'posted','spice');insert(15,6,1,9999999,'queued','spice');insert(16,6,5,9999999,'posted','spice'); const bank={query:async(text,args)=>db.prepare(text).all(...args)}; - assert.deepEqual(await bankQuestIncome(bank,'player',1000,2000),{wages:1,earned:270000}); - db.exec('UPDATE pb_accounts SET balance_minor=0');assert.deepEqual(await bankQuestIncome(bank,'player',1000,2000),{wages:1,earned:270000}); + assert.deepEqual(await bankQuestIncome(bank,'player',1000,2000),{wages:1,earned:280000}); + db.exec('UPDATE pb_accounts SET balance_minor=0');assert.deepEqual(await bankQuestIncome(bank,'player',1000,2000),{wages:1,earned:280000}); assert.deepEqual(await bankQuestIncome(bank,'unknown',1000,2000),{wages:0,earned:0}); }finally{db.close();} }); diff --git a/website/tests/game-spice.test.mjs b/website/tests/game-spice.test.mjs index 7e112013..453524e9 100644 --- a/website/tests/game-spice.test.mjs +++ b/website/tests/game-spice.test.mjs @@ -1,15 +1,15 @@ import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs'; import {createGameSpiceAPI,spiceFingerprint,spiceQuote,activeSmugglerQuest} from '../node/game-spice.mjs'; -async function fixture({readOnlyReceipts=false}={}){ +async function fixture({readOnlyReceipts=false,recordSale}={}){ const bank=new BankFixture(),user={id:randomUUID(),username:'Miner'},uuid=randomUUID(),entity={id:randomUUID(),kind:'person',key:user.id,name:user.username};let active=false,now=100000; await new PostbankService(bank,async()=>({entities:[{...entity,canView:true,canActivate:true,canPay:true}]})).activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()}); const target=await bank.first("SELECT * FROM pb_accounts WHERE type_code='102'"); for(const key of ['sys_payroll_po','sys_tax_treasury'])await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES(?,'979',?,0,'active',1)",[key,key]); - bank.sqlite.exec("ATTACH DATABASE ':memory:' AS game;CREATE TABLE game.dune_exchange_inventory_ops(id TEXT PRIMARY KEY,actor_uuid TEXT,kind TEXT,fingerprint TEXT,listing_id INT,created_at INT);CREATE TABLE pb_spice_sales(id TEXT PRIMARY KEY,actor_id TEXT,player_uuid TEXT,channel TEXT,quantity INT,fingerprint TEXT,created_at INT,expires_at INT);"); + bank.sqlite.exec("ATTACH DATABASE ':memory:' AS game;CREATE TABLE game.dune_exchange_inventory_ops(id TEXT PRIMARY KEY,actor_uuid TEXT,kind TEXT,fingerprint TEXT,listing_id INT,created_at INT);CREATE TABLE pb_spice_sales(id TEXT PRIMARY KEY,actor_id TEXT,player_uuid TEXT,channel TEXT,quantity INT,fingerprint TEXT,created_at INT,expires_at INT,quest_reported_at INT);"); const db={query:async(sql,args)=>args[0]===uuid?[user]:[]},secret='spice-api-test-secret-123456789012345'; const receiptReader={query:bank.query.bind(bank),first:bank.first.bind(bank),transaction:work=>bank.transaction(tx=>work({...tx,first(sql,args){if(sql.includes('dune_exchange_inventory_ops')&&/FOR\s+(UPDATE|SHARE)|LOCK\s+IN/i.test(sql))throw Error('Inventory receipts are read-only');return tx.first(sql,args);}}))}; - const api=createGameSpiceAPI(db,readOnlyReceipts?receiptReader:bank,null,{GAME_LINK_SECRET:secret},{verifyStorage:async()=> 'game',clock:()=>now,pol:{quests:{list:async()=>({quests:[{id:'POL-SMUGGLERS-02',branch:'smugglers',state:active?'active':'claimed'}]})}}}); + const api=createGameSpiceAPI(db,readOnlyReceipts?receiptReader:bank,null,{GAME_LINK_SECRET:secret},{verifyStorage:async()=> 'game',clock:()=>now,recordSale,pol:{quests:{list:async()=>({quests:[{id:'POL-SMUGGLERS-02',branch:'smugglers',state:active?'active':'claimed'}]})}}}); const call=async(input,token=secret)=>{const response=await api(new Request('https://cp.dunerealms.com/internal/game/spice',{method:'POST',headers:{authorization:'Bearer '+token,'content-type':'application/json'},body:JSON.stringify({uuid,server:'arrakis',...input})}));return {status:response.status,body:await response.json()};}; const prepare=(channel='guild')=>({action:'prepare',requestId:randomUUID(),channel,amount:64,confirmed:true}); async function receipt(input){await bank.query('INSERT INTO game.dune_exchange_inventory_ops VALUES(?,?,?,?,?,?)',[input.requestId,uuid,'spice-'+input.channel,spiceFingerprint(uuid,input.channel,input.amount),input.amount,now+100]);} @@ -21,3 +21,12 @@ test('Arrakis-only and authenticated; locked Smuggler cannot prepare and quotes test('only a committed exact inventory receipt pays; retry posts once with balanced P&O and tax entries',async()=>{const f=await fixture();try{const input=f.prepare();assert.equal((await f.call(input)).status,200);assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,409);await f.receipt(input);const paid=await f.call({action:'settle',requestId:input.requestId});assert.equal(paid.status,200,JSON.stringify(paid.body));assert.equal((await f.call({action:'settle',requestId:input.requestId})).body.replayed,true);assert.equal(Number((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor),spiceQuote('guild',64).netMinor);assert.equal(Number((await f.bank.first('SELECT SUM(amount_minor) n FROM pb_entries')).n),0);assert.equal(Number((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n),2);}finally{f.bank.close();}}); test('recoverable receipt remains payable after quote expiry; forged quantity or actor earns nothing',async()=>{const f=await fixture();try{const input=f.prepare();await f.call(input);await f.receipt(input);f.expire();assert.deepEqual((await f.call({action:'pending'})).body.pending,[input.requestId]);assert.equal((await f.call({action:'settle',requestId:input.requestId,uuid:randomUUID()})).status,403);await f.bank.query('UPDATE game.dune_exchange_inventory_ops SET listing_id=65');assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,409);await f.bank.query('UPDATE game.dune_exchange_inventory_ops SET listing_id=64');assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,200);}finally{f.bank.close();}}); test('a ledger failure rolls back the whole payout and remains recoverable',async()=>{const f=await fixture();try{const input=f.prepare();await f.call(input);await f.receipt(input);f.bank.sqlite.exec("CREATE TRIGGER fail_tax BEFORE INSERT ON pb_orders WHEN NEW.memo='Spice sale · Trust levy' BEGIN SELECT RAISE(ABORT,'tax fault');END;");assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,409);assert.equal(Number((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n),0);assert.equal(Number((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor),0);f.bank.sqlite.exec('DROP TRIGGER fail_tax');assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,200);}finally{f.bank.close();}}); + +test('paid spice is reported to quests only after the ledger commits and only once',async()=>{ + let reports=0,f;f=await fixture({recordSale:async(user,input)=>{reports++;assert.equal(user.id,f.user.id);assert.equal((await f.bank.first('SELECT state FROM pb_orders WHERE id=?',[input.requestId])).state,'posted');}}); + try{const input=f.prepare();await f.call(input);assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,409);assert.equal(reports,0);await f.receipt(input);assert.equal((await f.call({action:'settle',requestId:input.requestId})).status,200);await f.call({action:'settle',requestId:input.requestId});assert.equal(reports,1);assert.deepEqual((await f.call({action:'pending'})).body.pending,[]);}finally{f.bank.close();} +}); +test('quest reporting failure preserves the payment and reconnect retries evidence without paying again',async()=>{ + let fail=true,reports=0;const f=await fixture({recordSale:async()=>{reports++;if(fail)throw Error('Quest store unavailable');}}); + try{const input=f.prepare();await f.call(input);await f.receipt(input);const paid=await f.call({action:'settle',requestId:input.requestId});assert.equal(paid.status,200);assert.equal(paid.body.questProgressPending,true);assert.deepEqual((await f.call({action:'pending'})).body.pending,[input.requestId]);const balance=(await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor;fail=false;const recovered=await f.call({action:'settle',requestId:input.requestId});assert.equal(recovered.body.replayed,true);assert.equal(reports,2);assert.equal((await f.bank.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,balance);assert.deepEqual((await f.call({action:'pending'})).body.pending,[]);assert.equal(Number((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n),2);}finally{f.bank.close();} +}); diff --git a/website/tests/spice-quest-receipts.test.mjs b/website/tests/spice-quest-receipts.test.mjs new file mode 100644 index 00000000..80e68385 --- /dev/null +++ b/website/tests/spice-quest-receipts.test.mjs @@ -0,0 +1,32 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {BankFixture} from './postbank-fixture.mjs';import {systemCharacterFixture} from './system-character-fixture.mjs'; +import {initializeProgression} from '../node/progression-schema.mjs';import {ensureProgressionPolicy} from '../node/progression-policy.mjs'; +import {initializePersonalActivityEvents} from '../node/personal-activity-events.mjs';import {initializePOLProgression,ensurePOLProgressionPolicy} from '../node/progression-pol.mjs';import {initializePOLActivityEvents} from '../node/pol-activity-events.mjs'; +import {createSpiceQuestReceipts} from '../node/spice-quest-receipts.mjs'; + +test('only posted P&O sales issue idempotent quest keys; normal and smuggled spice stay separate',async()=>{ + const f=await systemCharacterFixture(),bank=new BankFixture(); + try{ + for(const name of ['stilgar','esmar_tuek'])await f.characters.provision(f.people.Owner,name); + await initializeProgression(f.db);await ensureProgressionPolicy(f.db,f.keys,{clock:()=>1000});await initializePersonalActivityEvents(f.db); + await initializePOLProgression(f.db);await ensurePOLProgressionPolicy(f.db,f.keys,{clock:()=>1000});await initializePOLActivityEvents(f.db);f.db.polActivityEventsEnabled=true; + bank.sqlite.exec('CREATE TABLE pb_spice_sales(id TEXT PRIMARY KEY,actor_id TEXT,player_uuid TEXT,channel TEXT,quantity INT,fingerprint TEXT,created_at INT,expires_at INT)'); + await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES('sys_payroll_po','979','P&O',0,'active',1)"); + await bank.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES('sys_tax_treasury','979','Test recipient',0,'active',1)"); + const source=await bank.first("SELECT id FROM pb_accounts WHERE system_key='sys_payroll_po'"),user=f.people.Member,uuid=randomUUID(); + await f.db.query('UPDATE site_game_links SET minecraft_uuid=? WHERE user_id=?',[uuid,user.id]); + const record=createSpiceQuestReceipts(f.db,bank,f.keys,{clock:()=>2000}); + for(const channel of ['guild','smuggler']){ + const id=randomUUID();await bank.query('INSERT INTO pb_spice_sales VALUES(?,?,?,?,?,?,?,?)',[id,user.id,uuid,channel,64,'proof-'+id,1000,3000]); + await assert.rejects(record(user,{requestId:id,uuid}),/posted native/); + await bank.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at,posted_at) VALUES(?,?,?,?,?,1000,'Spice sale','spice','posted',1000,2000)",[id,user.id,source.id,2,'proof-'+id]); + await assert.rejects(record(user,{requestId:id,uuid:randomUUID()}),/posted native/); + await record(user,{requestId:id,uuid});await record(user,{requestId:id,uuid}); + } + assert.equal((await f.db.first('SELECT COUNT(*) n FROM jarvis_personal_activity_events')).n,1); + assert.equal((await f.db.first('SELECT metric FROM jarvis_personal_activity_events')).metric,'spice-harvest'); + const rows=await f.db.query('SELECT metric,quantity FROM jarvis_pol_activity_events ORDER BY metric'); + assert.deepEqual(rows.map(r=>[r.metric,Number(r.quantity)]),[['pol-repeat-smuggling',64],['pol-repeat-spice',64]]); + assert.equal(Number((await bank.first('SELECT COUNT(*) n FROM pb_orders')).n),2); + }finally{f.db.close();bank.close();} +});