diff --git a/website/node/deed-purchases.mjs b/website/node/deed-purchases.mjs new file mode 100644 index 00000000..8680094d --- /dev/null +++ b/website/node/deed-purchases.mjs @@ -0,0 +1,52 @@ +import {createHash} from 'node:crypto'; +import {createDeedSaleKeys} from './deed-sale-keys.mjs'; +import {createDeedPurchasePayments} from './deed-purchase-payments.mjs'; +import {PostbankPayments,standardCycle} from './postbank-payments.mjs'; +import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs'; +import {JarvisError} from './jarvis-listings.mjs'; +import {entityId} from './postbank-authority.mjs'; +export const DEED_PURCHASE_SCHEMA="CREATE TABLE IF NOT EXISTS jarvis_deed_purchases(id CHAR(36) PRIMARY KEY,listing_id CHAR(36) NOT NULL,listing_revision INTEGER NOT NULL,actor_id CHAR(36) NOT NULL,seller_id CHAR(36) NOT NULL,key_id CHAR(36) NOT NULL,parent_kind VARCHAR(12) NOT NULL,parent_id CHAR(36) NOT NULL,source_account BIGINT NOT NULL,recipient_account BIGINT NOT NULL,price_minor BIGINT NOT NULL,fingerprint CHAR(64) NOT NULL,quote_json TEXT NOT NULL,state VARCHAR(16) NOT NULL,due_at BIGINT NOT NULL,cleanup_needed INTEGER NOT NULL DEFAULT 0,last_error VARCHAR(80) NULL,created_at BIGINT NOT NULL,updated_at BIGINT NOT NULL,INDEX deed_purchase_due(state,due_at),INDEX deed_purchase_listing(listing_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; +const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(v); +const accountSQL='SELECT a.*,c.entity_id,e.kind,e.external_key,e.active AS entity_active,p.state AS package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id'; +const fail=(message,status=409)=>{throw new JarvisError(message,status);}; +const paymentInput=j=>({keyId:j.key_id,listingId:j.listing_id,requestId:j.id,actorId:j.actor_id,sellerId:j.seller_id,parentKind:j.parent_kind,parentId:j.parent_id,sourceAccount:String(j.source_account),recipientAccount:String(j.recipient_account),priceMinor:Number(j.price_minor)}); +const matches=(j,p)=>j&&j.id===p.requestId&&j.actor_id===p.buyerId&&j.seller_id===p.sellerId&&j.key_id===p.keyId&&j.listing_id===p.listingId&&j.parent_kind===p.parent.kind&&j.parent_id===p.parent.id&&String(j.source_account)===p.sourceAccount&&String(j.recipient_account)===p.recipientAccount&&Number(j.price_minor)===p.priceMinor; +const receipt=j=>({purchaseId:j.id,listingId:j.listing_id,state:j.state,nextProcessingAt:Number(j.due_at),paymentReference:j.id,complete:j.state==='posted',message:j.state==='posted'?'Deed acquisition and payment completed.':j.state==='failed'?'The deed or payment authority changed. No purchase was completed.':'Purchase reserved for the ordinary bank processing window.'}); +export function createDeedPurchases(central,bank,keys,{authority,clock=Date.now,resolveActor=async id=>(await central.query("SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]))[0]||null}={}){ + if(typeof authority!=='function')throw TypeError('Current bank authority adapter required'); + const job=async id=>bank.first('SELECT * FROM jarvis_deed_purchases WHERE id=?',[id]); + const sales=createDeedSaleKeys(central,keys,{clock, + verifyPurchaseIntent:async(_actor,p)=>{const j=await job(p.requestId);if(!matches(j,p))return false;const order=await bank.first('SELECT state FROM pb_orders WHERE id=?',[j.id]);return p.releasing?j.state==='failed'&&(!order||order.state==='cancelled'):j.state==='preparing'&&!order;}, + verifyPurchaseFunding:async(_actor,p)=>{const j=await job(p.requestId);if(!matches(j,p)||j.state!=='funded')return false;const o=await bank.first('SELECT * FROM pb_orders WHERE id=?',[j.id]);return !!o&&o.mode==='deed'&&o.state==='escrow'&&o.actor_id===j.actor_id&&String(o.source_id)===String(j.source_account)&&String(o.target_id)===String(j.recipient_account)&&Number(o.amount_minor)===Number(j.price_minor);} + }); + const payments=createDeedPurchasePayments(bank,authority,{clock, + verifyTransfer:async input=>{const j=await job(input.requestId),s=await sales.purchaseState(input.keyId);return j?.state==='applied'&&s?.applied===true&&s.requestId===j.id&&s.buyerId===j.actor_id;}, + canRelease:async input=>{const j=await job(input.requestId),s=await sales.purchaseState(input.keyId);return j?.state==='funded'&&s&&!s.keyUsed&&s.state==='reserved'&&s.requestId===j.id&&s.buyerId===j.actor_id;} + }); + async function parents(actor){const rows=[];if(central.clanDeedsEnabled)rows.push(...(await central.query("SELECT c.id,c.name,'clan' kind FROM site_clans c JOIN site_clan_charters ch ON ch.clan_id=c.id LEFT JOIN site_clan_institutions i ON i.clan_id=c.id WHERE c.active=1 AND c.owner_id=? AND ch.charter_kind IN ('original','royal') AND i.institution_key IS NULL",[actor.id])));if(central.companyDeedsEnabled)rows.push(...(await central.query("SELECT c.id,c.name,'company' kind FROM corrino_companies c JOIN site_company_deeds d ON d.company_id=c.id LEFT JOIN site_company_institutions i ON i.company_id=c.id WHERE c.status='active' AND d.owner_account_id=? AND d.charter_kind IN ('original','royal') AND i.institution_key IS NULL",[actor.id])));return rows;} + async function payout(sellerId){const rows=await bank.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? ORDER BY a.id",[sellerId]);const account=rows.find(ordinaryPaymentAccount);if(!account)fail('The seller needs an active personal payment account.');return account;} + async function currentOffer(listingId){const listing=await bank.first("SELECT * FROM jarvis_listings WHERE id=? AND definition_id='entity-transfer' AND state='open'",[listingId]);if(!listing)fail('This deed offer is no longer open.');const offer=await sales.purchaseOffer(listingId);if(listing.actor_id!==offer.sellerId||listing.organisation_id!==offer.entityId||listing.organisation_kind!==offer.kind)fail('The listing and deed disagree.');return {listing,offer};} + async function cleanup(j){const s=await sales.purchaseState(j.key_id);if(s?.state==='reserved'&&s.requestId===j.id&&s.buyerId===j.actor_id)await sales.releasePurchase({id:j.actor_id},{keyId:j.key_id,requestId:j.id});else if(s?.keyUsed||s?.state==='reserved')return;await bank.query('UPDATE jarvis_deed_purchases SET cleanup_needed=0 WHERE id=? AND state=\'failed\'',[j.id]);} + async function abort(id,error){await bank.transaction(async tx=>{const j=await tx.first('SELECT * FROM jarvis_deed_purchases WHERE id=? FOR UPDATE',[id]);if(!j||!['preparing','funded'].includes(j.state))return;if(j.state==='funded')await payments.release(tx,paymentInput(j));await tx.query("UPDATE jarvis_deed_purchases SET state='failed',cleanup_needed=1,last_error=?,updated_at=? WHERE id=?",[(error.name+':'+error.status).slice(0,80),clock(),id]);await tx.query("UPDATE jarvis_listings SET state='open',revision=revision+1,updated_at=? WHERE id=? AND state='reserved' AND revision=?",[clock(),j.listing_id,Number(j.listing_revision)+1]);});const j=await job(id);if(j?.state==='failed'&&Number(j.cleanup_needed))await cleanup(j);} + async function process(id){ + for(let step=0;step<3;step++)try{const result=await bank.transaction(async tx=>{ + const j=await tx.first('SELECT * FROM jarvis_deed_purchases WHERE id=? FOR UPDATE',[id]);if(!j)fail('Purchase not found.',404); + if(j.state==='preparing'){const actor=await resolveActor(j.actor_id);if(!actor)fail('The purchasing account is unavailable.',403);await sales.reservePurchase(actor,{keyId:j.key_id,requestId:j.id,parentKind:j.parent_kind,parentId:j.parent_id,sourceAccount:String(j.source_account),recipientAccount:String(j.recipient_account)});await payments.reserve(tx,actor,paymentInput(j));await tx.query("UPDATE jarvis_deed_purchases SET state='funded',updated_at=? WHERE id=?",[clock(),id]);return 'continue';} + if(j.state==='funded'){if(Number(j.due_at)>clock())return 'wait';const actor=await resolveActor(j.actor_id);if(!actor)fail('The purchasing account is unavailable.',403);await sales.applyPurchase(actor,{keyId:j.key_id,requestId:j.id});await tx.query("UPDATE jarvis_deed_purchases SET state='applied',updated_at=? WHERE id=?",[clock(),id]);return 'continue';} + if(j.state==='applied'){await payments.settle(tx,paymentInput(j));await tx.query("UPDATE jarvis_deed_purchases SET state='posted',updated_at=? WHERE id=?",[clock(),id]);await tx.query("UPDATE jarvis_listings SET state='sold',revision=revision+1,updated_at=? WHERE id=? AND state='reserved'",[clock(),j.listing_id]);return 'done';} + return 'done'; + });if(result!=='continue')break;}catch(error){const j=await job(id);if(!j)throw error;const s=await sales.purchaseState(j.key_id);if(error.status>=400&&error.status<500&&(j.state==='preparing'||j.state==='funded'&&s&&!s.keyUsed&&s.state==='reserved'&&s.requestId===id)){await abort(id,error);}else await bank.query('UPDATE jarvis_deed_purchases SET last_error=?,updated_at=? WHERE id=?',[(error.name||'Error').slice(0,80),clock(),id]);break;} + const j=await job(id);if(j.state==='failed'&&Number(j.cleanup_needed))await cleanup(j);return receipt(j); + } + return Object.freeze({sales, + async quote(actor,listingId){if(!uuid(actor?.id)||!uuid(listingId))fail('Choose a deed offer.',400);const {listing,offer}=await currentOffer(listingId);if(offer.sellerId===actor.id)fail('Choose a deed belonging to another owner.');const recipient=await payout(offer.sellerId),owned=await parents(actor),accounts=(await new PostbankPayments(bank,authority,{clock}).accounts(actor)).filter(a=>a.canDebit);return {listingId,revision:Number(listing.revision),name:offer.name,kind:offer.kind,priceMinor:offer.priceMinor,recipientAccount:String(recipient.id),recipientName:recipient.display_name,recipientNumber:recipient.account_number,parents:owned.filter(p=>p.kind!==offer.kind||p.id!==offer.entityId).map(p=>({...p,entityId:entityId(p.kind,p.id)})),accounts,nextProcessingAt:standardCycle(clock()).nextAt,terms:'Acquire parent-deed control. The local owner, roster and personal votes remain unchanged. Payment and transfer complete at the ordinary bank processing window.'};}, + async begin(actor,input){ + const fields=['listingId','revision','parentKind','parentId','sourceAccount','recipientAccount','expectedPriceMinor','requestId','confirmed'];if(!uuid(actor?.id)||!input||Object.keys(input).some(k=>!fields.includes(k))||input.confirmed!==true||!uuid(input.listingId)||!uuid(input.requestId)||!uuid(input.parentId)||!['clan','company'].includes(input.parentKind)||!Number.isSafeInteger(input.revision)||input.revision<1||!Number.isSafeInteger(input.expectedPriceMinor)||input.expectedPriceMinor<1||!/^\d{1,12}$/.test(input.sourceAccount)||!/^\d{1,12}$/.test(input.recipientAccount))fail('Review and confirm the current deed purchase.',400); + const fingerprint=createHash('sha256').update(JSON.stringify([actor.id,...fields.filter(k=>k!=='confirmed').map(k=>input[k])])).digest('hex');let previous=await job(input.requestId);if(previous){if(previous.actor_id!==actor.id||previous.fingerprint!==fingerprint)fail('Purchase reference conflict.');return process(previous.id);} + const {listing,offer}=await currentOffer(input.listingId),recipient=await payout(offer.sellerId);if(offer.sellerId===actor.id||Number(listing.revision)!==input.revision||offer.priceMinor!==input.expectedPriceMinor||String(recipient.id)!==input.recipientAccount)fail('The deed price or recipient changed. Refresh before confirming.');if(!(await parents(actor)).some(p=>p.id===input.parentId&&p.kind===input.parentKind))fail('Current purchasing deed authority required.',403); + await bank.transaction(async tx=>{const row=await tx.first('SELECT * FROM jarvis_listings WHERE id=? FOR UPDATE',[input.listingId]),prior=await tx.first('SELECT * FROM jarvis_deed_purchases WHERE id=?',[input.requestId]);if(prior){if(prior.actor_id!==actor.id||prior.fingerprint!==fingerprint)fail('Purchase reference conflict.');return;}if(!row||row.state!=='open'||Number(row.revision)!==input.revision)fail('This deed is no longer available.');const now=clock();await tx.query("INSERT INTO jarvis_deed_purchases(id,listing_id,listing_revision,actor_id,seller_id,key_id,parent_kind,parent_id,source_account,recipient_account,price_minor,fingerprint,quote_json,state,due_at,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,'preparing',?,?,?)",[input.requestId,input.listingId,input.revision,actor.id,offer.sellerId,offer.keyId,input.parentKind,input.parentId,input.sourceAccount,input.recipientAccount,offer.priceMinor,fingerprint,JSON.stringify(offer),standardCycle(now).nextAt,now,now]);await tx.query("UPDATE jarvis_listings SET state='reserved',revision=revision+1,updated_at=? WHERE id=?",[now,input.listingId]);});return process(input.requestId); + }, + async status(actor,id){const j=uuid(id)&&await job(id);if(!j||j.actor_id!==actor?.id)fail('Purchase not found.',404);return receipt(j);}, + async drain(){const jobs=await bank.query("SELECT id FROM jarvis_deed_purchases WHERE state='preparing' OR state='funded' AND due_at<=? OR state='applied' OR state='failed' AND cleanup_needed=1 ORDER BY created_at,id LIMIT 25",[clock()]);let posted=0,failed=0;for(const j of jobs)try{const result=await process(j.id);if(result.state==='posted')posted++;if(result.state==='failed')failed++;}catch{failed++;}return {attempted:jobs.length,posted,failed};} + }); +} diff --git a/website/node/deed-sale-keys.mjs b/website/node/deed-sale-keys.mjs index a40a3948..e7adc7a6 100644 --- a/website/node/deed-sale-keys.mjs +++ b/website/node/deed-sale-keys.mjs @@ -46,6 +46,12 @@ export function createDeedSaleKeys(central,keys,{clock=Date.now,verifyPurchaseIn return {keyId:grant.id,listingId:input.requestId,kind:input.kind,entityId:input.entityId,title:offer.manifest.deed.name+' ยท deed',message:fields.reference,priceMinor,created:grant.created}; }, + async purchaseOffer(listingId){ + if(!uuid(listingId))throw new JarvisError('Choose a deed offer.');const row=await first(central,'SELECT key_id FROM jarvis_generated_instructions WHERE request_id=? AND action_id=?',[listingId,action]);const offer=row&&await currentOffer(row.key_id);if(!offer)throw new JarvisError('Current deed offer unavailable.',409);return {keyId:row.key_id,listingId,sellerId:offer.manifest.deed.ownerId,kind:offer.manifest.deed.kind,entityId:offer.manifest.deed.id,name:offer.manifest.deed.name,priceMinor:offer.manifest.priceMinor}; + }, + async purchaseState(keyId){ + if(!uuid(keyId))throw new JarvisError('Choose a purchase key.');const row=await readOffer(keyId);if(!row)return null;const purchase=JSON.parse(row.manifest_json).purchase;const used=await first(central,'SELECT target_id,request_id FROM organisation_keys WHERE id=?',[keyId]);return {state:row.state,keyUsed:row.used_at!=null,keyRevoked:row.revoked_at!=null,requestId:purchase?.requestId||null,buyerId:purchase?.buyerId||null,applied:row.state==='applied'&&row.used_at!=null&&used?.request_id===purchase?.requestId&&used?.target_id===purchase?.parent?.id}; + }, async reservePurchase(actor,input){ if(!uuid(actor?.id)||!input||Object.keys(input).some(k=>!['keyId','requestId','parentKind','parentId','sourceAccount','recipientAccount'].includes(k))||!uuid(input.keyId)||!uuid(input.requestId)||!uuid(input.parentId)||!['clan','company'].includes(input.parentKind)||!/^\d{1,12}$/.test(input.sourceAccount)||!/^\d{1,12}$/.test(input.recipientAccount))throw new JarvisError('Review the purchase and its payment accounts.'); return central.transaction(async tx=>{ diff --git a/website/tests/deed-purchases.test.mjs b/website/tests/deed-purchases.test.mjs new file mode 100644 index 00000000..67794a6c --- /dev/null +++ b/website/tests/deed-purchases.test.mjs @@ -0,0 +1,18 @@ +import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto'; +import {companyFixture} from './company-deed-fixture.mjs';import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';import {entityId} from '../node/postbank-authority.mjs';import {GENERATOR_SCHEMA} from '../node/jarvis-master-generator.mjs';import {JARVIS_LISTING_SCHEMA,createJarvisListings} from '../node/jarvis-listings.mjs';import {DEED_PURCHASE_SCHEMA,createDeedPurchases} from '../node/deed-purchases.mjs'; +async function fixture(){ + const f=await companyFixture(),child=await f.create();f.actor('Member');const created=await f.call('',{...f.registration,slug:'buyer-parent',name:'Buyer Company',requestId:randomUUID()});assert.equal(created.status,201);const parent=(await created.json()).companyId;await f.db.query("UPDATE site_company_deeds SET charter_kind='original' WHERE company_id=?",[parent]);await f.db.query(GENERATOR_SCHEMA);await f.db.query('CREATE TABLE account_audit(id TEXT PRIMARY KEY,actor_id TEXT,action TEXT,details TEXT,created_at INTEGER)'); + const bank=new BankFixture();for(const sql of [...JARVIS_LISTING_SCHEMA,DEED_PURCHASE_SCHEMA])await bank.query(sql.replace(/ ENGINE=InnoDB DEFAULT CHARSET=utf8mb4/g,'').replace(/,INDEX \w+\([^)]*\)/g,'').replace(/UNIQUE KEY \w+\(/g,'UNIQUE(')); + let now=Date.parse('2026-11-20T10:00:00Z'),canPay=true;const buyer=f.people.Member,seller=f.people.Owner,buyerEntity={id:entityId('company',parent),kind:'company',key:parent,name:'Buyer Company'},sellerEntity={id:entityId('person',seller.id),kind:'person',key:seller.id,name:'Seller'}; + const authority=async actor=>({entities:actor.id===buyer.id?[{...buyerEntity,canView:true,canActivate:true,canPay}]:actor.id===seller.id?[{...sellerEntity,canView:true,canActivate:true,canPay:true}]:[]}); + for(const [user,entity]of [[buyer,buyerEntity],[seller,sellerEntity]])await new PostbankService(bank,authority).activate(user,{entityId:entity.id,packageKey:entity.kind==='person'?'pb_start':'pb_connect',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()}); + const account=async id=>bank.first("SELECT a.* FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE c.entity_id=? AND a.type_code<>'106' ORDER BY a.id LIMIT 1",[id]),source=await account(buyerEntity.id),target=await account(sellerEntity.id);await bank.query('UPDATE pb_accounts SET balance_minor=10000 WHERE id=?',[source.id]);await bank.query('UPDATE pb_accounts SET balance_minor=0 WHERE id=?',[target.id]); + const flow=createDeedPurchases(f.db,bank,f.keys,{authority,clock:()=>now}),key=await flow.sales.issue(seller,{kind:'company',entityId:child,version:1,price:'25.00',message:'Patronage',requestId:randomUUID(),confirmed:true});const listings=createJarvisListings(bank,{authority:async actor=>({canPublish:actor.id===seller.id}),reserveFee:async()=>{throw Error('Not a recruitment charge');},edition:async()=>({stage:'alpha',version:'1.0.1.2',season:'S01'}),clock:()=>now});const {listing}=await listings.publishKey(seller,key.keyId,{verify:flow.sales.listing}); + const quote=await flow.quote(buyer,listing.id),input={listingId:listing.id,revision:quote.revision,parentKind:'company',parentId:parent,sourceAccount:String(source.id),recipientAccount:quote.recipientAccount,expectedPriceMinor:quote.priceMinor,requestId:randomUUID(),confirmed:true}; + return {...f,child,parent,bank,buyer,seller,source,target,flow,key,listing,input,clock:value=>now=value,revoke:()=>canPay=false,close(){f.db.close();bank.close();}}; +} +test('confirmed purchase reserves once, waits for the existing bank window, then applies XFR and balanced posting once',async()=>{const f=await fixture();try{const pending=await f.flow.begin(f.buyer,f.input);assert.equal(pending.state,'funded');assert.equal((await f.flow.begin(f.buyer,f.input)).state,'funded');await assert.rejects(f.flow.status(f.people.Other,f.input.requestId));assert.equal((await f.bank.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,2500);assert.equal((await f.db.query('SELECT * FROM jarvis_entity_relations WHERE child_id=?',[f.child])).length,0);f.clock(pending.nextProcessingAt+1);assert.equal((await f.flow.drain()).posted,1);assert.equal((await f.flow.status(f.buyer,f.input.requestId)).complete,true);assert.equal((await f.flow.begin(f.buyer,f.input)).state,'posted');assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_entries WHERE order_id=?',[f.input.requestId])).n,2);assert.equal((await f.bank.first('SELECT SUM(amount_minor) n FROM pb_entries WHERE order_id=?',[f.input.requestId])).n,0);assert.equal((await f.db.first('SELECT parent_id FROM jarvis_entity_relations WHERE child_id=?',[f.child])).parent_id,f.parent);assert.equal((await f.db.first('SELECT owner_account_id FROM site_company_deeds WHERE company_id=?',[f.child])).owner_account_id,f.seller.id);}finally{f.close();}}); +test('changed purchaser deed releases only the unexecuted purchase and preserves all balances and local ownership',async()=>{const f=await fixture();try{const pending=await f.flow.begin(f.buyer,f.input);await f.db.query('UPDATE site_company_deeds SET version=version+1 WHERE company_id=?',[f.parent]);f.clock(pending.nextProcessingAt+1);await f.flow.drain();assert.equal((await f.flow.status(f.buyer,f.input.requestId)).state,'failed');assert.equal((await f.bank.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,0);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_entries WHERE order_id=?',[f.input.requestId])).n,0);assert.equal((await f.db.query('SELECT * FROM jarvis_entity_relations WHERE child_id=?',[f.child])).length,0);assert.equal((await f.flow.sales.purchaseState(f.key.keyId)).state,'issued');}finally{f.close();}}); +test('revoked bank authority fails before any transfer and safely releases the sale-key reservation',async()=>{const f=await fixture();try{f.revoke();const result=await f.flow.begin(f.buyer,f.input);assert.equal(result.state,'failed');assert.equal((await f.flow.sales.purchaseState(f.key.keyId)).state,'issued');assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders WHERE id=?',[f.input.requestId])).n,0);assert.equal((await f.bank.first('SELECT state FROM jarvis_listings WHERE id=?',[f.listing.id])).state,'open');}finally{f.close();}}); +test('applied transfer with blocked payout retains escrow and reconciles payment without transferring or charging twice',async()=>{const f=await fixture();try{const pending=await f.flow.begin(f.buyer,f.input);await f.bank.query("UPDATE pb_accounts SET state='blocked' WHERE id=?",[f.target.id]);f.clock(pending.nextProcessingAt+1);await f.flow.drain();assert.equal((await f.flow.status(f.buyer,f.input.requestId)).state,'applied');assert.equal((await f.bank.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,2500);assert.equal((await f.flow.sales.purchaseState(f.key.keyId)).applied,true);await f.bank.query("UPDATE pb_accounts SET state='active' WHERE id=?",[f.target.id]);assert.equal((await f.flow.drain()).posted,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_entries WHERE order_id=?',[f.input.requestId])).n,2);}finally{f.close();}}); +test('lost bank acknowledgement after committed key execution replays the key receipt and posts once',async()=>{const f=await fixture();try{const pending=await f.flow.begin(f.buyer,f.input);f.bank.sqlite.exec("CREATE TRIGGER lose_ack BEFORE UPDATE OF state ON jarvis_deed_purchases WHEN NEW.state='applied' BEGIN SELECT RAISE(ABORT,'injected'); END;");f.clock(pending.nextProcessingAt+1);await f.flow.drain();assert.equal((await f.flow.status(f.buyer,f.input.requestId)).state,'funded');assert.equal((await f.flow.sales.purchaseState(f.key.keyId)).applied,true);assert.equal((await f.bank.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,2500);f.bank.sqlite.exec('DROP TRIGGER lose_ack');assert.equal((await f.flow.drain()).posted,1);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_entries WHERE order_id=?',[f.input.requestId])).n,2);}finally{f.close();}});