Reserve quoted Rihla transfers once and release on sender cancellation

This commit is contained in:
unimatrixgit 2026-11-28 15:58:12 +01:00
commit 719a282f30

View file

@ -25,6 +25,10 @@ export function createRihlaAPI(central,bank,{authenticate=r=>identity(r,central)
export function createGameRihlaAPI(central,bank,settings={},deps={}){
const clock=deps.clock??Date.now;
const quoteReference=(actor,recipient,quote)=>createHash('sha256')
.update(JSON.stringify([actor.id,recipient.id,quote.amountMinor,quote.taxMinor])).digest('hex');
const transferView=row=>({number:row.transaction_number,state:row.state,
amountMinor:String(row.amount_minor),taxMinor:String(row.tax_minor)});
const resolve=deps.resolve??(async uuid=>{
const rows=await central.query(`SELECT a.id,a.username FROM site_accounts a
JOIN site_game_links l ON l.user_id=a.id
@ -42,21 +46,68 @@ export function createGameRihlaAPI(central,bank,settings={},deps={}){
input=JSON.parse(body);
}catch{return json({message:'Invalid Rihla request.'},400);}
if(!input||!validUuid(input.uuid))return json({message:'Invalid Rihla request.'},400);
const fields={read:['action','uuid'],quote:['action','uuid','amount','recipientUuid']};
const fields={
read:['action','uuid'],quote:['action','uuid','amount','recipientUuid'],
create:['action','uuid','amount','recipientUuid','quoteReference','requestId'],
cancel:['action','uuid','number']
};
if(!Object.hasOwn(fields,input.action)||Object.keys(input).some(key=>!fields[input.action].includes(key)))
return json({message:'Invalid Rihla request.'},400);
try{
const actor=await resolve(input.uuid);
if(!actor)return json({message:'Link your active personal website account first.'},403);
if(!bank)return json({message:'Rihla records are temporarily unavailable.'},503);
if(input.action==='quote'){
if(input.action==='create'&&deps.reservationsEnabled!==true)
return json({message:'Rihla transfer settlement is unavailable.'},503);
if(input.action==='quote'||input.action==='create'){
if(!validUuid(input.recipientUuid)||input.recipientUuid===input.uuid)
return json({message:'Choose another linked player.'},400);
let quote;
try{quote=rihlaQuote(input.amount);}catch(error){return json({message:error.message},400);}
const recipient=await resolve(input.recipientUuid);
if(!recipient||recipient.id===actor.id)return json({message:'Choose another linked player.'},400);
return json({...quote,recipientName:recipient.username});
const reference=quoteReference(actor,recipient,quote);
if(input.action==='quote')return json({...quote,recipientName:recipient.username,quoteReference:reference});
if(!validUuid(input.requestId)||input.quoteReference!==reference)
return json({message:'The Rihla quote changed. Request a fresh quote.'},409);
return await bank.transaction(async tx=>{
await ensureRihlaAccount(tx,actor.id,{clock});
const account=await tx.first('SELECT balance_minor,reserved_minor FROM ria_accounts WHERE owner_id=? FOR UPDATE',[actor.id]);
const prior=await tx.first('SELECT * FROM ria_transfers WHERE jarvis_instance_id=? FOR UPDATE',[input.requestId]);
if(prior){
if(prior.sender_id!==actor.id||prior.recipient_id!==recipient.id||
String(prior.amount_minor)!==quote.amountMinor||String(prior.tax_minor)!==quote.taxMinor)
return json({message:'This Rihla request reference was already used.'},409);
return json(transferView(prior));
}
const total=BigInt(quote.totalMinor),reserved=BigInt(account.reserved_minor),balance=BigInt(account.balance_minor);
if(reserved<0n||balance-reserved<total)return json({message:'Insufficient available Rihla balance.'},409);
const number='RIA-'+input.requestId.replaceAll('-','').toUpperCase();
await tx.query(`INSERT INTO ria_transfers(id,transaction_number,sender_id,recipient_id,sender_name,recipient_name,
amount_minor,tax_minor,state,jarvis_instance_id,created_at) VALUES(?,?,?,?,?,?,?,?,'created',?,?)`,
[input.requestId,number,actor.id,recipient.id,actor.username,recipient.username,
quote.amountMinor,quote.taxMinor,input.requestId,clock()]);
await tx.query('UPDATE ria_accounts SET reserved_minor=? WHERE owner_id=?',[String(reserved+total),actor.id]);
return json({number,state:'created',amountMinor:quote.amountMinor,taxMinor:quote.taxMinor},201);
});
}
if(input.action==='cancel'){
if(typeof input.number!=='string'||!/^RIA-[A-Z0-9-]{1,36}$/.test(input.number))
return json({message:'Invalid RIA reference.'},400);
return await bank.transaction(async tx=>{
const account=await tx.first('SELECT reserved_minor FROM ria_accounts WHERE owner_id=? FOR UPDATE',[actor.id]);
const row=await tx.first('SELECT * FROM ria_transfers WHERE transaction_number=? AND sender_id=? FOR UPDATE',
[input.number,actor.id]);
if(!row)return json({message:'Transfer unavailable.'},404);
if(row.state==='cancelled')return json(transferView(row));
if(row.state!=='created')return json({message:'This transfer cannot be cancelled.'},409);
const released=BigInt(row.amount_minor)+BigInt(row.tax_minor);
if(!account||released<=0n||BigInt(account.reserved_minor)<released)throw Error('Rihla reservation is inconsistent.');
await tx.query('UPDATE ria_accounts SET reserved_minor=? WHERE owner_id=?',
[String(BigInt(account.reserved_minor)-released),actor.id]);
await tx.query("UPDATE ria_transfers SET state='cancelled' WHERE id=?",[row.id]);
return json(transferView({...row,state:'cancelled'}));
});
}
return json(await bank.transaction(async tx=>{
await ensureRihlaAccount(tx,actor.id,{clock});