1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/http-dispatcher-gQhek6ro.js","assets/money-Czq7zInz.js"])))=>i.map(i=>d[i]); 2import{f as p,a as h,t as I,e as E,c as Ve,r as mt,b as Nn,z as qs,m as ze,S as Pn,d as H,g as Ge,h as Ir,i as js,n as Ks,j as br,k as Vs,l as Xt,o as zs,p as B,q as ht,s as Gs,E as Ws,v as Ys,u as Js,D as ee,w as Xs,x as Cn,y as pe}from"./money-Czq7zInz.js";function M(e){return`${e}:spendable`}function Zs(e,t){return`${e}:${t}:escrow`}function Qs(e){if(Ye(e)!=="escrow")return null;const t=e.indexOf(":"),n=e.lastIndexOf(":");return t<0||n<=t?null:{userId:e.slice(0,t),sessionId:e.slice(t+1,n)}}function D(e){return`${e}:earned`}function $(e){return`${e}:promo`}const w={TRUST_CASH:"platform:trust_cash",REVENUE:"platform:revenue",STORED_VALUE:"platform:stored_value",PAYOUT_RESERVE:"platform:payout_reserve",RECEIVABLE:"platform:receivable",PROMO_FLOAT:"platform:promo_float",USD_CLEARING:"platform:usd_clearing",REVENUE_USD:"platform:revenue_usd",OPENING_EQUITY:"platform:opening_equity",NETTING_CLEARING:"platform:netting_clearing",SETTLEMENT_ACCRUAL:"platform:settlement_accrual"},Er=new Set([w.REVENUE,w.PROMO_FLOAT,w.STORED_VALUE,w.TRUST_CASH,w.USD_CLEARING,w.REVENUE_USD,w.PAYOUT_RESERVE,w.SETTLEMENT_ACCRUAL]);function Ce(e){if(!e.startsWith("platform:"))return e;const t=e.indexOf("#");return t<0?e:e.slice(0,t)}function vr(e,t){return t===0?e:`${e}#${t}`}function Zt(e,t){const n=[];for(let r=0;r<Math.max(1,t);r+=1)n.push(vr(e,r));return n}function eo(e){return Er.has(e)}function q(e,t,n){return n<2||!Er.has(e)?e:vr(e,to(t)%n)}function Te(e,t,n){return n<2?e:e.map(r=>{const s=q(r.account,t,n);return s===r.account?r:{...r,account:s}})}function to(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function le(e){return e.includes(":")&&!e.startsWith("platform:")}function We(e){const t=e.lastIndexOf(":");return t<0?e:e.slice(0,t)}const Qt=new Map([[w.TRUST_CASH,{currency:"USD",debitNormal:!0,class:"house-asset"}],[w.USD_CLEARING,{currency:"USD",debitNormal:!0,class:"house-asset"}],[w.REVENUE_USD,{currency:"USD",debitNormal:!0,class:"house-asset"}],[w.STORED_VALUE,{currency:"CREDIT",debitNormal:!0,class:"house-asset"}],[w.RECEIVABLE,{currency:"CREDIT",debitNormal:!0,class:"house-asset"}],[w.OPENING_EQUITY,{currency:"CREDIT",debitNormal:!0,class:"house-asset"}],[w.PROMO_FLOAT,{currency:"CREDIT",debitNormal:!0,class:"house-liability"}],[w.REVENUE,{currency:"CREDIT",debitNormal:!1,class:"house-liability"}],[w.PAYOUT_RESERVE,{currency:"CREDIT",debitNormal:!1,class:"excluded"}],[w.SETTLEMENT_ACCRUAL,{currency:"CREDIT",debitNormal:!1,class:"excluded"}]]);function J(e){return Qt.get(Ce(e))?.currency??"CREDIT"}function kr(e){const t=Qt.get(Ce(e));if(t)return t.class;const n=Ye(e);return n==="spendable"||n==="escrow"?"custodial":"excluded"}function Ee(e){return Qt.get(Ce(e))?.debitNormal??!1}function en(e,t=1,n=!1){const r=no[e.kind];return r(e,t,n)}const Ln=[w.REVENUE,w.PROMO_FLOAT,w.RECEIVABLE],no={topUp:(e,t)=>[M(e.userId),q(w.STORED_VALUE,e.idempotencyKey,t),q(w.TRUST_CASH,e.idempotencyKey,t),q(w.USD_CLEARING,e.idempotencyKey,t),q(w.REVENUE_USD,e.idempotencyKey,t)],spend:(e,t,n)=>[$(e.buyerId),M(e.buyerId),q(w.PROMO_FLOAT,e.idempotencyKey,t),q(w.REVENUE,e.idempotencyKey,t),...n?[q(w.SETTLEMENT_ACCRUAL,e.idempotencyKey,t)]:(e.recipients??[]).map(r=>D(r.sellerId))],refund:()=>[...Ln],clawback:e=>[M(e.userId),w.STORED_VALUE,w.RECEIVABLE],requestPayout:(e,t)=>[D(e.userId),q(w.PAYOUT_RESERVE,e.userId,t)],subscribe:(e,t,n)=>n?[$(e.userId),M(e.userId),q(w.PROMO_FLOAT,e.idempotencyKey,t),q(w.REVENUE,e.idempotencyKey,t),q(w.SETTLEMENT_ACCRUAL,e.idempotencyKey,t)]:[$(e.userId),M(e.userId),w.PROMO_FLOAT,w.REVENUE,D(e.sellerId)],c
2ancelSubscription:()=>[],grantEntitlement:()=>[],revokeEntitlement:()=>[],grantPromo:e=>[$(e.userId),w.PROMO_FLOAT],adjust:e=>[e.account,w.OPENING_EQUITY],reverse:()=>[...Ln],reversePayout:(e,t)=>[q(w.PAYOUT_RESERVE,e.userId,t),D(e.userId)],settlePayout:()=>[w.PAYOUT_RESERVE,w.REVENUE,w.USD_CLEARING,w.TRUST_CASH]};function Ye(e){const t=e.lastIndexOf(":");if(t<0)return null;const n=e.slice(t+1);return n==="spendable"||n==="earned"||n==="promo"||n==="escrow"?n:null}function At(e,t){return{rate:1n,scale:0,rateId:`${e}->${t}:1`}}function ro(e){const t=(r,s,o,a)=>r*10n**BigInt(a)>=o*10n**BigInt(s);if(!(t(e.buyRate,e.buyScale,e.parRate,e.parScale)&&t(e.parRate,e.parScale,e.payoutRate,e.payoutScale)))throw p(h.CONFIG_INVALID,"Rates must hold buy >= par >= payout (USD per credit).",{detail:{buy:`${e.buyRate}/${e.buyScale}`,par:`${e.parRate}/${e.parScale}`,payout:`${e.payoutRate}/${e.payoutScale}`},retryable:!1})}function qe(e){ro(e);const t={rate:e.buyRate,scale:e.buyScale,rateId:`buy:CREDIT->USD:${e.buyRate}/${e.buyScale}`},n={rate:e.parRate,scale:e.parScale,rateId:`par:CREDIT->USD:${e.parRate}/${e.parScale}`},r={rate:e.payoutRate,scale:e.payoutScale,rateId:`payout:CREDIT->USD:${e.payoutRate}/${e.payoutScale}`};return{buy(s){return s==="CREDIT"?t:At("USD","USD")},par(s){return s==="CREDIT"?n:At("USD","USD")},async payout(s,o,a,i){if(s===o)return At(s,o);if(s==="CREDIT"&&o==="USD")return r;throw new Error(`configuredRates has no ${s}->${o} rate (only CREDIT->USD and same-currency are configured).`)}}}const so=/^-?\d+$/;function x(e,t,n){return we(e,n)??t}function we(e,t){if(e===void 0||!so.test(e))return null;const n=Number.parseInt(e,10);if(!Number.isSafeInteger(n))return null;const r=t?.min??0,s=t?.max??Number.MAX_SAFE_INTEGER;return n>=r&&n<=s?n:null}function rt(e,t){return Pe(e)??t}function Pe(e){return e===void 0||!/^\d+$/.test(e)?null:BigInt(e)}function Oe(e){return e===void 0||e===""?null:e}function oo(e){return(e??"").split(",").map(t=>t.trim()).filter(t=>t!=="")}function ao(e){return e==="1"||e==="true"}function Je(e){return e.NODE_ENV==="production"}const io=e=>e.startsWith("postgres://")||e.startsWith("postgresql://"),co=e=>e.startsWith("mysql://");function tn(e){return{redis:Oe(e.REDIS_URL),sqs:Oe(e.SQS_QUEUE_URL),dispatcher:Oe(e.DISPATCHER_URL),processor:Oe(e.PROCESSOR_URL),taskq:Oe(e.TASKQ_DATABASE_URL),tiliaPayees:Oe(e.TILIA_PAYEE_DATABASE_URL)}}const uo=1000000000000000n;function lo(e,t){if(t===void 0||t.trim()==="")return{};const n=t.split(",").map(o=>o.trim());if(!n.every(o=>{if(!/^\d+$/.test(o))return!1;const a=BigInt(o);return a>0n&&a<=uo}))throw p(h.CONFIG_INVALID,"TOP_UP_BUNDLES_MINOR must be a comma-separated list of positive minor-unit counts.",{detail:{value:t},retryable:!1});const s=Object.freeze([...new Set(n.map(BigInt))].sort((o,a)=>o<a?-1:o>a?1:0));return{[e]:s}}function Un(e,t){const n=Pe(t);return n===null?{}:{[e]:n}}function fo(e,t={}){const n=oo(e.SIGNING_SECRETS_PRIOR),r={webhookSecret:t.webhookSecret??e.WEBHOOK_SECRET??"",signingSecret:t.signingSecret??e.SIGNING_SECRET??"",...t.signingSecretsPrior!==void 0?{signingSecretsPrior:t.signingSecretsPrior}:n.length>0?{signingSecretsPrior:n}:{}};if(Je(e)){const s=Ar(r);if(s.length>0)throw p(h.CONFIG_INVALID,"Required secrets are missing.",{detail:{missing:s}})}return r}function Ar(e){const t=[];return e.webhookSecret===""&&t.push("WEBHOOK_SECRET"),e.signingSecret===""&&t.push("SIGNING_SECRET"),t}function Sr(e,t={}){if(!Je(e))return[];const n=[];return t.maturityHorizonMs?.card===void 0&&(e.MATURITY_HORIZON_CARD_MS??"")===""&&n.push("MATURITY_HORIZON_CARD_MS"),t.velocityLimitMinor===void 0&&(e.VELOCITY_LIMIT_MINOR??"")===""&&n.push("VELOCITY_LIMIT_MINOR"),n}function mo(e){const t=x(e.MATURITY_HORIZON_CARD_MS,0);return{replayWindowMs:x(e.REPLAY_WINDOW_MS,5*6e4),maxPayoutAttempts:x(e.MAX_PAYOUT_ATTEMPTS,5,{min:1}),maxOutboxAttempts:x(e.MAX_OUTBOX_ATTEMPTS,10,{min:1}),maxInboxAttempts:x(e.MAX_INBOX_ATTEMPTS,10,{min:1}),maxSubscriptionAttempts:x(e.MAX_SUBSCRIPTION_ATTEMPTS,10,{min:1}),maxPayoutAgeMs:x(e.MAX_PAYOUT_AGE_MS,4320*6e4),platformFeeBps:x(e.PLATFORM_FEE_BPS,1530,{max:1e4}),payoutFeeBps:x(e.PAYOUT_FEE_BPS,150,{max:1e4}),velocityLimitMinor:rt(e.VELOCITY_LIMIT_MINOR,100000n),...Un("velocityInflowLimitMinor",e.VELOCITY_INFLOW_LIMIT_MINOR),...Un("velocityOutflowLimitMinor",e.VELOCITY_OUTFLOW_LIMIT_MINOR),subscriptionPriceMinMinor:rt(e.SUBSCRIPTION_PRICE_MIN_MINOR,10000n),subscriptionPriceMaxMinor:rt(e.SUBSCRIPTION_PRICE_MAX_MINOR,1000000n),...lo("topUpBundlesMinor",e.TOP_UP_BUNDLES_MINOR),velocityWindowMs:x(e.VELOCITY_WINDOW_MS,60*6e4,{min:1}),maturityHorizonMs:{card:t,crypto:x(e.MATURITY_HORIZON_CRYPTO_MS,t),steam:x(e.MATURITY_HORIZON_STEAM_MS,t),meta:x(e.MATURITY_HORIZON_META_MS,t),default:x(e.MATURITY_HORIZON_DEFAULT_MS,t)},payoutSla:{PENDING:x(e.SLA_PENDING_MS,3e4),SUBMITTED:x(e.SLA_SUBMITTED_MS,12e4),DEFAULT:x(e.
2SLA_DEFAULT_MS,6e4)},payoutMinimumEarnedMinor:rt(e.PAYOUT_MIN_EARNED_MINOR,2000000n),payoutMinIntervalMs:x(e.PAYOUT_MIN_INTERVAL_MS,1440*6e4),pauseStartMs:we(e.ECONOMY_PAUSE_START_MS),pauseEndMs:we(e.ECONOMY_PAUSE_END_MS),dbPoolMax:we(e.DB_POOL_MAX),platformShards:x(e.PLATFORM_SHARDS,1,{min:1}),accrualDrain:e.ACCRUAL_DRAIN==="1"||e.ACCRUAL_DRAIN==="true"}}function Rr(e,t){const n={...e,...t};return t.maturityHorizonMs&&(n.maturityHorizonMs={...e.maturityHorizonMs,...t.maturityHorizonMs}),t.payoutSla&&(n.payoutSla={...e.payoutSla,...t.payoutSla}),n}function ho(e={},t={}){const n=Sr(e,t);if(n.length>0)throw p(h.CONFIG_INVALID,"Required configuration is missing.",{detail:{missing:n}});return Rr(mo(e),t)}function nn(e,t){const{pauseStartMs:n,pauseEndMs:r}=t;return n===null||r===null?!1:n<=e&&e<r}const po="modulepreload",yo=function(e){return"/console/"+e},xn={},Ie=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let c=function(u){return Promise.all(u.map(m=>Promise.resolve(m).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),i=a?.nonce||a?.getAttribute("nonce");s=c(n.map(u=>{if(u=yo(u),u in xn)return;xn[u]=!0;const m=u.endsWith(".css"),g=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${g}`))return;const y=document.createElement("link");if(y.rel=m?"stylesheet":po,m||(y.as="script"),y.crossOrigin="",y.href=u,i&&y.setAttribute("nonce",i),document.head.appendChild(y),m)return new Promise((v,S)=>{y.addEventListener("load",v),y.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${u}`)))})}))}function o(a){const i=new Event("vite:preloadError",{cancelable:!0});if(i.payload=a,window.dispatchEvent(i),!i.defaultPrevented)throw a}return s.then(a=>{for(const i of a||[])i.status==="rejected"&&o(i.reason);return t().catch(o)})},go=(()=>{const e=new Array(256);for(let t=0;t<256;t+=1)e[t]=t.toString(16).padStart(2,"0");return e})();function z(e){let t="";for(let n=0;n<e.length;n+=1)t+=go[e[n]];return t}function oe(e){if(e.length%2!==0)throw p(h.MALFORMED_OPERATION,"Hex string has an odd length.",{detail:{length:e.length}});const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n+=1){const r=$n(e.charCodeAt(n*2)),s=$n(e.charCodeAt(n*2+1));t[n]=r<<4|s}return t}function rn(e){if(e<-(2n**63n)||e>=2n**63n)throw p(h.AMOUNT_OVERFLOW,"Value does not fit in a signed 64-bit integer.",{detail:{value:e.toString()}});const t=new Uint8Array(8);return new DataView(t.buffer).setBigInt64(0,e),t}function fe(e,t){return e<t?-1:e>t?1:0}function $n(e){if(e>=48&&e<=57)return e-48;if(e>=97&&e<=102)return e-87;throw p(h.MALFORMED_OPERATION,"Hex string has a non-hex digit.",{detail:{code:e}})}const wo=new Uint8Array(32),me="0".repeat(64);function N(e,t){return{account:e,amount:t}}function O(e,t){return{account:e,amount:I(t.currency,-t.minor)}}function Z(e){const t=Ee(e.account)?1n:-1n;return I(e.amount.currency,e.amount.minor*t)}async function Ne(e,t,n){const r=[...new Set(t)].sort();if(e.lockMany){await e.lockMany(r,n);return}for(const s of r)await e.lock(s,n)}async function F(e,t,n){const r=Mr(t);return Or(r),Tr(r),await Dr(e,r,n),await Nr(e,r,n),e.append(r,n)}async function _r(e,t,n){if(e.appendAll===void 0)return Bn(e,t,n);const r=t.map(Mr),s=new Set;let o=!0;for(const a of r)for(const i of new Set(a.legs.map(c=>c.account)))s.has(i)&&(o=!1),s.add(i);if(!o)return Bn(e,t,n);for(const a of r)Or(a),Tr(a),await Dr(e,a,n),await Nr(e,a,n);return e.appendAll(r,n)}async function Bn(e,t,n){const r=[];for(const s of t)r.push(await F(e,s,n));return r}function Mr(e){const t=e.legs.filter(n=>n.amount.minor!==0n);return t.length===e.legs.length?e:{...e,legs:t}}function Io(e){const t=[];t.push(e.accountPrevHash),t.push(St(e.txnId));const n=e.legs.filter(r=>r.account===e.account).map(r=>E(r.amount)).sort();return t.push(St(n.join("\0"))),t.push(St(Bt(e.meta))),vo(t)}async function sn(e,t){return z(await e.hash(Io(t)))}function Or(e){for(const t of e.legs)if(t.amount.currency!==J(t.account))throw p(h.CURRENCY_MISMATCH,"A leg currency does not match its account.",{detail:{txnId:e.txnId,account:t.account,legCurrency:t.amount.currency,accountCurrency:J(t.account)}})}function Tr(e){const t=new Map;for(const n of e.legs)t.set(n.amount.currency,(t.get(n.amount.currency)??0n)+n.amount.minor);for(const[n,r]of t)if(r!==0n)throw p(h.LEDGER_UNBALANCED,"A posting does not balance.",{detail:{txnId:e.txnId,currency:n,residual:E(I(n,r))}})}async function Dr(e,t,n){for(const r of t.legs)if(!await e.hasAccount(r.account,n))throw p(h.UNKNOWN_ACCOUNT,"A posting names an unknown account.",{detail:{txnId:t.txnId,account:r.account}})}async function Nr(e,t,n){const r=new Map;for(const s of t.legs){if(!bo(s.account))continue;const o=r.get(s.account)??0n;r.set(s.account,o+Z(s).minor)}for(const[s,o]of r){if(o>=0n)continue;const a=await e.balance(s,n),i=I(a.currency,a.minor+o);if(i.minor<0n)throw p(h.OVERDRAFT,"A posting would overdraw a user account.",{detail:{account:s,projected:E(i)}})}}function bo(e){const t=kr(e);return(t==="custodial"||t==="excluded")&&e.includes(":")}const Eo=new TextEncoder;function St(e){return Eo.encode(e)}function Bt(e){if(Array.isArray(e))return`[${e.map(Bt).join(",")}]`;if(e!==null&&typeof e=="object"){const t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Bt(t[n])}`).join(",")}}`}if(typeof e=="bigint")throw p(h.MALFORMED_OPERATION,"A bigint reached canonical meta unencoded.",{detail:{value:e.toString()}});return JSON.stringify(e)}function vo(e){const t=e.reduce((s,o)=>s+4+o.length,0),n=new Uint8Array(t);let r=0;for(const s of e)n[r]=s.length>>>24&255,n[r+1]=s.length>>>16&255,n[r+2]=s.length>>>8&255,n[r+3]=s.length&255,n.set(s,r+4),r+=4+s.length;return n}async function Pr(e,t){const n=[...await xr(e.ledger)].sort((s,o)=>fe(s[0],o[0])),r=n.length;for(const[s]of n){const o=await ko(e,s,t);if(o)return{intact:!1,firstBreak:o,count:r}}return{intact:!0,firstBreak:null,count:r}}async function ko(e,t,n){const r=e.boundary?.anchors.get(t);let s=me,o=r===void 0,a=!0;for await(const i of e.ledger.lineage(t,n)){if(a&&r!==void 0&&i.prevHash===r&&(s=r,o=!0),i.prevHash!==s){
2if(!a||r===void 0)return{account:t,txnId:i.txnId,reason:"broken-link",expected:s,actual:i.prevHash};s=i.prevHash}const c=await on(e.digest,t,i);if(c!==i.hash)return{account:t,txnId:i.txnId,reason:"tampered-hash",expected:c,actual:i.hash};s=i.hash,i.hash===r&&(o=!0),a=!1}return!o&&!a?{account:t,txnId:"",reason:"broken-link",expected:r,actual:s}:null}function on(e,t,n){return sn(e,{accountPrevHash:oe(n.prevHash),txnId:n.txnId,account:t,legs:n.legs,meta:n.meta})}async function Le(e,t,n){const r=await e.ledger.posting(t,n);if(r===null)return null;const s=new Map((await e.ledger.links(t,n)).map(o=>[o.account,o]));for(const o of new Set(r.legs.map(a=>a.account))){const a=s.get(o),i=a===void 0?null:await sn(e.digest,{accountPrevHash:oe(a.prevHash),txnId:t,account:o,legs:r.legs,meta:r.meta});if(i===null||i!==a.hash)throw p(h.CHAIN_BROKEN,"A stored posting failed to re-derive against its chain links; refusing to derive money from tampered history.",{retryable:!1,detail:{txnId:t,account:o}})}return Ao(r),r}function Ao(e){const t=new Map;for(const n of e.legs)t.set(n.amount.currency,(t.get(n.amount.currency)??0n)+n.amount.minor);for(const[n,r]of t)if(r!==0n)throw p(h.CHAIN_BROKEN,"A stored posting no longer nets to zero; refusing to derive money from tampered history.",{retryable:!1,detail:{txnId:e.txnId,currency:n,sum:r.toString()}})}async function Cr(e,t){for(const n of t){const r=await on(e,n.account,n);if(r!==n.hash)return{account:n.account,txnId:n.txnId,reason:"tampered-hash",expected:r,actual:n.hash}}return null}async function So(e,t){const n=[...t].sort((s,o)=>fe(s[0],o[0]));let r=[];for(const[s,o]of n)r.push(await e.hash(No(s,o)));if(r.length===0)return new Uint8Array(32);for(;r.length>1;)r=await Po(e,r);return r[0]}async function Ue(e,t){const n=[...t].sort((s,o)=>fe(s[0],o[0]));let r=[];for(const[s,o,a]of n)r.push({hash:await e.hash(xo(s,o,a)),sum:a});if(r.length===0)return{hash:new Uint8Array(32),sum:0n};for(;r.length>1;){const s=[];for(let o=0;o<r.length;o+=2){const a=r[o],i=r[o+1];s.push(i?{hash:await e.hash($o(a,i)),sum:a.sum+i.sum}:a)}r=s}return r[0]}async function Ro(e,t){const n=await an(e.checkpoints,e,t),r=Bo(await $r(e.ledger,t),n),s=await _o(e,r,t),o=s.mode==="incremental"?await Mo(e,s,t):(await Pr({ledger:e.ledger,digest:e.digest,boundary:n},t)).firstBreak;if(o!==null)throw p(h.CHAIN_BROKEN,"The hash chain failed to re-derive; refusing to sign a checkpoint over a tampered ledger.",{retryable:!1,detail:{firstBreak:o}});const a=await Ue(e.digest,r);if(a.sum!==0n)throw p(h.LEDGER_UNBALANCED,"The ledger sums to a nonzero total; refusing to sign a checkpoint over unbalanced books.",{retryable:!1,detail:{sum:a.sum.toString()}});const i=await e.signer.sign(Xe(a)),c={id:e.ids.next("chk"),root:z(a.hash),signature:z(i),count:r.length,at:e.clock.now(),v:2,sum:a.sum.toString(),kid:await e.signer.kid?.()??null};return await e.checkpoints.put(c,t),e.checkpoints.putSealHeads!==void 0&&await e.checkpoints.putSealHeads(s.mode==="incremental"?s.dirty:r,s.mode==="incremental"?t:{...t,replaceAll:!0}),c}async function _o(e,t,n){if(e.checkpoints.sealHeads===void 0||e.checkpoints.putSealHeads===void 0)return{mode:"full"};const r=await e.checkpoints.sealHeads(n),s=await e.checkpoints.latest(n);if(r.length===0||s===null||s.v!==2||s.sum===null)return{mode:"full"};const o=await Ue(e.digest,r);if(z(o.hash)!==s.root||o.sum.toString()!==s.sum||!await e.signer.verify(Xe(o),oe(s.signature)))return{mode:"full"};const a=new Map;for(const[c,u]of r)a.set(c,u);const i=new Set(t.map(([c])=>c));for(const c of a.keys())if(!i.has(c))throw p(h.CHAIN_BROKEN,"A sealed account has vanished from the live heads; refusing to sign over a truncated ledger.",{retryable:!1,detail:{account:c}});return{mode:"incremental",dirty:t.filter(([c,u])=>a.get(c)!==u),since:a}}async function Mo(e,t,n){for(const[r,s]of t.dirty){const o=t.since.get(r);let a=o??me,i=!1;for await(const c of e.ledger.lineage(r,{...n,...o===void 0?{}:{sinceHash:o}})){if(c.prevHash!==a)return{account:r,txnId:c.txnId,reason:"broken-link",expected:a,actual:c.prevHash};const u=await on(e.digest,r,c);if(u!==c.hash)return{account:r,txnId:c.txnId,reason:"tampered-hash",expected:u,actual:c.hash};a=c.hash,a===s&&(i=!0)}if(!i)return{account:r,txnId:"",reason:"broken-link",expected:s,actual:a}}return null}async function Oo(e,t){if(t.v===2){const s=await $r(e.ledger);if(s.length<t.count)return!1;const o=await Ue(e.digest,s);return z(o.hash)!==t.root||t.sum===null||BigInt(t.sum)!==o.sum?!1:e.signer.verify(Xe(o),oe(t.signature))}const n=await xr(e.ledger);if(n.length<t.count)return!1;const r=await So(e.digest,n);return z(r)!==t.root?!1:e.signer.verify(oe(t.root),oe(t.signature))}const To=0,Do=1;function No(e,t){const n=Br.encode(`${e}:${t}`),r=new Uint8Array(1+n.length);return r[0]=To,r.set(n,1),r}async function Po(e,t){const n=[];for(let r=0;r<t.length;r+=2){const s=t[r],o=t[r+1];n.push(o?await e.hash(Co(s,o)):s)}return n}function Co(e,t){const n=new Uint8Array(1+e.length+t.length);return n[0]=Do,n.set(e,1),n.set(t,1+e.length),n}const Lo=2,Uo=3;
2function xo(e,t,n){const r=Br.encode(`${e}:${t}:`),s=new Uint8Array(1+r.length+8);return s[0]=Lo,s.set(r,1),s.set(rn(n),1+r.length),s}function $o(e,t){const n=new Uint8Array(1+e.hash.length+t.hash.length+8);return n[0]=Uo,n.set(e.hash,1),n.set(t.hash,1+e.hash.length),n.set(rn(e.sum+t.sum),1+e.hash.length+t.hash.length),n}const Rt=new TextEncoder().encode("economy-lab:archive-heads:v1");function Lr(e){const t=Xe(e),n=new Uint8Array(Rt.length+t.length);return n.set(Rt,0),n.set(t,Rt.length),n}async function Ur(e,t,n){const r=await Ue(e.digest,t.map(s=>[s.account,s.head,s.sum]));return z(r.hash)!==n.root?!1:e.signer.verify(Lr(r),oe(n.signature))}async function an(e,t,n){if(e.archiveState===void 0||e.archiveHeads===void 0)return null;const r=await e.archiveState(n);if(r===null)return null;const s=await e.archiveHeads(n);if(!await Ur(t,s,r))throw p(h.CHAIN_BROKEN,"The archive heads failed authentication against their signed root; refusing to prove or seal over a tampered boundary.",{retryable:!1});const o=new Map,a=new Map;for(const i of s)o.set(i.account,i.head),a.set(i.account,i.sum);return{anchors:o,rawSums:a,state:r}}function Bo(e,t){if(t===null)return e;const n=new Set,r=e.map(([s,o,a])=>{n.add(s);const i=t.rawSums.get(s)??0n;return[s,o,a+i]});for(const[s,o]of t.rawSums)n.has(s)||r.push([s,t.anchors.get(s),o]);return r}function Xe(e){const t=new Uint8Array(e.hash.length+8);return t.set(e.hash,0),t.set(rn(e.sum),e.hash.length),t}async function xr(e){const t=[];for await(const n of e.heads())t.push(n);return t}async function $r(e,t){const n=[];for await(const r of e.headSums(t))n.push(r);return n}const Br=new TextEncoder;async function Fo(e,t){const{store:n}=e,r=await Ho(e,t),s=await jo(n.ledger,qo(r),t),o=cn(s.custodialCreditMinor,e.rates.par("CREDIT")),a=un(o,s.trustCashMinor),i=await Pr({ledger:n.ledger,digest:e.digest,boundary:r},t);return{conserved:Vo(s.signedByCurrency),backed:a===0n,noOverdraft:!s.anyUserNegative,chainIntact:i.intact,consistent:s.drift.length===0,drift:s.drift,shortfall:I("USD",a)}}async function Ho(e,t){const n=e.store.checkpoints;if(e.signer!==void 0)return an(n,{digest:e.digest,signer:e.signer},t);if((n.archiveState===void 0?null:await n.archiveState(t))!==null)throw p(h.CONFIG_INVALID,"This store has an archived prefix but the prover was built without a signer; the boundary cannot be authenticated.",{retryable:!1});return null}function qo(e){const t=new Map;if(e===null)return t;for(const[n,r]of e.rawSums)t.set(n,r*(Ee(n)?1n:-1n));return t}async function jo(e,t,n){const r=new Map,s={custodialCreditMinor:0n,trustCashMinor:0n};let o=!1;const a=[],i=new Set;for await(const[c]of e.heads()){i.add(c);const u=(t.get(c)??0n)+await Ko(e,c,r,n),m=await e.balance(c,n);Fn(c,m,u,a),ct(s,c,m.minor),le(c)&&m.minor<0n&&(o=!0)}for await(const c of e.balanceAccounts(n)){if(i.has(c))continue;const u=await e.balance(c,n);Fn(c,u,t.get(c)??0n,a),t.has(c)&&(ct(s,c,u.minor),le(c)&&u.minor<0n&&(o=!0))}return{signedByCurrency:r,...s,anyUserNegative:o,drift:a}}async function Ko(e,t,n,r){const s=Ee(t)?1n:-1n;let o=0n;for(const a of await e.derivedBalances(t,r)){o+=a.minor;const i=a.minor*s,c=a.currency;n.set(c,(n.get(c)??0n)+i)}return o}function Fn(e,t,n,r){t.minor!==n&&r.push({account:e,materialized:t,derived:I(J(e),n)})}function Fr(e){return kr(e)==="custodial"&&J(e)==="CREDIT"}function Hr(e){return Ce(e)===w.TRUST_CASH}function ct(e,t,n){Fr(t)&&(e.custodialCreditMinor+=n),Hr(t)&&(e.trustCashMinor+=n)}async function qr(e,t){const n={custodialCreditMinor:0n,trustCashMinor:0n};for await(const[r]of e)(Fr(r)||Hr(r))&&ct(n,r,(await t(r)).minor);return n}function cn(e,t){return Ve(I("CREDIT",e),t,"USD").minor}function un(e,t){return t<e?e-t:0n}function Vo(e){for(const t of e.values())if(t!==0n)return!1;return!0}async function zo(e,t,n){const r=t.toLowerCase(),s=n?.scanMax??2e4;let o=0;for await(const a of e.accounts(n))for await(const i of e.lineage(a,n)){if(o+=1,o>s)return null;if(i.hash.toLowerCase()===r)return{account:a,link:i,field:"hash"};if(i.prevHash!==me&&i.prevHash.toLowerCase()===r)return{account:a,link:i,field:"prevHash"}}return null}function xe(e,t,n){return{id:e.next("obx"),event:t,status:"pending",attempts:0,reason:null,correlationId:n??null}}function G(e,t){if(e.kind!==t)throw p(h.MALFORMED_OPERATION,`Handler received the wrong operation kind: ${e.kind}.`,{detail:{kind:e.kind,expected:t}})}function jr(e){if(e.actor.kind!=="operator")throw p(h.MALFORMED_OPERATION,`${e.kind} requires an operator principal.`,{detail:{kind:e.kind,actor:e.actor.kind}})}function dn(e){if(e.reason.trim()==="")throw p(h.MALFORMED_OPERATION,`${e.kind} requires a non-empty reason.`,{detail:{kind:e.kind}})}function Go(e,t,n,r={}){if(e.length===0)throw p(h.MALFORMED_OPERATION,`A ${n} names at least one recipient.`,{detail:r});let s=0;const o=new Set;for(const a of e){if(a.sellerId===t)throw p(h.MALFORMED_OPERATION,`A ${n} recipient may not be the buyer (self-dealing).`,{detail:{...r,buyerId:t}});if(o.has(a.sellerId))throw p(h.MALFORMED_OPERATION,`A ${n} may not name the same sellerId twice.`,{detail:{...r,sellerId:a.sellerId}});if(o.add(a.sellerId),a.shareBps<=0||a.shareBps>
21e4)throw p(h.MALFORMED_OPERATION,"Each recipient share must be > 0 and <= 10000 basis points.",{detail:{...r,sellerId:a.sellerId,shareBps:a.shareBps}});s+=a.shareBps}if(s!==1e4)throw p(h.MALFORMED_OPERATION,"Recipient shareBps must sum to 10000.",{detail:{...r,total:s}})}async function Kr(e,t){const n=await e.sagas.load(t.sagaId);if(n===null)throw p(h.MALFORMED_OPERATION,`${t.kind} names a payout that does not exist.`,{detail:{kind:t.kind,sagaId:t.sagaId}});return n}function ut(e){return`reversed:${e}`}function ln(e){return{id:e.ids.next("txn"),postedAt:e.clock.now(),legs:[],links:[],meta:{}}}function Ft(){return{id:"",postedAt:0,legs:[],links:[],meta:{}}}async function pt(e,t){const n=()=>p(h.CHAIN_BROKEN,"A payout saga does not re-derive from its reserve posting; refusing to move money for an unverifiable saga.",{retryable:!1,detail:{sagaId:t.id,txnId:t.txnId,userId:t.userId}}),r=await Le(e,t.txnId);if(r===null||t.payoutUsd===null)throw n();const s=r.meta,o=r.legs.find(a=>a.account===D(t.userId));if(s.kind!=="requestPayout"||s.sagaId!==t.id||s.rateId!==t.rateId||s.payoutUsd!==E(t.payoutUsd)||o===void 0||o.amount.minor!==t.reserve.minor)throw n();return t.payoutUsd}async function Wo(e,t){const n=()=>p(h.CHAIN_BROKEN,"A subscription does not re-derive from its first-charge posting; refusing to renew from an unverifiable row.",{retryable:!1,detail:{subscriptionId:t.id,txnId:t.txnId}}),r=await Le(e,t.txnId);if(r===null)throw n();const s=r.meta;if(s.kind!=="subscribe"||s.subscriptionId!==t.id||s.userId!==t.userId||s.sellerId!==t.sellerId||s.price!==E(t.price)||s.periodMs!==t.periodMs)throw n()}async function Yo(e,t,n){G(e,"topUp"),Xo(e.source);const r=mt(e.amount,"topUp.amount");Jo(r,n.config.topUpBundlesMinor);const s=n.rates.buy("CREDIT"),o=n.rates.par("CREDIT"),a=Nn(r,s,"USD"),i=Nn(r,o,"USD"),c=I("USD",a.minor-i.minor);if(c.minor<0n)throw p(h.CONFIG_INVALID,"Rates are misordered: buy is below par.",{retryable:!1,detail:{buyRateId:s.rateId,parRateId:o.rateId}});const u=[N(w.TRUST_CASH,i)];c.minor>0n&&u.push(N(w.REVENUE_USD,c)),u.push(O(w.USD_CLEARING,a));const[m]=await _r(t.ledger,[{txnId:n.ids.next("txn"),legs:Te([N(w.STORED_VALUE,r),O(M(e.userId),r)],e.idempotencyKey,n.config.platformShards),meta:{kind:"topUp",source:e.source}},{txnId:n.ids.next("txn"),legs:Te(u,e.idempotencyKey,n.config.platformShards),meta:{kind:"topUp.cash",rateId:s.rateId,parRateId:o.rateId}}]);return{status:"committed",transaction:m}}function Jo(e,t){if(!(t===void 0||t.includes(e.minor)))throw p(h.MALFORMED_OPERATION,"topUp.amount is not in the configured purchase catalog.",{detail:{amount:E(e),bundles:t.map(n=>E(I("CREDIT",n)))}})}function Xo(e){if(e.trim()==="")throw p(h.MALFORMED_OPERATION,"topUp.source must be a non-empty funding source.",{detail:{source:e}})}const it="default";function Vr(e,t){const n=t.maturityHorizonMs,r=n[e];return r!==void 0?r:n[it]??n.card??0}function Zo(e,t){return e.toppedUpAt+Vr(e.source,t)}const Hn=64;async function*fn(e,t,n,r){let s=n;for(let o=0;s>0n;o+=Hn){let a=0;for await(const i of e.timeline(t,{order:"desc",limit:Hn,offset:o})){a+=1;const c=i.amount.minor<s?i.amount.minor:s,u=Zo(i,r.config);if(yield{take:c,matured:u<=r.now,maturesAt:u,source:i.source},s-=c,s===0n)return}if(a===0)return}}async function mn(e,t,n,r){const s=r.amount.minor,o={source:it,availableAt:n+Vr(it,r.config)};if(s<=0n)return{source:it,availableAt:n};const a=r.live??await e.balance(t,{signal:r.signal});if(a.minor<s)return o;const i=[];for await(const u of fn(e,t,a.minor,{now:n,config:r.config}))i.push(u);i.sort((u,m)=>u.maturesAt-m.maturesAt);let c=0n;for(const u of i)if(c+=u.take,c>=s)return{source:u.source,availableAt:u.maturesAt};return o}async function Qo(e,t,n,r){const s=await e.balance(t,{signal:r.signal}),o=J(t);if(s.minor<=0n)return qs(o);let a=0n;for await(const i of fn(e,t,s.minor,{now:n,config:r.config}))i.matured&&(a+=i.take);return I(o,a)}async function yt(e,t,n,r){const s=r.amount.minor;if(s<=0n)return!0;const o=r.live??await e.balance(t,{signal:r.signal});if(o.minor<=0n)return!1;let a=0n;for await(const i of fn(e,t,o.minor,{now:n,config:r.config}))if(i.matured&&(a+=i.take,a>=s))return!0;return!1}function hn(e){const t=new Map;return{legs:e.map(r=>{if(Ye(r.account)!=="earned"||r.amount.minor>=0n)return r;const s=We(r.account);
2return t.set(s,(t.get(s)??0n)-r.amount.minor),{...r,account:w.SETTLEMENT_ACCRUAL}}),shares:t}}function pn(e){const t={};for(const[n,r]of e)r>0n&&(t[n]=r.toString());return t}function yn(e){const t=q(w.SETTLEMENT_ACCRUAL,e.routeKey,e.shards),n=[];for(const[r,s]of e.shares)s<=0n||n.push({orderId:e.orderId,sellerId:r,seq:0,amount:I("CREDIT",s),shard:t,status:"pending",txnId:e.txnId,settledTxnId:null,recordedAt:e.recordedAt});return n}const ea=1e4,zr=10000n;function Gr(){return e=>ta(e.price,e.recipients,e.feeBps)}function ta(e,t,n){na(t);const r=e.minor-gt(e.minor,n),s=[];for(const o of t)s.push(O(D(o.sellerId),I(e.currency,Yr(r,o.shareBps))));return s.push(O(w.REVENUE,I(e.currency,Wr(e,t,n)))),s}function Wr(e,t,n){const r=gt(e.minor,n),s=e.minor-r;let o=0n;for(const a of t)o+=Yr(s,a.shareBps);return r+(s-o)}function Yr(e,t){return ze(e,BigInt(t),zr,"floor")}function gt(e,t){const r=ze(e,BigInt(t),zr*Pn,"ceil")*Pn;return r>e?e:r}function na(e){if(e.length===0)return;let t=0;for(const n of e)t+=n.shareBps;if(t!==ea)throw p(h.MALFORMED_OPERATION,"Recipient shareBps must sum to 10000.",{detail:{total:t,recipientCount:e.length}})}async function ra(e,t){return G(e,"spend"),await t.sales.get(e.orderId)===null?null:H("DUPLICATE_ORDER",{orderId:e.orderId})}async function sa(e,t,n){G(e,"spend"),ma(e);const r=mt(e.price,"spend.price");Go(e.recipients??[],e.buyerId,"spend",{kind:e.kind,orderId:e.orderId});const s=fa(e);if(await t.sales.get(e.orderId)!==null)return H("DUPLICATE_ORDER",{orderId:e.orderId});const a=$(e.buyerId),i=M(e.buyerId),c=t.balances?.get(a)??await t.ledger.balance(a),u=gn(r,c);if(!await yt(t.ledger,i,n.clock.now(),{config:n.config,amount:u.spendablePart,live:t.balances?.get(i)}))return H("FUNDS_IMMATURE",await mn(t.ledger,i,n.clock.now(),{config:n.config,amount:u.spendablePart,live:t.balances?.get(i)}));const g=ia(e,u,n),y=n.config.accrualDrain?hn(g):null,v=Te(y?.legs??g,e.idempotencyKey,n.config.platformShards),S=await F(t.ledger,{txnId:n.ids.next("txn"),legs:v,meta:oa(e,s,y)});return await t.sales.put(la(e,u,S,n.config.platformFeeBps)),y!==null&&await aa(t,n,e,{shares:y.shares,transaction:S}),await t.entitlements.grant(s,e.sku,{source:"sale:"+e.orderId}),{status:"committed",transaction:S}}function oa(e,t,n){const r={kind:"spend",orderId:e.orderId};return e.ageRestricted&&(r.ageRestricted=!0),t!==e.buyerId&&(r.isGift=!0,r.giftTo=t),n!==null&&(r.shares=pn(n.shares)),r}async function aa(e,t,n,r){await e.accruals.put(yn({orderId:n.orderId,shares:r.shares,routeKey:n.idempotencyKey,shards:t.config.platformShards,txnId:r.transaction.id,recordedAt:r.transaction.postedAt}))}function gn(e,t){const n=t.minor>0n?t.minor:0n,r=n<e.minor?n:e.minor;return{promoPart:I(e.currency,r),spendablePart:I(e.currency,e.minor-r)}}function ia(e,t,n){const r=[];return ca(r,e,t),ua(r,e,t,n),r}function ca(e,t,n){if(n.promoPart.minor===0n)return;e.push(N($(t.buyerId),n.promoPart)),e.push(O(w.PROMO_FLOAT,n.promoPart));const r=da(e,n.promoPart,t.recipients);e.push(N(w.REVENUE,r))}function ua(e,t,n,r){if(n.spendablePart.minor!==0n){e.push(N(M(t.buyerId),n.spendablePart));for(const s of r.pricing({price:n.spendablePart,recipients:t.recipients,feeBps:r.config.platformFeeBps,buyerId:t.buyerId,sku:t.sku}))e.push(s)}}function da(e,t,n){let r=0n;for(const s of n){const o=ze(t.minor,BigInt(s.shareBps),10000n,"floor");r+=o,o>0n&&e.push(O(D(s.sellerId),I(t.currency,o)))}return I(t.currency,r)}function la(e,t,n,r){const s=Wr(t.spendablePart,e.recipients,r);return{orderId:e.orderId,buyerId:e.buyerId,recipientId:e.giftTo??e.buyerId,sku:e.sku,price:e.price,fee:I(e.price.currency,s),legs:n.legs.map(o=>({...o})),txnId:n.id,postedAt:n.postedAt}}function fa(e){if(e.giftTo===void 0)return e.buyerId;if(e.giftTo.trim()==="")throw p(h.MALFORMED_OPERATION,"spend.giftTo must be a non-empty user id.",{detail:{orderId:e.orderId}});return e.giftTo}function ma(e){if(typeof e.sku!="string"||e.sku.trim()==="")throw p(h.MALFORMED_OPERATION,"spend.sku must be a non-empty string.",{detail:{kind:e.kind,orderId:e.orderId}});if(typeof e.orderId!="string"||e.orderId.trim()==="")throw p(h.MALFORMED_OPERATION,"spend.orderId must be a non-empty string.",{detail:{kind:e.kind}});const t=new Set;for(const n of e.recipients??[]){if(t.has(n.sellerId))throw p(h.MALFORMED_OPERATION,"spend.recipients may not name the same sellerId twice.",{detail:{kind:e.kind,orderId:e.orderId,sellerId:n.sellerId}});t.add(n.sellerId);const r=D(n.sellerId);if(!le(r)||We(r).trim()==="")throw p(h.MALFORMED_OPERATION,"spend.recipients sellerId must be a user wallet, not a house account.",{detail:{kind:e.kind,orderId:e.orderId,sellerId:n.sellerId}})}}
2async function ha(e,t,n){G(e,"refund"),ka(e.orderId);const r=await t.sales.get(e.orderId);if(r===null)return H("UNKNOWN_ORDER",{orderId:e.orderId});const s=await Le({ledger:t.ledger,digest:n.digest},r.txnId);if(s===null)throw p(h.CHAIN_BROKEN,"A sales row names a posting the ledger does not hold; refusing to reverse unverifiable history.",{retryable:!1,detail:{orderId:r.orderId,txnId:r.txnId}});ya(r,s),await pa(t,s.legs);const o=ut(e.orderId),a=await t.idempotency.claim(o);if(!a.claimed)return{status:"duplicate",transaction:a.transaction};const i=n.ids.next("txn"),c=await t.accruals.claimByOrder(r.orderId),u=c.filter(y=>y.txnId===r.txnId),m=u.length>0?await wa(t,n,s,{claimed:c,saleRows:u,txnId:i}):{legs:Ea(await ga(t,s.legs)),recovered:null},g=await F(t.ledger,{txnId:i,legs:m.legs,meta:va(e,r,m.recovered)});return await t.idempotency.record(o,g),await t.entitlements.revoke(r.recipientId??r.buyerId,r.sku),{status:"committed",transaction:g}}async function pa(e,t){await Ne(e.ledger,t.map(n=>n.account))}function ya(e,t){const n=o=>`${o.account}|${o.amount.currency}|${o.amount.minor}`,r=[...t.legs].map(n).sort(),s=[...e.legs].map(n).sort();if(r.length!==s.length||r.some((o,a)=>o!==s[a]))throw p(h.CHAIN_BROKEN,"A sales row no longer matches its verified posting; refusing to reverse tampered history.",{retryable:!1,detail:{orderId:e.orderId,txnId:e.txnId}})}async function ga(e,t){const n=Jr(t),r=[],s=[];let o=0n;for(const a of n){if(a.delta===0n)continue;if(a.delta<0n){r.push({account:a.account,delta:-a.delta,currency:a.currency});continue}const i=a.delta,c=await Xr(e,a.account),u=c<i?c>0n?c:0n:i;u>0n&&s.push({account:a.account,covered:u,currency:a.currency}),o+=i-u}return{uncapped:r,capped:s,shortfall:o}}async function wa(e,t,n,r){const{claimed:s,saleRows:o,txnId:a}=r;Ia(o,n);const i=o.filter(v=>v.status==="pending"&&v.amount.minor>0n),c=o.filter(v=>v.status==="drained"&&v.amount.minor>0n),u=[];let m=0n;for(const v of Jr(n.legs)){if(v.delta===0n)continue;if(v.delta<0n){u.push(je(v.account,I(v.currency,-v.delta)));continue}if(Ce(v.account)===w.SETTLEMENT_ACCRUAL)continue;const S=v.delta,U=await Xr(e,v.account),L=U<S?U>0n?U:0n:S;L>0n&&u.push(Ht(v.account,I(v.currency,L))),m+=S-L}for(const v of i)u.push(Ht(v.shard,v.amount));let g=0n;for(const v of c)g+=v.amount.minor;g>0n&&u.push(je(w.RECEIVABLE,I("CREDIT",g))),m>0n&&u.push(je(w.RECEIVABLE,I("CREDIT",m))),await e.accruals.markRefunded(i.map(({orderId:v,sellerId:S,seq:U})=>({orderId:v,sellerId:S,seq:U})),a);const y=new Map;for(const v of c)y.set(v.sellerId,v.amount.minor);return c.length>0&&await e.accruals.put(ba(s,c,a,t)),{legs:u,recovered:y.size>0?y:null}}function Ia(e,t){const n=t.meta.shares??null;for(const r of e){const s=n?.[r.sellerId];if(r.seq!==0||s===void 0||BigInt(s)!==r.amount.minor)throw p(h.CHAIN_BROKEN,"An accrual row does not match the share map sealed in its posting; refusing to reverse tampered history.",{retryable:!1,detail:{orderId:r.orderId,sellerId:r.sellerId,seq:r.seq,txnId:t.txnId}})}}function ba(e,t,n,r){const s=new Map;for(const a of e){const i=`${a.orderId}::${a.sellerId}`;s.set(i,Math.max(s.get(i)??0,a.seq+1))}const o=r.clock.now();return t.map(a=>{const i=`${a.orderId}::${a.sellerId}`,c=s.get(i);return s.set(i,c+1),{orderId:a.orderId,sellerId:a.sellerId,seq:c,amount:I("CREDIT",-a.amount.minor),shard:a.shard,status:"pending",txnId:n,settledTxnId:null,recordedAt:o}})}function Ea(e){const t=[];for(const n of e.uncapped)t.push(je(n.account,I(n.currency,n.delta)));for(const n of e.capped)t.push(Ht(n.account,I(n.currency,n.covered)));return e.shortfall>0n&&t.push(je(w.RECEIVABLE,I("CREDIT",e.shortfall))),t}function je(e,t){const n=Ee(e)?1n:-1n;return{account:e,amount:I(t.currency,t.minor*n)}}function Ht(e,t){const n=Ee(e)?-1n:1n;return{account:e,amount:I(t.currency,t.minor*n)}}function Jr(e){const t=new Map;for(const n of e){const r=Z(n),s=t.get(n.account);s===void 0?t.set(n.account,{account:n.account,delta:r.minor,currency:r.currency}):s.delta+=r.minor}return[...t.values()]}async function Xr(e,t){return(await e.ledger.balance(t)).minor}function va(e,t,n){const r={kind:"refund",orderId:e.orderId,reversedTxnId:t.txnId};if(e.reason!==void 0&&(r.reason=e.reason),n!==null){const s={};for(const[o,a]of n)s[o]=a.toString();r.recovered=s}return r}function ka(e){if(e.trim()==="")throw p(h.MALFORMED_OPERATION,"refund.orderId must not be blank.",{detail:{orderId:e}})}async function Aa(e,t,n){G(e,"clawback");const r=mt(e.amount,"clawback.amount");if(e.orderId!==void 0){const c=Sa(e.orderId),u=await t.idempotency.claim(ut(c));if(!u.claimed)return{status:"duplicate",transaction:u.transaction}}
2const s=await t.ledger.balance(M(e.userId)),o=Ra(r,s),a=_a(e.userId,r,o),i=await F(t.ledger,{txnId:n.ids.next("txn"),legs:a,meta:Ma(e,o)});return e.orderId!==void 0&&await t.idempotency.record(ut(e.orderId),i),{status:"committed",transaction:i}}function Sa(e){if(e.trim()==="")throw p(h.MALFORMED_OPERATION,"clawback.orderId must be a non-empty order id when present.");return e}function Ra(e,t){const n=t.minor>0n?t.minor:0n,r=n<e.minor?n:e.minor;return{recovered:I(e.currency,r),shortfall:I(e.currency,e.minor-r)}}function _a(e,t,n){const r=[];return n.recovered.minor>0n&&r.push(N(M(e),n.recovered)),n.shortfall.minor>0n&&r.push(N(w.RECEIVABLE,n.shortfall)),r.push(O(w.STORED_VALUE,t)),r}function Ma(e,t){const n={kind:"clawback",recovered:E(t.recovered),shortfall:E(t.shortfall)};return e.orderId!==void 0&&(n.orderId=e.orderId),e.key!==void 0&&(n.key=e.key),e.reason!==void 0&&(n.reason=e.reason),n}async function Oa(e,t,n){G(e,"requestPayout");const r=La(e.amount);if(r.minor<n.config.payoutMinimumEarnedMinor)return H("BELOW_MINIMUM",{minimum:I("CREDIT",n.config.payoutMinimumEarnedMinor),amount:r});const s=await t.sagas.lastPayoutAt(e.userId);if(s!==null&&n.clock.now()-s<n.config.payoutMinIntervalMs)return H("PAYOUT_TOO_SOON",{retryAt:s+n.config.payoutMinIntervalMs});if(n.payees!==void 0&&(await n.payees.status(e.userId)).state!=="CLEARED")return H("PAYEE_UNVERIFIED",{userId:e.userId});const o=await t.ledger.balance(D(e.userId)),a=await Da(t,e.userId,o);if(Ge(a,r)<0)return H("INSUFFICIENT_FUNDS",{account:D(e.userId),need:r,have:a});if(!await yt(t.ledger,D(e.userId),n.clock.now(),{config:n.config,amount:r,live:o}))return H("FUNDS_IMMATURE",await mn(t.ledger,D(e.userId),n.clock.now(),{config:n.config,amount:r,live:o}));const c=await Na(n,r);return{status:"committed",transaction:await Ta(t,n,{operation:e,amount:r,quote:c})}}async function Ta(e,t,n){const{operation:r,amount:s}=n,{rateId:o,payoutUsd:a}=n.quote,i=t.ids.next("pay"),c=t.ids.next("txn"),u=await F(e.ledger,{txnId:c,legs:Te([N(D(r.userId),s),O(w.PAYOUT_RESERVE,s)],r.userId,t.config.platformShards),meta:{kind:"requestPayout",rateId:o,sagaId:i,payoutUsd:E(a)}}),m={id:i,reserve:s,rateId:o,payoutUsd:a,txnId:c};return await e.sagas.open(Pa(r,m,t)),u}async function Da(e,t,n){const r=await e.accruals.netPending(t);return r<0n?I("CREDIT",n.minor+r):n}async function Na(e,t){const n=await e.rates.payout("CREDIT","USD",e.clock.now()),r=e.rates.par("CREDIT");if(!Ir(r,n))throw p(h.CONFIG_INVALID,"Rates are misordered: payout is above par.",{retryable:!1,detail:{parRateId:r.rateId,payoutRateId:n.rateId}});return{rateId:n.rateId,payoutUsd:Ve(t,n,"USD")}}function Pa(e,t,n){const r=n.clock.now();return{id:t.id,userId:e.userId,reserve:t.reserve,rateId:t.rateId,txnId:t.txnId,state:"RESERVED",providerRef:null,reason:null,payoutUsd:t.payoutUsd,attempts:0,dueAt:r+Ca(n),updatedAt:r}}function Ca(e){const t=e.config.payoutSla;return t.PENDING??t.DEFAULT??0}function La(e){if(e.currency!=="CREDIT")throw p(h.MALFORMED_OPERATION,"requestPayout.amount must be earned CREDIT.",{detail:{amount:E(e)}});if(e.minor<=0n)throw p(h.INVALID_AMOUNT,"requestPayout.amount must be positive.",{detail:{amount:E(e)}});return e}const qn=10*365*24*60*6e4;async function Ua(e,t,n){G(e,"subscribe"),xa(e),$a(e);const r=Ba(e.price,n.config);if(await t.subscriptions.activeFor(e.userId,e.sku,e.sellerId)!==null)return H("ALREADY_SUBSCRIBED",{userId:e.userId,sku:e.sku});const o=await t.ledger.balance($(e.userId)),a=gn(r,o),i=await Fa(t,n,e.userId,a);if(i)return i;const c=n.ids.next("sub"),u=await Ha({operation:e,plan:a,subscriptionId:c},t,n);return await Ka(e,c,u,t),await t.entitlements.grant(e.userId,e.sku,{expiresAt:u.postedAt+e.periodMs,source:"subscription:"+c}),{status:"committed",transaction:u}}function xa(e){if(e.userId===e.sellerId)throw p(h.MALFORMED_OPERATION,"subscribe.userId and subscribe.sellerId must differ; a buyer cannot subscribe to themselves.",{detail:{userId:e.userId,sellerId:e.sellerId}})}function $a(e){const t=e.periodMs;if(!Number.isInteger(t)||t<=0||t>qn)throw p(h.MALFORMED_OPERATION,"subscribe.periodMs must be a finite positive integer no larger than the ten-year ceiling.",{detail:{periodMs:t,max:qn}});if(typeof e.sku!="string"||e.sku.trim()==="")throw p(h.MALFORMED_OPERATION,"subscribe.sku must be a non-empty string.",{detail:{sku:e.sku}})}function Ba(e,t){if(e.currency!=="CREDIT")throw p(h.MALFORMED_OPERATION,"subscribe.price must be CREDIT.",{detail:{amount:E(e)}});const n=t.subscriptionPriceMinMinor,r=t.subscriptionPriceMaxMinor;if(e.minor<n||e.minor>r)throw p(h.MALFORMED_OPERATION,"subscribe.price is outside the configured price band.",{detail:{amount:E(e),min:E(I("CREDIT",n)),max:E(I("CREDIT",r))}});return e}async function Fa(e,t,n,r){const s=await e.ledger.balance(M(n));return Ge(s,r.spendablePart)<0?H("INSUFFICIENT_FUNDS",{account:M(n),need:r.spendablePart,have:s}):await yt(e.ledger,M(n),t.clock.now(),{config:t.config,amount:r.spendablePart,live:s})?null:H("FUNDS_IMMATURE",await mn(e.ledger,M(n),t.clock.now(),{config:t.config,amount:r.spendablePart,live:s}))}
2async function Ha(e,t,n){const{operation:r,plan:s,subscriptionId:o}=e,a=[];qa(a,r,s.promoPart),ja(a,r,s.spendablePart,n);const i=n.config.accrualDrain?hn(a):null,c=i===null?a:Te(i.legs,r.idempotencyKey,n.config.platformShards),u=await F(t.ledger,{txnId:n.ids.next("txn"),legs:c,meta:{kind:"subscribe",sku:r.sku,sellerId:r.sellerId,subscriptionId:o,userId:r.userId,price:E(r.price),periodMs:r.periodMs,...i===null?{}:{shares:pn(i.shares)}}});return i!==null&&await t.accruals.put(yn({orderId:u.id,shares:i.shares,routeKey:r.idempotencyKey,shards:n.config.platformShards,txnId:u.id,recordedAt:u.postedAt})),u}function qa(e,t,n){n.minor!==0n&&(e.push(N($(t.userId),n)),e.push(O(w.PROMO_FLOAT,n)),e.push(N(w.REVENUE,n)),e.push(O(D(t.sellerId),n)))}function ja(e,t,n,r){if(n.minor===0n)return;const s=gt(n.minor,r.config.platformFeeBps),o=n.minor-s;e.push(N(M(t.userId),n)),e.push(O(D(t.sellerId),I("CREDIT",o))),e.push(O(w.REVENUE,I("CREDIT",s)))}async function Ka(e,t,n,r){const s=n.postedAt,o={id:t,userId:e.userId,sellerId:e.sellerId,sku:e.sku,price:e.price,txnId:n.id,periodMs:e.periodMs,state:"ACTIVE",period:1,attempts:0,nextDueAt:s+e.periodMs,updatedAt:s};await r.subscriptions.open(o)}async function Va(e,t,n){G(e,"cancelSubscription"),za(e.subscriptionId);const r=await t.subscriptions.load(e.subscriptionId);return r===null||r.state==="CANCELED"?H("UNKNOWN_SUBSCRIPTION",{subscriptionId:e.subscriptionId}):(Ga(e,r),await t.subscriptions.cancel(e.subscriptionId),{status:"committed",transaction:ln(n)})}function za(e){if(e.trim()==="")throw p(h.MALFORMED_OPERATION,"cancelSubscription requires a non-empty subscriptionId.",{detail:{kind:"cancelSubscription"}})}function Ga(e,t){const n=e.actor;if(n.kind==="user"&&n.userId!==t.userId)throw p(h.UNAUTHORIZED,"A user may cancel only their own subscription.",{detail:{kind:e.kind,actor:n.kind,subscriptionId:e.subscriptionId}})}async function Wa(e,t,n){return G(e,"grantEntitlement"),Zr(e.userId,e.sku),Ja(e.attrs),await t.entitlements.grant(e.userId,e.sku,e.attrs??Xa),{status:"committed",transaction:ln(n)}}async function Ya(e,t,n){return G(e,"revokeEntitlement"),Zr(e.userId,e.sku),await t.entitlements.owns(e.userId,e.sku)?(await t.entitlements.revoke(e.userId,e.sku),{status:"committed",transaction:ln(n)}):H("NOT_ENTITLED",{userId:e.userId,sku:e.sku})}function Zr(e,t){if(e.trim()==="")throw p(h.MALFORMED_OPERATION,"entitlement operation names a blank userId.",{detail:{field:"userId"}});if(t.trim()==="")throw p(h.MALFORMED_OPERATION,"entitlement operation names a blank sku.",{detail:{field:"sku"}})}function Ja(e){if(e!==void 0){if(e.expiresAt!==void 0&&e.expiresAt!==null&&!Number.isFinite(e.expiresAt))throw p(h.MALFORMED_OPERATION,"entitlement attrs.expiresAt must be a finite number.",{detail:{field:"attrs.expiresAt",value:e.expiresAt}});if(e.quantity!==void 0&&(!Number.isInteger(e.quantity)||e.quantity<=0))throw p(h.MALFORMED_OPERATION,"entitlement attrs.quantity must be a positive integer.",{detail:{field:"attrs.quantity",value:e.quantity}})}}const Xa={};async function Za(e,t,n){G(e,"grantPromo");const r=mt(e.amount,"grantPromo.amount"),s=Qa(e.expiresAt,n,"grantPromo.expiresAt"),o=await F(t.ledger,{txnId:n.ids.next("txn"),legs:[N(w.PROMO_FLOAT,r),O($(e.userId),r)],meta:{kind:"grantPromo",expiresAt:s}});return await t.promos.open({id:o.id,userId:e.userId,amount:r,expiresAt:s,reversed:!1}),{status:"committed",transaction:o}}const jn=5*365*24*60*6e4;function Qa(e,t,n){const r=t.clock.now();if(!Number.isInteger(e)||e<=r)throw p(h.MALFORMED_OPERATION,`${n} must be a whole-millisecond timestamp in the future.`,{detail:{label:n,expiresAt:e,now:r}});if(e>r+jn)throw p(h.MALFORMED_OPERATION,`${n} is too far in the future.`,{detail:{label:n,expiresAt:e,now:r,maxAheadMs:jn}});return e}async function ei(e,t,n){G(e,"adjust"),jr(e),dn(e);const r=ri(e.amount,"adjust.amount");return{status:"committed",transaction:await F(t.ledger,{txnId:n.ids.next("txn"),legs:ti(e.account,r),meta:ni(e)})}}function ti(e,t){const n=Ee(e)?t.minor:-t.minor;return[{account:e,amount:I(t.currency,n)},{account:w.OPENING_EQUITY,amount:I(t.currency,-n)}]}function ni(e){return{kind:"adjust",amount:E(e.amount),reason:e.reason}}function ri(e,t){if(e.currency!=="CREDIT")throw p(h.MALFORMED_OPERATION,`${t} must be CREDIT.`,{detail:{label:t,amount:E(e)}});if(js(e))throw p(h.INVALID_AMOUNT,`${t} must be non-zero.`,{detail:{label:t,amount:E(e)}});return e}async function si(e,t,n){G(e,"reverse"),jr(e),dn(e);const r=await oi(t,n,e.txnId);ai(e,r),await ii(t,r.legs);const s=ut(e.txnId),o=await t.idempotency.claim(s);if(!o.claimed)return{status:"duplicate",transaction:o.transaction};const a=await F(t.ledger,{txnId:n.ids.next("txn"),legs:ci(r.legs),meta:ui(e)});return await t.idempotency.record(s,a),{status:"committed",transaction:a}}async function oi(e,t,n){const r=await Le({ledger:e.ledger,digest:t.digest},n);if(r===null)throw p(h.MALFORMED_OPERATION,"reverse names a posting that does not exist.",{detail:{kind:"reverse",txnId:n}});return r}function ai(e,t){if(t.meta.kind==="reverse")throw p(h.MALFORMED_OPERATION,"reverse cannot undo a reversal.",{detail:{kind:"reverse",txnId:e.txnId}})}async function ii(e,t){await Ne(e.ledger,t.map(n=>n.account))}function ci(e){return e.map(t=>({account:t.account,amount:Ks(t.amount)}))}function ui(e){return{kind:"reverse",txnId:e.txnId,reason:e.reason}}async function di(e,t,n){G(e,"reversePayout"),dn(e);const r=await Kr(t,e);return li(e.userId,r),fi(r),mi(e,r,n),r.state!=="RESERVED"&&r.state!=="SUBMITTED"?{status:"duplicate",transaction:Ft()}:await t.sagas.advance(r.id,r.state,"FAILED",{updatedAt:n.clock.now()})?(await pt({ledger:t.ledger,digest:n.digest},r),{status:"committed",transaction:await F(t.ledger,{txnId:n.ids.next("txn"),legs:Te([N(w.PAYOUT_RESERVE,r.reserve),O(D(r.userId),r.reserve)],e.userId,n.config.platformShards),meta:{kind:"reversePayout",sagaId:r.id,reason:e.reason,...e.providerReported===!0?{providerReported:!0}
2:{}}})}):{status:"duplicate",transaction:Ft()}}function li(e,t){if(e!==t.userId)throw p(h.MALFORMED_OPERATION,"reversePayout userId does not match the payout it names.",{detail:{sagaId:t.id,userId:e,sagaUserId:t.userId}})}function fi(e){if(e.state==="SETTLED")throw p(h.INVALID_TRANSITION,"Cannot reverse a settled payout.",{detail:{sagaId:e.id,state:e.state}})}function mi(e,t,n){if(e.providerReported!==!0&&t.state==="SUBMITTED"&&n.clock.now()-t.updatedAt<=n.config.maxPayoutAgeMs)throw p(h.INVALID_TRANSITION,"Cannot reverse a payout still within its provider settlement window.",{detail:{sagaId:t.id,state:t.state,ageMs:n.clock.now()-t.updatedAt,maxPayoutAgeMs:n.config.maxPayoutAgeMs}})}async function hi(e,t,n){G(e,"settlePayout");const r=await Kr(t,e);if(r.state==="SETTLED")return{status:"duplicate",transaction:Ft()};pi(r);const s=await pt({ledger:t.ledger,digest:n.digest},r),o=gi(s,n.config.payoutFeeBps),a=I("USD",s.minor-o.minor),i=await yi(t,n,{saga:r,usd:s,fee:o,net:a,rateId:r.rateId}),c=await t.sagas.advance(r.id,"SUBMITTED","SETTLED",{updatedAt:n.clock.now(),payoutUsd:s});return wi(c,r,"SETTLED"),await t.outbox.enqueue(xe(n.ids,{id:n.ids.next("evt"),type:"economy.payout.settled",version:1,occurredAt:n.clock.now(),subject:r.userId,data:{sagaId:r.id,userId:r.userId,reserve:E(r.reserve),usd:E(s),payoutFee:E(o),netUsd:E(a),rateId:r.rateId},audience:"internal"})),{status:"committed",transaction:i}}function pi(e){if(e.state!=="SUBMITTED")throw p(h.INVALID_TRANSITION,"Cannot settle a payout that is not submitted.",{detail:{sagaId:e.id,state:e.state},retryable:e.state!=="FAILED"})}async function yi(e,t,n){const{saga:r,usd:s,fee:o,net:a,rateId:i}=n,c=q(w.PAYOUT_RESERVE,r.userId,t.config.platformShards);c!==w.PAYOUT_RESERVE&&await Ne(e.ledger,[c]);const[u]=await _r(e.ledger,[{txnId:t.ids.next("txn"),legs:[N(c,r.reserve),O(w.REVENUE,r.reserve)],meta:{kind:"settlePayout",sagaId:r.id,rateId:i}},{txnId:t.ids.next("txn"),legs:[N(w.USD_CLEARING,s),O(w.TRUST_CASH,s)],meta:{kind:"settlePayout.cash",sagaId:r.id,rateId:i,payoutFee:E(o),netUsd:E(a)}}]);return u}function gi(e,t){return I("USD",ze(e.minor,BigInt(t),10000n,"floor"))}function wi(e,t,n){if(!e)throw p(h.INVALID_TRANSITION,"The payout was advanced by another actor first.",{detail:{sagaId:t.id,from:t.state,to:n},retryable:!0})}const Ii={spend:ra},Qr={topUp:Yo,spend:sa,refund:ha,clawback:Aa,requestPayout:Oa,subscribe:Ua,cancelSubscription:Va,grantEntitlement:Wa,revokeEntitlement:Ya,grantPromo:Za,adjust:ei,reverse:si,reversePayout:di,settlePayout:hi},es="CREDIT";function bi(e){return e.kind==="spend"?{subject:`out:${e.buyerId}`,class:"out"}:e.kind==="requestPayout"||e.kind==="subscribe"?{subject:`out:${e.userId}`,class:"out"}:e.kind==="topUp"||e.kind==="grantPromo"?{subject:`in:${e.userId}`,class:"in"}:null}function Ei(e,t){return(t==="in"?e.velocityInflowLimitMinor:e.velocityOutflowLimitMinor)??e.velocityLimitMinor}function vi(e){return e.kind==="spend"||e.kind==="subscribe"?e.price.minor:e.kind==="topUp"||e.kind==="grantPromo"||e.kind==="requestPayout"?e.amount.minor:0n}function Be(e){return{account:e.account,amount:E(e.amount)}}function Fe(e){const t=e;return{account:t.account,amount:ne(t.amount)}}function ne(e){return Xt(e)}const ts={amount:E,movement:e=>({...e,legs:e.legs.map(Be)}),posting:e=>({txnId:e.txnId,legs:e.legs.map(Be),meta:e.meta}),storedLink:e=>({txnId:e.txnId,legs:e.legs.map(Be),meta:e.meta,prevHash:e.prevHash,hash:e.hash}),transaction:e=>({id:e.id,postedAt:e.postedAt,legs:e.legs.map(Be),links:e.links,meta:e.meta}),sale:e=>({...e,price:E(e.price),fee:E(e.fee),legs:e.legs.map(Be)}),saga:e=>({...e,reserve:E(e.reserve),payoutUsd:e.payoutUsd===null?null:E(e.payoutUsd)}),sagaPatch:e=>{const t={...e};return e.reserve!==void 0&&(t.reserve=E(e.reserve)),e.payoutUsd!==void 0&&(t.payoutUsd=e.payoutUsd===null?null:E(e.payoutUsd)),t},subscription:e=>({...e,price:E(e.price)}),promoGrant:e=>({...e,amount:E(e.amount)}),attempt:e=>({...e,amount:E(e.amount)}),inboxMessage:e=>({...e,operation:br(e.operation)})},wn={amount:e=>ne(e),movement:e=>{const t=e;return{...t,legs:t.legs.map(Fe)}},posting:e=>{const t=e;return{txnId:t.txnId,legs:t.legs.map(Fe),meta:t.meta}},transaction:e=>{const t=e;return{id:t.id,postedAt:t.postedAt,legs:t.legs.map(Fe),links:t.links.map(n=>({...n,account:n.account})),meta:t.meta??{}}},claim:e=>{const t=e;return t.claimed?{claimed:!0}:{claimed:!1,transaction:wn.transaction(t.transaction)}},sale:e=>{const t=e;return{...t,price:ne(t.price),fee:ne(t.fee),legs:t.legs.map(Fe)}},saga:e=>{const t=e;return{...t,reserve:ne(t.reserve),payoutUsd:t.payoutUsd===null?null:ne(t.payoutUsd)}},subscription:e=>{const t=e;return{...t,price:ne(t.price)}},promoGrant:e=>{const t=e;return{...t,amount:ne(t.amount)}},inboxMessage:e=>{const t=e;return{...t,operation:Vs(t.operation)}},velocity:e=>{const t=e;return{...t,spent:ne(t.spent)}},lot:e=>{const t=e;return{...t,amount:ne(t.amount)}},statement:e=>{const t=e;return{account:t.account,entries:t.entries.map(n=>({txnId:n.txnId,amount:ne(n.amount),postedAt:n.postedAt})),cursor:t.cursor}},storedLink:e=>{const t=e;return{txnId:t.txnId,legs:t.legs.map(Fe),meta:t.meta,prevHash:t.prevHash,hash:t.hash}}},re={historySizePostings:1e7,reproofMaxAgeMs:1440*6e4,checkpointMaxAgeMs:60*6e4,accrualMaxPendingAgeMs:60*6e4,tableRows:1e7,enumerationCap:1e4};function ki(e){const t=e.store;Object.freeze(e.config),Object.freeze(e.config.maturityHorizonMs),Object.freeze(e.config.payoutSla),Ai(e.rates);const n=Si(e),r=Qr;return{submit:(s,o)=>rs({store:t,registry:r,ctx:n},s,o),submitBatch:(s,o)=>Mi({store:t,registry:r,ctx:n},s,o),read:{balance:(s,o)=>_i(n,t.ledger,s,o),statement:(s,o,a)=>
2t.ledger.statement(s,o,a),posting:(s,o)=>t.ledger.posting(s,o),saga:(s,o)=>t.sagas.load(s,o),entitled:(s,o,a)=>t.entitlements.owns(s,o,a),status:()=>Ri(n),capacity:s=>ji(t,n,s),accounts:s=>t.ledger.balanceAccounts(s),payouts:s=>t.sagas.list(s),postings:s=>t.ledger.list(s),lineage:(s,o)=>t.ledger.lineage(s,o),export:s=>rc(t,s),checkpoint:s=>t.checkpoints.latest(s),health:s=>zi(t,n,s)},close:()=>t.close()}}function Ai(e){const t=e.buy("CREDIT"),n=e.par("CREDIT");if(!Ir(t,n))throw p(h.CONFIG_INVALID,"Rates are misordered: buy is below par, so every top-up would book a loss.",{retryable:!1,detail:{buyRateId:t.rateId,parRateId:n.rateId}})}function Si(e){return{clock:e.clock,ids:e.ids,digest:e.digest,signer:e.signer,processor:e.processor,config:e.config,pricing:e.pricing,rates:e.rates,logger:e.logger,meter:e.meter,cache:e.cache,payees:e.payees}}function Ri(e){const{pauseStartMs:t,pauseEndMs:n}=e.config,r=nn(e.clock.now(),e.config);return{maintenanceActive:r,pauseStart:t,pauseEnd:n,resumesAt:r?n:null}}function ns(e){return`bal:${e}`}async function qt(e,t,n,r){try{return await n()}catch(s){return e.logger.log("warn","economy.cache.degraded",{op:t,error:s instanceof Error?s.message:String(s)}),r}}async function _i(e,t,n,r){const s=e.config.platformShards;if(s>1&&eo(n)){let o=0n;for(const a of Zt(n,s))o+=(await Kn(e,t,a,r)).minor;return I(J(n),o)}return Kn(e,t,n,r)}async function Kn(e,t,n,r){const s=e.cache;if(!s)return t.balance(n,r);const o=ns(n),a=await qt(e,"get",()=>s.get(o),null);if(a!==null)return Xt(a);const i=await t.balance(n,r);return await qt(e,"set",()=>s.set(o,E(i)),void 0),i}async function rs(e,t,n){const{meter:r,clock:s}=e.ctx,o=String(t?.kind??"unknown"),a=s.now();let i="fault",c;try{const u=await Ni(e,t,n);return i=u.status,u.status==="rejected"&&(c=u.detail.reason),u}finally{try{r.count("economy.submit",1,{kind:o,status:i,...c===void 0?{}:{reason:c}}),r.observe("economy.submit.ms",s.now()-a,{kind:o})}catch{}}}async function Mi(e,t,n){if(e.store.batchTransaction===void 0)return Oi(e,t,n);const r=t.map(()=>null),s=Ti(e,t,r);if(s.length===0)return await Vn(e,t,r),r;const o=await e.store.batchTransaction(s.map(a=>i=>ss({pipeline:e,unit:i,operation:a.operation,options:n,staged:(c,u)=>{a.staged={subject:c,attempt:u}}})),n).catch(async a=>{for(const i of s)i.staged&&await e.store.trust.bump(i.staged.subject,i.staged.attempt,n).catch(()=>{});throw a});for(let a=0;a<s.length;a+=1)r[s[a].index]=await Di(e,s[a],o[a],n);return await Vn(e,t,r),r}async function Oi(e,t,n){const r=[];for(const s of t)try{r.push({ok:!0,outcome:await rs(e,s,n)})}catch(o){r.push({ok:!1,error:o})}try{e.ctx.meter.count("economy.submit.batch",1,{size:String(t.length)})}catch{}return r}function Ti(e,t,n){const r=e.ctx,s=[],o=new Set;return t.forEach((a,i)=>{try{if(os(a,r.config),is(a),o.has(a.idempotencyKey))throw p(h.MALFORMED_OPERATION,"A submitBatch may not carry the same idempotencyKey twice.",{detail:{kind:a.kind}});if(o.add(a.idempotencyKey),a.actor.kind==="user"&&nn(r.clock.now(),r.config)){n[i]={ok:!0,outcome:H("ECONOMY_PAUSED",{resumesAt:r.config.pauseEndMs})};return}s.push({index:i,operation:a,staged:null})}catch(c){n[i]={ok:!1,error:c}}}),s}async function Di(e,t,n,r){if(n.ok)return{ok:!0,outcome:n.value};if(n.error instanceof In){if(t.staged)try{await e.store.trust.bump(t.staged.subject,t.staged.attempt,r)}catch(s){return{ok:!1,error:s}}return{ok:!0,outcome:n.error.outcome}}return t.staged&&await e.store.trust.bump(t.staged.subject,t.staged.attempt,r).catch(()=>{}),{ok:!1,error:n.error}}async function Vn(e,t,n){for(let r=0;r<t.length;r+=1){const s=n[r];s?.ok===!0&&await as(e,t[r],s.outcome);try{const o=s==null?"fault":s.ok?s.outcome.status:"fault",a=s?.ok===!0&&s.outcome.status==="rejected"?s.outcome.detail.reason:void 0;e.ctx.meter.count("economy.submit",1,{kind:String(t[r]?.kind??"unknown"),status:o,...a===void 0?{}:{reason:a}})}catch{}}try{e.ctx.meter.count("economy.submit.batch",1,{size:String(t.length)})}catch{}}async function Ni(e,t,n){os(t,e.ctx.config),is(t);const r=e.ctx;if(t.actor.kind==="user"&&nn(r.clock.now(),r.config))return H("ECONOMY_PAUSED",{resumesAt:r.config.pauseEndMs});let s=null;const o=await e.store.transaction(a=>ss({pipeline:e,unit:a,operation:t,options:n,staged:(i,c)=>{s={subject:i,attempt:c}}}),n).catch(async a=>{if(a instanceof In)return s&&await e.store.trust.bump(s.subject,s.attempt,n),a.outcome;throw s&&await e.store.trust.bump(s.subject,s.attempt,n).catch(()=>{}),a});return await as(e,t,o),o}
2class In extends Error{outcome;constructor(t){super("rejected outcome rolled back"),this.outcome=t}}async function ss(e){const t=await Ui(e);if(t.status==="rejected")throw new In(t);return t}const Pi=1000000000000000n;function os(e,t){if(!(e.kind in Qr))throw p(h.MALFORMED_OPERATION,`Unknown operation kind "${e.kind}".`,{detail:{kind:e.kind}});if(typeof e.idempotencyKey!="string"||e.idempotencyKey.trim()==="")throw p(h.MALFORMED_OPERATION,"operation is missing a non-empty idempotencyKey.",{detail:{kind:e.kind}});for(const n of en(e,t.platformShards,t.accrualDrain))if(le(n)&&We(n).trim()==="")throw p(h.MALFORMED_OPERATION,"operation names a wallet account with a blank user id.",{detail:{kind:e.kind}});Li(e)}function Ci(e){switch(e.kind){case"topUp":case"requestPayout":case"grantPromo":case"clawback":case"adjust":return e.amount;case"spend":case"subscribe":return e.price;default:return null}}function Li(e){const t=Ci(e);if(t===null)return;if(!(e.kind==="adjust"?t.minor!==0n:t.minor>0n))throw p(h.INVALID_AMOUNT,e.kind==="adjust"?"operation amount must be non-zero.":"operation amount must be positive.",{detail:{kind:e.kind,amount:E(t)}});if((t.minor<0n?-t.minor:t.minor)>Pi)throw p(h.INVALID_AMOUNT,"operation amount exceeds the maximum allowed.",{detail:{kind:e.kind,amount:E(t)}})}async function as(e,t,n){const r=e.ctx.cache;if(!r||n.status!=="committed")return;const{platformShards:s,accrualDrain:o}=e.ctx.config;for(const a of new Set(en(t,s,o)))await qt(e.ctx,"invalidate",()=>r.invalidate(ns(a)),void 0)}async function Ui(e){const{unit:t,operation:n,options:r}=e,s=await t.idempotency.claim(n.idempotencyKey,r);if(!s.claimed)return{status:"duplicate",transaction:s.transaction};const o=Ii[n.kind];if(o){const m=await o(n,t);if(m)return m}const a=await Fi(e);if(a)return a;await Hi(e),t.balances=new Map;const i=await $i(e);if(i)return i;const u=await Ji(e.pipeline.registry,n)(n,t,e.pipeline.ctx);return u.status==="committed"&&(await t.idempotency.record(n.idempotencyKey,u.transaction,r),await qi(e,u)),u}function is(e){const t=e.actor;if(t.kind!=="operator"&&t.kind!=="system"){if(Qi.has(e.kind))throw Gn(e,"operation requires a system or operator principal");for(const n of xi(e))if(!Xi(n,t.userId))throw Gn(e,"a user may not debit another account")}}function xi(e){return e.kind==="spend"?[$(e.buyerId),M(e.buyerId)]:e.kind==="subscribe"?[$(e.userId),M(e.userId)]:e.kind==="requestPayout"?[D(e.userId)]:[]}async function $i(e){const{unit:t,operation:n,options:r}=e;for(const s of await Bi(t,n,r)){const o=await cs(t,s.account,r);if(Ge(o,s.amount)<0)return H("INSUFFICIENT_FUNDS",{account:s.account,need:s.amount,have:o})}return null}async function Bi(e,t,n){if(t.kind!=="spend")return[];const r=await cs(e,$(t.buyerId),n),s=gn(t.price,r);return[{account:M(t.buyerId),amount:s.spendablePart}]}async function cs(e,t,n){const r=e.balances?.get(t);if(r!==void 0)return r;const s=await e.ledger.balance(t,n);return e.balances?.set(t,s),s}async function Fi(e){const{pipeline:t,unit:n,operation:r,options:s}=e,o=bi(r);if(o===null)return null;const a={idempotencyKey:r.idempotencyKey,amount:I(es,vi(r)),at:t.ctx.clock.now(),outcome:"committed"};e.staged?.(o.subject,a);const i=await n.trust.record(o.subject,a,s),c=t.ctx.config,u=Ei(c,o.class);return i.spent.minor>u?H("RISK_DENIED",{window:o.class==="in"?"inflow":"outflow",limitMinor:u}):null}async function Hi(e){const{unit:t,operation:n,options:r}=e,{platformShards:s,accrualDrain:o}=e.pipeline.ctx.config;await Ne(t.ledger,en(n,s,o),r)}async function qi(e,t){const{unit:n,operation:r,options:s}=e,o=e.pipeline.ctx,a=ec[r.kind];if(!a)return;const i={id:o.ids.next("evt"),type:a.type,version:1,occurredAt:t.transaction.postedAt,subject:a.subject(r,t),data:a.data(r,t),audience:a.audience};await n.outbox.enqueue(xe(o.ids,i,s?.correlationId),s)}async function zn(e){let t=0;for await(const n of e)if(t+=1,t>=re.enumerationCap)return{count:t,capped:!0};return{count:t,capped:!1}}async function ji(e,t,n){const r=t.clock.now(),s=e.ledger.historySize===void 0?null:await e.ledger.historySize(n),a=(e.checkpoints.reproof===void 0?null:await e.checkpoints.reproof(n))?.rotatedAt??null,i=await e.checkpoints.latest(n),c=await e.accruals.stats(n),u=e.movements.sessionIds===void 0?{count:null,capped:!1}:await zn(e.movements.sessionIds(n)),m=e.reservations===void 0?{accounts:null,capped:!1}:await zn(e.reservations.entries(n)).then(y=>({accounts:y.count,capped:y.capped}
2)),g=await Ki(e,n);return{historySize:s,reproof:{rotatedAt:a,ageMs:a===null?null:r-a},checkpoint:{at:i?.at??null,count:i?.count??null,ageMs:i===null?null:r-i.at},accruals:{pendingMinor:c.pendingMinor.toString(),oldestPendingAgeMs:c.oldestPendingAgeMs},sessions:u,reservations:m,tables:g,advisories:Vi({now:r,historySize:s,rotatedAt:a,checkpointAt:i?.at??null,oldestPendingAgeMs:c.oldestPendingAgeMs,tables:g})}}async function Ki(e,t){return e.tableSizes===void 0?{movements:null,idempotency:null,sales:null,outbox:null,sagas:null,accruals:null}:e.tableSizes(t)}function Vi(e){const{now:t}=e,n=[];e.historySize!==null&&e.historySize>=re.historySizePostings&&n.push(`history holds ${e.historySize} postings (threshold ${re.historySizePostings}): the partitioning DDL variant and the archival mover now earn their provisioning cost`),e.rotatedAt!==null&&t-e.rotatedAt>re.reproofMaxAgeMs&&n.push(`the re-proof watermark is ${t-e.rotatedAt}ms old (threshold ${re.reproofMaxAgeMs}): full-history rotation lags the coverage story`),e.checkpointAt!==null&&t-e.checkpointAt>re.checkpointMaxAgeMs&&n.push(`the latest checkpoint is ${t-e.checkpointAt}ms old (threshold ${re.checkpointMaxAgeMs}): the seal cadence stalled`),e.oldestPendingAgeMs!==null&&e.oldestPendingAgeMs>re.accrualMaxPendingAgeMs&&n.push(`the oldest accrual row has been pending ${e.oldestPendingAgeMs}ms (threshold ${re.accrualMaxPendingAgeMs}): the drain lags its backlog`);const r=[["movements","the retention sweep's session horizon is its mover"],["idempotency","the retention sweep's idempotency horizon is its mover"],["sales","no in-system mover exists; retention is a host policy decision"],["outbox","no in-system mover exists; retention is a host policy decision"],["sagas","no in-system mover exists; retention is a host policy decision"],["accruals","rows are the permanent refund share record, never pruned; growth tracks sales"]];for(const[s,o]of r){const a=e.tables[s];a!==null&&a>=re.tableRows&&n.push(`\`${s}\` holds ${a} rows (threshold ${re.tableRows}): ${o}`)}return n}async function zi(e,t,n){const r=await an(e.checkpoints,{digest:t.digest,signer:t.signer},n),s=await Gi(e,r,n),o=cn(s.custodialCreditMinor,t.rates.par("CREDIT")),a=un(o,s.trustCashMinor);return{conserved:[...s.signedByCurrency.values()].every(i=>i===0n),backed:a===0n,noOverdraft:!s.anyUserNegative,chainIntact:s.chainIntact,consistent:s.drift.length===0,drift:s.drift,shortfall:I("USD",a)}}async function Gi(e,t,n){const r=new Map,s={custodialCreditMinor:0n,trustCashMinor:0n};let o=!1,a=!0;const i=[],c=new Set,u=g=>{const y=t?.rawSums.get(g);return y===void 0?0n:y*(Ee(g)?1n:-1n)},m=(g,y,v)=>{const S=J(g),U=Ee(g)?1n:-1n;r.set(S,(r.get(S)??0n)+v*U),y.minor!==v&&i.push({account:g,materialized:y,derived:I(S,v)}),ct(s,g,y.minor),le(g)&&zs(y)&&(o=!0)};for await(const[g,y]of e.ledger.heads()){c.add(g);const v=await e.ledger.balance(g,n),S=u(g)+await Wi(e,g,n);m(g,v,S),Zi(y)||(a=!1)}if(t!==null)for(const g of t.rawSums.keys()){if(c.has(g))continue;const y=await e.ledger.balance(g,n);m(g,y,u(g))}return{signedByCurrency:r,...s,anyUserNegative:o,chainIntact:a,drift:i}}async function Wi(e,t,n){let r=0n;const s=await e.ledger.statement(t,Yi,n);for(const o of s.entries)r+=o.amount.minor;return r}const Yi={from:Number.MIN_SAFE_INTEGER,to:Number.MAX_SAFE_INTEGER};function Ji(e,t){const n=e[t.kind];if(!n)throw p(h.MALFORMED_OPERATION,`No handler is registered for operation ${t.kind}.`,{detail:{kind:t.kind}});return n}function Xi(e,t){return e.startsWith(`${t}:`)}function Zi(e){return/^[0-9a-f]{64}$/.test(e)}function Gn(e,t){return p(h.UNAUTHORIZED,t,{detail:{kind:e.kind,actor:e.actor.kind}})}const Qi=new Set(["grantPromo","grantEntitlement","revokeEntitlement","topUp","adjust","reverse","refund","clawback","reversePayout","settlePayout"]),ec={topUp:{type:"economy.credits.topped_up",audience:"client",subject:_t,data:jt},grantPromo:{type:"economy.promo.granted",audience:"client",subject:_t,data:jt},spend:{type:"economy.sale.completed",audience:"client",subject:_t,data:tc},refund:{type:"economy.sale.refunded",audience:"client",subject:(e,t)=>
2Wn(t),data:(e,t)=>({txnId:t.transaction.id,orderId:e.orderId,buyerId:Wn(t)})},clawback:{type:"economy.credits.clawed_back",audience:"internal",subject:e=>e.userId,data:(e,t)=>{const n=e,r={txnId:t.transaction.id,userId:n.userId,amount:E(n.amount)};return n.orderId!==void 0&&(r.orderId=n.orderId),r}},requestPayout:{type:"economy.payout.requested",audience:"client",subject:e=>e.userId,data:(e,t)=>{const n=e;return{txnId:t.transaction.id,userId:n.userId,amount:E(n.amount)}}},subscribe:{type:"economy.subscription.started",audience:"client",subject:e=>e.userId,data:(e,t)=>{const n=e;return{txnId:t.transaction.id,userId:n.userId,sku:n.sku,period:1}}},cancelSubscription:{type:"economy.subscription.canceled",audience:"client",subject:e=>e.subscriptionId,data:(e,t)=>({txnId:t.transaction.id,subscriptionId:e.subscriptionId})},reversePayout:{type:"economy.payout.reversed",audience:"internal",subject:e=>e.userId,data:e=>{const t=e;return{sagaId:t.sagaId,reason:t.reason}}}};function jt(e,t){return{txnId:t.transaction.id}}function tc(e,t){const n=jt(e,t);return e.kind==="spend"&&e.giftTo!==void 0&&e.giftTo!==e.buyerId?{...n,isGift:!0,giftTo:e.giftTo}:n}function Wn(e){for(const t of e.transaction.legs){if(!le(t.account))continue;const n=Ye(t.account);if(n==="spendable"||n==="promo")return We(t.account)}return"unknown"}function _t(e){return e.kind==="spend"?e.buyerId:e.kind==="topUp"||e.kind==="grantPromo"?e.userId:"unknown"}const nc="economy-lab/ledger-export";async function*rc(e,t){yield JSON.stringify({format:nc,v:1});const n=[];for await(const[s]of e.ledger.heads())n.push(s);for(const s of n)for await(const o of e.ledger.lineage(s,t))yield JSON.stringify({type:"link",account:s,link:ts.storedLink(o)});const r=await e.checkpoints.latest(t);r!==null&&(yield JSON.stringify({type:"checkpoint",checkpoint:r}))}const Yn="17";function sc(e,t){if(e===Yn)return;const n=e===null?"has no schema_meta row (an un-migrated or pre-versioning database)":`is at schema version ${e}`;throw new Error(`economy-lab: the ${t} database ${n}, but this build expects schema version ${Yn}
2. Re-apply the schema with \`make db-migrate\` so the database matches this code.`)}function oc(e,t){if(e.length!==0)throw new Error(`economy-lab: the ${t} database failed ${e.length} money conformance vector(s); first: ${e[0]}. The money functions were just installed, so the engine computes different arithmetic than this build. Refusing to run against it.`)}let dt=null,Mt=null;async function ac(){try{const{createHash:e}=await Ie(async()=>{const{createHash:t}=await import("./no-node-crypto-CRsAV7S8.js");return{createHash:t}},[]);dt=t=>new Uint8Array(e("sha256").update(t).digest())}catch{dt=null}}async function ic(e){return new Uint8Array(await crypto.subtle.digest("SHA-256",e))}function bn(){return{hash:async e=>{let t=dt;return t===null&&(Mt===null&&(Mt=ac()),await Mt,t=dt),t?t(e):ic(e)}}}new Set(Object.values(w));function cc(e){return new Promise(t=>setTimeout(t,e))}const uc=new RegExp(["tuple concurrently updated",'duplicate key value violates unique constraint "pg_(proc|namespace)',"FUNCTION [\\w.]+ already exists"].join("|"),"i");async function dc(e){for(let t=1;;t++)try{return await e()}catch(n){const r=n instanceof Error?n.message:String(n);if(t>=5||!uc.test(r))throw n;await cc(50*t+Math.random()*150)}}const lt=1,lc=[`create table if not exists money_meta ( 3 version integer not null 4)`,`delete from money_meta where version <> ${lt}`,`insert into money_meta (version) 5 select ${lt} from dual where not exists (select 1 from money_meta)`,"drop function if exists money_div_round",`create function money_div_round(num decimal(40, 0), den decimal(40, 0), mode varchar(16)) 6returns bigint deterministic 7begin 8 declare q decimal(40, 0); 9 declare r decimal(40, 0); 10 declare negative bool; 11 declare twice decimal(40, 0); 12 declare magnitude decimal(40, 0); 13 declare step int; 14 if den = 0 then 15 signal sqlstate '45000' set message_text = 'div_round: zero divisor'; 16 end if; 17 set q = num div den; 18 set r = num - q * den; 19 if r <> 0 then 20 set negative = (num < 0) <> (den < 0); 21 if mode = 'floor' then 22 if negative then set q = q - 1; end if; 23 elseif mode = 'ceil' then 24 if not negative then set q = q + 1; end if; 25 elseif mode = 'halfEven' or mode = 'halfUp' then 26 set twice = 2 * abs(r); 27 set magnitude = abs(den); 28 set step = if(negative, -1, 1); 29 if twice > magnitude then 30 set q = q + step; 31 elseif twice = magnitude then 32 if mode = 'halfUp' or q % 2 <> 0 then set q = q + step; end if; 33 end if; 34 elseif mode <> 'trunc' then 35 signal sqlstate '45000' set message_text = 'div_round: unknown mode'; 36 end if; 37 end if; 38 if q < -9223372036854775808 or q > 9223372036854775807 then 39 signal sqlstate '45000' set message_text = 'i64 overflow'; 40 end if; 41 return q; 42end`,"drop function if exists money_split_bps",`create function money_split_bps(minor bigint, bps json) 43returns json deterministic 44begin 45 declare total int default 0; 46 declare i int default 0; 47 declare n int; 48 declare b int; 49 declare share decimal(40, 0); 50 declare used decimal(40, 0) default 0; 51 declare shares json default json_array(); 52 set n = json_length(bps); 53 while i < n do 54 set b = json_extract(bps, concat('$[', i, ']')); 55 if b < 0 then 56 signal sqlstate '45000' set message_text = 'split_bps: bad bps'; 57 end if; 58 set total = total + b; 59 set i = i + 1; 60 end while; 61 if total > 10000 then 62 signal sqlstate '45000' set message_text = 'split_bps: bps exceed 10000'; 63 end if; 64 set i = 0; 65 while i < n do 66 set b = json_extract(bps, concat('$[', i, ']')); 67 set share = cast(minor as decimal(40, 0)) * b div 10000; 68 set used = used + share; 69 set shares = json_array_append(shares, '$', cast(share as char)); 70 set i = i + 1; 71 end while; 72 return json_object('shares', shares, 'remainder', cast(minor - used as char)); 73end`];async function fc(e){for(const t of lc)await e.run(t)}const mc={async version(e){const t=await e.run("select version from money_meta");return String(t[0]?.version)},async div(e,t,n,r){const s=await e.run("select cast(money_div_round(?, ?, ?) as char) as r",[t,n,r]);return String(s[0]?.r)},async bps(e,t,n){const r=await e.run("select cast(money_split_bps(?, cast(? as json)) as char) as r",[t,n]);return JSON.parse(String(r[0]?.r))}};async function hc(e,t,n){const r=[],s=await t.version(e).catch(a=>`unreadable: ${a}`);if(s!==String(lt))return r.push(`meta version ${s}, package expects ${lt}`),r;let o=0;for(const a of n){const i=a[0];if(i==="div"||i==="muldiv"){const[c,u,m,g]=i==="div"?[String(a[1]),String(a[2]),String(a[3]),String(a[4])]:[(BigInt(String(a[1]))*BigInt(String(a[2]))).toString(),String(a[3]),String(a[4]),String(a[5])];o+=1;try{const y=await t.div(e,c,u,m);g==="throws"?r.push(`${JSON.stringify(a)} got ${y}, wanted raise`):y!==g&&r.push(`${JSON.stringify(a)} got ${y}`)}catch(y){g!=="throws"&&r.push(`${JSON.stringify(a)} raised: ${y}`)}}else if(i==="bps"){o+=1;try{const c=await t.bps(e,String(a[1]),JSON.stringify(a[2])),u=a[3].map(String),m=c.shares.reduce((g,y)=>g+BigInt(y),0n)+BigInt(c.remainder)===BigInt(String(a[1]));c.shares.length!==u.length||c.shares.some((g,y)=>
73g!==u[y])||c.remainder!==String(a[4])?r.push(`${JSON.stringify(a)} got ${c.shares} r ${c.remainder}`):m||r.push(`${JSON.stringify(a)} does not conserve`)}catch(c){r.push(`${JSON.stringify(a)} raised: ${c}`)}}}return o===0&&r.push("no div, muldiv, or bps vectors supplied"),r}function pc(e,t){return hc(e,mc,t)}const Kt=-(2n**63n),Vt=2n**63n-1n,A={unreachable:0,block:2,loop:3,if:4,end:11,br:12,brIf:13,localGet:32,localSet:33,i64Load:41,i32Const:65,i64Const:66,i32GeU:79,i64LtS:83,i32Add:106,i32Shl:116,i64Add:124,i64And:131,i64Xor:133,void:64,i32:127,i64:126,funcType:96};function us(e){const t=[];let n=e;do{const r=n&127;n>>>=7,t.push(n===0?r:r|128)}while(n!==0);return t}function He(e,t){return[e,...us(t.length),...t]}function Jn(e){return[e.length,...[...e].map(t=>t.charCodeAt(0))]}function yc(){const a=[2,3,A.i64,1,A.i32,A.localGet,0,A.localGet,1,A.i32Const,3,A.i32Shl,A.i32Add,A.localSet,5,A.block,A.void,A.loop,A.void,A.localGet,0,A.localGet,5,A.i32GeU,A.brIf,1,A.localGet,0,A.i64Load,3,0,A.localSet,3,A.localGet,2,A.localGet,3,A.i64Add,A.localSet,4,A.localGet,2,A.localGet,4,A.i64Xor,A.localGet,3,A.localGet,4,A.i64Xor,A.i64And,A.i64Const,0,A.i64LtS,A.if,A.void,A.unreachable,A.end,A.localGet,4,A.localSet,2,A.localGet,0,A.i32Const,8,A.i32Add,A.localSet,0,A.br,0,A.end,A.end,A.localGet,2,A.end];return Uint8Array.from([0,97,115,109,1,0,0,0,...He(1,[1,A.funcType,2,A.i32,A.i32,1,A.i64]),...He(3,[1,0]),...He(5,[1,0,1]),...He(7,[2,...Jn("memory"),2,0,...Jn("fold"),0,0]),...He(10,[1,...us(a.length),...a])])}function gc(e){let t=0n;for(const n of e){if(n<Kt||n>Vt)throw new RangeError("i64 overflow");if(t+=n,t<Kt||t>Vt)throw new RangeError("i64 overflow")}return t}function wc(){const t=new WebAssembly.Instance(new WebAssembly.Module(yc())).exports;function n(s){const o=s*8,a=t.memory.buffer.byteLength;return o>a&&t.memory.grow(Math.ceil((o-a)/65536)),new BigInt64Array(t.memory.buffer,0,s)}function r(s,o){try{return t.fold(s,o)}catch{throw new RangeError("i64 overflow")}}return{view:n,fold(s){const o=s.length;if(s instanceof BigInt64Array&&s.buffer===t.memory.buffer)return r(s.byteOffset,o);const a=n(o);if(s instanceof BigInt64Array)a.set(s);else for(let i=0;i<o;i+=1){const c=s[i];if(c<Kt||c>Vt)throw new RangeError("i64 overflow");a[i]=c}return r(0,o)}}}class Ic{buffer;size=0;constructor(t=8){this.buffer=new BigInt64Array(t)}get length(){return this.size}push(t){if(this.size===this.buffer.length){const n=new BigInt64Array(this.buffer.length*2);n.set(this.buffer),this.buffer=n}this.buffer[this.size]=t,this.size+=1}pop(){this.size>0&&(this.size-=1)}view(){return this.buffer.subarray(0,this.size)}}const bc=256;let st;function Ec(){if(st===void 0)try{st=wc()}catch{st=null}return st}function vc(e){const t=e.view();if(t.length<bc){let r=0n;for(let s=0;s<t.length;s+=1)r+=t[s];return r}const n=Ec();try{return n?n.fold(t):gc(t)}catch(r){throw r instanceof RangeError||typeof WebAssembly<"u"&&r instanceof WebAssembly.RuntimeError?p(h.AMOUNT_OVERFLOW,"Re-derived balance leaves the 64-bit range the ledger stores."):r}}function kc(e,t,n){const r=e[t];return typeof r=="string"?r:n}function Ac(e,t,n){const r=e[t];return typeof r=="number"?r:n}function ae(){let e=null;return{begin:()=>{if(e)throw new Error("in-memory transactions do not nest");e=[]},commit:()=>{e=null},rollback:()=>{if(e){for(let t=e.length-1;t>=0;t-=1)e[t]();e=null}},recording:()=>e!==null,record:t=>{e?.push(t)},mark:()=>e?.length??0,rollbackTo:t=>{if(e)for(;e.length>t;)e.pop()()}}}function X(e,t,n){const r=t.get(n),s=t.has(n);e.record(()=>s?t.set(n,r):t.delete(n))}function Sc(){return bn()}function Rc(){return{now:()=>0}}function _c(e,t){return t.has(Ce(e))||Ye(e)!==null}function ds(e){const t=new Set,n=[];for(const r of e)t.has(r.account)||(t.add(r.account),n.push(r.account));return n}async function Mc(e,t,n){const r=[];for(const s of ds(n.legs)){const o=e.heads.get(s)??me,a=o===me?wo:oe(o),i=await sn(t,{accountPrevHash:a,txnId:n.txnId,account:s,legs:n.legs,meta:n.meta});r.push({account:s,prevHash:o,hash:i})}return r}function Oc(e,t){const n=t.links.map(c=>({account:c.account,prev:e.heads.get(c.account)})),r=e.journal.recording()?new Set(t.legs.filter(c=>!e.balances.has(c.account)).map(c=>c.account)):null,s=new Map,o=[];for(const c of t.legs){const u=Z(c),m=s.get(c.account)??e.balances.get(c.account)??0n;s.set(c.account,I(c.amount.currency,m+u.minor).minor),o.push(u)}e.log.push(t);const a=e.log.length-1,i=ls(t.legs);for(const c of i){let u=e.lotIndexByAccount.get(c);u===void 0&&(u=[],e.lotIndexByAccount.set(c,u)),u.push(a)}for(const c of t.links)e.heads.set(c.account,c.hash);
73t.legs.forEach((c,u)=>{e.balances.set(c.account,s.get(c.account)),En(e,c.account,o[u])}),e.journal.record(()=>Tc(e,t,{priorHeads:n,created:r,lotted:i}))}function ls(e){return ds(e.filter(t=>Z(t).minor>0n))}function Tc(e,t,n){e.log.pop();for(const r of n.lotted){const s=e.lotIndexByAccount.get(r);s!==void 0&&(s.pop(),s.length===0&&e.lotIndexByAccount.delete(r))}for(const{account:r,prev:s}of n.priorHeads)s===void 0?e.heads.delete(r):e.heads.set(r,s);for(const r of t.legs){const s=(e.balances.get(r.account)??0n)-Z(r).minor;s===0n&&n.created?.has(r.account)?e.balances.delete(r.account):e.balances.set(r.account,s),Dc(e,r.account,r.amount.currency)}}function En(e,t,n){let r=e.deltaColumns.get(t);r===void 0&&(r=new Map,e.deltaColumns.set(t,r));let s=r.get(n.currency);s===void 0&&(s=new Ic,r.set(n.currency,s)),s.push(n.minor)}function Dc(e,t,n){const r=e.deltaColumns.get(t);if(r===void 0)return;const s=r.get(n);s!==void 0&&(s.pop(),s.length===0&&(r.delete(n),r.size===0&&e.deltaColumns.delete(t)))}function Nc(e){e.deltaColumns.clear();for(const t of e.log)for(const n of t.legs)En(e,n.account,Z(n))}function Pc(e){const t={journal:ae(),log:[],seq:0,balances:new Map,heads:new Map,registered:new Set(Object.values(w)),lotIndexByAccount:new Map,deltaColumns:new Map};return{journal:t.journal,hasAccount:async n=>_c(n,t.registered),lock:async()=>{},append:async n=>{const r=e.clock.now(),s=await Mc(t,e.digest,n);t.seq+=1;const o={txnId:n.txnId,legs:n.legs,meta:n.meta,postedAt:r,seq:t.seq,links:s};return Oc(t,o),{id:o.txnId,postedAt:r,legs:o.legs,links:s,meta:o.meta}},balance:async n=>I(J(n),t.balances.get(n)??0n),statement:async(n,r)=>$c(t.log,n,r),derivedBalances:async n=>Bc(t.deltaColumns.get(n)),timeline:(n,r)=>Fc(t,n,r),heads:async function*(){for(const[n,r]of fs(t.heads))yield[n,r]},headSums:()=>Cc(t),balanceAccounts:async function*(){for(const n of[...t.balances.keys()].sort(fe))yield n},lineage:(n,r)=>qc(t.log,n,r?.sinceHash),posting:async n=>jc(t.log,n),links:async n=>{const r=t.log.find(s=>
73s.txnId===n);return r===void 0?[]:r.links.map(s=>({...s}))},linksPage:async(n,r)=>Uc(t.log,n,r),historySize:async()=>t.log.length===0?0:t.log[t.log.length-1].seq,archivePage:async(n,r)=>Lc(t.log,n,r),prune:async n=>xc(t,n),list:()=>Kc(t.log),__tamper:(n,r)=>Vc(t,n,r),__seedBalance:(n,r)=>t.balances.set(n,r.minor)}}async function*Cc(e){const t=new Map;for(const n of e.log)for(const r of n.legs)t.set(r.account,(t.get(r.account)??0n)+r.amount.minor);for(const[n,r]of fs(e.heads))yield[n,r,t.get(n)??0n]}function Lc(e,t,n){const r=e.filter(o=>t===null||o.seq>t),s=r.slice(0,n);return{postings:s.map(o=>({txnId:o.txnId,seq:o.seq,postedAt:o.postedAt,meta:o.meta,legs:[...o.legs],links:o.links.map(a=>({...a}))})),cursor:s.length<r.length?s[s.length-1].seq:null}}function Uc(e,t,n){const r=e.filter(a=>t===null||a.seq>t),s=r.slice(0,n),o=[];for(const a of s)for(const i of a.links)o.push({account:i.account,txnId:a.txnId,legs:a.legs,meta:a.meta,prevHash:i.prevHash,hash:i.hash});return{links:o,cursor:s.length<r.length?s[s.length-1].seq:null}}function xc(e,t){const n=new Set(t),r=e.log,s=e.lotIndexByAccount,o=e.deltaColumns,a=r.filter(c=>!n.has(c.txnId));if(a.length===r.length)return;const i=new Map;a.forEach((c,u)=>{for(const m of ls(c.legs)){const g=i.get(m)??[];g.push(u),i.set(m,g)}}),e.log=a,e.lotIndexByAccount=i,e.deltaColumns=new Map;for(const c of a)for(const u of c.legs)En(e,u.account,Z(u));e.journal.record(()=>{e.log=r,e.lotIndexByAccount=s,e.deltaColumns=o})}function fs(e){return[...e].sort((t,n)=>fe(t[0],n[0]))}function $c(e,t,n){const r=[];for(const s of e)if(!(s.postedAt<n.from||s.postedAt>=n.to))for(const o of s.legs)o.account===t&&r.push({txnId:s.txnId,amount:Z(o),postedAt:s.postedAt});return{account:t,entries:r,cursor:null}}function Bc(e){return e===void 0?[]:[...e].map(([t,n])=>I(t,vc(n))).sort((t,n)=>fe(t.currency,n.currency))}async function*Fc(e,t,n){const r=n?.order??"asc",s=n?.offset??0,o=n?.limit??1/0,a=e.lotIndexByAccount.get(t)??[],i=r==="desc"?-1:1,c=r==="desc"?a.length-1:0;let u=0,m=0;for(let g=0;g<a.length&&m<o;g+=1){const y=e.log[a[c+i*g]];for(const v of Hc(y,t)){if(u<s){u+=1;continue}if(m>=o)break;m+=1,yield v}}}function*Hc(e,t){for(const n of e.legs){if(n.account!==t)continue;const r=Z(n);r.minor<=0n||(yield{txnId:e.txnId,amount:r,source:kc(e.meta,"source","unknown"),toppedUpAt:e.postedAt,maturesAt:Ac(e.meta,"maturesAt",e.postedAt)})}}async function*qc(e,t,n){let r=n===void 0;for(const s of e){const o=s.links.find(a=>a.account===t);if(o){if(!r){o.hash===n&&(r=!0);continue}yield{txnId:s.txnId,legs:s.legs,meta:s.meta,prevHash:o.prevHash,hash:o.hash}}}}function jc(e,t){const n=e.find(r=>r.txnId===t);return n?{txnId:n.txnId,legs:n.legs,meta:n.meta}:null}async function*Kc(e){const t=[...e].reverse();for(const n of t)yield{txnId:n.txnId,legs:n.legs,meta:n.meta}}function Vc(e,t,n){const r=e.log.find(s=>
73s.txnId===t);r&&(n(r.legs),Nc(e))}function zc(e){const t=ae(),n=new Map,r=new Set,s=new Map;return{journal:t,claim:async(o,a)=>{const i=n.get(o);if(i)return{claimed:!1,transaction:i};r.add(o);const c=s.has(o);return c||s.set(o,e.clock.now()),t.record(()=>{r.delete(o),c||s.delete(o)}),{claimed:!0}},record:async(o,a,i)=>{n.set(o,a),r.delete(o);const c=s.has(o);c||s.set(o,e.clock.now()),t.record(()=>{n.delete(o),r.add(o),c||s.delete(o)})},deleteOlderThan:async(o,a,i)=>{const c=[...s.entries()].filter(([,u])=>u<o).sort((u,m)=>u[1]-m[1]).slice(0,a);for(const[u]of c)s.delete(u),n.delete(u),r.delete(u);return c.length},size:()=>s.size}}function Gc(){const e=ae(),t=new Map;return{journal:e,size:()=>t.size,put:async(n,r)=>{X(e,t,n.orderId),t.set(n.orderId,n)},get:async(n,r)=>t.get(n)??null}}function Wc(e){const t=ae(),n=new Map,r=[],s=new Map;return{journal:t,size:()=>n.size,enqueue:async(o,a)=>{n.set(o.id,o),r.push(o.id),s.set(o.id,e.clock.now()),t.record(()=>{n.delete(o.id),r.pop(),s.delete(o.id)})},claimBatch:async(o,a)=>{const i=[];for(const c of r){if(i.length>=o)break;const u=n.get(c);u&&u.status==="pending"&&i.push({...u})}return i},markRelayed:async(o,a)=>{for(const i of o){const c=n.get(i);if(c&&c.status==="pending"){const u=c.status;t.record(()=>{c.status=u}),c.status="relayed"}}},recordFailure:async(o,a)=>{const i=n.get(o);if(!i||i.status!=="pending")return;const c=i.attempts;t.record(()=>{i.attempts=c}),i.attempts+=1},deadLetter:async(o,a,i)=>{const c=n.get(o);if(!c||c.status!=="pending")return;const u={...c};t.record(()=>n.set(o,u)),n.set(o,{...c,status:"dead",reason:a})},stats:async o=>Yc(n,s,e.clock)}}function Yc(e,t,n){let r=0,s=null;for(const[o,a]of e){if(a.status!=="pending")continue;r+=1;const i=t.get(o);i!==void 0&&(s===null||i<s)&&(s=i)}return{pending:r,oldestPendingAgeMs:s===null?null:n.now()-s}}function Jc(){const e=ae(),t=new Map,n=[],r=new Map;return{journal:e,enqueueInbound:async(s,o)=>{const a=r.get(s.key);return a!==void 0?{...t.get(a)}:(t.set(s.id,{...s}),n.push(s.id),r.set(s.key,s.id),e.record(()=>{t.delete(s.id),n.pop(),r.delete(s.key)}),{...s})},claimInbound:async(s,o)=>{const a=[];for(const i of n){const c=t.get(i);c&&c.status==="pending"&&a.push({...c})}return a.sort((i,c)=>i.receivedAt-c.receivedAt),a.slice(0,s.limit)},markApplied:async(s,o)=>{const a=t.get(s);if(!a||a.status!=="pending")return;const i=a.status;e.record(()=>{a.status=i}),a.status="applied"},bumpAttempt:async(s,o)=>{const a=t.get(s);if(!a||a.status!=="pending")return;const i=a.attempts;e.record(()=>{a.attempts=i}),a.attempts+=1},deadLetter:async(s,o,a)=>{const i=t.get(s);if(!i||i.status!=="pending")return;const c={...i};e.record(()=>t.set(s,c)),t.set(s,{...i,status:"dead",reason:o})},reviveDead:async(s,o)=>Xc(e,t,s)}}function Xc(e,t,n){const r=[];for(const o of t.values())o.status==="dead"&&r.push(o);r.sort((o,a)=>o.receivedAt-a.receivedAt);const s=[];for(const o of r.slice(0,Math.max(0,n))){const a={...o};e.record(()=>t.set(o.id,a));const i={...o,status:"pending",attempts:0,reason:null};t.set(o.id,i),s.push({...i})}return s}async function*Zc(e,t){const n=t===void 0?null:new Set(t),r=[...e.values()].filter(s=>n===null||n.has(s.state)).sort((s,o)=>o.updatedAt-s.updatedAt||(o.id>s.id?1:o.id<s.id?-1:0));for(const s of r)yield{...s}}async function Qc(e,t){let n=null;for(const r of e.values())r.providerRef===t&&(n===null||r.updatedAt>n.updatedAt)&&(n=r);return n===null?null:{...n}}function eu(){const e=ae(),t=new Map,n=new Map,r=(s,o)=>{const a=n.get(s);a!==void 0&&a>=o||(n.set(s,o),e.record(()=>a===void 0?n.delete(s):n.set(s,a)))};return{journal:e,size:()=>t.size,open:async(s,o)=>{X(e,t,s.id),t.set(s.id,{...s}),r(s.userId,s.updatedAt)},load:async(s,o)=>{const a=t.get(s);return a?{...a}:null},findByProviderRef:(s,o)=>Qc(t,s),list:s=>Zc(t,s?.states),claimDue:async(s,o,a)=>{const i=[];for(const c of t.values()){if(i.length>=o)break;c.dueAt<=s&&(c.state==="RESERVED"||c.state==="SUBMITTED")&&i.push({...c})}return i},advance:async(s,o,a,i)=>{const c=t.get(s);return!c||c.state!==o?!1:(X(e,t,s),t.set(s,{...c,...i,state:a}),r(c.userId,i.updatedAt??c.updatedAt),!0)},lastPayoutAt:async(s,o)=>n.get(s)??null,deadLetter:async(s,o,a)=>{const i=t.get(s);i&&(X(e,t,s),t.set(s,{...i,state:"FAILED",reason:o}))}}}function tu(e){const t=ae(),n=new Map,r=(s,o)=>`${s}::${o}`;return{journal:t,grant:async(s,o,a,i)=>{const c=r(s,o);X(t,n,c),n.set(c,{attrs:{...a},revoked:!1})},revoke:async(s,o,a)=>{const i=r(s,o),c=n.get(i);!c||c.revoked||(X(t,n,i),n.set(i,{...c,revoked:!0}))},owns:async(s,o,a)=>{const i=n.get(r(s,o));if(!i||i.revoked)return!1;const c=i.attrs.expiresAt;return c==null||e.clock.now()<=c},list:async function*(s,o){const a=`${s}::`,i=[];for(const[c,u]of n)!c.startsWith(a)||u.revoked||i.push({sku:c.slice(a.length),expiresAt:u.attrs.expiresAt??null});i.sort((c,u)=>fe(c.sku,u.sku)),yield*i}}}function nu(){const e=ae(),t=new Map;return{journal:e,open:async(n,r)=>{X(e,t,n.id),t.set(n.id,{...n})},load:async(n,r)=>{const s=t.get(n);return s?{...s}:null},activeFor:async(n,r,s,o)=>{for(const a of t.values())if(a.userId===n&&a.sku===r&&a.sellerId===s&&a.state==="ACTIVE")return{...a};return null},cancel:async(n,r)=>{const s=t.get(n);s&&(X(e,t,n),t.set(n,{...s,state:"CANCELED"}))},claimDue:async(n,r,s)=>{const o=[];for(const a of t.values()){if(o.length>=r)break;a.state==="ACTIVE"&&a.nextDueAt<=n&&o.push({...a})}return o},markBilled:async(n,r,s,o)=>{const a=t.get(n);return!a||a.nextDueAt!==s?!1:(X(e,t,n),t.set(n,{...a,nextDueAt:r,period:a.period+1,attempts:0}),!0)},markLapsed:async(n,r)=>{const s=t.get(n);s&&(X(e,t,n),t.set(n,{...s,state:"LAPSED"}))}}}function ru(){const e=ae(),t=new Map;return{journal:e,open:async(n,r)=>{t.has(n.id)||(e.record(()=>t.delete(n.id)),t.set(n.id,{...n}))},claimDue:async(n,r,s)=>{const o=[];for(const a of t.values())a.reversed===!1&&a.expiresAt<=n&&o.push({...a});return o.sort((a,i)=>a.expiresAt-i.expiresAt),o.slice(0,r)},markReversed:async(n,r)=>{const s=t.get(n);!s||s.reversed||(X(e,t,n),t.set(n,{...s,reversed:!0}))}}}function su(e,t){const n=new Map,r=new Set,s=ae(),o=(c,u)=>{r.delete(u.idempotencyKey);const m=n.get(c);if(m===void 0)return;const g=m.attempts.findIndex(y=>y.idempotencyKey===u.idempotencyKey);g<0||(m.attempts.splice(g,1),g>=m.head?m.sumMinor-=u.amount.minor:m.head-=1)},a=(c,u)=>{if(r.has(u.idempotencyKey))return;r.add(u.idempotencyKey);let m=n.get(c);m===void 0&&(m={attempts:[],head:0,sumMinor:0n},n.set(c,m)),m.attempts.push(u),m.sumMinor+=u.amount.minor,s.record(()=>o(c,u))},i=(c,u)=>{const m=n.get(c),g=u-t;if(m!==void 0){const v=m.attempts;for(;m.head<v.length&&v[m.head].at<=g;)m.sumMinor-=v[m.head].amount.minor,m.head+=1;m.head>0&&m.head*2>=v.length&&(m.attempts=v.slice(m.head),m.head=0)}const y=m===void 0?0:m.attempts.length-m.head;return{subject:c,windowStart:y>0?m.attempts[m.head].at:0,spent:I(es,m?.sumMinor??0n),attempts:y}};return{read:async(c,u)=>i(c,e.now()),bump:async(c,u,m)=>a(c,u),record:async(c,u,m)=>(a(c,u),i(c,e.now())),journal:s}}function ou(e){const t=ae(),n=new Map,r=[],s=a=>`${a.orderId}::${a.sellerId}::${a.seq}`,o=(a,i,c)=>{for(const u of a){const m=s(u),g=n.get(m);!g||g.status!=="pending"||(X(t,n,m),n.set(m,{...g,status:i,settledTxnId:c}))}};return{journal:t,size:()=>n.size,put:async(a,i)=>{for(const c of a){const u=s(c);if(n.has(u))throw new Error(`duplicate accrual row: ${u}`);n.set(u,{...c}),r.push(u),t.record(()=>{n.delete(u),r.pop()})}},claimByOrder:async(a,i)=>ms(n,r,c=>c.orderId===a),pendingSellers:async(a,i)=>{const c=[];for(const u of r){const m=n.get(u);if(m&&m.status==="pending"&&!c.includes(m.sellerId)&&(c.push(m.sellerId),c.length>=a))break}return c},claimPendingBySeller:async(a,i,c)=>au(n,r,a,i),markDrained:async(a,i,c)=>o(a,"drained",i),markRefunded:async(a,i,c)=>o(a,"refunded",i),stats:async a=>iu(n,e.clock),netPending:async(a,i)=>{let c=0n;for(const u of n.values())u.sellerId===a&&u.status==="pending"&&(c+=u.amount.minor);return c}}}function au(e,t,n,r){const s=ms(e,t,o=>o.sellerId===n&&o.status==="pending");return[...s.filter(o=>o.amount.minor>0n),...s.filter(o=>o.amount.minor<0n)].slice(0,r)}function ms(e,t,n,r=1/0){const s=[];for(const o of t){if(s.length>=r)break;const a=e.get(o);a&&n(a)&&s.push({...a})}return s}function iu(e,t){let n=0n,r=null;for(const s of e.values())s.status==="pending"&&(s.amount.minor>0n&&(n+=s.amount.minor),(r===null||s.recordedAt<r)&&(r=s.recordedAt));return{pendingMinor:n,oldestPendingAgeMs:r===null?null:t.now()-r}}function cu(){const e=[],t=new Set,n=new Set;return{append:async r=>{for(const s of r){if(t.has(s.idempotencyKey))throw new Error(`duplicate movement idempotency key: ${s.idempotencyKey}`);if(n.has(`${s.sessionId}::${s.seq}`))throw new Error(`duplicate movement position: ${s.sessionId}::${s.seq}`)}for(const s of r)t.add(s.idempotencyKey),n.add(`${s.sessionId}::${s.seq}`),e.push({...s,legs:s.legs.map(o=>({...o}))})}
73,bySession:async function*(r){const s=e.filter(o=>o.sessionId===r);s.sort((o,a)=>o.seq-a.seq),yield*s},sessionIds:async function*(){const r=new Set;for(const s of e)r.add(s.sessionId);yield*[...r].sort()},pruneSession:async r=>{let s=0;for(let o=e.length-1;o>=0;o-=1){const a=e[o];a.sessionId===r&&(t.delete(a.idempotencyKey),n.delete(`${a.sessionId}::${a.seq}`),e.splice(o,1),s+=1)}return s},size:()=>e.length}}function uu(){const e=new Map;return{add:async(t,n)=>{const r=(e.get(t)??0n)+n;return e.set(t,r),r},pending:async t=>e.get(t)??0n,entries:async function*(){yield*[...e.entries()].sort(([t],[n])=>t<n?-1:1)}}}function du(){const e=[],t=new Map,n=new Map;let r=null,s=null;return{reproof:async o=>r===null?null:{...r},putReproof:async(o,a)=>{r={...o}},put:async(o,a)=>{e.push({...o})},latest:async o=>{const a=e[e.length-1];return a?{...a}:null},putSealHeads:async(o,a)=>{a?.replaceAll===!0&&t.clear();for(const[i,c,u]of o)t.set(i,{head:c,sum:u})},sealHeads:async o=>[...t].map(([a,i])=>[a,i.head,i.sum]),archiveState:async o=>s===null?null:{...s},archiveHeads:async o=>[...n].map(([a,i])=>({account:a,head:i.head,sum:i.sum})),putArchiveBoundary:async(o,a,i)=>{s={...o};for(const c of a)n.set(c.account,{head:c.head,sum:c.sum})}}}function lu(){const e=new Set;return{claim:async(t,n)=>e.has(t)?{claimed:!1}:(e.add(t),{claimed:!0})}}function fu(e,t){return async()=>({movements:t.size(),idempotency:e.idempotency.size(),sales:e.sales.size(),outbox:e.outbox.size(),sagas:e.sagas.size(),accruals:e.accruals.size()})}function mu(e){const t=e?.digest??Sc(),n=e?.clock??Rc(),r=e?.velocityWindowMs??60*6e4,s=Pc({digest:t,clock:n}),o=zc({clock:n}),a=Gc(),i=Wc({clock:n}),c=Jc(),u=eu(),m=tu({clock:n}),g=nu(),y=ru(),v=su(n,r),S=ou({clock:n}),U=du(),L=cu(),Ze=lu(),Qe=uu(),Se={ledger:s,idempotency:o,sales:a,outbox:i,inbox:c,sagas:u,entitlements:m,subscriptions:g,promos:y,trust:v,accruals:S},ie=Object.values(Se);let ce=Promise.resolve();return{...Se,checkpoints:U,movements:L,replay:Ze,reservations:Qe,tableSizes:fu(Se,L),transaction:$e=>{const Re=ce.then(async()=>{let et=0;try{for(const _e of ie)_e.journal.begin(),et+=1;const C=await $e(Se);for(const _e of ie)_e.journal.commit();return C}catch(C){throw hs(ie,et),C}});return ce=Re.catch(()=>{}),Re},batchTransaction:$e=>{const Re=ce.then(()=>hu(ie,Se,$e));return ce=Re.catch(()=>{}),Re},close:async()=>{}}}async function hu(e,t,n){let r=0;try{for(const o of e)o.journal.begin(),r+=1;const s=[];for(const o of n){const a=e.map(i=>i.journal.mark());try{s.push({ok:!0,value:await o(t)})}catch(i){for(let c=e.length-1;c>=0;c-=1)e[c].journal.rollbackTo(a[c]);s.push({ok:!1,error:i})}}for(const o of e)o.journal.commit();return s}catch(s){throw hs(e,r),s}}function hs(e,t){for(let n=t-1;n>=0;n-=1)try{e[n].journal.rollback()}catch{}}function pu(e){const t=e.fetch??globalThis.fetch;return{submitPayout:async(n,r)=>gu(e,t,n,r)}}function yu(e={}){const t=new Map,n={submitPayout:r=>{const s=t.get(r.key);if(s!==void 0)return Promise.resolve({providerRef:s});const o=`mem_${t.size+1}`;return t.set(r.key,o),Promise.resolve({providerRef:o})}};if(e.status!==void 0){const r=e.status;n.payoutStatus=()=>Promise.resolve({state:r})}return n}async function gu(e,t,n,r){let s;try{s=await t(e.endpoint,{method:"POST",headers:bu(e),body:wu(n),signal:r?.signal})}catch(a){throw Ot("Processor submitPayout request failed.",{cause:a})}let o;try{o=await s.text()}catch(a){throw Ot("Processor submitPayout response read failed.",{cause:a})}if(!s.ok)throw Ot("Processor submitPayout returned a non-2xx status.",{status:s.status,body:o});return{providerRef:Iu(o)}}function wu(e){return JSON.stringify({key:e.key,userId:e.userId,amount:E(e.amount)})}function Iu(e){let t;try{t=JSON.parse(e)}catch(n){throw p(h.PROVIDER_FAILURE,"Processor submitPayout body is not JSON.",{cause:n,retryable:!1})}if(t===null||typeof t!="object"||typeof t.providerRef!="string"||t.providerRef.length===0)throw p(h.PROVIDER_FAILURE,"Processor submitPayout body is missing providerRef.",{retryable:!1,detail:{body:e}});return t.providerRef}function bu(e){const t={"content-type":"application/json"};return e.apiKey!==void 0&&(t.authorization=`Bearer ${e.apiKey}`),t}function Ot(e,t){const n=t.cause===void 0?void 0:B(t.cause),r={};return t.status!==void 0&&(r.status=t.status),t.body!==void 0&&(r.body=t.body),p(h.PROVIDER_FAILURE,e,{cause:n,retryable:!0,detail:r})}function Eu(){return{now:()=>Date.now()}}function vu(){return{next:e=>`${e}_${crypto.randomUUID()}`}}function ku(){return bn()}const Tt=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);async function Xn(e){const t=new Uint8Array(await crypto.subtle.digest("SHA-256",oe(e))),n=new Uint8Array(Tt.length+t.length);n.set(Tt,0),n.set(t,Tt.length);const r=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),s=await crypto.subtle.exportKey("jwk",r),o=await crypto.subtle.importKey("jwk",{kty:"OKP",crv:"Ed25519",x:s.x},{name:"Ed25519"},!0,["verify"]);return{privateKey:r,publicKey:o}}function ps(e){const t=Xn(e.signingKey),n=[t.then(s=>s.publicKey),...(e.priorKeys??[]).map(s=>Xn(s).then(o=>o.publicKey))],r=t.then(s=>crypto.subtle.exportKey("raw",s.publicKey)).then(s=>
73z(new Uint8Array(s)).slice(0,16));return{kid:async()=>r,sign:async s=>new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},(await t).privateKey,s)),verify:async(s,o)=>{for(const a of n)if(await crypto.subtle.verify({name:"Ed25519"},await a,o,s))return!0;return!1}}}function ys(e={}){const t=e.service??"economy-lab",n=e.now??(()=>Date.now()),r=e.out??(o=>console.warn(o)),s=e.err??(o=>console.error(o));return{log:(o,a,i)=>{(o==="error"?s:r)(JSON.stringify({ts:n(),level:o,service:t,event:a,...i}))}}}function Au(){return{every:(e,t)=>{const n=setInterval(()=>{t()},e),r=n;return typeof r.unref=="function"&&r.unref(),()=>clearInterval(n)}}}function gs(){return{count:()=>{},observe:()=>{}}}const ws=new TextEncoder,Su="dev-signing-secret",zt={buyRate:8333n,buyScale:6,parRate:5n,parScale:3,payoutRate:5n,payoutScale:3};function Is(e,t={}){if(!Je(e))return[];const n=[];if(t.rates===void 0){for(const r of["CREDIT_BUY_RATE","CREDIT_PAR_RATE","PAYOUT_RATE"])Pe(e[r])===null&&n.push(r);for(const r of["CREDIT_BUY_SCALE","CREDIT_PAR_SCALE","PAYOUT_SCALE"])we(e[r])===null&&n.push(r)}return t.processor===void 0&&tn(e).processor===null&&n.push("PROCESSOR_URL"),n}function se(e,t,n){for(const r of n)if(typeof t?.[r]!="function")throw p(h.CONFIG_INVALID,`${e}.${r} is not a function; if it comes from a factory such as silentLogger, pass the factory's result.`,{detail:{owner:e,method:r},retryable:!1})}function Ru(e,t,n){const r=Is(e,t);if(r.length>0)throw p(h.CONFIG_INVALID,`NODE_ENV=production requires real externals; missing or malformed: ${r.join(", ")}. Set the CREDIT-to-USD rates and the payout provider.`,{detail:{missing:r},retryable:!1});const s={signer:t.signer??_u(n),rates:Ou(e,t.rates),processor:t.processor??Tu(e),pricing:t.pricing??Gr()};return se("signer",s.signer,["sign","verify"]),se("rates",s.rates,["payout"]),se("processor",s.processor,["submitPayout"]),se("externals",s,["pricing"]),s}function _u(e){const t=(e.signingSecretsPrior??[]).map(n=>z(ws.encode(n)));return ps({signingKey:Mu(e.signingSecret),...t.length>0?{priorKeys:t}:{}})}function Mu(e){return z(ws.encode(e===""?Su:e))}function Ou(e,t){return t!==void 0?typeof t.payout=="function"?t:qe(t):Je(e)?qe({buyRate:Pe(e.CREDIT_BUY_RATE)??0n,buyScale:we(e.CREDIT_BUY_SCALE)??0,parRate:Pe(e.CREDIT_PAR_RATE)??0n,parScale:we(e.CREDIT_PAR_SCALE)??0,payoutRate:Pe(e.PAYOUT_RATE)??0n,payoutScale:we(e.PAYOUT_SCALE)??0}):qe(zt)}function Tu(e){const t=tn(e).processor;return t!==null?pu({endpoint:t,apiKey:e.PROCESSOR_API_KEY}):yu()}async function Du(e,t,n){const r=await e.sagas.claimDue(n.now,n.limit),s={submitted:[],deadLettered:[],retrying:[]};for(const o of r)t.meter.observe("worker.payouts.saga_age_ms",n.now-o.updatedAt,{state:o.state}),await Nu(e,t,o,s);return s}async function Nu(e,t,n,r){try{await Uu(e,t,n,r)}catch(s){const o=B(s);if(o.retryable&&n.attempts+1<t.config.maxPayoutAttempts){await Pu(e,t,n),r.retrying.push({id:n.id,code:o.code});return}try{await Gt(e,t,n,o.code)&&r.deadLettered.push({id:n.id,reason:o.code})}catch(a){const i=B(a).code;t.logger.log("error","worker.payouts.wedged",{id:n.id,code:i}),r.retrying.push({id:n.id,code:i})}}}async function Pu(e,t,n){await e.sagas.advance(n.id,n.state,n.state,{attempts:n.attempts+1,updatedAt:t.clock.now()})}async function Gt(e,t,n,r){const s=await e.transaction(async o=>{await pt({ledger:o.ledger,digest:t.digest},n);const a=q(w.PAYOUT_RESERVE,n.userId,t.config.platformShards);return await Ne(o.ledger,[a,D(n.userId)]),await o.sagas.advance(n.id,n.state,"FAILED",{updatedAt:t.clock.now(),reason:r})?(await F(o.ledger,{txnId:t.ids.next("txn"),legs:[N(a,n.reserve),O(D(n.userId),n.reserve)],meta:{kind:"payouts.dead_letter",sagaId:n.id,reason:r}}),await o.outbox.enqueue(xe(t.ids,{id:t.ids.next("evt"),type:"economy.payout.reversed",version:1,occurredAt:t.clock.now(),subject:n.userId,data:{sagaId:n.id,userId:n.userId,reserve:E(n.reserve),reason:r},audience:"internal"})),!0):!1});if(s)try{t.logger.log("error","worker.payouts.dead_lettered",{sagaId:n.id,userId:n.userId,reason:r}),t.meter.count("worker.payouts.dead_lettered",1,{reason:r})}catch{}return s}const Zn="payout.timeout",Cu="payout.provider_failed",Lu="payout.provider_returned";async function Uu(e,t,n,r){if(n.state==="RESERVED"){await Bu(e,t,n),r.submitted.push(n.id);return}n.state==="SUBMITTED"&&await xu(e,t,n,r)}async function xu(e,t,n,r){const s=await $u(t,n);if(s==="FAILED"||s==="RETURNED"){const a=s==="FAILED"?Cu:Lu;await Gt(e,t,n,a)&&r.deadLettered.push({id:n.id,reason:a});return}if(s==="SETTLED"){t.logger.log("error","worker.payouts.settlement_unreported",{sagaId:n.id,providerRef:n.providerRef}),t.meter.count("worker.payouts.settlement_unreported",1),await Dt(e,t,n,{});return}const o=t.clock.now()-n.updatedAt>t.config.maxPayoutAgeMs;
73if(s==="PENDING"){if(o){t.logger.log("warn","worker.payouts.pending_past_timeout",{sagaId:n.id,providerRef:n.providerRef,ageMs:t.clock.now()-n.updatedAt}),t.meter.count("worker.payouts.pending_past_timeout",1),await Dt(e,t,n,{updatedAt:t.clock.now()});return}await Dt(e,t,n,{});return}o&&await Gt(e,t,n,Zn)&&r.deadLettered.push({id:n.id,reason:Zn})}async function $u(e,t){if(e.processor.payoutStatus===void 0||t.providerRef===null)return null;try{const n=await e.processor.payoutStatus({providerRef:t.providerRef});return n.state==="UNKNOWN"?null:n.state}catch(n){return e.logger.log("warn","worker.payouts.status_probe_failed",{sagaId:t.id,code:B(n).code}),null}}async function Dt(e,t,n,r){await e.sagas.advance(n.id,"SUBMITTED","SUBMITTED",{dueAt:t.clock.now()+bs(t),...r})}async function Bu(e,t,n){const r=await pt({ledger:e.ledger,digest:t.digest},n),{providerRef:s}=await t.processor.submitPayout({key:n.id,userId:n.userId,amount:r}),o=t.clock.now();await e.sagas.advance(n.id,"RESERVED","SUBMITTED",{providerRef:s,attempts:n.attempts+1,dueAt:o+bs(t),updatedAt:o})}function bs(e){const t=e.config.payoutSla;return t.SUBMITTED??t.DEFAULT??0}async function Fu(e,t,n){const r=await e.subscriptions.claimDue(n.now,n.limit),s={charged:[],lapsed:[],deadLettered:[],retrying:[]};for(const o of r)await Hu(e,t,o,s);return s}async function Hu(e,t,n,r){try{await ju(e,t,n,r)}catch(s){const o=B(s);if(o.retryable){await Es({store:e,ctx:t,sub:n,code:o.code,tally:r});return}await qu({store:e,ctx:t,sub:n,reason:o.code,tally:r})}}async function Es(e){const{store:t,ctx:n,sub:r,code:s,tally:o}=e,a=r.attempts+1;if(a>=n.config.maxSubscriptionAttempts){await vs(t,n,r,o);return}await t.subscriptions.open({...r,attempts:a}),o.retrying.push({id:r.id,code:s})}async function qu(e){const{store:t,ctx:n,sub:r,reason:s,tally:o}=e;await ks(t,n,r),n.logger.log("error","worker.subscriptions.dead_lettered",{subscriptionId:r.id,userId:r.userId,reason:s}),o.deadLettered.push({id:r.id,reason:s})}async function vs(e,t,n,r){await ks(e,t,n),t.logger.log("warn","worker.subscriptions.lapsed",{subscriptionId:n.id,userId:n.userId}),r.lapsed.push(n.id)}async function ks(e,t,n){await e.transaction(async r=>{await r.subscriptions.markLapsed(n.id),await r.entitlements.revoke(n.userId,n.sku),await r.outbox.enqueue(xe(t.ids,Vu(t,n)))})}async function ju(e,t,n,r){let s=!1,o=!1;if(await e.transaction(async a=>{await a.ledger.lock(M(n.userId));const i=await a.ledger.balance(M(n.userId));if(Ge(i,n.price)<0){s=!0;return}if(!await yt(a.ledger,M(n.userId),t.clock.now(),{config:t.config,amount:n.price,live:i})){o=!0;return}const u="sub:"+n.id+":p"+(n.period+1);if(!(await a.idempotency.claim(u)).claimed)return;const g=n.nextDueAt+n.periodMs;if(!await a.subscriptions.markBilled(n.id,g,n.nextDueAt))return;await Wo({ledger:a.ledger,digest:t.digest},n);const v=await zu(a,t,n,u);await a.idempotency.record(u,v),await a.entitlements.grant(n.userId,n.sku,{expiresAt:g,source:n.id}),await a.outbox.enqueue(xe(t.ids,Ku(t,n))),r.charged.push(n.id)}),o){await Es({store:e,ctx:t,sub:n,code:"FUNDS_IMMATURE",tally:r});return}s&&await vs(e,t,n,r)}function Ku(e,t){return{id:e.ids.next("evt"),type:"economy.subscription.renewed",version:1,occurredAt:e.clock.now(),subject:t.userId,audience:"client",data:{subscriptionId:t.id,userId:t.userId,sku:t.sku,period:t.period+1}}}function Vu(e,t){return{id:e.ids.next("evt"),type:"economy.subscription.lapsed",version:1,occurredAt:e.clock.now(),subject:t.userId,audience:"client",data:{subscriptionId:t.id,userId:t.userId,sku:t.sku,period:t.period}}}async function zu(e,t,n,r){const s=gt(n.price.minor,t.config.platformFeeBps),o=n.price.minor-s,a=[N(M(n.userId),n.price),O(D(n.sellerId),I("CREDIT",o)),O(w.REVENUE,I("CREDIT",s))],i=t.config.accrualDrain?hn(a):null,c=i===null?a:Te(i.legs,r,t.config.platformShards),u=await F(e.ledger,{txnId:t.ids.next("txn"),legs:c,meta:{kind:"subscriptions.renew",subscriptionId:n.id,sku:n.sku,sellerId:n.sellerId,...i===null?{}:{shares:pn(i.shares)}}});return i!==null&&await e.accruals.put(yn({orderId:u.id,shares:i.shares,routeKey:r,shards:t.config.platformShards,txnId:u.id,recordedAt:u.postedAt})),u}async function Gu(e,t,n){const r={position:null,breaches:[],retrying:[],failed:[]};try{const s=await Wu(e,t);r.position=s,Yu(t,s,n.now),s.backed||Ju(t,s,n.now,r)}catch(s){const o=B(s);o.retryable?r.retrying.push({code:o.code}):r.failed.push({code:o.code})}return r}async function Wu(e,t){const{custodialCreditMinor:n,trustCashMinor:r}=await qr(e.ledger.heads(),i=>e.ledger.balance(i)),s=t.rates.par("CREDIT"),o=cn(n,s),a=un(o,r);return{custodialCredit:I("CREDIT",n),required:I("USD",o),trustCash:I("USD",r),shortfall:I("USD",a),backed:a===0n}}function Yu(e,t,n){e.meter.observe("worker.treasury.custodial_credit",Ke(t.custodialCredit.minor)),e.meter.observe("worker.treasury.trust_cash",Ke(t.trustCash.minor)),e.meter.observe("worker.treasury.shortfall",Ke(t.shortfall.minor)),e.logger.log("debug","worker.treasury.swept",{backed:t.backed,at:n})}function Ju(e,t,n,r){const s={shortfall:E(t.shortfall),required:E(t.required),held:E(t.trustCash)};r.breaches.push(s),e.meter.count("worker.treasury.breach",1),e.logger.log("error","worker.treasury.under_backed",{...s,at:n})}function Ke(e){return Number(e)}async function Xu(e,t,n,r){const s={position:null,breaches:[],retrying:[],failed:[]};try{const o=await Zu(e,t,n,r.now);if(s.position=o,t.meter.observe("worker.treasury.float",Ke(o.float.minor)),t.meter.observe("worker.treasury.float_obligations",Ke(o.obligations.minor)),t.logger.log("debug","worker.treasury.float_swept",{covered:o.covered,at:r.now}),!o.covered){const a={shortfall:E(o.shortfall),obligations:E(o.obligations),float:E(o.float)};s.breaches.push(a),t.meter.count("worker.treasury.float_breach",1),t.logger.log("error","worker.treasury.float_uncovered",{...a,at:r.now})}}catch(o){const a=B(o);a.retryable?s.retrying.push({code:a.code}):s.failed.push({code:a.code})}return s}async function Zu(e,t,n,r){const s=await t.rates.payout("CREDIT","USD",r);let o=0n;for await(const c of e.sagas.list())(c.state==="RESERVED"||c.state==="SUBMITTED")&&(o+=(c.payoutUsd??Ve(c.reserve,s,"USD")).minor);const a=await n.balance().catch(c=>{throw ht(c)}),i=a.minor<o?o-a.minor:0n;return{float:a,obligations:I("USD",o),shortfall:I("USD",i),covered:i===0n}}function Qu(e,t){if(!(e.minor<=t))throw p(h.COMMINGLING,`Sweeping ${E(e)} exceeds the sweepable revenue ${E(I("CREDIT",t))}.`,{detail:{amount:E(e),sweepable:E(I("CREDIT",t))}})}async function ed(e,t,n){const{amount:r,key:s}=n;if(r.minor<=0n)throw p(h.INVALID_AMOUNT,"A fee sweep amount must be positive.",{detail:{amount:E(r)}});return e.transaction(async o=>{if(s!==void 0&&!(await o.idempotency.claim(`sweep:${s}`)).claimed)return{duplicate:!0,swept:I("CREDIT",0n)};await Ne(o.ledger,[w.TRUST_CASH,w.USD_CLEARING,...Zt(w.REVENUE,t.config.platformShards),w.STORED_VALUE]),Qu(r,await As(e,t,o));const a=t.rates.par("CREDIT"),i=Ve(r,a,"USD"),c=await F(o.ledger,{txnId:t.ids.next("txn"),legs:[...await nd(t,o,r),O(w.STORED_VALUE,r)],meta:{kind:"treasury.fee_sweep",amount:E(r),rateId:a.rateId}});return await F(o.ledger,{txnId:t.ids.next("txn"),legs:[N(w.USD_CLEARING,i),O(w.TRUST_CASH,i)],meta:{kind:"treasury.fee_sweep.cash",amount:E(i),rateId:a.rateId}}),s!==void 0&&await o.idempotency.record(`sweep:${s}`,c),await o.outbox.enqueue(xe(t.ids,{id:t.ids.next("evt"),type:"economy.fees.swept",version:1,occurredAt:t.clock.now(),subject:c.id,audience:"internal",data:{swept:E(r)}})),{duplicate:!1,swept:r,transaction:c}})}async function td(e,t,n){const r=await e.transaction(o=>As(e,t,o));if(r<=0n)return{swept:E(I("CREDIT",0n)),skipped:!0,duplicate:!1};const s=await ed(e,t,{amount:I("CREDIT",r),key:`fees:${n.now}`});return{swept:E(s.swept),skipped:!1,duplicate:s.duplicate}}
73async function As(e,t,n){const r=await rd(e,t,n);let s=0n;for(const{maturedMinor:a}of await Ss(t,n))s+=a;const o=r<s?r:s;return o<0n?0n:o}async function Ss(e,t){const n=[];for(const r of Zt(w.REVENUE,e.config.platformShards)){const s=await Qo(t.ledger,r,e.clock.now(),{config:e.config});n.push({shard:r,maturedMinor:s.minor})}return n}async function nd(e,t,n){const r=[];let s=n.minor;for(const{shard:o,maturedMinor:a}of await Ss(e,t)){if(s===0n)break;const i=a<s?a:s;i>0n&&(r.push(N(o,I(n.currency,i))),s-=i)}return r}async function rd(e,t,n){const{custodialCreditMinor:r,trustCashMinor:s}=await qr(e.ledger.heads(),i=>n.ledger.balance(i)),o=t.rates.par("CREDIT");return sd(s,o)-r}function sd(e,t){const n=t.rate;return n===0n?0n:ze(e,10n**BigInt(t.scale),n,"floor")}async function od(e,t){const n={sealed:null,skipped:!1,deadLettered:[],retrying:[]},r=t.clock.now();try{await id(e,t,n)}catch(s){const o=B(s);o.retryable?n.retrying.push({code:o.code}):n.deadLettered.push({reason:o.code})}return t.meter.observe("worker.checkpoint.seal_ms",t.clock.now()-r,{outcome:ad(n)}),n}function ad(e){return e.sealed!==null?"sealed":e.skipped?"skipped":e.retrying.length>0?"retrying":"dead_lettered"}async function id(e,t,n){if(await ud(e)){n.skipped=!0;return}n.sealed=await Ro({ledger:e.ledger,checkpoints:e.checkpoints,digest:t.digest,signer:t.signer,clock:t.clock,ids:t.ids}),await cd(t,n.sealed)}async function cd(e,t){if(e.anchor!==void 0)try{await e.anchor.publish(t),e.meter.count("worker.checkpoint.anchored",1)}catch(n){e.logger.log("warn","worker.checkpoint.anchor_failed",{checkpointId:t.id,code:B(n).code}),e.meter.count("worker.checkpoint.anchor_failed",1)}}async function ud(e){for await(const t of e.ledger.heads())return!1;return!0}async function dd(e,t){const n={verified:null,skipped:!1,mismatch:!1,deadLettered:[],retrying:[]};try{await ld(e,t,n)}catch(r){const s=B(r);s.retryable?n.retrying.push({code:s.code}):n.deadLettered.push({reason:s.code})}return n}async function ld(e,t,n){const r=await e.checkpoints.latest();if(r===null){n.skipped=!0;return}const s=await Oo({ledger:e.ledger,digest:t.digest,signer:t.signer},r);if(n.verified=r.id,n.mismatch=!s,!s){t.logger.log("error","worker.checkpoint.mismatch",{id:r.id}),t.meter.count("worker.checkpoint.verify",1,{outcome:"mismatch"});return}t.meter.count("worker.checkpoint.verify",1,{outcome:"ok"})}const Qn="worker.promos.expired";async function fd(e,t,n,r){const s=await e.promos.claimDue(n.now,n.limit,r),o={reversed:[],failed:[]};for(const a of s)await md({store:e,ctx:t,grant:a,tally:o,options:r});return yd(t,o),o}async function md(e){const{grant:t,tally:n}=e;try{const r=await hd(e);n.reversed.push({id:t.id,amount:r})}catch(r){const s=B(r);n.failed.push({id:t.id,code:s.code})}}async function hd(e){const{store:t,ctx:n,grant:r,options:s}=e;return t.transaction(async o=>{const a=await Le({ledger:o.ledger,digest:n.digest},r.id),i=a?.legs.find(g=>g.account===$(r.userId));if(a===null||i===void 0||-i.amount.minor!==r.amount.minor||a.meta.expiresAt!==r.expiresAt)throw p(h.CHAIN_BROKEN,"A promo grant does not re-derive from its granting posting; refusing to reverse by an unverifiable row.",{retryable:!1,detail:{id:r.id,userId:r.userId}});await o.ledger.lock($(r.userId),s);const c=await o.ledger.balance($(r.userId),s),u=c.minor<r.amount.minor?c.minor:r.amount.minor,m=I("CREDIT",u);return u>0n&&await pd({unit:o,ctx:n,grant:r,amount:m,options:s}),await o.promos.markReversed(r.id,s),m},s)}async function pd(e){const{unit:t,ctx:n,grant:r,amount:s,options:o}=e;await F(t.ledger,{txnId:n.ids.next("txn"),legs:[N($(r.userId),s),O(w.PROMO_FLOAT,s)],meta:{kind:"promos.expiry",grantId:r.id}},o)}function yd(e,t){e.logger.log("info","worker.promos.swept",{reversed:t.reversed.length,failed:t.failed.length,failedIds:t.failed.map(n=>n.id)}),e.meter.count(Qn,t.reversed.length,{outcome:"reversed"}),e.meter.count(Qn,t.failed.length,{outcome:"failed"})}const gd=new TextEncoder;function wd(){const e=new Map;return{scope:"process",pending:t=>e.get(t)??0n,add:(t,n)=>{const r=(e.get(t)??0n)+n;return e.set(t,r),r}}}function Id(e){const t=e.reservations;if(t===void 0)throw p(h.CONFIG_INVALID,"This store offers no shared reservation counter.",{retryable:!1});return{scope:"shared",pending:n=>t.pending(n),add:(n,r)=>t.add(n,r)}}async function Rs(e,t,n){const r=new Ed(e,t,n);return await r.__recover(),r}async function bd(e,t,n){const r=Zs(n,t),s=await e.ledger.balance(r);if(s.minor<=0n)return null;const o=`esc_refund_${t}_${n}`;return await e.ledger.posting(o)!==null?null:(await e.transaction(a=>F(a.ledger,{txnId:o,legs:[N(r,s),O(M(n),s)],meta:{kind:"prefund_refund",sessionId:t,userId:n}})),s.minor)}class Ed{deps;sessionId;maxBatch;chunkWidth;reservations;outcomes=new Map;settled=!1;replayForced=!1;accepted=[];pending=[];opening=new Map;head=me;seq=0;constructor(t,n,r){this.deps=t,this.sessionId=n,this.maxBatch=r?.maxBatch??64,this.chunkWidth=r?.chunkWidth??16,this.reservations=r?.reservations??wd()}async record(t){if(this.settled)throw p(h.SESSION_SETTLED,"A settled session refuses further movements; rotate to a new session id (epoch).",{detail:{sessionId:this.sessionId}});const n=this.outcomes.get(t.idempotencyKey);if(n)return n;const r=await this.reserve(t.legs);if(r)return this.remember(t.idempotencyKey,{status:"rejected",reason:r});
73const s={sessionId:this.sessionId,seq:this.seq,idempotencyKey:t.idempotencyKey,legs:t.legs.map(a=>({...a})),prevHash:this.head,hash:await this.chain(this.head,t),recordedAt:this.deps.clock.now()};this.seq+=1,this.head=s.hash,this.accepted.push(s),this.pending.push(s);const o=this.remember(t.idempotencyKey,{status:"accepted",seq:s.seq});return this.pending.length>=this.maxBatch&&await this.flush(),o}async flush(){if(this.pending.length===0)return;const t=this.pending;this.pending=[],await this.deps.store.movements.append(t)}wasSettled(){return this.settled}async settle(){await this.flush();const t=await this.journal();if(t.length===0)return{mode:"netted",postings:0,rejected:[],journalHead:me,netted:0};const n=t[t.length-1].hash;if(this.replayForced)return this.settled=!0,this.replay(t,n);const r=new Map;for(const c of t)for(const u of c.legs)r.set(u.account,(r.get(u.account)??0n)+u.amount.minor);const s=[...r].filter(([,c])=>c!==0n),o=[];for(let c=0;c<s.length;c+=this.chunkWidth)o.push(s.slice(c,c+this.chunkWidth));const a=[],i={of:o.length,netted:t.length,journalHead:n};try{for(let c=0;c<o.length;c++)await this.postChunk(o[c],{index:c,...i}),a.push(c)}catch{for(const c of a.reverse())await this.postChunk(o[c],{index:c,...i},!0);return this.settled=!0,this.replay(t,n)}return await this.releaseReservations(),this.settled=!0,{mode:"netted",postings:o.length,rejected:[],journalHead:n,netted:t.length}}async reserve(t){let n=0n;for(const s of t){if(s.amount.currency!=="CREDIT"||s.amount.minor===0n)throw p(h.MALFORMED_OPERATION,"A movement leg must carry a nonzero CREDIT amount.",{detail:{account:s.account}});n+=s.amount.minor}if(n!==0n||t.length===0)throw p(h.LEDGER_UNBALANCED,"A movement must carry legs that sum to zero.");const r=[];try{for(const s of t){if(!le(s.account))continue;const o=Z(s).minor,a=await this.reservations.add(s.account,o);if(r.push([s.account,o]),o<0n&&await this.openingBalance(s.account)+a<0n)return await this.unwind(r),"INSUFFICIENT_FUNDS"}}catch(s){throw await this.unwind(r).catch(()=>{}),s}return null}async unwind(t){for(const[n,r]of[...t].reverse())await this.reservations.add(n,-r)}async openingBalance(t){const n=this.opening.get(t);if(n!==void 0)return n;const r=await this.deps.store.ledger.balance(t);return this.opening.set(t,r.minor),r.minor}released=!1;async releaseReservations(){if(!this.released){if(this.reservations.scope==="shared"){const t=`resv_release:${this.sessionId}`;if(!await this.deps.store.transaction(async r=>(await r.idempotency.claim(t)).claimed?(await r.idempotency.record(t,{id:t,postedAt:this.deps.clock.now(),legs:[],links:[],meta:{kind:"reservation_release",sessionId:this.sessionId}}),!0):!1)){this.released=!0;return}}for(const t of this.accepted)for(const n of t.legs)le(n.account)&&await this.reservations.add(n.account,-Z(n).minor);this.released=!0}}remember(t,n){return this.outcomes.set(t,n),n}async chain(t,n){const r=n.legs.map(s=>`${s.account}:${s.amount.currency}:${s.amount.minor}`).join(";");return z(await this.deps.digest.hash(gd.encode(`${t}|${n.idempotencyKey}|${r}`)))}async journal(){const t=[];for await(const r of this.deps.store.movements.bySession(this.sessionId))t.push(r);let n=me;for(const r of t){const s=await this.chain(n,r);if(r.prevHash!==n||r.hash!==s)throw p(h.CHAIN_BROKEN,"The session journal failed to re-derive; refusing to settle over a tampered journal.",{retryable:!1,detail:{sessionId:this.sessionId,seq:r.seq}});n=r.hash}return t}async postChunk(t,n,r=!1){const{index:s,of:o,netted:a,journalHead:i}=n,c=r?`net_${this.sessionId}_c${s}_comp`:`net_${this.sessionId}_c${s}`,u=r?-1n:1n;let m=0n;const g=t.map(([y,v])=>(m-=v*u,{account:y,amount:I("CREDIT",v*u)}));m!==0n&&g.push({account:w.NETTING_CLEARING,amount:I("CREDIT",m)}),await this.deps.store.transaction(async y=>{await y.ledger.posting(c)===null&&await F(y.ledger,{txnId:c,legs:g,meta:{kind:r?"instance_settlement_compensation":"instance_settlement",sessionId:this.sessionId,netted:a,journalHead:i,chunk:`${s+1}/${o}`}})})}async replay(t,n){const r=[];let s=0;for(const o of t){const a=`mv_${this.sessionId}_${o.seq}`;try{await this.deps.store.transaction(async i=>{await i.ledger.posting(a)===null&&await F(i.ledger,{txnId:a,legs:o.legs,meta:{kind:"instance_movement_replay",sessionId:this.sessionId,seq:o.seq,journalHead:n}})}),s+=1}catch(i){const c=B(i).code;r.push({idempotencyKey:o.idempotencyKey,reason:c}),this.remember(o.idempotencyKey,{status:"rejected",reason:c})}}return await this.releaseReservations(),{mode:"replayed",postings:s,rejected:r,journalHead:n,netted:t.length}}async __recover(){const t=await this.journal();for(const r of t){if(this.accepted.push(r),this.reservations.scope==="process")for(const s of r.legs)le(s.account)&&await this.reservations.add(s.account,Z(s).minor);this.outcomes.set(r.idempotencyKey,{status:"accepted",seq:r.seq}),this.head=r.hash,this.seq=r.seq+1}const n=r=>this.deps.store.ledger.posting(r);for(let r=0;r<this.chunkCount();r+=1)if(await n(`net_${this.sessionId}_c${r}_comp`)!==null){this.settled=!0,this.replayForced=!0;return}for(const r of this.accepted)if(await n(`mv_${this.sessionId}_${r.seq}`)!==null){this.settled=!0,this.replayForced=!0;return}await n(`net_${this.sessionId}_c0`)!==null&&(this.settled=!0)}chunkCount(){const t=new Map;for(const r of this.accepted)for(const s of r.legs)t.set(s.account,(t.get(s.account)??0n)+s.amount.minor);let n=0;for(const r of t.values())r!==0n&&(n+=1);return Math.ceil(n/this.chunkWidth)}}async function vd(e,t,n){const r={scanned:0,orphans:[],settled:[],escrowRefunds:[],failed:[]};
73if(e.movements.sessionIds===void 0)return{...r,skipped:!0};const s=n.reservations??(e.reservations!==void 0?Id(e):void 0),o={store:e,digest:t.digest,clock:t.clock};for await(const a of e.movements.sessionIds()){if(r.scanned>=n.limit)break;r.scanned+=1;try{const i=await Rs(o,a,{...s===void 0?{}:{reservations:s}});if(i.wasSettled()){await Wt(e,a,r);continue}const c=n.now-await _s(e,a);if(r.orphans.push({sessionId:a,ageMs:c}),n.settleOlderThanMs!==void 0&&c>n.settleOlderThanMs){const u=await i.settle();r.settled.push({sessionId:a,mode:u.mode}),await Wt(e,a,r),t.logger.log("warn","worker.orphans.settled",{sessionId:a,mode:u.mode,ageMs:c})}}catch(i){const c=B(i).code;r.failed.push({sessionId:a,code:c}),t.logger.log("error","worker.orphans.failed",{sessionId:a,code:c})}}return t.meter.count("worker.orphans.scanned",r.scanned),t.meter.observe("worker.orphans.open",r.orphans.length),t.meter.count("worker.orphans.settled",r.settled.length),r}async function Wt(e,t,n){const r=new Set;for await(const s of e.movements.bySession(t))for(const o of s.legs){const a=Qs(o.account);a!==null&&a.sessionId===t&&r.add(a.userId)}for(const s of r){const o=await bd(e,t,s);o!==null&&n.escrowRefunds.push({sessionId:t,userId:s,minor:o.toString()})}}async function _s(e,t){let n=0;for await(const r of e.movements.bySession(t))r.recordedAt>n&&(n=r.recordedAt);return n}function kd(e){const{ledger:t,checkpoints:n}=e;return t.archivePage===void 0||t.prune===void 0||n.archiveState===void 0||n.archiveHeads===void 0||n.putArchiveBoundary===void 0||n.sealHeads===void 0?null:{archivePage:t.archivePage.bind(t),prune:t.prune.bind(t),archiveState:n.archiveState.bind(n),archiveHeads:n.archiveHeads.bind(n),putArchiveBoundary:n.putArchiveBoundary.bind(n),sealHeads:n.sealHeads.bind(n)}}async function Ad(e,t,n,r){const s=await t.sealHeads(r),o=await Ue(e.digest,s);if(!(z(o.hash)===n.root&&s.length===n.count&&await e.signer.verify(Xe(o),oe(n.signature))))throw p(h.CHAIN_BROKEN,"The seal-head snapshot failed authentication against the signed checkpoint; refusing to archive under an unverified seal.",{retryable:!1,detail:{checkpointId:n.id}})}async function Sd(e,t,n,r){const s=kd(e);if(s===null)return{moved:0,throughSeq:null,finished:!1,skipped:!0,reason:"the store lacks the archival surfaces"};const o=await _d(e,n,r);if("summary"in o)return o.summary;const a=o.checkpoint;await Ad(t,s,a,r);const{prior:i,heads:c}=await Md(t,s,r),u={moved:0,throughSeq:i?.throughSeq??null,finished:!1};let m=i?.cursor??i?.throughSeq??null;for(;;){const g=await s.archivePage(m,n.limit,r),y=Rd(g.postings,a.at);if(y.length===0)return u.finished=!0,u;await Od(t,y,c),await n.sink.put(y,r);const v=g.cursor===null||y.length<g.postings.length,S=y[y.length-1];if(await Td(e,t,{surfaces:s,heads:c,eligible:y,state:{throughSeq:S.seq,cursor:v?null:S.seq,checkpointId:a.id,at:n.now},options:r}),u.moved+=y.length,u.throughSeq=S.seq,t.meter.count("worker.archive.moved",y.length),v)return u.finished=!0,t.logger.log("info","worker.archive.finished",{throughSeq:S.seq,moved:u.moved}),u;m=S.seq}}function Rd(e,t){const n=[];for(const r of e){if(r.postedAt>t)break;n.push(r)}return n}async function _d(e,t,n){const r=await e.checkpoints.latest(n);return r===null||r.v!==2?{summary:{moved:0,throughSeq:null,finished:!1,skipped:!0,reason:"no v2 sum-carrying checkpoint to archive under"}}:t.now-r.at<t.checkpointOlderThanMs?{summary:{moved:0,throughSeq:null,finished:!0,reason:`the latest checkpoint is ${t.now-r.at}ms old; archival waits for one older than the checkpointOlderThanMs bound (${t.checkpointOlderThanMs}ms)`}}:{checkpoint:r}}async function Md(e,t,n){const r=await t.archiveState(n),s=new Map;if(r!==null){const o=await t.archiveHeads(n);if(!await Ur(e,o,r))throw p(h.CHAIN_BROKEN,"The archive heads failed authentication against their signed root; refusing to archive over a tampered boundary.",{retryable:!1});for(const a of o)s.set(a.account,{head:a.head,sum:a.sum})}return{prior:r,heads:s}}async function Od(e,t,n){const r=[];for(const o of t)for(const a of o.links){r.push({account:a.account,txnId:o.txnId,legs:o.legs,meta:o.meta,prevHash:a.prevHash,hash:a.hash});const i=n.get(a.account)?.head??me;if(a.prevHash!==i)throw p(h.CHAIN_BROKEN,"An archival page does not extend the signed archive boundary; refusing to move discontinuous history.",{retryable:!1,detail:{account:a.account,txnId:o.txnId}});const c=n.get(a.account)?.sum??0n,u=o.legs.filter(m=>m.account===a.account).reduce((m,g)=>m+g.amount.minor,0n);n.set(a.account,{head:a.hash,sum:c+u})}const s=await Cr(e.digest,r);
73if(s!==null)throw p(h.CHAIN_BROKEN,"An archival page failed to re-derive from its own content; refusing to move edited history.",{retryable:!1,detail:{...s}})}async function Td(e,t,n){const r=[...n.heads].map(([a,i])=>({account:a,head:i.head,sum:i.sum})),s=await Ue(t.digest,r.map(a=>[a.account,a.head,a.sum]));if(s.sum!==0n)throw p(h.LEDGER_UNBALANCED,"The archive-head sums do not net to zero; refusing to prune under an unbalanced boundary.",{retryable:!1,detail:{sum:s.sum.toString()}});const o=z(await t.signer.sign(Lr(s)));await n.surfaces.putArchiveBoundary({...n.state,root:z(s.hash),signature:o},r,n.options),await e.transaction(a=>a.ledger.prune(n.eligible.map(i=>i.txnId)),n.options)}async function Dd(e,t,n){const r=await Nd(e,n),s=await Pd(e,t,n);return t.meter.count("worker.retention.idempotency_deleted",r.deleted),t.meter.count("worker.retention.sessions_pruned",s.pruned.length),{idempotency:r,sessions:s}}async function Nd(e,t){return t.idempotencyOlderThanMs===void 0||e.idempotency.deleteOlderThan===void 0?{deleted:0,skipped:!0}:{deleted:await e.idempotency.deleteOlderThan(t.now-t.idempotencyOlderThanMs,t.limit)}}async function Pd(e,t,n){const r={scanned:0,pruned:[],escrowRefunds:[],failed:[]};if(n.sessionsOlderThanMs===void 0||e.movements.sessionIds===void 0||e.movements.pruneSession===void 0)return{...r,skipped:!0};const s={store:e,digest:t.digest,clock:t.clock};for await(const o of e.movements.sessionIds()){if(r.scanned>=n.limit)break;r.scanned+=1;try{if(!(await Rs(s,o,{})).wasSettled()||n.now-await _s(e,o)<=n.sessionsOlderThanMs)continue;await Wt(e,o,r);const c=await e.movements.pruneSession(o);r.pruned.push({sessionId:o,movements:c})}catch(a){const i=B(a).code;r.failed.push({sessionId:o,code:i}),t.logger.log("error","worker.retention.failed",{sessionId:o,code:i})}}return r}async function Cd(e,t,n,r){await Ld(e,t,r);const s=await e.outbox.claimBatch(n.limit,r),o={relayed:[],failed:[],deadLettered:[]};for(const a of s)await Ud(e,t,{dispatcher:n.dispatcher,message:a,options:r},o);return await xd(e,t,o.relayed,r),o}async function Ld(e,t,n){try{const r=await e.outbox.stats(n);t.meter.observe("worker.relay.backlog",r.pending),r.oldestPendingAgeMs!==null&&t.meter.observe("worker.relay.backlog_age_ms",r.oldestPendingAgeMs)}catch{}}async function Ud(e,t,n,r){const{dispatcher:s,message:o,options:a}=n;try{await s(o.event,a),r.relayed.push(o.id)}catch(i){const c=ht(i),u=o.attempts+1;if(u>=t.config.maxOutboxAttempts){t.logger.log("error","worker.relay.dead_lettered",{messageId:o.id,correlationId:o.correlationId,code:c.code,attempts:u}),await e.outbox.deadLetter(o.id,c.code,a),r.deadLettered.push({id:o.id,reason:c.code});return}t.logger.log("warn","worker.relay.failed",{messageId:o.id,correlationId:o.correlationId,code:c.code,retryable:c.retryable,attempts:u}),await e.outbox.recordFailure(o.id,a),r.failed.push({id:o.id,code:c.code,retryable:c.retryable})}}async function xd(e,t,n,r){if(n.length!==0)try{await e.outbox.markRelayed(n,r)}catch(s){const o=B(s);t.meter.count("worker.relay.mark_failed",n.length,{code:o.code}),t.logger.log("error","worker.relay.mark_failed",{count:n.length,code:o.code})}}async function $d(e,t,n,r){const s=await e.inbox.claimInbound({now:n.now,limit:n.limit},r),o={applied:[],failed:[],deadLettered:[]};for(const a of s)await Bd(e,t,{economy:n.economy,entry:a,options:r},o);return o}async function Bd(e,t,n,r){const{economy:s,entry:o,options:a}=n;let i;try{i=await s.submit(o.operation,a)}catch(c){await Fd(e,t,{entry:o,normalized:ht(c),options:a},r);return}if(i.status==="rejected"){t.logger.log("warn","worker.inbox.rejected",{entryId:o.id,reason:i.detail.reason}),await e.inbox.deadLetter(o.id,i.detail.reason,a),r.deadLettered.push({id:o.id,reason:i.detail.reason});return}await e.inbox.markApplied(o.id,a),r.applied.push(o.id)}async function Fd(e,t,n,r){const{entry:s,normalized:o,options:a}=n,i=s.attempts+1;if(!o.retryable||i>=t.config.maxInboxAttempts){t.logger.log("error","worker.inbox.dead_lettered",{entryId:s.id,code:o.code,attempts:i}),await e.inbox.deadLetter(s.id,o.code,a),r.deadLettered.push({id:s.id,reason:o.code});return}t.logger.log("warn","worker.inbox.failed",{entryId:s.id,code:o.code,retryable:o.retryable,attempts:i}),await e.inbox.bumpAttempt(s.id,a),r.failed.push({id:s.id,code:o.code,retryable:o.retryable})}
73async function Hd(e,t,n){const r={drained:[],failed:[],skipped:!1};if(!t.config.accrualDrain)return r.skipped=!0,r;await qd(e,t);const s=await e.accruals.pendingSellers(n.limit);for(const o of s)try{const a=await e.transaction(i=>jd(i,t,o,n));a!==null&&r.drained.push(a)}catch(a){const i=B(a);t.logger.log("error","worker.accrual.failed",{sellerId:o,code:i.code}),r.failed.push({sellerId:o,code:i.code})}return r}async function qd(e,t){try{const n=await e.accruals.stats();t.meter.observe("worker.accrual.backlog",Number(n.pendingMinor)),n.oldestPendingAgeMs!==null&&t.meter.observe("worker.accrual.backlog_age_ms",n.oldestPendingAgeMs)}catch{}}async function jd(e,t,n,r){const s=await e.accruals.claimPendingBySeller(n,r.limit);await Kd(e,t,s);const o=s.filter(S=>S.amount.minor>0n);if(o.length===0)return null;const a=s.filter(S=>S.amount.minor<0n);let i=0n;const c=new Map;for(const S of o)i+=S.amount.minor,c.set(S.shard,(c.get(S.shard)??0n)+S.amount.minor);const u=zd(a,i),m=i-u.recoveredMinor,g=[];for(const[S,U]of c)g.push(N(S,I("CREDIT",U)));m>0n&&g.push(O(D(n),I("CREDIT",m))),u.recoveredMinor>0n&&g.push(O(w.RECEIVABLE,I("CREDIT",u.recoveredMinor)));const y=await Gd(t,s);await Ne(e.ledger,g.map(S=>S.account)),await e.ledger.posting(y)===null&&await F(e.ledger,{txnId:y,legs:g,meta:{kind:"accrual_drain",sellerId:n,orders:[...new Set(s.map(S=>S.orderId))].sort(),...u.residual===null?{}:{residual:{orderId:u.residual.orderId,seq:u.residual.seq,minor:u.residual.amount.minor.toString()}}}});const v=[...o,...u.consumed].map(({orderId:S,sellerId:U,seq:L})=>({orderId:S,sellerId:U,seq:L}));return await e.accruals.markDrained(v,y),u.residual!==null&&await e.accruals.put([{...u.residual,txnId:y,recordedAt:r.now}]),{sellerId:n,txnId:y,earnedMinor:m.toString(),recoveredMinor:u.recoveredMinor.toString()}}async function Kd(e,t,n){const r=new Map;for(const s of n){let o=r.get(s.txnId);if(o===void 0){const a=await Le({ledger:e.ledger,digest:t.digest},s.txnId);if(a===null)throw er(s);r.set(s.txnId,a),o=a}if(!Vd(s,o.meta))throw er(s)}}function Vd(e,t){if(e.amount.minor>0n){const r=t.shares?.[e.sellerId];return e.seq===0&&r!==void 0&&BigInt(r)===e.amount.minor}if(t.kind==="refund"){const r=t.recovered?.[e.sellerId];return r!==void 0&&BigInt(r)===-e.amount.minor}if(t.kind==="accrual_drain"){const n=t.residual;return n!==void 0&&t.sellerId===e.sellerId&&n.orderId===e.orderId&&n.seq===e.seq&&BigInt(n.minor??"0")===e.amount.minor}return!1}function er(e){return p(h.CHAIN_BROKEN,"An accrual row does not re-derive from the posting that created it; refusing to drain tampered rows.",{retryable:!1,detail:{orderId:e.orderId,sellerId:e.sellerId,seq:e.seq,txnId:e.txnId}})}function zd(e,t){let n=t,r=0n;const s=[];let o=null;for(const a of e){if(n===0n)break;const i=-a.amount.minor;if(i<=n){s.push(a),r+=i,n-=i;continue}s.push(a),r+=n,o={orderId:a.orderId,sellerId:a.sellerId,seq:a.seq+1,amount:I("CREDIT",-(i-n)),shard:a.shard,status:"pending",settledTxnId:null},n=0n;break}return{recoveredMinor:r,consumed:s,residual:o}}async function Gd(e,t){const n=t.map(s=>`${s.orderId}|${s.sellerId}|${s.seq}`).sort().join(` 74`),r=await e.digest.hash(new TextEncoder().encode(n));return`acc_${z(r).slice(0,32)}`}async function Wd(e,t,n){if(e.checkpoints.reproof===void 0||e.checkpoints.putReproof===void 0)return{checked:0,cursor:null,rotatedAt:null,skipped:!0};const r=await e.checkpoints.reproof()??{cursor:null,rotatedAt:null},s=await e.ledger.linksPage(r.cursor,n.limit),o=await Cr(t.digest,s.links);if(o!==null)throw p(h.CHAIN_BROKEN,"A stored chain link failed to re-derive from its own content; stored history was edited in place.",{retryable:!1,detail:{...o}});const a={cursor:s.cursor,rotatedAt:s.cursor===null?n.now:r.rotatedAt};return await e.checkpoints.putReproof(a),Yd(t,n.now,a.rotatedAt),{checked:s.links.length,cursor:a.cursor,rotatedAt:a.rotatedAt,skipped:!1}}function Yd(e,t,n){try{n!==null&&e.meter.observe("worker.reproof.horizon_age_ms",t-n)}catch{}}function Jd(e,t){const n=tr(t.processor,e,o=>o.settledAt),r=tr(t.ledger,e,o=>o.postedAt),s=Xd(n,r);return el(e,n,r,s)}function Xd(e,t){const n=nl(t),r=[],s=Zd(e,n,r);return Qd(n,r),{matched:s,discrepancies:r}}
74function Zd(e,t,n){let r=0;for(const s of e){const o=Ms(s.kind,s.matchKey),a=t.get(o)?.shift();if(a===void 0){n.push(sl(s));continue}rl(s.amount,a.amount)?r+=1:n.push(al(s,a))}return r}function Qd(e,t){for(const n of e.values())for(const r of n)t.push(ol(r))}function el(e,t,n,r){const s=[...r.discrepancies].sort(il),o=Nt(s,"processor_orphan"),a=Nt(s,"ledger_orphan"),i=Nt(s,"amount_drift");return tl({matched:r.matched,amountDrifts:i,processorOrphans:o,ledgerOrphans:a,processorCount:t.length,ledgerCount:n.length}),{window:e,reconciled:s.length===0,matched:r.matched,processorCount:t.length,ledgerCount:n.length,processorOrphans:o,ledgerOrphans:a,amountDrifts:i,discrepancies:s}}function tl(e){const t=e.matched+e.amountDrifts+e.processorOrphans,n=e.matched+e.amountDrifts+e.ledgerOrphans;if(t!==e.processorCount||n!==e.ledgerCount)throw new Error(`reconcile: internal accounting mismatch â processor ${t}/${e.processorCount}, ledger ${n}/${e.ledgerCount} (matched=${e.matched}, drifts=${e.amountDrifts}, processorOrphans=${e.processorOrphans}, ledgerOrphans=${e.ledgerOrphans})`)}function tr(e,t,n){return e.filter(r=>{const s=n(r);return s>=t.from&&s<t.to})}function nl(e){const t=new Map;for(const n of e){const r=Ms(n.kind,n.matchKey),s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}return t}function Ms(e,t){return`${e}:${t}`}function rl(e,t){return e.currency!==t.currency?!1:Ge(e,t)===0}function sl(e){return{kind:"processor_orphan",matchKey:e.matchKey,recordKind:e.kind,processorAmount:E(e.amount)}}function ol(e){return{kind:"ledger_orphan",matchKey:e.matchKey,recordKind:e.kind,ledgerAmount:E(e.amount)}}function al(e,t){return{kind:"amount_drift",matchKey:e.matchKey,recordKind:e.kind,processorAmount:E(e.amount),ledgerAmount:E(t.amount)}}function Nt(e,t){let n=0;for(const r of e)r.kind===t&&(n+=1);return n}function il(e,t){return fe(e.kind,t.kind)||fe(e.matchKey,t.matchKey)||fe(e.recordKind,t.recordKind)}async function cl(e,t,n,r){const s={reconciled:[],drifted:[],failed:[]},o={feed:e,ctx:t,options:r};for(const a of n.windows)await ul(o,a,s);return s}async function ul(e,t,n){try{const r=await e.feed.pull(t,e.options).catch(s=>{throw ht(s)});dl(e.ctx,t,Jd(t,r),n)}catch(r){const s=B(r);n.failed.push({window:t,code:s.code,retryable:s.retryable}),e.ctx.logger.log("error","worker.reconcile.failed",{from:t.from,to:t.to,code:s.code,retryable:s.retryable})}}function dl(e,t,n,r){if(e.meter.observe("worker.reconcile.discrepancies",n.discrepancies.length),n.reconciled){r.reconciled.push(n),e.logger.log("info","worker.reconcile.reconciled",{from:t.from,to:t.to,matched:n.matched});return}r.drifted.push(n),e.logger.log("warn","worker.reconcile.drifted",{from:t.from,to:t.to,processorOrphans:n.processorOrphans,ledgerOrphans:n.ledgerOrphans,amountDrifts:n.amountDrifts})}const Os=100;async function nr(e,t,n={}){const r=n.now??t.clock.now(),s=n.limit??Os,o=n.options,a=await fl(e,t,n,{now:r,limit:s,options:o});try{t.meter.count("worker.sweep",1,{failed:String(Object.values(a).filter(i=>!i.ok).length)})}catch{}return a}const be={payouts:{submitted:[],deadLettered:[],retrying:[]},subscriptions:{charged:[],lapsed:[],deadLettered:[],retrying:[]},treasury:{position:null,breaches:[],retrying:[],failed:[]},feeSweep:{swept:E(I("CREDIT",0n)),skipped:!0,duplicate:!1},floatCoverage:{position:null,breaches:[],retrying:[],failed:[]},checkpointVerify:{verified:null,skipped:!0,mismatch:!1,deadLettered:[],retrying:[]},checkpoint:{sealed:null,skipped:!0,deadLettered:[],retrying:[]},relay:{relayed:[],failed:[],deadLettered:[]},drainInbox:{applied:[],failed:[],deadLettered:[]},reconcile:{reconciled:[],drifted:[],failed:[]},promos:{reversed:[],failed:[]},accrualDrain:{drained:[],failed:[],skipped:!0},reproof:{checked:0,cursor:null,rotatedAt:null,skipped:!0},orphans:{scanned:0,orphans:[],settled:[],escrowRefunds:[],failed:[],skipped:!0},archive:{moved:0,throughSeq:null,finished:!1,skipped:!0},retention:{idempotency:{deleted:0,skipped:!0},sessions:{scanned:0,pruned:[],escrowRefunds:[],failed:[],skipped:!0}}};function ll(e){return(t,n)=>e.only===void 0||e.only.includes(t)?n():Promise.resolve({ok:!0,summary:be[t]})}async function fl(e,t,n,{now:r,limit:s,options:o}){const a=ll(n);return{payouts:await a("payouts",()=>j(()=>Du(e,t,{now:r,limit:s}))),subscriptions:await a("subscriptions",()=>j(()=>Fu(e,t,{now:r,limit:s}))),treasury:await a("treasury",()=>j(()=>Gu(e,t,{now:r}))),feeSweep:await a("feeSweep",()=>j(()=>td(e,t,{now:r}))),floatCoverage:await a("floatCoverage",()=>n.float===void 0?Promise.resolve({ok:!0,summary:be.floatCoverage}):j(()=>Xu(e,t,n.float,{now:r}))),checkpointVerify:await a("checkpointVerify",()=>j(()=>dd(e,t))),checkpoint:await a("checkpoint",()=>j(()=>od(e,t))),relay:await a("relay",()=>n.dispatcher===void 0?Promise.resolve({ok:!0,summary:be.relay}):j(()=>Cd(e,t,{dispatcher:n.dispatcher,limit:s},o))),drainInbox:await a("drainInbox",()=>n.economy===void 0?Promise.resolve({ok:!0,summary:be.drainInbox}):j(()=>$d(e,t,{economy:n.economy,now:r,limit:s},o))),reconcile:await a("reconcile",()=>hl(t,n,o)),promos:await a("promos",()=>j(()=>fd(e,t,{now:r,limit:s},o))),accrualDrain:await a("accrualDrain",()=>j(()=>Hd(e,t,{now:r,limit:s}))),reproof:await a("reproof",()=>j(()=>Wd(e,t,{now:r,limit:s}))),orphans:await a("orphans",()=>pl(e,t,n,{now:r,limit:s}
74)),archive:await a("archive",()=>ml(e,t,n,{now:r,limit:s,options:o})),retention:await a("retention",()=>yl(e,t,n,{now:r,limit:s}))}}function ml(e,t,n,r){if(n.archive===void 0)return Promise.resolve({ok:!0,summary:be.archive});const s=n.archive;return j(()=>Sd(e,t,{now:r.now,limit:r.limit,...s},r.options))}function hl(e,t,n){if(t.feed===void 0)return Promise.resolve({ok:!0,summary:be.reconcile});const r=t.feed;return j(()=>cl(r,e,{windows:t.windows??[]},n))}function pl(e,t,n,r){if(n.orphans===void 0)return Promise.resolve({ok:!0,summary:be.orphans});const s=n.orphans;return j(()=>vd(e,t,{...r,...s}))}function yl(e,t,n,r){if(n.retention===void 0)return Promise.resolve({ok:!0,summary:be.retention});const s=n.retention;return j(()=>Dd(e,t,{...r,...s}))}async function j(e){try{return{ok:!0,summary:await e()}}catch(t){const n=B(t);return{ok:!1,code:n.code,retryable:n.retryable}}}function gl(e,t,n={}){const r=e.store,s=c=>({now:c.now??e.clock.now(),limit:c.limit??n.limit??Os,only:c.only??n.only,dispatcher:c.dispatcher??n.dispatcher??e.dispatcher,economy:c.economy??t,float:c.float??n.float,feed:c.feed??n.feed,windows:c.windows??n.windows,orphans:c.orphans??n.orphans,archive:c.archive??n.archive,retention:c.retention??n.retention,options:c.options});let o=!1;const a=e.scheduler??Au();return{sweep:async(c={})=>{const u=[],m={...e,ids:{next:y=>{const v=e.ids.next(y);return y==="txn"&&u.push(v),v}}};return{batch:await nr(r,m,s(c)),postings:u}},start:(c,u={})=>a.every(c,async()=>{o||await nr(r,e,s(u))},u.options),pause:()=>{o=!0},resume:()=>{o=!1},get sweepsPaused(){return o}}}function wl(e){return`whk:${e}`}function Il(e){const t={eventId:e.eventId,provider:e.provider,...e.sku===void 0?{}:{sku:e.sku}};return{kind:"topUp",idempotencyKey:wl(e.eventId),actor:{kind:"system",service:`webhook:${e.provider}`},userId:e.userId,amount:e.amount,source:e.source,meta:t}}function bl(e){return Il(e)}async function El(e,t,n,r){const s={id:t.ids.next("ibx"),key:n.eventId,operation:bl(n),status:"pending",attempts:0,receivedAt:t.clock.now(),reason:null},o=await e.transaction(i=>i.inbox.enqueueInbound(s,r),r),a=o.id!==s.id;return a&&t.meter?.count("economy.webhook.duplicate",1,{provider:n.provider,layer:"inbox"}),{status:a?"duplicate":"accepted",entry:o}}function vl(e,t){if(t===null||typeof t!="object")throw ft("Webhook body must be a JSON object.");const n=t,r=ot(n.eventId,"eventId"),s=ot(n.userId,"userId"),o=ot(n.source,"source"),a=kl(n.amount),i=n.sku===void 0?void 0:ot(n.sku,"sku");return{provider:e,eventId:r,userId:s,amount:a,source:o,...i===void 0?{}:{sku:i}}}function ot(e,t){if(typeof e!="string")throw ft(`Webhook field '${t}' must be a string.`);return e}function kl(e){if(typeof e!="string")throw ft("Webhook field 'amount' must be an encoded amount string.");if(e.indexOf(":")<0)throw ft("Webhook field 'amount' must be 'CURRENCY:decimal'.");return Xt(e)}function ft(e){return p(h.MALFORMED_OPERATION,e)}const Al=64*1024,Sl=1e4,Rl="x-economy-client-ip",vn="x-request-id",_l="x-signature",Ml="x-timestamp";function Ol(e){if(e.authenticate===void 0)throw p(h.CONFIG_INVALID,"createServer requires 'authenticate': pass a verifier, or false to trust the body's actor (in-process hosts only).",{retryable:!1});const t=e.economy;return async n=>{const r=Ll(n,e);if(n.method==="OPTIONS"&&e.cors!==void 0)return Ul(n,r);const s=await Tl(t,e,n);return r!==null&&(s.headers.set("access-control-allow-origin",r),s.headers.append("vary","origin")),s}}async function Tl(e,t,n){const r=new URL(n.url).pathname.split("/").filter(Boolean);return n.method==="GET"&&r.length===1&&r[0]==="healthz"?xl():n.method==="GET"&&r.length===1&&r[0]==="readyz"?$l(e):n.method==="POST"?Dl(e,t,r,n):ve(404,"Not found.")}function Dl(e,t,n,r){return n.length===1&&n[0]==="submit"?Bl(e,t,r):n.length===2&&n[0]==="webhooks"?ql(t,n[1],r):n.length===3&&n[0]==="instances"&&n[2]==="purchase"&&t.instances!==void 0?Nl(t,n[1],r):Promise.resolve(ve(404,"Not found."))}async function Nl(e,t,n){const r=Ts(n),s=await Pl(e,t,n);return s.headers.set(vn,r),s}async function Pl(e,t,n){const r=decodeURIComponent(t);if(!/^[\w.:-]{1,128}$/.test(r))return ve(400,"Malformed scope.");let s;if(e.authenticate!==void 0&&e.authenticate!==!1){let i;try{i=await e.authenticate(n)}catch(c){return he(c)}if(i===null)return he(p(h.UNAUTHORIZED,"Request is not authenticated."));s=i}const o=await Ds(e,n,s);if(o!==null)return o;let a;try{a=await kn(n,e)}catch(i){return An(i)}try{const i=Cl(Ps(a),s),c=await e.instances.laneFor(r).purchase(i);return De(200,c)}catch(i){return he(i)}}function Cl(e,t){const n=e??{};
74if(typeof n.buyerId!="string"||n.buyerId.trim()==="")throw p(h.MALFORMED_OPERATION,"purchase.buyerId must be a non-empty string.");if(t!==void 0&&t.kind==="user"&&t.userId!==n.buyerId)throw p(h.UNAUTHORIZED,"A user may only purchase with their own wallet.");const r=n.product??{},s=Array.isArray(n.recipients)?n.recipients:[];return{buyerId:n.buyerId,price:wn.amount(n.price),recipients:s.map(o=>{const a=o??{};if(typeof a.sellerId!="string"||a.sellerId.trim()==="")throw p(h.MALFORMED_OPERATION,"purchase.recipients[].sellerId must be a non-empty string.");return{sellerId:a.sellerId,shareBps:Number(a.shareBps??0)}}),product:{sku:String(r.sku??""),kind:r.kind,...r.expiresAt===void 0?{}:{expiresAt:Number(r.expiresAt)}},...n.orderId===void 0?{}:{orderId:String(n.orderId)}}}function Ll(e,t){const n=e.headers.get("origin");return n===null||t.cors===void 0?null:t.cors.origins.includes(n)?n:null}function Ul(e,t){if(t===null)return new Response(null,{status:204});const n=new Headers({"access-control-allow-origin":t,"access-control-allow-methods":"GET, POST, OPTIONS","access-control-max-age":"600",vary:"origin"}),r=e.headers.get("access-control-request-headers");return r!==null&&n.set("access-control-allow-headers",r),new Response(null,{status:204,headers:n})}function xl(){return De(200,{status:"ok"})}async function $l(e){try{return await e.read.balance(w.REVENUE),De(200,{status:"ready"})}catch{return De(503,{status:"unavailable"})}}async function Bl(e,t,n){const r=Ts(n),s=await Fl(e,t,n,r);return s.headers.set(vn,r),s}function Ts(e){const n=e.headers.get("traceparent")?.match(/^[\da-f]{2}-([\da-f]{32})-[\da-f]{16}-[\da-f]{2}$/)?.[1];if(n!==void 0&&n!=="0".repeat(32))return n;const r=e.headers.get(vn);return r!==null&&/^[\w.:-]{1,128}$/.test(r)?r:`req_${crypto.randomUUID()}`}async function Fl(e,t,n,r){let s;if(t.authenticate!==void 0&&t.authenticate!==!1){let i;try{i=await t.authenticate(n)}catch(c){return he(c)}if(i===null)return he(p(h.UNAUTHORIZED,"Request is not authenticated."));s=i}const o=await Ds(t,n,s);if(o!==null)return o;let a;try{a=await kn(n,t)}catch(i){return An(i)}try{const i=zl(Ps(a),s);return De(200,Ql(await e.submit(i,{correlationId:r})))}catch(i){return he(i)}}async function Ds(e,t,n){const r=e.rateLimit;if(r===void 0||r===!1)return null;const s=r.keyFor?.(t,n)??Hl(t,n);let o;try{o=await r.limiter.allow(s)}catch{return e.ports.meter.count("economy.ratelimit.degraded",1),null}if(o.allowed)return null;const a=ve(429,"Too many requests.");return o.retryAfterMs!==void 0&&a.headers.set("retry-after",String(Math.ceil(o.retryAfterMs/1e3))),a}function Hl(e,t){if(t!==void 0)switch(t.kind){case"user":return`user:${t.userId}`;case"system":return`system:${t.service}`;case"operator":return`operator:${t.operatorId}`}return`ip:${e.headers.get(Rl)??"unknown"}`}async function ql(e,t,n){const r=e.webhook;if(r===void 0)return ve(404,"No webhook handler configured.");let s;try{s=await kn(n,e)}catch(m){return An(m)}const o=e.ports.secrets.webhookSecret;if(o==="")return rr(r,t,sr(n,s));try{if(!await Kl(s,Vl(n),o))throw p(h.INVALID_SIGNATURE,"Webhook signature is invalid.")}catch(m){return he(m)}const a=e.ports.clock.now(),i=n.headers.get(Ml),c=i===null?Number.NaN:Number(i);if(!Number.isFinite(c)||Math.abs(a-c)>e.ports.config.replayWindowMs)return e.ports.meter.count("economy.webhook.duplicate",1,{provider:t,layer:"stale"}),De(200,{status:"duplicate"});const u=await jl(e,t,s);return u!==null?u:rr(r,t,sr(n,s))}async function rr(e,t,n){try{return await e(t,n)}catch(r){return he(r)}}async function jl(e,t,n){if(e.replay===void 0)return null;let r;try{const s=new TextDecoder().decode(n);let o;try{o=JSON.parse(s)}catch(i){throw K("Webhook body is not valid JSON.",i)}const a=vl(t,o);r=(await e.replay.claim(a.eventId)).claimed}catch(s){return he(s)}return r?null:(e.ports.meter.count("economy.webhook.duplicate",1,{provider:t,layer:"replay"}),De(200,{status:"duplicate"}))}async function Kl(e,t,n){let r;try{r=oe(t)}catch{return!1}const s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("HMAC",s,r,e)}function Vl(e){return e.headers.get(_l)??""}
74function sr(e,t){return new Request(e.url,{method:e.method,headers:e.headers,body:t})}function zl(e,t){if(e===null||typeof e!="object")throw K("Operation body must be a JSON object.");const n=e;if(t!==void 0&&"actor"in n)throw K("Operation must not carry 'actor'; the server stamps it.");const r=n.kind;if(typeof r!="string"||!(r in or))throw K(`Unknown operation kind: ${String(r)}.`);const s=or[r];if(Gl(n,s,r),typeof n.idempotencyKey!="string"||n.idempotencyKey==="")throw K("Operation field 'idempotencyKey' must be a non-empty string.");t===void 0&&Zl(n.actor);const o={...n};return t!==void 0&&(o.actor=t),Wl(n,s,o),o}function Gl(e,t,n){for(const r of Object.keys(e))if(!(r==="kind"||r==="idempotencyKey"||r==="actor")&&!(r in t))throw K(`Operation field '${r}' is not part of ${n}.`)}function Wl(e,t,n){for(const[r,s]of Object.entries(t)){const o=s.endsWith("?"),a=e[r];o&&a===void 0||(n[r]=Yl(a,r,o?s.slice(0,-1):s))}}function Yl(e,t,n){return Jl[n](e,t)}const Jl={string:(e,t)=>{if(typeof e!="string"||e==="")throw K(`Operation field '${t}' must be a non-empty string.`);return e},int:(e,t)=>{if(typeof e!="number"||!Number.isSafeInteger(e))throw K(`Operation field '${t}' must be an integer.`);return e},boolean:(e,t)=>{if(typeof e!="boolean")throw K(`Operation field '${t}' must be a boolean.`);return e},amount:(e,t)=>{if(typeof e!="string")throw K(`Operation field '${t}' must be an encoded amount string.`);return wn.amount(e)},recipients:(e,t)=>{if(!Array.isArray(e))throw K(`Operation field '${t}' must be an array of recipients.`);if(!e.every(Xl))throw K(`Operation field '${t}' entries must be { sellerId: string, shareBps: integer }.`);return e},object:(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw K(`Operation field '${t}' must be an object.`);return e}};function Xl(e){const t=e;return t!==null&&typeof t=="object"&&typeof t.sellerId=="string"&&t.sellerId!==""&&typeof t.shareBps=="number"&&Number.isSafeInteger(t.shareBps)}function Zl(e){const t=e;if(!(t!==null&&typeof t=="object"&&(t.kind==="user"&&typeof t.userId=="string"&&t.userId!==""||t.kind==="system"&&typeof t.service=="string"&&t.service!==""||t.kind==="operator"&&typeof t.operatorId=="string"&&t.operatorId!=="")))throw K("Operation field 'actor' must be a user, system, or operator principal.")}const or={topUp:{userId:"string",amount:"amount",source:"string"},spend:{orderId:"string",buyerId:"string",sku:"string",price:"amount",recipients:"recipients",ageRestricted:"boolean?",giftTo:"string?"},refund:{orderId:"string",reason:"string?"},clawback:{userId:"string",amount:"amount",orderId:"string?",key:"string?",reason:"string?"},requestPayout:{userId:"string",amount:"amount"},subscribe:{userId:"string",sellerId:"string",sku:"string",price:"amount",periodMs:"int"},cancelSubscription:{subscriptionId:"string"},grantEntitlement:{userId:"string",sku:"string",attrs:"object?"},revokeEntitlement:{userId:"string",sku:"string",reason:"string?"},grantPromo:{userId:"string",amount:"amount",expiresAt:"int"},adjust:{account:"string",amount:"amount",reason:"string"},reverse:{txnId:"string",reason:"string"},reversePayout:{userId:"string",sagaId:"string",reason:"string",providerReported:"boolean?"},settlePayout:{sagaId:"string",providerRef:"string",providerAmount:"amount?"}};function Ql(e){return e.status==="rejected"?{status:e.status,reason:e.detail.reason,detail:br(e.detail)}:{status:e.status,transaction:ts.transaction(e.transaction)}}function he(e){const t=B(e);return ve(Gs(t),t.message,{code:t.code,retryable:t.retryable})}class Yt extends Error{}
74class Ns extends Error{}async function kn(e,t){const n=t.maxBodyBytes??Al;if(Number(e.headers.get("content-length")??"0")>n)throw new Yt;const r=e.body;if(r===null)return new Uint8Array(0);const s=r.getReader(),o=[];let a=0;const i=AbortSignal.timeout(t.readTimeoutMs??Sl);for(i.addEventListener("abort",()=>{s.cancel()});;){const{done:m,value:g}=await s.read();if(i.aborted)throw new Ns;if(m)break;if(a+=g.byteLength,a>n)throw s.cancel(),new Yt;o.push(g)}const c=new Uint8Array(a);let u=0;for(const m of o)c.set(m,u),u+=m.byteLength;return c}function An(e){return e instanceof Yt?ve(413,"Request body is too large."):e instanceof Ns?ve(408,"Request body read timed out."):he(e)}function Ps(e){if(e.byteLength===0)throw K("Request body is empty.");try{return JSON.parse(new TextDecoder().decode(e))}catch(t){throw K("Request body is not valid JSON.",t)}}function K(e,t){return new Ws(h.MALFORMED_OPERATION,e,{cause:t})}function De(e,t){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}})}function ve(e,t,n){const r={type:n?"https://economy-lab-docs.pages.dev/economy/reference/outcomes-and-reason-codes/":"about:blank",title:t,status:e,...n};return new Response(JSON.stringify(r),{status:e,headers:{"content-type":"application/problem+json"}})}function Ae(e){return t=>({kind:e,...t})}const ef=Ae("topUp"),Pt=Ae("spend"),tf=Ae("requestPayout"),nf=Ae("subscribe"),rf=Ae("cancelSubscription"),sf=Ae("grantPromo"),of=Ae("reversePayout"),af=Ae("settlePayout");async function ar(e,t){const n=Math.max(0,Math.floor(t.offset)||0),r=Math.max(0,Math.floor(t.limit)||0),s=[];let o=0;for await(const a of e)o>=n&&s.length<r&&s.push(a),o+=1;return{rows:s,total:o}}function wt(e){const t=Oe(e.DATABASE_URL),n=tn(e);return{store:t===null?{kind:"memory",url:null}:{kind:io(t)?"postgres":co(t)?"mysql":"unsupported",url:t},cache:n.redis===null?{kind:"none",url:null}:{kind:"redis",url:n.redis},dispatcher:n.sqs!==null?{kind:"sqs",url:n.sqs}:n.dispatcher!==null?{kind:"http",url:n.dispatcher}:{kind:"missing",url:null}}}const Sn=[{slot:"dispatcher",flag:"DISPATCHER_DECLINED"},{slot:"payees",flag:"PAYEES_DECLINED"},{slot:"anchor",flag:"ANCHOR_DECLINED"}];function Rn(e,t){const n=(s,o,a)=>s===!1||ao(e[o])?"declined":s!==void 0||a?"set":"missing",r=wt(e);return{dispatcher:n(t.dispatcher,"DISPATCHER_DECLINED",r.dispatcher.kind!=="missing"),payees:n(t.payees,"PAYEES_DECLINED",!1),anchor:n(t.anchor,"ANCHOR_DECLINED",!1)}}function cf(e={},t={}){return Je(e)?[...ir(e,t),...uf(e,t),...df(e,t),...lf(e,t),...ff(e,t),...cr(t),...mf(e,t)]:[...ir(e,t),...cr(t)]}function ke(e,t,n,r="error"){return{code:e,path:t,message:n,severity:r}}function ir(e,t){return t.store!==void 0?[]:wt(e).store.kind!=="unsupported"?[]:[ke("store.unsupported-url","DATABASE_URL","DATABASE_URL is not a postgres:// or mysql:// connection string.")]}function uf(e,t){const n={webhookSecret:t.secrets?.webhookSecret??e.WEBHOOK_SECRET??"",signingSecret:t.secrets?.signingSecret??e.SIGNING_SECRET??""};return Ar(n).map(r=>ke("secret.missing",r,`${r} is required in production but missing.`))}function df(e,t){return Sr(e,t.config??{}).map(n=>ke("config.missing",n,`${n} is required in production but missing.`))}function lf(e,t){return Is(e,t).map(n=>ke("external.missing",n,`${n} is required in production but missing or malformed.`))}function ff(e,t){const n=Rn(e,t);return Sn.filter(({slot:r})=>n[r]==="missing").map(({slot:r,flag:s})=>ke("port.absent",r,`Production requires ${r} to be set or explicitly declined (init ${r}: false, or env ${s}=1).`))}function cr(e){const t=[],n=(r,s)=>{try{s()}catch(o){t.push(ke("port.malformed",r,o instanceof Error?o.message:String(o)))}};return e.dispatcher!==void 0&&e.dispatcher!==!1&&typeof e.dispatcher!="function"&&t.push(ke("port.malformed","dispatcher","dispatcher is not a function; pass the dispatch function itself, not an object carrying one.")),e.payees!==void 0&&e.payees!==!1&&n("payees",()=>se("payees",e.payees,["status"])),e.anchor!==void 0&&e.anchor!==!1&&n("anchor",()=>se("anchor",e.anchor,["publish"])),t}function mf(e,t){const n=Rn(e,t),r={dispatcher:t.dispatcher!==void 0&&t.dispatcher!==!1||wt(e).dispatcher.kind!=="missing",payees:t.payees!==void 0&&t.payees!==!1,anchor:t.anchor!==void 0&&t.anchor!==!1};return Sn.filter(({slot:s})=>n[s]==="declined"&&r[s]).map(({slot:s})=>ke("port.decline-conflict",s,`${s} is declined but also configured; the decline wins and the configured ${s} is ignored.`,"warning"))}async function hf(e={},t={}){pf(e,t);const n=ho(e,t.config??{}),r=fo(e,t.secrets),s=vf(t),o=Ru(e,t,r),a=Rn(e,t),[i,c,u]=await yf(e,t,a,{...s,config:n}),m=t.payees===!1?void 0:t.payees,g=t.anchor===!1?void 0:t.anchor,y=t.scheduler
74===!1?void 0:t.scheduler;return gf(s.meter,a),Object.freeze(n),Object.freeze(n.maturityHorizonMs),Object.freeze(n.payoutSla),Object.freeze(r),{...s,...o,config:n,secrets:r,store:i,...c&&{cache:c},...u&&{dispatcher:u},...m&&{payees:m},...g&&{anchor:g},...y&&{scheduler:y}}}function pf(e,t){const n=cf(e,t).filter(r=>r.severity==="error");if(n.length!==0)throw p(h.CONFIG_INVALID,`Preflight failed: ${n.map(r=>r.message).join(" ")}`,{retryable:!1,detail:{issues:n.map(({code:r,path:s})=>({code:r,path:s}))}})}function yf(e,t,n,r){const s=wt(e),o=r.config;return Promise.all([t.store??wf(s.store,{digest:r.digest,clock:r.clock,velocityWindowMs:o.velocityWindowMs,poolMax:o.dbPoolMax,meter:r.meter,logger:r.logger}),t.cache===!1?void 0:t.cache??bf(s.cache),n.dispatcher!=="set"?void 0:typeof t.dispatcher=="function"?t.dispatcher:Ef(s.dispatcher)])}function gf(e,t){try{for(const{slot:n}of Sn)e.count("economy.preflight.absence",1,{slot:n,state:t[n]})}catch{}}async function wf(e,t){if(e.kind==="memory")return mu(t);if(e.kind==="postgres"){const{postgresStore:n}=await Ie(async()=>{const{postgresStore:r}=await import("./unavailable-BqHu1V-5.js");return{postgresStore:r}},[]);return n({url:e.url,digest:t.digest,clock:t.clock,velocityWindowMs:t.velocityWindowMs,...t.poolMax?{poolMax:t.poolMax}:{},meter:t.meter,logger:t.logger})}if(e.kind==="mysql")return If(e.url,t);throw p(h.CONFIG_INVALID,"DATABASE_URL must be a postgres:// or mysql:// DSN.",{detail:{scheme:e.url.split(":")[0]}})}async function If(e,t){const{createMysqlPool:n,mysqlStore:r,readSchemaVersion:s}=await Ie(async()=>{const{createMysqlPool:i,mysqlStore:c,readSchemaVersion:u}=await import("./unavailable-BqHu1V-5.js");return{createMysqlPool:i,mysqlStore:c,readSchemaVersion:u}},[]),o=await n(e,t.poolMax?{connectionLimit:t.poolMax}:{});sc(await s(o),"MySQL");const a={run:(i,c)=>o.query(i,c?[...c]:void 0).then(([u])=>u)};return await dc(()=>fc(a)),oc(await pc(a,Ys),"MySQL"),r({pool:o,digest:t.digest,clock:t.clock,velocityWindowMs:t.velocityWindowMs,meter:t.meter,logger:t.logger})}async function Cs(e,t){try{return await t()}catch(n){throw p(h.CONFIG_INVALID,`Could not load the "${e}" driver. Install the optional peer dependency: npm install ${e}`,{cause:n,retryable:!1})}}async function bf(e){if(e.kind==="none")return;const t=e.url,{redisCache:n}=await Ie(async()=>{const{redisCache:s}=await import("./unavailable-BqHu1V-5.js");return{redisCache:s}},[]),r=(await Cs("ioredis",()=>Ie(()=>import("./unavailable-BqHu1V-5.js"),[]))).default;return n(new r(t))}async function Ef(e){if(e.kind==="missing")return;if(e.kind==="sqs"){const n=e.url,{SQSClient:r,SendMessageCommand:s}=await Cs("@aws-sdk/client-sqs",()=>Ie(()=>import("./unavailable-BqHu1V-5.js"),[])),{sqsDispatcher:o}=await Ie(async()=>{const{sqsDispatcher:i}=await import("./unavailable-BqHu1V-5.js");return{sqsDispatcher:i}},[]),a=new r({});return o({queueUrl:n,client:{send:async(i,c)=>(await a.send(new s(i.input),c),{})}})}const{httpDispatcher:t}=await Ie(async()=>{const{httpDispatcher:n}=await import("./http-dispatcher-gQhek6ro.js");return{httpDispatcher:n}},__vite__mapDeps([0,1]));return t({url:e.url})}function vf(e){const t={clock:e.clock??Eu(),ids:e.ids??vu(),digest:e.digest??bn(),logger:e.logger??ys(),meter:e.meter??gs()};return se("clock",t.clock,["now"]),se("ids",t.ids,["next"]),se("digest",t.digest,["hash"]),se("logger",t.logger,["log"]),se("meter",t.meter,["count","observe"]),t}const kf=100,ye={topUp:"Deposit",spend:"Purchase",requestPayout:"Payout",grantPromo:"Promotional grant",payoutSettled:"Payout settled",payoutReversed:"Payout reversed",payoutCash:"Payout cash-out",feeSweep:"Fee sweep",promoExpiry:"Promo expired"};function Ls(e){return{[h.PROVIDER_FAILURE]:"provider failure","payout.timeout":"provider timeout"}[e]??e.replace(/[._]/g," ").toLowerCase()}function Af(e){if(!e)return"Background posting";const t=e.endsWith(".cash"),n=(t?e.slice(0,-5):e).replace(/[._]/g," ").trim(),r=n.charAt(0).toUpperCase()+n.slice(1);return t?`${r} (cash)`:r}const ur={"platform:stored_value":"Stored value (spendable credits in circulation)","platform:revenue":"Platform revenue","platform:held":"Escrow (funds held until a sale completes)","platform:payout_reserve":"Payout reserve (credits set aside for a pending payout)","platform:promo_float":"Promotional float (credits granted, not yet spent)","platform:trust_cash":"Trust cash (USD backing user credits)","platform:receivable":"Receivable (money owed to the platform)","platform:usd_clearing":"USD clearing (cash in transit to or from the bank)","platform:opening_equity":"Opening equity (starting balance)"},Sf=[{key:"storedValue",account:w.STORED_VALUE,label:"Stored value",sublabel:"Spendable credits in circulation"},{key:"reserve",account:w.PAYOUT_RESERVE,label:"Payout reserve",sublabel:"Credits set aside for pending payouts"},{key:"promoFloat",account:w.PROMO_FLOAT,label:"Promotional float",sublabel:"Granted promo credits not yet spent"},{key:"revenue",account:w.REVENUE,label:"Platform revenue",sublabel:"Fees awaiting the peri
74odic treasury sweep"},{key:"trustCash",account:w.TRUST_CASH,label:"Trust cash",sublabel:"Real USD held to back user credits"},{key:"usdClearing",account:w.USD_CLEARING,label:"USD clearing",sublabel:"Cash in transit to or from the bank"}];function V(e){return Number(e.minor)/kf}function te(e){const t=E(e).split(":")[1]??"0.00",n=t.startsWith("-")?"-":"",[r="0",s="00"]=(n?t.slice(1):t).split(".");return`${n}${r.replace(/\B(?=(\d{3})+(?!\d))/g,",")}.${s}`}function dr(e){if(ur[e])return ur[e];const t=e.lastIndexOf(":"),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):"";return`${n} · ${r==="spendable"?"Purchased":r==="earned"?"Earned":r==="promo"?"Promotional":r}`}const lr=50,Rf=200;function Ct(e){const t=Math.min(Rf,Math.max(1,Math.floor(Number(e?.limit??lr))||lr));return{offset:Math.max(0,Math.floor(Number(e?.offset??0))||0),limit:t}}const _f=12;function fr(e){return Math.min(_f,Math.max(2,Math.floor(Number(e))||2))}const Lt=2e4;function mr(e){return Number(e.rate)/10**e.scale*1e3}function hr(e){return{rate:BigInt(Math.round(e*1e3)),scale:6}}const Ut=1,xt=50,$t=3;function Mf(e){const t=e.includes("â¦")?"â¦":e.includes("...")?"...":null;if(t){const[r="",s=""]=e.split(t),o=r.trim().toLowerCase(),a=s.trim().toLowerCase();return i=>{const c=i.toLowerCase();return o!==""&&a!==""&&c.startsWith(o)&&c.endsWith(a)}}const n=e.toLowerCase();return r=>r.toLowerCase()===n}function pr(e,t){let n=0,r=0,s=0,o=0;for(const a of e)a.status==="committed"?n++:a.status==="duplicate"||a.detail.reason==="DUPLICATE_ORDER"?r++:a.detail.reason==="INSUFFICIENT_FUNDS"?s++:o++;return{attempts:e.length,committed:n,duplicates:r,insufficient:s,other:o,movedCredits:t}}async function yr(e){let t=0;for await(const n of e.read.payouts({states:["REQUESTED","RESERVED","SUBMITTED"]}))t++;return t}function gr(e){return{id:e.id,userId:e.userId,reserveCredits:V(e.reserve),state:e.state,providerRef:e.providerRef,attempts:e.attempts,dueAt:e.dueAt,reason:e.reason===null?null:Ls(e.reason),payoutUsd:e.payoutUsd===null?null:V(e.payoutUsd)}}async function wr(){const e=Xs();let t,n,r,s=!1,o=0,a=5,i=0,c=[],u=[],m=Promise.resolve(),g=!1;function y(d){if(g)return d();const l=async()=>{g=!0;try{return await d()}finally{g=!1}},f=m.then(l,l);return m=f.catch(()=>{}),f}const v=5e3;let S=null,U=null;function L(){S=null,U=null}const Ze=ku(),Qe={next:d=>`${d}_${++i}`},Se={submitPayout:async d=>{if(s)throw p(h.PROVIDER_FAILURE,"Tilia is unavailable.",{retryable:!0});return{providerRef:`tilia_${d.key}`}}};let ie={...zt},ce=!1;const $e=ps({signingKey:"00112233445566778899aabbccddeeff"}),Re=ys({out:()=>{},err:()=>{}}),et=gs();let C;async function _e(){i=0,e.set(0),ie={...zt},ce=!1,C=await hf(Js(o,a),{signer:$e,processor:Se,rates:qe(ie),pricing:Gr(),clock:e,ids:Qe,digest:Ze,logger:Re,meter:et}),It(),c=[],u=[]}function It(){t=ki(C),n=gl(C,t),r=C.store}function ge(d){C={...C,config:Rr(C.config,d)},It()}async function _n(d,l){const f=await d.read.balance(M(l)),b=await d.read.balance(D(l)),k=await d.read.balance($(l));return{userId:l,purchased:te(f),earned:te(b),promotional:te(k),total:te(Cn(Cn(f,b),k))}}async function bt(d){const l=new Set;for await(const f of d.read.accounts())le(f)&&l.add(We(f));return[...l]}async function tt(d){const l=V(await t.read.balance(M(d))),f=V(await t.read.balance($(d)));return l+f}function xs(d){return d.map(l=>{const f=V(l.amount);return{account:l.account,label:dr(l.account),side:l.amount.minor>0n?"debit":"credit",amount:`${f>=0?"+":""}${f.toFixed(2)}`,currency:J(l.account)==="USD"?"USD":"Cr"}})}function $s(d){return d.reduce((l,f)=>l+Number(f.amount.minor),0)}function Et(d){for(const l of d)if(!l.account.startsWith("platform:")){const f=l.account.lastIndexOf(":");return f>=0?l.account.slice(0,f):l.account}return null}function Bs(d){for(const l of d)if(l.account.endsWith(":earned"))return l.account.slice(0,l.account.lastIndexOf(":"));return null}async function vt(d,l,f){const b=f.meta,k=String(b.kind??""),_=f.legs[0],R=_?Math.abs(V(_.amount)):0,P=_&&J(_.account)==="USD"?"USD":"CREDIT",Y=b.sagaId?String(b.sagaId):void 0,Q=(Y?(await d.read.saga(Y))?.userId:null)??Et(f.legs)??"user",Tn=R.toLocaleStr
74ing("en-US",{minimumFractionDigits:2,maximumFractionDigits:2}),nt=`${Tn} Cr`,de={id:l,at:e.now(),paymentType:"Tilia",priceCredits:R,priceCurrency:P,buyer:"Platform",seller:Q,legs:xs(f.legs),balancedTo:$s(f.legs),sagaId:Y};if(k==="topUp")return{...de,kind:"topUp",label:ye.topUp,paymentType:"Card",listing:"Credit top-up",buyer:"Platform",seller:Q};if(k==="spend")return{...de,kind:"spend",label:ye.spend,paymentType:"Credits",listing:"Marketplace purchase",buyer:Et(f.legs)??"user",seller:Bs(f.legs)??Q};if(k==="requestPayout")return{...de,kind:"requestPayout",label:ye.requestPayout,paymentType:"Tilia",listing:"Payout to Tilia",buyer:"Platform",seller:Q};if(k==="grantPromo")return{...de,kind:"grantPromo",label:ye.grantPromo,paymentType:"Promotion",listing:"Promotional credits",buyer:"Platform",seller:Q};if(k==="payouts.dead_letter"){const Hs=Ls(String(b.reason??""));return{...de,kind:"payoutReversed",label:ye.payoutReversed,listing:"Reserve returned to seller",note:`Tilia payout failed (${Hs}) after the retry cap. The ${nt} reserve was returned to ${Q}'s earned balance â nothing is stranded.`}}if(k==="settlePayout")return{...de,kind:"payoutSettled",label:ye.payoutSettled,listing:`Settled to ${Q}`,note:`Payout to ${Q} settled â the ${nt} reserve was released to platform revenue.`};if(k==="settlePayout.cash")return{...de,kind:"payoutCash",label:ye.payoutCash,listing:`Cash to ${Q}`,note:`$${Tn} was paid out to ${Q} from trust cash.`};if(k==="treasury.fee_sweep")return{...de,kind:"feeSweep",label:ye.feeSweep,listing:"Marketplace fees to treasury",seller:"platform",paymentType:"System",note:`The platform swept ${nt} of accumulated marketplace fees out of revenue into its own treasury.`};if(k==="promos.expiry")return{...de,kind:"promoExpiry",label:ye.promoExpiry,listing:"Unspent promo reclaimed",paymentType:"Promotion",note:`${nt} of expired promotional credits was reclaimed from ${Q}.`};const Dn=Af(k);return{...de,kind:"other",label:Dn,listing:Dn,seller:Et(f.legs)??"platform",paymentType:"System",note:`Background ledger posting${k?` (${k})`:""}.`}}let kt=0;function W(d){return`${d}_${++kt}`}function Mn(d){return{conserved:d.conserved,backed:d.backed,noOverdraft:d.noOverdraft,chainIntact:d.chainIntact,consistent:d.consistent,shortfallUsd:V(d.shortfall),drift:d.drift.map(l=>({account:l.account,cachedCredits:V(l.materialized),derivedCredits:V(l.derived)})),allGreen:d.conserved&&d.backed&&d.noOverdraft&&d.chainIntact&&d.consistent}}async function ue(d){const l=await t.submit(d);return L(),l}async function Fs(){return{batch:(await n.sweep({now:e.now(),limit:100})).batch}}async function On(){await T.deposit({userId:"usr_alice",credits:5e3}),await T.deposit({userId:"usr_bjorn",credits:3e3}),await T.grantPromo({userId:"usr_alice",credits:500}),await T.grantPromo({userId:"usr_pixel",credits:600}),await T.purchase({buyerId:"usr_alice",sellerId:"usr_nova",listing:"Aurora Avatar",credits:2e3}),await T.purchase({buyerId:"usr_bjorn",sellerId:"usr_nova",listing:"Skyline World Pass",credits:1200}),await T.purchase({buyerId:"usr_alice",sellerId:"usr_pixel",listing:"Wave Emote Pack",credits:450}),await T.subscribe({userId:"usr_bjorn",sellerId:"usr_nova",sku:"Skyline Weekly Pass",credits:150,periodDays:7});const d=async f=>V(await t.read.balance(D(f))),l=async(f,b)=>Math.max(1,Math.floor(await d(f)*b));await T.requestPayout({userId:"usr_nova",credits:await l("usr_nova",.35)}),T.advanceTime(ee),await T.runJobs(),await T.settleSubmitted(),await T.requestPayout({userId:"usr_pixel",credits:await l("usr_pixel",.6)}),T.advanceTime(ee),await T.runJobs(),T.setFault(!0),await T.setMaxAttempts(1),await T.requestPayout({userId:"usr_nova",credits:await l("usr_nova",.3)}),T.advanceTime(ee),await T.runJobs(),T.setFault(!1),await T.setMaxAttempts(5),await T.requestPayout({userId:"usr_nova",credits:await l("usr_nova",.3)})}const T={get economy(){return t},deposit:({userId:d,credits:l})=>y(()=>ue(ef({idempotencyKey:W("idem"),actor:{kind:"system",service:"console"},source:"card",userId:d,amount:pe(l)}))),purchase:({buyerId:d,sellerId:l,listing:f,credits:b,actor:k,orderId:_,giftTo:R})=>y(()=>ue(Pt({idempotencyKey:W("idem"),actor:k??{kind:"user",userId:d},buyerId:d,sku:f,price:pe(b),recipients:[{sellerId:l,shareBps:1e4}],orderId:_??W("ord"),...R?{giftTo:R}:{}}))),requestPayout:({userId:d,credits:l,actor:f})=>y(()=>ue(tf({idempotencyKey:W("idem"),actor:f??{kind:"user",userId:d},userId:d,amount:pe(l)}))),grantPromo:({userId:d,credits:l})=>y(()=>ue(sf({idempotencyKey:W("idem"),actor:{kind:"system",service:"marketing"},userId:d,amount:pe(l),expiresAt:e.now()+720*60*6e4}))),reversePayout:({sagaId:d,userId:l,reason:f})=>y(()=>ue(of({idempotencyKey:W("idem"),actor:{kind:"operator",operatorId:"ops_console"},userId:l,sagaId:d,reason:f}
74))),settleSubmitted:()=>y(async()=>{const d=t,l=[];for await(const b of d.read.payouts())b.state==="SUBMITTED"&&l.push({sagaId:b.id,providerRef:b.providerRef??`tilia_${b.id}`});let f=0;for(const{sagaId:b,providerRef:k}of l)(await ue(af({idempotencyKey:W("idem"),actor:{kind:"system",service:"reconcile"},sagaId:b,providerRef:k}))).status==="committed"&&f++;return{settled:f}}),raceOrder:({buyerId:d,sellerId:l,listing:f,credits:b,count:k})=>y(async()=>{const _=await tt(d),R=W("ord"),P=[];for(let Me=0;Me<fr(k);Me++)P.push(await ue(Pt({idempotencyKey:W("idem"),actor:{kind:"user",userId:d},buyerId:d,sku:f,price:pe(b),recipients:[{sellerId:l,shareBps:1e4}],orderId:R})));const Y=await tt(d);return pr(P,_-Y)}),drainWallet:({buyerId:d,sellerId:l,listing:f,credits:b,count:k})=>y(async()=>{const _=await tt(d),R=[];for(let Y=0;Y<fr(k);Y++)R.push(await ue(Pt({idempotencyKey:W("idem"),actor:{kind:"user",userId:d},buyerId:d,sku:f,price:pe(b),recipients:[{sellerId:l,shareBps:1e4}],orderId:W("ord")})));const P=await tt(d);return pr(R,_-P)}),wallets:async d=>{const l=t,{offset:f,limit:b}=Ct(d),k=(await bt(l)).sort(),_=k.slice(f,f+b),R=[];for(const P of _)R.push(await _n(l,P));return{rows:R,total:k.length,offset:f,limit:b}},wallet:async d=>{const l=t;return await bt(l).then(b=>b.includes(d))?_n(l,d):null},ledger:async d=>{const l=t,{offset:f,limit:b}=Ct(d),k=await ar(l.read.postings(),{offset:f,limit:b}),_=[];for(const R of k.rows)_.push(await vt(l,R.txnId,R));return{rows:_,total:k.total,offset:f,limit:b}},payouts:async d=>{const l=t,{offset:f,limit:b}=Ct(d),k=await ar(l.read.payouts(),{offset:f,limit:b});return{rows:k.rows.map(gr),total:k.total,offset:f,limit:b}},payoutCounts:async()=>{const d=t,l={RESERVED:0,SUBMITTED:0,SETTLED:0,FAILED:0};for await(const f of d.read.payouts())switch(f.state){case"REQUESTED":case"RESERVED":l.RESERVED++;break;case"SUBMITTED":l.SUBMITTED++;break;case"SETTLED":l.SETTLED++;break;case"FAILED":l.FAILED++;break}return l},sagaDetail:async d=>{const l=t,f=await l.read.saga(d);if(f===null)return null;const b=[];let k=0,_=!1;for await(const R of l.read.postings()){if(k++>=2e3){_=!0;break}const P=R.meta;String(P.sagaId??"")===d&&b.push(await vt(l,R.txnId,R))}return{saga:gr(f),postings:b,reversible:f.state==="RESERVED"||f.state==="SUBMITTED",truncated:_}},health:async()=>{const d=e.now();if(U&&d-U.at<v)return U.value;const l=Mn(await t.read.health());return U={at:d,value:l},l},prove:()=>Fo({store:r,rates:C.rates,digest:Ze}).then(Mn),tamper:()=>y(async()=>{let d=null;for await(const l of t.read.postings()){const f=l.legs[0];if(f){d={txnId:l.txnId,account:f.account};break}}if(d===null)throw p(h.CONFIG_INVALID,"No posting to tamper with.");return r.ledger.__tamper(d.txnId,l=>{const f=l[0];f&&(l[0]={...f,amount:{...f.amount,minor:f.amount.minor+100n}})}),L(),d}),seedDrift:()=>y(async()=>{const d="usr_ghost:spendable";return r.ledger.__seedBalance(d,pe(123)),L(),{account:d}}),subscribe:({userId:d,sellerId:l,sku:f,credits:b,periodDays:k})=>y(async()=>{const _=await ue(nf({idempotencyKey:W("idem"),actor:{kind:"user",userId:d},userId:d,sellerId:l,sku:f,price:pe(b),periodMs:Math.max(1,Math.round(k))*ee}));if(_.status==="committed"){const R=await r.subscriptions.activeFor(d,f,l);R!==null&&!u.includes(R.id)&&u.push(R.id)}return _}),cancelSubscription:({subscriptionId:d})=>y(async()=>{const l=await r.subscriptions.load(d);if(l===null)throw p(h.CONFIG_INVALID,"Unknown subscription.");return ue(rf({idempotencyKey:W("idem"),actor:{kind:"user",userId:l.userId},subscriptionId:d}))}),subscriptions:async()=>{const d=[];for(const l of u){const f=await r.subscriptions.load(l);f!==null&&d.push({id:f.id,userId:f.userId,sellerId:f.sellerId,sku:f.sku,priceCredits:V(f.price),periodDays:f.periodMs/ee,period:f.period,state:f.state,nextDueAt:f.nextDueAt})}return d},solvency:async()=>{const d=t,l=e.now();if(S&&l-S.at<v)return S.value;let f=0n,b=0n,k=0n;for(const Me of await bt(d))f+=(await d.read.balance(M(Me))).minor,b+=(await d.read.balance(D(Me))).minor,k+=(await d.read.balance($(Me))).minor;const _=await d.read.health(),R=await d.read.balance(w.TRUST_CASH),P=Ve(I("CREDIT",f),C.rates.par("CREDIT"),"
74USD"),Y={userCredits:te(I("CREDIT",f+b+k)),backed:_.backed,backingUsd:te(P),shortfallUsd:te(_.shortfall),trustCashUsd:te(R),purchased:te(I("CREDIT",f)),earned:te(I("CREDIT",b)),promotional:te(I("CREDIT",k))};return S={at:l,value:Y},Y},platformAccounts:async()=>{const d=t,l=[];for(const f of Sf){const b=await d.read.balance(f.account);l.push({key:f.key,label:f.label,sublabel:f.sublabel,value:Math.abs(V(b)),currency:J(f.account)==="USD"?"USD":"CREDIT"})}return l},entitled:(d,l)=>t.read.entitled(d,l),posting:async d=>{const l=t,f=await l.read.posting(d);return f?vt(l,d,f):null},statement:async d=>{const l=t,f=d,[b,k]=await Promise.all([l.read.statement(f,{from:0,to:e.now()+ee}),l.read.balance(f)]);return{account:d,label:dr(d),balance:V(k),currency:J(f)==="USD"?"USD":"CREDIT",entries:b.entries.map(_=>({txnId:_.txnId,credits:V(_.amount),at:_.postedAt}))}},lineage:async d=>{const l=t,f=[];for await(const b of l.read.lineage(d)){const k=b.legs.filter(_=>_.account===d).reduce((_,R)=>_+V(R.amount),0);f.push({txnId:b.txnId,prevHash:b.prevHash,hash:b.hash,credits:k})}return f},checkpoint:async()=>{const d=await t.read.checkpoint();return d===null?null:{root:d.root,signature:d.signature,count:d.count,at:d.at,v:d.v}},find:async d=>{const l=t,f=d.trim();if(f==="")return null;if(f.startsWith("txn_"))return await l.read.posting(f)?{kind:"txn",txnId:f}:null;if(f.includes(":")){let R=null,P=0;for await(const Y of l.read.lineage(f))if(R=Y.txnId,P++>=Lt)break;return R?{kind:"account",account:f,txnId:R}:null}const b=Mf(f),k=await l.read.checkpoint();if(k){if(b(k.root))return{kind:"checkpoint",field:"root",checkpoint:k};if(b(k.signature))return{kind:"checkpoint",field:"signature",checkpoint:k}}if(!f.includes("â¦")&&!f.includes("...")){const R=await zo(l.read,f,{scanMax:Lt});return R?{kind:"link",txnId:R.link.txnId,account:R.account,field:R.field}:null}let _=0;for await(const R of l.read.accounts())for await(const P of l.read.lineage(R)){if(_++>=Lt)return null;if(b(P.hash))return{kind:"link",txnId:P.txnId,account:R,field:"hash"};if(P.prevHash!==me&&b(P.prevHash))return{kind:"link",txnId:P.txnId,account:R,field:"prevHash"}}return null},pipeline:()=>({delivered:c}),runRelay:()=>y(async()=>{const d=[],l=async k=>{d.push({id:k.id,type:k.type,subject:k.subject,at:k.occurredAt,audience:k.audience})},b=(await n.sweep({only:["relay"],dispatcher:l,limit:100})).batch.relay;if(!b.ok)throw p(h.STORE_FAILURE,`Relay failed: ${b.code}.`);return c=[...d,...c].slice(0,50),{relayed:b.summary.relayed.length,failed:b.summary.failed.length,deadLettered:b.summary.deadLettered.length}}),postWebhook:({eventId:d,userId:l,credits:f})=>y(async()=>{const b={provider:"console",eventId:d,kind:"purchase",userId:l,amount:pe(f),source:"card"},k=await El(r,{ids:Qe,clock:e},b),R=(await n.sweep({only:["drainInbox"],limit:100})).batch.drainInbox;return L(),{status:k.status,applied:R.ok&&R.summary.applied.length>0}}),httpFetch:d=>y(async()=>{const l=new URL(d.url);l.pathname=l.pathname.replace(/^\/console/,"");const f=await Ol({economy:t,ports:C,authenticate:!1})(new Request(l,d));return L(),f}),status:async()=>{const d=t.read.status();return{maintenanceActive:d.maintenanceActive,pauseStart:d.pauseStart,pauseEnd:d.pauseEnd,resumesAt:d.resumesAt}},advanceTime:d=>{e.advance(d),L()},now:()=>e.now(),settings:()=>({faultMode:s,maturityHorizonDays:o,maxPayoutAttempts:a,velocityLimitCredits:Number(C.config.velocityLimitMinor)/100,maintenancePaused:t.read.status().maintenanceActive,payoutMinimumCredits:Number(C.config.payoutMinimumEarnedMinor)/100,payoutIntervalDays:C.config.payoutMinIntervalMs/ee,now:e.now()}),setFault:d=>{s=d},setMaturityDays:d=>y(async()=>{o=Math.max(0,Math.round(d)),ge({maturityHorizonMs:{default:o*ee}})}),setMaxAttempts:d=>y(async()=>{a=Math.max(1,Math.round(d)),ge({maxPayoutAttempts:a})}),setVelocityLimit:d=>y(async()=>{ge({velocityLimitMinor:BigInt(Math.max(0,Math.round(d*100)))})}),rateBoard:async()=>{const d=t,l=mr(C.rates.buy("CREDIT")),f=mr(C.rates.par("CREDIT")),b=await yr(d);return{buyPerThousand:l,parPerThousand:f,payoutPerThousand:f,spreadPerThousand:l-f,locked:!ce,inFlightPayouts:b,maintenanceActive:t.read.status().maintenanceActive,parFloor:Ut,parCeil:xt,maxSpreadMultiple:$t}},unlockRates:()=>y(async()=>{const l=await yr(t);return l>0?{ok:!1,message:`Cannot reprice with ${l} payout${l===1?"":"s"} in flight â settle or reverse them first, so none settles at the new rate.`}:(ge({pauseStartMs:e.now(),pauseEndMs:e.now()+ee}),ce=!0,L(),{ok:!0,message:"Rate desk unlocked and everyday writes paused. Set the new rates, then re-lock to resume."})}),setRates:({buyPerThousand:d,parPerThousand:l})=>
74{if(!ce)return{ok:!1,message:"The rate desk is locked. Unlock it first."};if(!Number.isFinite(d)||!Number.isFinite(l)||d<=0||l<=0)return{ok:!1,message:"Both rates must be positive numbers."};if(l<Ut||l>xt)return{ok:!1,message:`The redemption rate must be between $${Ut.toFixed(2)} and $${xt.toFixed(2)} per 1,000 credits.`};if(d<l)return{ok:!1,message:"The buy rate cannot fall below the redemption rate."};if(d>l*$t)return{ok:!1,message:`The buy rate cannot exceed ${$t}à the redemption rate.`};const f=hr(d),b=hr(l);return ie={...ie,buyRate:f.rate,buyScale:f.scale,parRate:b.rate,parScale:b.scale,payoutRate:b.rate,payoutScale:b.scale},C={...C,rates:qe(ie)},It(),L(),{ok:!0,message:`Rates set â buy $${d.toFixed(2)}, redemption $${l.toFixed(2)} per 1,000 credits. Re-lock to resume.`}},lockRates:()=>y(async()=>(ce=!1,ge({pauseStartMs:null,pauseEndMs:null}),{ok:!0,message:"Rate desk locked and everyday writes resumed."})),setMaintenance:d=>y(async()=>{ge({pauseStartMs:d?e.now():null,pauseEndMs:d?e.now()+ee:null})}),setPayoutMinimum:d=>y(async()=>{ge({payoutMinimumEarnedMinor:BigInt(Math.max(0,Math.round(d*100)))})}),setPayoutIntervalDays:d=>y(async()=>{ge({payoutMinIntervalMs:Math.max(0,Math.round(d))*ee})}),reset:()=>y(async()=>{s=!1,o=0,a=5,kt=0,L(),await _e(),await On()}),clear:()=>y(async()=>{s=!1,o=0,a=5,kt=0,L(),await _e()}),runJobs:()=>y(async()=>{const{batch:d}=await Fs();L();const l=[];for(const[f,b]of Object.entries(d)){if(!b.ok){l.push(`${f}: error`);continue}const k=b.summary,_=Object.values(k).filter(Array.isArray).reduce((R,P)=>R+P.length,0);_>0&&l.push(`${f} ${_}`)}return l.length?l.join(" · "):"no due items"}),close:()=>t.close()};return await _e(),await On(),T}const Us="elab_journal",Of=2;function Tf(e){return JSON.parse(e,(t,n)=>n!==null&&typeof n=="object"&&"$bigint"in n?BigInt(n.$bigint):n)}function Df(e){return typeof e=="object"&&e!==null&&typeof e.kind=="string"&&typeof e.idempotencyKey=="string"}function Nf(){let e=null;try{e=localStorage.getItem(Us)}catch{return[]}if(e===null)return[];try{const t=Tf(e);return t.v!==Of||!Array.isArray(t.entries)||!t.entries.every(Df)?(Jt(),[]):t.entries}catch{return Jt(),[]}}function Jt(){try{localStorage.removeItem(Us)}catch{}}async function Pf(e,t){for(const n of t)try{await e.economy.submit(n)}catch{}return e}function Cf(){try{return new URLSearchParams(location.search).get("from")==="docs"}catch{return!1}}async function Lf(e){try{await Pf(e,Nf())}catch{Jt()}return e}let at=null;function xf(){if(at===null){const e=Cf()?wr().then(Lf):wr();e.catch(()=>{at=null}),at=e}return at}export{me as G,lr as P,Jt as c,xf as g};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.