// This journal contains public receipt identifiers only. It never authorizes a wallet operation. const prefix='solbound.pending.devnet.v1:'; const memory=new Map(), queues=new Map(); const address=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/; const signature=/^[1-9A-HJ-NP-Za-km-z]{64,88}$/; const fields=['owner','programId','registryVersion','signature','blockhash','lastValidBlockHeight','observedSlot','grantId', 'serviceFeeLamports','feeLamports','messageHash','startedAt','updatedAt','status','slot']; function key(owner){if(!address.test(owner??'')) throw Error('Invalid receipt owner.');return prefix+owner;} function checked(value) { if(!value || value.network!=='devnet' || !address.test(value.owner??'') || !address.test(value.programId??'') || !signature.test(value.signature??'') || !address.test(value.blockhash??'') || !address.test(value.grantId??'') || value.registryVersion!==3 || !['pending','confirmed'].includes(value.status) || !Number.isSafeInteger(value.lastValidBlockHeight) || value.lastValidBlockHeight<1 || !Number.isSafeInteger(value.observedSlot) || value.observedSlot<0 || !Number.isSafeInteger(value.serviceFeeLamports) || value.serviceFeeLamports<0 || value.serviceFeeLamports>1e9 || !Number.isSafeInteger(value.feeLamports) || value.feeLamports<0 || !/^[a-f0-9]{64}$/.test(value.messageHash??'') || !Number.isFinite(Date.parse(value.startedAt)) || !Number.isFinite(Date.parse(value.updatedAt)) || (value.slot!==undefined && (!Number.isSafeInteger(value.slot) || value.slot<0))) { throw Error('The saved transaction receipt could not be verified. Do not approve another payment until its status is checked.'); } return Object.freeze({network:'devnet',...Object.fromEntries(fields.filter(f=>value[f]!==undefined).map(f=>[f,value[f]]))}); } function storage(){return typeof window==='undefined'?null:window.localStorage;} export function readPending(owner) { const id=key(owner); let raw; try {raw=storage()?.getItem(id) ?? (typeof window==='undefined'?memory.get(id):null);} catch {throw Error('Saved transaction receipts are unavailable. Enable local storage before approving a payment.');} if(raw===undefined || raw===null) return null; if(typeof raw!=='string' || raw.length>4096) throw Error('The saved transaction receipt is invalid. Check its status before another payment.'); let parsed; try {parsed=JSON.parse(raw);} catch {throw Error('The saved transaction receipt is unreadable. Check its status before another payment.');} const record=checked(parsed); if(record.owner!==owner) throw Error('The saved receipt belongs to another vault.'); return record; } export function writePending(value) { const record=checked(value),id=key(record.owner),raw=JSON.stringify(record); try { if(typeof window!=='undefined') { const target=storage(); if(!target) throw Error('Storage unavailable'); target.setItem(id,raw); if(target.getItem(id)!==raw) throw Error('Receipt was not saved'); } else memory.set(id,raw); } catch {throw Error('Solbound could not save the receipt safely. Check your transaction before another approval and enable local storage.');} return record; } export function clearPending(owner,expectedSignature) { const current=readPending(owner); if(current && current.signature!==expectedSignature) throw Error('Another transaction is being checked. Refresh its status first.'); if(!current) return; try {if(typeof window==='undefined') memory.delete(key(owner));else storage().removeItem(key(owner));} catch {throw Error('The transaction was checked, but its saved receipt could not be cleared. Refresh its status before another payment.');} } export function pendingError(record) { const error=Error('A previous transaction is still being checked. Check its receipt before approving another payment.'); error.code='SOLBOUND_TRANSACTION_PENDING';error.signature=record.signature;error.pending=record; return error; } export async function withPendingLock(owner,action) { const id=key(owner); if(globalThis.navigator?.locks?.request) return navigator.locks.request(id,{mode:'exclusive'},action); // Production browsers must have an atomic cross-tab lock. A localStorage lease is not atomic. if(typeof window!=='undefined') throw Error('This browser cannot coordinate wallet approvals across tabs. Use a current browser with Web Locks support.'); const previous=queues.get(id)??Promise.resolve(); let release;const held=new Promise(resolve=>{release=resolve;}); const tail=previous.catch(()=>{}).then(()=>held);queues.set(id,tail); await previous.catch(()=>{}); try{return await action();}finally{release();if(queues.get(id)===tail) queues.delete(id);} } const finalOutcome=(record,status)=>({ ...record,status:status.err?'failed':'finalized',finalized:true,slot:status.slot, transactionError:status.err??null,updatedAt:new Date().toISOString() }); export async function recoverPending(connection,record) { record=checked(record); const read=async()=>{ const result=await connection.getSignatureStatuses([record.signature],{searchTransactionHistory:true}); if(!Array.isArray(result?.value) || result.value.length!==1 || !Number.isSafeInteger(result.context?.slot)) throw Error('The receipt provider returned an invalid status. Keep checking before another approval.'); const status=result.value[0]; if(status!==null && (!status || !Number.isSafeInteger(status.slot) || !['processed','confirmed','finalized'].includes(status.confirmationStatus))) { throw Error('The receipt provider returned an incomplete status. Keep checking before another approval.'); } return result; }; const first=await read(),status=first.value?.[0]; if(status?.confirmationStatus==='finalized') return finalOutcome(record,status); if(status) return {...record,status:'confirmed',slot:status.slot,updatedAt:new Date().toISOString()}; // Expiry is established by finalized chain height, never by wall-clock time or one null lookup. const height=await connection.getBlockHeight('finalized'); if(!Number.isSafeInteger(height)) throw Error('Could not check transaction expiry.'); if(height<=record.lastValidBlockHeight) return record; const firstAvailable=await connection.getFirstAvailableBlock(); if(!Number.isSafeInteger(firstAvailable) || firstAvailable<0 || firstAvailable>record.observedSlot) { throw Error('This provider no longer has the full submission history. Check the receipt with an archival provider before approving another payment.'); } const finalizedSlot=await connection.getSlot('finalized'); const second=await read(),again=second.value?.[0]; if(again?.confirmationStatus==='finalized') return finalOutcome(record,again); if(again) return {...record,status:'confirmed',slot:again.slot,updatedAt:new Date().toISOString()}; if(!Number.isSafeInteger(finalizedSlot) || !Number.isSafeInteger(second.context?.slot) || second.context.slot=end) return result; await new Promise(resolve=>setTimeout(resolve,Math.min(intervalMs,end-Date.now()))); } }