web/website/node/deed-acquisition-proof.mjs

17 lines
2.1 KiB
JavaScript

// A published offer or a parent relation alone is not proof of a paid acquisition.
// Use the existing consumed XFR receipt and balanced, posted Postbank order.
export async function verifyDeedAcquisition(central,bank,{accountId,kind,entityId,origin}){
if(!bank||!['clan','company'].includes(kind)||origin!==(kind==='clan'?'bend-the-knee':'purchase'))return false;
const jobs=await bank.query("SELECT j.* FROM jarvis_deed_purchases j JOIN pb_orders o ON o.id=j.id WHERE j.actor_id=? AND j.state='posted' AND o.state='posted' AND o.mode='deed' AND o.actor_id=j.actor_id AND o.source_id=j.source_account AND o.target_id=j.recipient_account AND o.amount_minor=j.price_minor",[accountId]);
for(const j of jobs){
let quote;try{quote=JSON.parse(j.quote_json);}catch{continue;}
if(quote.kind!==kind||quote.entityId!==entityId||quote.keyId!==j.key_id||quote.sellerId!==j.seller_id||quote.priceMinor!==Number(j.price_minor))continue;
const key=(await central.query("SELECT k.account_id,k.key_type,k.used_at,k.request_id,k.target_id,i.state,i.manifest_json FROM organisation_keys k JOIN jarvis_generated_instructions i ON i.key_id=k.id WHERE k.id=? AND i.action_id='relations.transfer'",[j.key_id]))[0];
if(!key||key.account_id!==j.seller_id||key.key_type!=='entity-transfer'||key.used_at==null||key.request_id!==j.id||key.target_id!==j.parent_id||key.state!=='applied')continue;
let m;try{m=JSON.parse(key.manifest_json);}catch{continue;}const p=m.purchase;
if(m.operation!=='deed-sale'||m.deed?.id!==entityId||m.deed.kind!==kind||m.priceMinor!==Number(j.price_minor)||p?.requestId!==j.id||p.buyerId!==accountId||p.parent?.kind!==j.parent_kind||p.parent?.id!==j.parent_id||p.sourceAccount!==String(j.source_account)||p.recipientAccount!==String(j.recipient_account))continue;
const entries=await bank.query('SELECT account_id,amount_minor FROM pb_entries WHERE order_id=?',[j.id]);
if(entries.length===2&&entries.some(e=>String(e.account_id)===String(j.source_account)&&BigInt(e.amount_minor)===-BigInt(j.price_minor))&&entries.some(e=>String(e.account_id)===String(j.recipient_account)&&BigInt(e.amount_minor)===BigInt(j.price_minor)))return true;
}
return false;
}