@oracle-agent/oracle 0.28.27 → 0.28.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -3
- package/SETUP.md +3 -0
- package/dist/assets/skills/bankrbot/SKILL.md +24 -0
- package/dist/assets/skills/oracle-agentic-crypto/SKILL.md +39 -0
- package/dist/assets/skills/oracle-chain-graphs-telegram-cards/SKILL.md +2 -0
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/assets/skills/oracle-uniswap-v4-hooks/SKILL.md +31 -0
- package/dist/assets/skills/oracle-x402/SKILL.md +30 -0
- package/dist/bin/desk-server.mjs +28 -26
- package/dist/bin/oracle-data-mcp.mjs +32 -12
- package/dist/bin/oracle-gateway.mjs +39 -26
- package/dist/bin/oracle-mev-arb-shadow.mjs +5 -5
- package/dist/bin/oracle-mev-shadow.mjs +5 -5
- package/dist/bin/oracle-public-server.mjs +4 -4
- package/dist/bin/oracle-route.mjs +15 -15
- package/dist/bin/oracle-scan.mjs +11 -11
- package/dist/bin/oracle.mjs +4 -3
- package/dist/cli/commands/auth.mjs +6 -6
- package/dist/cli/commands/chat.mjs +155 -155
- package/dist/cli/commands/doctor.mjs +1 -1
- package/dist/cli/commands/eval.mjs +77 -77
- package/dist/cli/commands/harness.mjs +4 -4
- package/dist/cli/commands/model.mjs +157 -157
- package/dist/cli/commands/receipt.mjs +1 -1
- package/dist/cli/commands/setup.mjs +23 -23
- package/dist/cli/commands/signer.mjs +8 -8
- package/dist/cli/commands/snipe.mjs +24 -0
- package/dist/cli/commands/swap.mjs +25 -25
- package/dist/cli/commands/venues.mjs +1 -1
- package/dist/control/approval-binding.mjs +1 -0
- package/dist/control/finality.mjs +1 -0
- package/dist/control-plane/index.mjs +6 -0
- package/dist/data/desk-data.mjs +26 -24
- package/dist/governance-prepare.mjs +2 -0
- package/dist/index.mjs +44 -31
- package/dist/local-marketplace.mjs +3 -0
- package/dist/local-pack-registry.mjs +3 -0
- package/dist/local-signer/index.mjs +3 -3
- package/dist/local-signer/runtime.mjs +8 -8
- package/dist/local-x402.mjs +3 -0
- package/dist/nft/index.mjs +1 -1
- package/dist/notifications/index.mjs +3 -0
- package/dist/position-health.mjs +2 -0
- package/dist/router/index.mjs +2 -2
- package/dist/router/prepare-bridge.mjs +2 -2
- package/dist/safety-intelligence.mjs +1 -0
- package/dist/scanner/index.mjs +3 -3
- package/dist/task.d.mts +130 -0
- package/dist/task.mjs +2 -0
- package/dist/tax-lots.mjs +5 -0
- package/dist/tenant-rbac.mjs +1 -0
- package/dist/workflow-telemetry.mjs +1 -0
- package/package.json +17 -2
- package/public/agent-connect/index.html +2 -2
- package/public/install.sh +2 -2
- package/public/oracle-splash/index.html +2 -2
- package/public/oracle-splash/install.sh +2 -2
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import st from"node:path";import{homedir as It}from"node:os";import{createHash as Ot,randomUUID as Tt}from"node:crypto";import i from"node:fs";import V from"node:path";import{createHash as ct,randomUUID as v}from"node:crypto";var M=1,w=class extends Error{constructor(e,n="DURABLE_STORE_ERROR"){super(e),this.name="DurableStoreError",this.code=n}};function C(t){if(t===null)return"null";if(typeof t=="string"||typeof t=="boolean")return JSON.stringify(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError("durable store values must contain finite numbers");return JSON.stringify(t)}if(Array.isArray(t))return`[${t.map(C).join(",")}]`;if(t&&typeof t=="object")return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${C(t[n])}`).join(",")}}`;throw new TypeError(`durable store values must be JSON-safe, got ${typeof t}`)}function tt(t){return ct("sha256").update(C(t)).digest("hex")}function k(t){let e=t(),n=e instanceof Date?e.getTime():typeof e=="string"?Date.parse(e):Number(e);if(!Number.isFinite(n))throw new TypeError("clock must return epoch milliseconds, an ISO string, or a Date");return Math.trunc(n)}function P(t){return t===void 0?void 0:JSON.parse(JSON.stringify(t))}function et(t){i.mkdirSync(t,{recursive:!0,mode:448});try{i.chmodSync(t,448)}catch{}}function X(t){try{let e=i.statSync(t);return{...JSON.parse(i.readFileSync(t,"utf8")),mtimeMs:e.mtimeMs}}catch{return null}}function nt({filePath:t,kind:e,initialData:n,validateData:o,clock:m=()=>Date.now(),maxBytes:l=4*1024*1024,lockStaleMs:N=3e4,lockWaitMs:_=2e3,lockIdFactory:J=()=>v()}={}){if(typeof t!="string"||t==="")throw new TypeError("filePath is required");if(!/^[a-z][a-z0-9._-]{0,63}$/i.test(String(e)))throw new TypeError("a bounded store kind is required");if(typeof n!="function"||typeof o!="function")throw new TypeError("initialData and validateData are required");if(!Number.isSafeInteger(l)||l<1024)throw new TypeError("maxBytes must be at least 1024");if(!Number.isSafeInteger(N)||N<1e3)throw new TypeError("lockStaleMs must be at least 1000");if(!Number.isSafeInteger(_)||_<0||_>3e4)throw new TypeError("lockWaitMs must be between 0 and 30000");let a=`${t}.lock`;function T(){let s=n();return o(s),{schemaVersion:M,kind:e,generation:0,data:s}}function E(s){let c;try{c=JSON.parse(s)}catch(d){throw new w(`corrupt ${e} snapshot: invalid JSON (${d.message})`,"STORE_CORRUPT")}if(!c||typeof c!="object"||Array.isArray(c))throw new w(`corrupt ${e} snapshot: root must be an object`,"STORE_CORRUPT");if(c.schemaVersion!==M)throw new w(`unsupported ${e} schemaVersion ${String(c.schemaVersion)}`,"STORE_SCHEMA");if(c.kind!==e||!Number.isSafeInteger(c.generation)||c.generation<0)throw new w(`corrupt ${e} snapshot metadata`,"STORE_CORRUPT");let{integrity:f,...p}=c;if(typeof f!="string"||!/^[a-f0-9]{64}$/.test(f)||tt(p)!==f)throw new w(`corrupt ${e} snapshot: checksum mismatch`,"STORE_CORRUPT");try{o(c.data)}catch(d){throw new w(`corrupt ${e} snapshot: ${d.message}`,"STORE_CORRUPT")}return p}function A(){if(!i.existsSync(t))return T();let s=i.statSync(t);if(!s.isFile()||s.size>l)throw new w(`${e} snapshot is not a bounded regular file`,"STORE_BOUNDS");try{i.chmodSync(t,384)}catch{}return E(i.readFileSync(t,"utf8"))}function b(){et(V.dirname(t));let s=k(m),c=String(J()),f=`${JSON.stringify({schemaVersion:1,lockId:c,pid:process.pid,acquiredAt:s})}
|
|
2
|
+
`,p=()=>{let O;try{return O=i.openSync(a,"wx",384),i.writeFileSync(O,f,"utf8"),i.fsyncSync(O),i.closeSync(O),{lockId:c}}catch(H){let $=O!==void 0;if($)try{i.closeSync(O)}catch{}if($)try{i.unlinkSync(a)}catch{}if(H?.code!=="EEXIST")throw H;return null}},u=k(m)+_,I=new Int32Array(new SharedArrayBuffer(4));for(;;){let O=p();if(O)return O;let H=k(m),$=X(a),B=!1;if($){let j=H-Number($.acquiredAt??$.mtimeMs);B=Number.isFinite(j)&&j>=N}else try{B=H-i.statSync(a).mtimeMs>=N}catch{B=!1}if(B){let j=X(a);if($?j?.lockId===$.lockId:j===null){try{i.unlinkSync(a)}catch(Q){if(Q?.code!=="ENOENT")throw Q}continue}}let W=u-H;if(W<=0)throw new w(`${e} store is busy`,"STORE_BUSY");Atomics.wait(I,0,0,Math.min(10,W))}}function g(s){if(X(a)?.lockId===s.lockId)try{i.unlinkSync(a)}catch(f){if(f?.code!=="ENOENT")throw f}}function S(s){o(s.data);let c={...s,integrity:tt(s)},f=`${C(c)}
|
|
3
|
+
`;if(Buffer.byteLength(f)>l)throw new w(`${e} snapshot exceeds ${l} bytes`,"STORE_BOUNDS");let p=V.dirname(t);et(p);let d=V.join(p,`.${V.basename(t)}.${process.pid}.${v()}.tmp`),u;try{u=i.openSync(d,"wx",384),i.writeFileSync(u,f,"utf8"),i.fsyncSync(u),i.closeSync(u),u=void 0,i.renameSync(d,t);try{i.chmodSync(t,384)}catch{}try{let I=i.openSync(p,"r");try{i.fsyncSync(I)}finally{i.closeSync(I)}}catch{}}finally{if(u!==void 0)try{i.closeSync(u)}catch{}try{i.unlinkSync(d)}catch(I){if(I?.code!=="ENOENT")throw I}}}function y(){return P(A().data)}function h(){let s=A();return{schemaVersion:s.schemaVersion,kind:s.kind,generation:s.generation,data:P(s.data)}}function D(s){if(typeof s!="function")throw new TypeError("mutator must be a function");let c=b();try{let f=A(),p=P(f.data),d=s(p,{generation:f.generation,now:k(m)});return o(p),S({schemaVersion:M,kind:e,generation:f.generation+1,data:p}),P(d)}finally{g(c)}}return Object.freeze({filePath:t,read:y,inspect:h,mutate:D})}import{wordlists as ut}from"ethers";var ft=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),dt=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],pt=new Set([12,15,18,21,24]);function mt(t){let e=String(t).trim().toLowerCase().split(/\s+/).filter(Boolean);return pt.has(e.length)&&e.every(n=>ut.en.getWordIndex(n)>=0)}var yt=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,lt=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,ht=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);function bt(t){let e=rt(t);return ht.has(e)||lt.test(e)}var L=class extends Error{constructor(e){super(`action receipt refused: secret-bearing field at ${e}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}};function rt(t){return String(t).replace(/[^a-z0-9]/gi,"").toLowerCase()}function gt(t){let e=rt(t);return[...ft].some(n=>e.includes(n))}function St(t,e,n){if(typeof e=="string"){if(dt.some(o=>o.test(e))||mt(e))throw new L(n);if(yt.test(e)&&!bt(t))throw new L(n)}}function G(t,e="$",n=""){if(t==null||typeof t=="boolean")return t;if(typeof t=="string")return St(n,t,e),t;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`action receipt: non-finite number at ${e}`);return t}if(typeof t=="bigint")return t.toString();if(Array.isArray(t))return t.map((m,l)=>G(m,`${e}[${l}]`,n));if(typeof t!="object"||Object.getPrototypeOf(t)!==Object.prototype)throw new TypeError(`action receipt: JSON-like value required at ${e}`);let o={};for(let m of Object.keys(t).sort()){let l=`${e}.${m}`;if(gt(m))throw new L(l);t[m]!==void 0&&(o[m]=G(t[m],l,m))}return o}function ot(t){return G(t)}var q=1,it="Oracle local x402 budget. Armed for the owner-local signer. Pay requires an explicit instruction. Not Telegram A2A.",Gt=Object.freeze(["open","cancelled","armed","submitted"]),Et=/^(?:0|[1-9][0-9]*)$/,At=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,wt=/^0x[a-fA-F0-9]{40}$/,xt=/^0x[a-fA-F0-9]{64}$/,Nt=/[\u0000-\u001f\u007f]/,Z=class extends Error{constructor(e,n="LOCAL_X402_INVALID"){super(`local-x402: ${e}`),this.name="LocalX402Error",this.code=n}};function r(t,e){throw new Z(t,e)}function F(t){if(t&&typeof t=="object"&&!Object.isFrozen(t)){for(let e of Object.values(t))F(e);Object.freeze(t)}return t}function U(t,e,{max:n=256}={}){typeof t!="string"&&r(`${e} must be a string`);let o=t.trim();return(!o||o.length>n||Nt.test(o))&&r(`${e} is invalid`),o}function x(t,e){let n=U(t,e,{max:128});return At.test(n)||r(`${e} must be a bounded id`),n}function z(t,e,{positive:n=!1}={}){typeof t=="number"&&r(`${e} must be an exact integer string`);let o=typeof t=="bigint"?t.toString():String(t??"");return Et.test(o)||r(`${e} must be a canonical integer string`),n&&o==="0"&&r(`${e} must be positive`),o}function R(t,e){let n=U(t,e,{max:42}).toLowerCase();return wt.test(n)||r(`${e} must be a 20-byte EVM address`),n}function $t(t){let e=U(t,"resource",{max:2048}),n;try{n=new URL(e)}catch{r("resource must be an https URL")}return n.protocol!=="https:"&&r("resource must be https"),(n.username||n.password)&&r("resource must not contain credentials"),n.toString()}function at(t,e){return(!t||typeof t!="object"||Array.isArray(t)||Object.getPrototypeOf(t)!==Object.prototype)&&r(`${e} must be a plain object`),t}function Rt(t){let e=t(),n=e instanceof Date?e.getTime():typeof e=="string"?Date.parse(e):Number(e);return(!Number.isSafeInteger(n)||n<0)&&r("clock must return a safe integer millisecond timestamp","CLOCK_INVALID"),n}function _t(t){return new Date(t).toISOString()}function Ht(t=process.env){let e=t.ORACLE_CONFIG_DIR||st.join(It(),".config","oracle");return st.join(e,"local-x402.v1.json")}function K(t){let e=t.status==="submitted";return F({schemaVersion:q,intentId:t.intentId,tenantId:t.tenantId,payer:t.payer,payTo:t.payTo,resource:t.resource,amount:t.amount,maxBudget:t.maxBudget,asset:t.asset,chainId:t.chainId,status:t.status,createdAt:t.createdAt,intentHash:t.intentHash,transactionHash:t.transactionHash||null,label:it,custody:"none",execution:e?"local-signer-instructed":"armed-local",armed:!e,signed:e,broadcast:e,telegram:!1,pluginExecution:!1})}function Ct(t){(!t||t.schemaVersion!==q||!Array.isArray(t.intents))&&r("invalid x402 snapshot","STORE_INVALID"),t.intents.length>1e4&&r("x402 capacity exceeded","STORE_LIMIT")}function Y(t){return F({schemaVersion:q,recordType:"local-x402-armed",intentId:t.intentId,tenantId:t.tenantId,payer:t.payer,payTo:t.payTo,resource:t.resource,amount:t.amount,asset:t.asset,chainId:t.chainId,intentHash:t.intentHash,unsigned:{kind:"local-x402-pay",from:t.payer,to:t.payTo,amount:t.amount,asset:t.asset,chainId:t.chainId,resource:t.resource},review:`Oracle local x402 ${t.intentId} is armed: pay ${t.amount} ${t.asset} to ${t.payTo} for ${t.resource}. Sign and broadcast still require an explicit instruction.`,label:it,custody:"none",execution:"armed-local",armed:!0,signed:!1,broadcast:!1,requiresWalletSignature:!0,backendSigner:!1,refusesSignHash:!0,telegram:!1})}function Dt(t,e){typeof t=="string"&&r("raw hash artifacts are refused; pass a typed local-signer artifact","SIGNHASH_REFUSED");let n=at(t,"instruction.artifact");(Object.prototype.hasOwnProperty.call(n,"signHash")||Object.prototype.hasOwnProperty.call(n,"hashToSign"))&&r("generic signHash is refused","SIGNHASH_REFUSED");let o=R(n.from??e.payer,"artifact.from"),m=R(n.to??e.payTo,"artifact.to"),l=z(n.amount??e.amount,"artifact.amount",{positive:!0});o!==e.payer&&r("artifact.from must match payer","ARTIFACT_MISMATCH"),m!==e.payTo&&r("artifact.to must match payTo","ARTIFACT_MISMATCH"),l!==e.amount&&r("artifact.amount must match the armed intent","ARTIFACT_MISMATCH");let N=BigInt(e.maxBudget);return BigInt(l)>N&&r("amount exceeds maxBudget","BUDGET"),n}function jt(t,e){if(t==null)return{action:"arm"};let n=at(t,"instruction");Object.prototype.hasOwnProperty.call(n,"signHash")&&n.signHash!==!1&&r("generic signHash is refused","SIGNHASH_REFUSED");let o=U(n.action??"arm","instruction.action",{max:64});return o==="arm"?{action:"arm"}:(o==="prepare"&&r("prepare is refused; arm the payment, then instruct sign-and-broadcast","INSTRUCTION_INVALID"),o!=="sign-and-broadcast"&&r("instruction.action must be arm or sign-and-broadcast","INSTRUCTION_INVALID"),(n.confirm!==!0||n.sign!==!0||n.broadcast!==!0)&&r("sign-and-broadcast requires confirm, sign, and broadcast all true","INSTRUCTION_INVALID"),n.intentHash&&n.intentHash!==e.intentHash&&r("instruction.intentHash must match","ARTIFACT_MISMATCH"),n)}function Kt({filePath:t=Ht(),clock:e=()=>Date.now(),idFactory:n=()=>Tt()}={}){let o=nt({filePath:t,kind:"oracle-local-x402",clock:e,maxBytes:4194304,initialData:()=>({schemaVersion:q,intents:[]}),validateData:Ct});function m(a={}){ot(a);let T=x(a.tenantId,"tenantId"),E=R(a.payer,"payer"),A=R(a.payTo,"payTo"),b=$t(a.resource),g=z(a.amount,"amount",{positive:!0}),S=z(a.maxBudget??g,"maxBudget",{positive:!0});BigInt(g)>BigInt(S)&&r("amount exceeds maxBudget","BUDGET");let y=U(a.asset??"USDC","asset",{max:32}),h=z(a.chainId,"chainId",{positive:!0}),D=Rt(e),s=x(String(a.intentId??`x402-${n()}`),"intentId");return o.mutate(c=>{c.intents.some(d=>d.intentId===s)&&r("intentId already exists","DUPLICATE");let f={intentId:s,tenantId:T,payer:E,payTo:A,resource:b,amount:g,maxBudget:S,asset:y,chainId:h,status:"open",createdAt:_t(D),custody:"none",execution:"armed-local"},p={...f,intentHash:Ot("sha256").update(C(f),"utf8").digest("hex")};return c.intents.push(p),K(p)})}function l({tenantId:a}={}){let T=x(a,"tenantId");return F(o.read().intents.filter(E=>E.tenantId===T).map(K))}function N({tenantId:a,intentId:T,actor:E}={}){let A=x(a,"tenantId"),b=x(T,"intentId"),g=R(E,"actor");return o.mutate(S=>{let y=S.intents.find(h=>h.tenantId===A&&h.intentId===b);return y||r("intent not found","NOT_FOUND"),y.payer!==g&&r("only the payer can cancel","FORBIDDEN"),y.status!=="open"&&r("intent is not open","NOT_OPEN"),y.status="cancelled",K(y)})}function _({tenantId:a,intentId:T,actor:E}={}){let A=x(a,"tenantId"),b=x(T,"intentId"),g=R(E,"actor");return o.mutate(S=>{let y=S.intents.find(h=>h.tenantId===A&&h.intentId===b);return y||r("intent not found","NOT_FOUND"),y.payer!==g&&r("only the payer can arm","FORBIDDEN"),["open","armed"].includes(y.status)||r("intent is not open","NOT_OPEN"),y.status="armed",Y(y)})}async function J({tenantId:a,intentId:T,actor:E,instruction:A,executor:b}={}){let g=x(a,"tenantId"),S=x(T,"intentId"),y=R(E,"actor"),h=o.mutate(d=>{let u=d.intents.find(O=>O.tenantId===g&&O.intentId===S);u||r("intent not found","NOT_FOUND"),u.payer!==y&&r("only the payer can instruct pay","FORBIDDEN"),["open","armed"].includes(u.status)||r("intent is not open","NOT_OPEN");let I=jt(A,u);return u.status="armed",{armed:Y(u),instruction:I}});if(h.instruction.action==="arm")return h.armed;let D=o.read().intents.find(d=>d.tenantId===g&&d.intentId===S),s=Dt(h.instruction.artifact,D);(!b||typeof b.executeConfirmedArtifact!="function")&&r("sign-and-broadcast requires an injected local-signer executor","EXECUTOR_REQUIRED"),typeof b.signHash=="function"&&r("generic signHash executors are refused","SIGNHASH_REFUSED");let c=await b.executeConfirmedArtifact(s,h.instruction.nonce,b),f=c?.receipt?.transactionHash??c?.transactionHash;(typeof f!="string"||!xt.test(f))&&r("local-signer receipt must include a 32-byte transaction hash","RECEIPT_INVALID");let p=c?.receipt?.status??c?.status;return p!==1&&p!=="0x1"&&r("local-signer broadcast did not return a successful receipt","RECEIPT_INVALID"),o.mutate(d=>{let u=d.intents.find(I=>I.tenantId===g&&I.intentId===S);return(!u||u.status!=="armed")&&r("intent is not armed","NOT_OPEN"),u.status="submitted",u.transactionHash=f.toLowerCase(),F({...Y(u),recordType:"local-x402-submitted",execution:"local-signer-instructed",armed:!1,signed:!0,broadcast:!0,backendSigner:!0,requiresWalletSignature:!1,transactionHash:u.transactionHash,review:`Oracle local x402 ${u.intentId} signed and broadcast. transactionHash=${u.transactionHash}`})})}return Object.freeze({createIntent:m,listIntents:l,cancelIntent:N,armPayment:_,instructPay:J})}export{it as LOCAL_X402_LABEL,Gt as LOCAL_X402_STATES,q as LOCAL_X402_VERSION,Z as LocalX402Error,Kt as createLocalX402};
|
package/dist/nft/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function re(t,e="value"){if(typeof t=="number"){if(!Number.isFinite(t))throw new Error(`${e} must be a finite number`);if(Math.abs(t)>Number.MAX_SAFE_INTEGER)throw new Error(`${e} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new Error(`${e} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return String(t)}if(typeof t=="string"){if(t!==t.trim())throw new Error(`${e} must be a number or decimal string`);return t}throw new Error(`${e} must be a number or decimal string`)}function M(t,e="amount"){if(typeof t=="bigint")return t;if(typeof t=="number"){if(!Number.isInteger(t))throw new Error(`${e} must be an integer`);if(!Number.isSafeInteger(t))throw new Error(`${e} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(t)}let r=re(t,e);if(r==="")throw new Error(`${e} is required`);if(!/^-?\d+$/.test(r)&&!/^0x[0-9a-fA-F]+$/.test(r))throw new Error(`${e} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(r)}`);try{return BigInt(r)}catch{throw new Error(`${e} must be an integer, got ${JSON.stringify(r)}`)}}var _=1,o=Object.freeze({BUY:"BUY",PASS:"PASS",NO_TRADE:"NO_TRADE"}),j=Object.freeze(["reveal","repriced","reprice","price_drop","relisted"]),F=10000n,G=Object.freeze({minTraitSales:3,minTraitVolumeWei:"1000000000000000000",minVolumeCoverage:3,minEdgeBps:1200,minEdgeBpsWithoutEvent:2e3,maxPremiumOverCollectionFloorBps:5e3,maxListingAgeMs:900*1e3,maxEventAgeMs:1800*1e3,maxMarketDataAgeMs:3600*1e3,maxTraitWindowHours:72,marketplaceFeeBps:250,royaltyBps:500,maxSpendWei:null});function P(t,e,r,{positive:i=!0,allowZero:p=!1}={}){if(t==null||t==="")return r.push(`${e}: missing`),null;let n;try{n=M(t,e)}catch(a){return r.push(`${e}: ${String(a?.message||a)}`),null}return n<0n?(r.push(`${e}: must not be negative`),null):i&&!p&&n===0n?(r.push(`${e}: must be positive`),null):n}function ie(t,e,r){if(t==null||t==="")return r.push(`${e}: missing`),null;let i=Number(t);return!Number.isInteger(i)||i<0?(r.push(`${e}: must be a non-negative integer`),null):i}function x(t){let e=Number(t);return Number.isFinite(e)?e:null}function u(...t){for(let e of t)if(e!=null&&e!=="")return e;return null}function C(t,e){return e==null||e===0n?null:Number(t*F/e)}function ne(t){let e=x(u(t?.rarityPct,t?.rarity_pct));if(e!=null&&e>0)return Math.round(e*100);let r=x(u(t?.traitSupply,t?.supply,t?.count)),i=x(u(t?.collectionSupply,t?.totalSupply));return r!=null&&i!=null&&r>0&&i>0?Math.round(r/i*1e4):null}function oe(t={}){let e={...G,...t||{}},r=Number(e.marketplaceFeeBps)||0,i=Number(e.royaltyBps)||0;if(r<0||i<0||r+i>=1e4)throw new Error("trait sniper: marketplaceFeeBps + royaltyBps must be >= 0 and < 10000");return e}function d(t,e,r,i={}){return{ok:t===o.BUY,decision:t,failureKind:e,reasons:r,version:_,executed:!1,signed:!1,broadcast:!1,requiresUserSignature:!0,...i}}function U(t={}){let e;try{e=oe(t.policy)}catch(w){return d(o.NO_TRADE,"bad-policy",[String(w?.message||w)])}let r=Number.isFinite(Number(t.nowMs))?Number(t.nowMs):Date.now(),i=t.listing||{},p=t.trait||{},n=t.traitMarket||t.traitStats||{},a=t.collectionMarket||t.collection||{},c={chainId:x(u(t.chainId,i.chainId))??null,contract:String(u(t.contract,t.collectionAddress,i.contract,"")||"")||null,tokenId:String(u(i.tokenId,t.tokenId,"")||"")||null,marketplace:String(u(i.marketplace,i.source,"")||"")||null,trait:{type:String(u(p.type,p.traitType,"")||"")||null,value:String(u(p.value,p.traitValue,"")||"")||null,rarityBps:ne(p)}},l=[],s=P(u(i.priceWei,i.price),"listing.priceWei",l),h=P(u(n.floorPriceWei,n.floorWei),"traitMarket.floorPriceWei",l),y=P(u(n.volumeWei,n.volume),"traitMarket.volumeWei",l,{allowZero:!0}),A=P(u(a.floorPriceWei,a.floorWei),"collectionMarket.floorPriceWei",l),b=ie(u(n.sales,n.salesCount),"traitMarket.sales",l),g=x(u(n.windowHours,n.window_hours));if((g==null||g<=0)&&l.push("traitMarket.windowHours: missing"),l.length)return d(o.NO_TRADE,"insufficient-data",[`missing or unusable market data \u2014 ${l.join("; ")}`],{identity:c,dataGaps:l,liquidity:null,edge:null});if(g>e.maxTraitWindowHours)return d(o.NO_TRADE,"window-too-wide",[`trait stats aggregate ${g}h > maxTraitWindowHours ${e.maxTraitWindowHours}h \u2014 not recent liquidity`],{identity:c,dataGaps:[],liquidity:null,edge:null});let T=x(u(n.observedAtMs,n.asOfMs,a.observedAtMs));if(T==null)return d(o.NO_TRADE,"insufficient-data",["missing or unusable market data \u2014 traitMarket.observedAtMs: missing"],{identity:c,dataGaps:["traitMarket.observedAtMs: missing"],liquidity:null,edge:null});let E=r-T;if(E>e.maxMarketDataAgeMs)return d(o.NO_TRADE,"stale-market-data",[`market snapshot is ${E}ms old > maxMarketDataAgeMs ${e.maxMarketDataAgeMs}ms`],{identity:c,marketAgeMs:E,liquidity:null,edge:null});if(i.flagged===!0||i.reported===!0)return d(o.NO_TRADE,"listing-flagged",["listing is flagged/reported by the marketplace \u2014 a cheap flagged token is cheap for a reason"],{identity:c,liquidity:null,edge:null});let z=y>=s*BigInt(Math.max(0,Math.trunc(e.minVolumeCoverage))),R=M(e.minTraitVolumeWei??0,"policy.minTraitVolumeWei"),W={sales:b,minSales:e.minTraitSales,volumeWei:y.toString(),minVolumeWei:R.toString(),windowHours:g,coverageX:s===0n?null:Number(y/s),minCoverageX:e.minVolumeCoverage,illiquid:!1},$=[];if(b<e.minTraitSales&&$.push(`only ${b} trait sale(s) in ${g}h, need ${e.minTraitSales}`),y<R&&$.push(`trait volume ${y} wei below minTraitVolumeWei ${R} wei`),z||$.push(`trait volume ${y} wei does not cover ${e.minVolumeCoverage}x the ${s} wei listing \u2014 no exit depth`),$.length){W.illiquid=!0;let w=c.trait.rarityBps;return w!=null&&w<=100&&$.push(`trait is rare (${w} bps of supply) but rarity is ranking-only \u2014 an unsold rare trait is an illiquid bag, not an edge`),d(o.NO_TRADE,"illiquid-trait",$,{identity:c,liquidity:W,edge:null,marketAgeMs:E})}let O=String(u(t.event?.kind,t.event?.type,i.eventKind,"")||"").toLowerCase(),V=x(u(t.event?.atMs,i.eventAtMs)),v=V==null?null:r-V,N=j.includes(O)&&v!=null&&v>=0&&v<=e.maxEventAgeMs,B=N?e.minEdgeBps:e.minEdgeBpsWithoutEvent,Z=BigInt(Math.trunc(e.marketplaceFeeBps)),Q=BigInt(Math.trunc(e.royaltyBps)),H=h*(F-Z-Q)/F,q=H-s,ee=C(h-s,h),I=C(s-A,A),k=C(q,s),te={listingPriceWei:s.toString(),traitFloorWei:h.toString(),collectionFloorWei:A.toString(),netExitWei:H.toString(),edgeWei:q.toString(),edgeBps:k,requiredEdgeBps:B,discountToTraitFloorBps:ee,premiumToCollectionFloorBps:I,feeBps:e.marketplaceFeeBps,royaltyBps:e.royaltyBps,triggered:N,eventKind:O||null,eventAgeMs:v},S={identity:c,liquidity:W,edge:te,marketAgeMs:E},L=x(u(i.listedAtMs,i.listedAt)),m=L==null?null:r-L;if(i.stale===!0)return d(o.PASS,"listing-stale",["listing is marked stale by the caller"],S);if(m==null)return d(o.NO_TRADE,"insufficient-data",["missing or unusable market data \u2014 listing.listedAtMs: missing"],{...S,dataGaps:["listing.listedAtMs: missing"]});if(m<0)return d(o.NO_TRADE,"listing-in-future",[`listing.listedAtMs is ${-m}ms in the future`],S);if(m>e.maxListingAgeMs)return d(o.PASS,"listing-stale",[`listing is ${m}ms old > maxListingAgeMs ${e.maxListingAgeMs}ms \u2014 the mispricing is not live`],{...S,listingAgeMs:m});if(e.maxSpendWei!=null&&e.maxSpendWei!==""){let w=M(e.maxSpendWei,"policy.maxSpendWei");if(s>w)return d(o.PASS,"spend-cap",[`listing ${s} wei exceeds maxSpendWei ${w} wei`],{...S,listingAgeMs:m})}return s>=h?d(o.PASS,"no-discount",[`listing ${s} wei is at or above the trait floor ${h} wei`],{...S,listingAgeMs:m}):I!=null&&I>e.maxPremiumOverCollectionFloorBps?d(o.PASS,"collection-floor-premium",[`listing sits ${I} bps over the collection floor > maxPremiumOverCollectionFloorBps ${e.maxPremiumOverCollectionFloorBps} bps`],{...S,listingAgeMs:m}):q<=0n||k==null||k<B?d(o.PASS,"edge-below-threshold",[`net edge ${k??0} bps after ${e.marketplaceFeeBps}+${e.royaltyBps} bps costs is below the ${B} bps required${N?"":" without a reveal/reprice trigger"}`],{...S,listingAgeMs:m}):d(o.BUY,null,[`${b} trait sale(s) and ${y} wei of volume in ${g}h clear the liquidity gate`,`net edge ${k} bps vs trait floor after ${e.marketplaceFeeBps}+${e.royaltyBps} bps costs, required ${B} bps`,N?`${O} event ${v}ms ago explains the mispricing`:"no trigger event \u2014 cleared the higher untriggered bar"],{...S,listingAgeMs:m})}function se(t=[],e={}){if(!Array.isArray(t))throw new TypeError("scanTraitListings: listings array required");let r=t.map((n,a)=>{let c={...e,...n,policy:{...e.policy||{},...n?.policy||{}}},l=U(c);return{index:a,...l}}),i=r.filter(n=>n.decision===o.BUY),p=[...i].sort((n,a)=>{let c=(a.edge?.edgeBps??0)-(n.edge?.edgeBps??0);if(c!==0)return c;let l=n.identity?.trait?.rarityBps??Number.MAX_SAFE_INTEGER,s=a.identity?.trait?.rarityBps??Number.MAX_SAFE_INTEGER;return l!==s?l-s:n.index-a.index});return{evaluated:r,ranked:p,counts:{total:r.length,buy:i.length,pass:r.filter(n=>n.decision===o.PASS).length,noTrade:r.filter(n=>n.decision===o.NO_TRADE).length},executed:!1,signed:!1,broadcast:!1}}import{createHash as ae,createHmac as ce,timingSafeEqual as be}from"node:crypto";var le=2,ue=300*1e3,pe=(()=>{let t=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(t)&&t>0?t:1800*1e3})();function D(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(D).join(",")}]`:`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${D(t[r])}`).join(",")}}`}function Y(t){let e=String(t?.ORACLE_STAMP_HMAC_SECRET||"").trim();return e.length>=16?e:""}function X(t=process.env){return Y(process.env)||Y(t)}function de(t){let{prepareHash:e,prepareMac:r,note:i,...p}=t||{};return p}function me(t){let e=de(t);return ae("sha256").update(D(e)).digest("hex")}function ge(t,e=X()){return e?ce("sha256",e).update(String(t)).digest("hex"):""}function J(t,{provider:e,kind:r,env:i=process.env,nowMs:p=Date.now(),expiresAtMs:n}={}){if(!t||typeof t!="object")throw new Error("stampPrepared: payload object required");let a=Object.prototype.hasOwnProperty.call(t,"oraclePrepared");if(a&&typeof t.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let c={...t,provider:t.provider||e,kind:t.kind||r,requiresUserSignature:t.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:a?t.oraclePrepared:!0};if(!c.provider)throw new Error("stampPrepared: provider required");if(!c.kind)throw new Error("stampPrepared: kind required");let l=Number(p),s=n==null?l+ue:Number(n),h=s-l;if(!Number.isSafeInteger(l)||!Number.isSafeInteger(s)||h<=0||h>pe)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let A={...c,preparedAt:l,expiresAt:s,prepareVersion:le},b=me(A),g=X(i),T=g?ge(b,g):void 0,E={...A,prepareHash:b};return T&&(E.prepareMac=T),E}var fe=/^0x[0-9a-fA-F]{40}$/,he=10000n,f=class extends Error{constructor(e,r){super(e),this.name="TraitSnipePrepareError",this.failureKind=r}};function K(t={}){let e=t.verdict;if(!e||typeof e!="object")throw new f("prepareTraitSnipeCandidate: verdict object required","verdict-required");if(e.decision!==o.BUY||e.ok!==!0)throw new f(`prepareTraitSnipeCandidate: refusing to prepare a ${e.decision||"unknown"} verdict \u2014 only BUY is preparable`,"not-a-buy");if(!e.edge||!e.liquidity||e.liquidity.illiquid===!0)throw new f("prepareTraitSnipeCandidate: verdict is missing its edge/liquidity evidence","evidence-required");let r=String(t.buyer||"").trim();if(!fe.test(r))throw new f("prepareTraitSnipeCandidate: buyer must be a 0x EVM address \u2014 Oracle never derives it from a key","buyer-required");let i=e.identity||{};if(!i.contract||!i.tokenId)throw new f("prepareTraitSnipeCandidate: verdict identity needs contract and tokenId","identity-required");let p=Number(i.chainId);if(!Number.isInteger(p)||p<=0)throw new f("prepareTraitSnipeCandidate: chainId required","chain-required");let n=M(e.edge.listingPriceWei,"listingPriceWei"),a=BigInt(Math.max(0,Math.trunc(Number(t.maxSlippageBps??0))));if(a>1000n)throw new f("prepareTraitSnipeCandidate: maxSlippageBps is capped at 1000","slippage-cap");let c=n+n*a/he;return J({provider:"nft-trait-sniper",kind:"nft-trait-snipe-intent",traitSniperVersion:_,chainId:p,contract:i.contract,tokenId:i.tokenId,marketplace:i.marketplace,trait:i.trait,buyer:r,intent:{action:"nft-buy-listing",chainId:p,contract:i.contract,tokenId:i.tokenId,marketplace:i.marketplace,listingPriceWei:n.toString(),maxPriceWei:c.toString(),maxSlippageBps:Number(a),buyer:r},transaction:null,calldata:null,decision:e.decision,reasons:e.reasons,liquidity:e.liquidity,edge:e.edge,requiresUserSignature:!0,requiresExternalFillRoute:!0,marketplaceContacted:!1,orderSubmitted:!1,note:"Unsigned intent metadata only. Oracle did not contact a marketplace, build fill calldata, sign, or broadcast. A user-controlled client must source the order and the user must sign it."},{provider:"nft-trait-sniper",kind:"nft-trait-snipe-intent"})}function Se(t={},e={}){let r=Array.isArray(t.ranked)?t.ranked[0]:null;return r?{candidate:K({...e,verdict:r}),verdict:r}:{candidate:null,verdict:null}}export{G as DEFAULT_TRAIT_SNIPE_POLICY,o as TRAIT_DECISIONS,_ as TRAIT_SNIPER_VERSION,j as TRIGGER_EVENTS,f as TraitSnipePrepareError,U as evaluateTraitListing,Se as prepareTopTraitSnipe,K as prepareTraitSnipeCandidate,se as scanTraitListings};
|
|
1
|
+
function se(e,t="value"){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${t} must be a finite number`);if(Math.abs(e)>Number.MAX_SAFE_INTEGER)throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return String(e)}if(typeof e=="string"){if(e!==e.trim())throw new Error(`${t} must be a number or decimal string`);return e}throw new Error(`${t} must be a number or decimal string`)}function q(e,t="amount"){if(typeof e=="bigint")return e;if(typeof e=="number"){if(!Number.isInteger(e))throw new Error(`${t} must be an integer`);if(!Number.isSafeInteger(e))throw new Error(`${t} exceeds safe integer precision \u2014 pass it as a decimal string or BigInt so the exact value is preserved`);return BigInt(e)}let r=se(e,t);if(r==="")throw new Error(`${t} is required`);if(!/^-?\d+$/.test(r)&&!/^0x[0-9a-fA-F]+$/.test(r))throw new Error(`${t} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(r)}`);try{return BigInt(r)}catch{throw new Error(`${t} must be an integer, got ${JSON.stringify(r)}`)}}var j=1,c=Object.freeze({BUY:"BUY",PASS:"PASS",NO_TRADE:"NO_TRADE"}),K=Object.freeze(["reveal","repriced","reprice","price_drop","relisted"]),J=10000n,Z=Object.freeze({minTraitSales:3,minTraitVolumeWei:"1000000000000000000",minVolumeCoverage:3,minEdgeBps:1200,minEdgeBpsWithoutEvent:2e3,maxPremiumOverCollectionFloorBps:5e3,maxListingAgeMs:900*1e3,maxEventAgeMs:1800*1e3,maxMarketDataAgeMs:3600*1e3,maxTraitWindowHours:72,marketplaceFeeBps:250,royaltyBps:500,maxSpendWei:null});function U(e,t,r,{positive:n=!0,allowZero:o=!1}={}){if(e==null||e==="")return r.push(`${t}: missing`),null;let i;try{i=q(e,t)}catch(s){return r.push(`${t}: ${String(s?.message||s)}`),null}return i<0n?(r.push(`${t}: must not be negative`),null):n&&!o&&i===0n?(r.push(`${t}: must be positive`),null):i}function ce(e,t,r){if(e==null||e==="")return r.push(`${t}: missing`),null;let n=Number(e);return!Number.isInteger(n)||n<0?(r.push(`${t}: must be a non-negative integer`),null):n}function _(e){let t=Number(e);return Number.isFinite(t)?t:null}function p(...e){for(let t of e)if(t!=null&&t!=="")return t;return null}function Y(e,t){return t==null||t===0n?null:Number(e*J/t)}function le(e){let t=_(p(e?.rarityPct,e?.rarity_pct));if(t!=null&&t>0)return Math.round(t*100);let r=_(p(e?.traitSupply,e?.supply,e?.count)),n=_(p(e?.collectionSupply,e?.totalSupply));return r!=null&&n!=null&&r>0&&n>0?Math.round(r/n*1e4):null}function ue(e={}){let t={...Z,...e||{}},r=Number(t.marketplaceFeeBps)||0,n=Number(t.royaltyBps)||0;if(r<0||n<0||r+n>=1e4)throw new Error("trait sniper: marketplaceFeeBps + royaltyBps must be >= 0 and < 10000");return t}function g(e,t,r,n={}){return{ok:e===c.BUY,decision:e,failureKind:t,reasons:r,version:j,executed:!1,signed:!1,broadcast:!1,requiresUserSignature:!0,...n}}function Q(e={}){let t;try{t=ue(e.policy)}catch(N){return g(c.NO_TRADE,"bad-policy",[String(N?.message||N)])}let r=Number.isFinite(Number(e.nowMs))?Number(e.nowMs):Date.now(),n=e.listing||{},o=e.trait||{},i=e.traitMarket||e.traitStats||{},s=e.collectionMarket||e.collection||{},l={chainId:_(p(e.chainId,n.chainId))??null,contract:String(p(e.contract,e.collectionAddress,n.contract,"")||"")||null,tokenId:String(p(n.tokenId,e.tokenId,"")||"")||null,marketplace:String(p(n.marketplace,n.source,"")||"")||null,trait:{type:String(p(o.type,o.traitType,"")||"")||null,value:String(p(o.value,o.traitValue,"")||"")||null,rarityBps:le(o)}},u=[],a=U(p(n.priceWei,n.price),"listing.priceWei",u),m=U(p(i.floorPriceWei,i.floorWei),"traitMarket.floorPriceWei",u),x=U(p(i.volumeWei,i.volume),"traitMarket.volumeWei",u,{allowZero:!0}),P=U(p(s.floorPriceWei,s.floorWei),"collectionMarket.floorPriceWei",u),M=ce(p(i.sales,i.salesCount),"traitMarket.sales",u),w=_(p(i.windowHours,i.window_hours));if((w==null||w<=0)&&u.push("traitMarket.windowHours: missing"),u.length)return g(c.NO_TRADE,"insufficient-data",[`missing or unusable market data \u2014 ${u.join("; ")}`],{identity:l,dataGaps:u,liquidity:null,edge:null});if(w>t.maxTraitWindowHours)return g(c.NO_TRADE,"window-too-wide",[`trait stats aggregate ${w}h > maxTraitWindowHours ${t.maxTraitWindowHours}h \u2014 not recent liquidity`],{identity:l,dataGaps:[],liquidity:null,edge:null});let $=_(p(i.observedAtMs,i.asOfMs,s.observedAtMs));if($==null)return g(c.NO_TRADE,"insufficient-data",["missing or unusable market data \u2014 traitMarket.observedAtMs: missing"],{identity:l,dataGaps:["traitMarket.observedAtMs: missing"],liquidity:null,edge:null});let y=r-$;if(y>t.maxMarketDataAgeMs)return g(c.NO_TRADE,"stale-market-data",[`market snapshot is ${y}ms old > maxMarketDataAgeMs ${t.maxMarketDataAgeMs}ms`],{identity:l,marketAgeMs:y,liquidity:null,edge:null});if(n.flagged===!0||n.reported===!0)return g(c.NO_TRADE,"listing-flagged",["listing is flagged/reported by the marketplace \u2014 a cheap flagged token is cheap for a reason"],{identity:l,liquidity:null,edge:null});let G=x>=a*BigInt(Math.max(0,Math.trunc(t.minVolumeCoverage))),R=q(t.minTraitVolumeWei??0,"policy.minTraitVolumeWei"),B={sales:M,minSales:t.minTraitSales,volumeWei:x.toString(),minVolumeWei:R.toString(),windowHours:w,coverageX:a===0n?null:Number(x/a),minCoverageX:t.minVolumeCoverage,illiquid:!1},v=[];if(M<t.minTraitSales&&v.push(`only ${M} trait sale(s) in ${w}h, need ${t.minTraitSales}`),x<R&&v.push(`trait volume ${x} wei below minTraitVolumeWei ${R} wei`),G||v.push(`trait volume ${x} wei does not cover ${t.minVolumeCoverage}x the ${a} wei listing \u2014 no exit depth`),v.length){B.illiquid=!0;let N=l.trait.rarityBps;return N!=null&&N<=100&&v.push(`trait is rare (${N} bps of supply) but rarity is ranking-only \u2014 an unsold rare trait is an illiquid bag, not an edge`),g(c.NO_TRADE,"illiquid-trait",v,{identity:l,liquidity:B,edge:null,marketAgeMs:y})}let S=String(p(e.event?.kind,e.event?.type,n.eventKind,"")||"").toLowerCase(),D=_(p(e.event?.atMs,n.eventAtMs)),F=D==null?null:r-D,k=K.includes(S)&&F!=null&&F>=0&&F<=t.maxEventAgeMs,O=k?t.minEdgeBps:t.minEdgeBpsWithoutEvent,L=BigInt(Math.trunc(t.marketplaceFeeBps)),V=BigInt(Math.trunc(t.royaltyBps)),H=m*(J-L-V)/J,C=H-a,X=Y(m-a,m),I=Y(a-P,P),A=Y(C,a),f={listingPriceWei:a.toString(),traitFloorWei:m.toString(),collectionFloorWei:P.toString(),netExitWei:H.toString(),edgeWei:C.toString(),edgeBps:A,requiredEdgeBps:O,discountToTraitFloorBps:X,premiumToCollectionFloorBps:I,feeBps:t.marketplaceFeeBps,royaltyBps:t.royaltyBps,triggered:k,eventKind:S||null,eventAgeMs:F},h={identity:l,liquidity:B,edge:f,marketAgeMs:y},b=_(p(n.listedAtMs,n.listedAt)),d=b==null?null:r-b;if(n.stale===!0)return g(c.PASS,"listing-stale",["listing is marked stale by the caller"],h);if(d==null)return g(c.NO_TRADE,"insufficient-data",["missing or unusable market data \u2014 listing.listedAtMs: missing"],{...h,dataGaps:["listing.listedAtMs: missing"]});if(d<0)return g(c.NO_TRADE,"listing-in-future",[`listing.listedAtMs is ${-d}ms in the future`],h);if(d>t.maxListingAgeMs)return g(c.PASS,"listing-stale",[`listing is ${d}ms old > maxListingAgeMs ${t.maxListingAgeMs}ms \u2014 the mispricing is not live`],{...h,listingAgeMs:d});if(t.maxSpendWei!=null&&t.maxSpendWei!==""){let N=q(t.maxSpendWei,"policy.maxSpendWei");if(a>N)return g(c.PASS,"spend-cap",[`listing ${a} wei exceeds maxSpendWei ${N} wei`],{...h,listingAgeMs:d})}return a>=m?g(c.PASS,"no-discount",[`listing ${a} wei is at or above the trait floor ${m} wei`],{...h,listingAgeMs:d}):I!=null&&I>t.maxPremiumOverCollectionFloorBps?g(c.PASS,"collection-floor-premium",[`listing sits ${I} bps over the collection floor > maxPremiumOverCollectionFloorBps ${t.maxPremiumOverCollectionFloorBps} bps`],{...h,listingAgeMs:d}):C<=0n||A==null||A<O?g(c.PASS,"edge-below-threshold",[`net edge ${A??0} bps after ${t.marketplaceFeeBps}+${t.royaltyBps} bps costs is below the ${O} bps required${k?"":" without a reveal/reprice trigger"}`],{...h,listingAgeMs:d}):g(c.BUY,null,[`${M} trait sale(s) and ${x} wei of volume in ${w}h clear the liquidity gate`,`net edge ${A} bps vs trait floor after ${t.marketplaceFeeBps}+${t.royaltyBps} bps costs, required ${O} bps`,k?`${S} event ${F}ms ago explains the mispricing`:"no trigger event \u2014 cleared the higher untriggered bar"],{...h,listingAgeMs:d})}function de(e=[],t={}){if(!Array.isArray(e))throw new TypeError("scanTraitListings: listings array required");let r=e.map((i,s)=>{let l={...t,...i,policy:{...t.policy||{},...i?.policy||{}}},u=Q(l);return{index:s,...u}}),n=r.filter(i=>i.decision===c.BUY),o=[...n].sort((i,s)=>{let l=(s.edge?.edgeBps??0)-(i.edge?.edgeBps??0);if(l!==0)return l;let u=i.identity?.trait?.rarityBps??Number.MAX_SAFE_INTEGER,a=s.identity?.trait?.rarityBps??Number.MAX_SAFE_INTEGER;return u!==a?u-a:i.index-s.index});return{evaluated:r,ranked:o,counts:{total:r.length,buy:n.length,pass:r.filter(i=>i.decision===c.PASS).length,noTrade:r.filter(i=>i.decision===c.NO_TRADE).length},executed:!1,signed:!1,broadcast:!1}}import{createHash as me,createHmac as pe,timingSafeEqual as Fe}from"node:crypto";var fe=2,ge=300*1e3,he=(()=>{let e=Number(process.env.ORACLE_PREPARE_HARD_MAX_AGE_MS);return Number.isFinite(e)&&e>0?e:1800*1e3})();function z(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(z).join(",")}]`:`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${z(e[r])}`).join(",")}}`}function ee(e){let t=String(e?.ORACLE_STAMP_HMAC_SECRET||"").trim();return t.length>=16?t:""}function te(e=process.env){return ee(process.env)||ee(e)}function we(e){let{prepareHash:t,prepareMac:r,note:n,...o}=e||{};return o}function xe(e){let t=we(e);return me("sha256").update(z(t)).digest("hex")}function Se(e,t=te()){return t?pe("sha256",t).update(String(e)).digest("hex"):""}function re(e,{provider:t,kind:r,env:n=process.env,nowMs:o=Date.now(),expiresAtMs:i}={}){if(!e||typeof e!="object")throw new Error("stampPrepared: payload object required");let s=Object.prototype.hasOwnProperty.call(e,"oraclePrepared");if(s&&typeof e.oraclePrepared!="boolean")throw new Error("stampPrepared: oraclePrepared must be boolean");let l={...e,provider:e.provider||t,kind:e.kind||r,requiresUserSignature:e.requiresUserSignature!==!1,signingReady:!1,broadcastReady:!1,executionReady:!1,oraclePrepared:s?e.oraclePrepared:!0};if(!l.provider)throw new Error("stampPrepared: provider required");if(!l.kind)throw new Error("stampPrepared: kind required");let u=Number(o),a=i==null?u+ge:Number(i),m=a-u;if(!Number.isSafeInteger(u)||!Number.isSafeInteger(a)||m<=0||m>he)throw new Error("stampPrepared: bounded preparedAt/expiresAt required");let P={...l,preparedAt:u,expiresAt:a,prepareVersion:fe},M=xe(P),w=te(n),$=w?Se(M,w):void 0,y={...P,prepareHash:M};return $&&(y.prepareMac=$),y}var ye=/^0x[0-9a-fA-F]{40}$/,be=10000n,E=class extends Error{constructor(t,r){super(t),this.name="TraitSnipePrepareError",this.failureKind=r}};function ne(e={}){let t=e.verdict;if(!t||typeof t!="object")throw new E("prepareTraitSnipeCandidate: verdict object required","verdict-required");if(t.decision!==c.BUY||t.ok!==!0)throw new E(`prepareTraitSnipeCandidate: refusing to prepare a ${t.decision||"unknown"} verdict \u2014 only BUY is preparable`,"not-a-buy");if(!t.edge||!t.liquidity||t.liquidity.illiquid===!0)throw new E("prepareTraitSnipeCandidate: verdict is missing its edge/liquidity evidence","evidence-required");let r=String(e.buyer||"").trim();if(!ye.test(r))throw new E("prepareTraitSnipeCandidate: buyer must be a 0x EVM address \u2014 Oracle never derives it from a key","buyer-required");let n=t.identity||{};if(!n.contract||!n.tokenId)throw new E("prepareTraitSnipeCandidate: verdict identity needs contract and tokenId","identity-required");let o=Number(n.chainId);if(!Number.isInteger(o)||o<=0)throw new E("prepareTraitSnipeCandidate: chainId required","chain-required");let i=q(t.edge.listingPriceWei,"listingPriceWei"),s=BigInt(Math.max(0,Math.trunc(Number(e.maxSlippageBps??0))));if(s>1000n)throw new E("prepareTraitSnipeCandidate: maxSlippageBps is capped at 1000","slippage-cap");let l=i+i*s/be;return re({provider:"nft-trait-sniper",kind:"nft-trait-snipe-intent",traitSniperVersion:j,chainId:o,contract:n.contract,tokenId:n.tokenId,marketplace:n.marketplace,trait:n.trait,buyer:r,intent:{action:"nft-buy-listing",chainId:o,contract:n.contract,tokenId:n.tokenId,marketplace:n.marketplace,listingPriceWei:i.toString(),maxPriceWei:l.toString(),maxSlippageBps:Number(s),buyer:r},transaction:null,calldata:null,decision:t.decision,reasons:t.reasons,liquidity:t.liquidity,edge:t.edge,requiresUserSignature:!0,requiresExternalFillRoute:!0,marketplaceContacted:!1,orderSubmitted:!1,note:"Unsigned intent metadata only. Oracle did not contact a marketplace, build fill calldata, sign, or broadcast. A user-controlled client must source the order and the user must sign it."},{provider:"nft-trait-sniper",kind:"nft-trait-snipe-intent"})}function Ae(e={},t={}){let r=Array.isArray(e.ranked)?e.ranked[0]:null;return r?{candidate:ne({...t,verdict:r}),verdict:r}:{candidate:null,verdict:null}}var Ee=/^0x[0-9a-f]{40}$/,Te=32,Pe=16;function W(e,t){let r=String(e||"").trim().toLowerCase();if(!Ee.test(r)||r==="0x0000000000000000000000000000000000000000")throw new Error(`mint-fanout: valid non-zero ${t} required`);return r}function T(e,t,{allowZero:r=!1}={}){let n=String(e??"").trim();if(!/^(0|[1-9][0-9]*)$/.test(n))throw new Error(`mint-fanout: ${t} must be an unsigned integer`);let o=BigInt(n);if(!r&&o===0n)throw new Error(`mint-fanout: ${t} must be positive`);return o}function Me(e){let t=e>>>0;return()=>{t|=0,t=t+1831565813|0;let r=Math.imul(t^t>>>15,1|t);return r=r+Math.imul(r^r>>>7,61|r)^r,((r^r>>>14)>>>0)/4294967296}}function $e({minMs:e=0,maxMs:t=0,rng:r}){let n=Math.max(0,Number(e)||0),o=Math.max(n,Number(t)||0);return o===0?0:Math.floor(n+r()*(o-n+1))}function Ie(e){return BigInt(e).toString(16).padStart(64,"0")}function ie(e){return e.slice(2).padStart(64,"0")}function oe(e,t,r){return`0x42842e0e${ie(e)}${ie(t)}${Ie(r)}`}function ae(e={}){let t=[];if(!e||typeof e!="object")return{ok:!1,problems:["grant is required"]};let r;try{r=W(e.main,"main")}catch(i){t.push(i.message)}try{W(e.contract,"contract")}catch(i){t.push(i.message)}Number.isInteger(Number(e.chainId))||t.push("grant.chainId is required");let n=Number(e.maxWallets);!Number.isInteger(n)||n<1?t.push("grant.maxWallets must be a positive integer"):n>32&&t.push("grant.maxWallets exceeds hard max 32");try{T(e.maxTotalWei,"grant.maxTotalWei")}catch(i){t.push(i.message)}let o;try{o=W(e.sweepTo,"sweepTo")}catch(i){t.push(i.message)}return r&&o&&o!==r&&t.push("grant.sweepTo must equal grant.main (children may only consolidate back to main)"),{ok:t.length===0,problems:t}}function Ne(e={}){let t=W(e.main,"main"),r=Number(e.chainId);if(!Number.isInteger(r))throw new Error("mint-fanout: chainId required");let n=W(e.contract,"contract"),o=e.grant,i=ae(o);if(!i.ok)throw new Error(`mint-fanout: ${i.problems.join("; ")}`);let s=Array.isArray(e.children)?e.children:[];if(s.length===0)throw new Error("mint-fanout: at least one child wallet required");let l=Math.min(Number(o.maxWallets),32);if(s.length>l)throw new Error(`mint-fanout: ${s.length} children exceeds grant.maxWallets ${l}`);let u=new Set,a=s.map((f,h)=>{let b=Number(f.index);if(!Number.isInteger(b)||b<1)throw new Error(`mint-fanout: child ${h} index must be >= 1 (0 is main)`);let d=W(f.address,`child[${h}]`);if(d===t)throw new Error("mint-fanout: child address must not equal main");if(u.has(d))throw new Error(`mint-fanout: duplicate child ${d}`);return u.add(d),{index:b,address:d}}),m=e.mint||{},x=String(m.data||"").toLowerCase();if(!/^0x[0-9a-f]*$/.test(x)||x.length<10)throw new Error("mint-fanout: mint.data must be hex calldata");let P=T(m.valueWei??m.value??"0","mint.valueWei",{allowZero:!0}),M=T(m.gasLimit,"mint.gasLimit"),w=T(m.maxFeePerGas??m.maxFeePerGasWei,"mint.maxFeePerGas"),$=T(m.maxPriorityFeePerGas??m.maxPriorityFeePerGasWei??"0","mint.maxPriorityFeePerGas",{allowZero:!0}),y=T(e.fundWeiPerChild,"fundWeiPerChild"),G=T(o.maxTotalWei,"grant.maxTotalWei"),R=BigInt(a.length),B=y*R,v=P*R;if(B>G)throw new Error(`mint-fanout: total fund ${B} exceeds grant.maxTotalWei ${G}`);let S=e.sweep||{},D=S.nft!==!1,F=S.native!==!1,k=W(o.sweepTo,"sweepTo"),O=T(S.gasLimit??"150000","sweep.gasLimit"),L=T(S.maxFeePerGas??S.maxFeePerGasWei??m.maxFeePerGas??m.maxFeePerGasWei,"sweep.maxFeePerGas"),V=T(S.maxPriorityFeePerGas??S.maxPriorityFeePerGasWei??$.toString(),"sweep.maxPriorityFeePerGas",{allowZero:!0}),H=Array.isArray(e.tokenIds)?e.tokenIds:[],C=Me(Number(e.rngSeed)>>>0),X={minMs:e.delayMs?.min??0,maxMs:e.delayMs?.max??0,rng:C},I=[],A=f=>{I.push({...f,step:I.length+1,delayMsAfter:$e(X)})};for(let f of a)A({kind:"fund",walletIndex:0,from:t,to:f.address,data:"0x",value:y.toString(),chainId:r,gasLimit:(S.fundGasLimit||"21000").toString(),maxFeePerGas:w.toString(),maxPriorityFeePerGas:$.toString()});for(let f of a)A({kind:"mint",walletIndex:f.index,from:f.address,to:n,data:x,value:P.toString(),chainId:r,gasLimit:M.toString(),maxFeePerGas:w.toString(),maxPriorityFeePerGas:$.toString()});if(D&&a.forEach((f,h)=>{let b=H[h],d=b!=null&&String(b).length>0;A({kind:"sweep-nft",walletIndex:f.index,from:f.address,to:n,data:d?oe(f.address,k,BigInt(b)):"0x",value:"0",chainId:r,gasLimit:O.toString(),maxFeePerGas:L.toString(),maxPriorityFeePerGas:V.toString(),needsTokenId:!d,tokenId:d?String(b):null,nftTo:k})}),F)for(let f of a)A({kind:"sweep-native",walletIndex:f.index,from:f.address,to:k,data:"0x",value:"0",valueMode:"remainder",chainId:r,gasLimit:"21000",maxFeePerGas:L.toString(),maxPriorityFeePerGas:V.toString()});return{execution:"prepare-only",signed:!1,main:t,chainId:r,contract:n,children:a,hopCount:I.length,totals:{wallets:a.length,fundWei:B.toString(),mintValueWei:v.toString()},graph:"fan-out-fan-in (common funder + common sink, linkable)",hops:I}}export{Z as DEFAULT_TRAIT_SNIPE_POLICY,Pe as FANOUT_DEFAULT_MAX,Te as FANOUT_HARD_MAX,c as TRAIT_DECISIONS,j as TRAIT_SNIPER_VERSION,K as TRIGGER_EVENTS,E as TraitSnipePrepareError,oe as erc721SafeTransferCalldata,Q as evaluateTraitListing,Ne as planMintFanout,Ae as prepareTopTraitSnipe,ne as prepareTraitSnipeCandidate,de as scanTraitListings,ae as validateFanoutGrant};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import R from"node:fs";import oe from"node:path";import{createHash as Xe,randomUUID as Te}from"node:crypto";var ae=1,j=class extends Error{constructor(t,r="DURABLE_STORE_ERROR"){super(t),this.name="DurableStoreError",this.code=r}};function L(e){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError("durable store values must contain finite numbers");return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map(L).join(",")}]`;if(e&&typeof e=="object")return`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${L(e[r])}`).join(",")}}`;throw new TypeError(`durable store values must be JSON-safe, got ${typeof e}`)}function xe(e){return Xe("sha256").update(L(e)).digest("hex")}function se(e){let t=e(),r=t instanceof Date?t.getTime():typeof t=="string"?Date.parse(t):Number(t);if(!Number.isFinite(r))throw new TypeError("clock must return epoch milliseconds, an ISO string, or a Date");return Math.trunc(r)}function ie(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}function _e(e){R.mkdirSync(e,{recursive:!0,mode:448});try{R.chmodSync(e,448)}catch{}}function me(e){try{let t=R.statSync(e);return{...JSON.parse(R.readFileSync(e,"utf8")),mtimeMs:t.mtimeMs}}catch{return null}}function J({filePath:e,kind:t,initialData:r,validateData:o,clock:n=()=>Date.now(),maxBytes:i=4*1024*1024,lockStaleMs:l=3e4,lockWaitMs:d=2e3,lockIdFactory:E=()=>Te()}={}){if(typeof e!="string"||e==="")throw new TypeError("filePath is required");if(!/^[a-z][a-z0-9._-]{0,63}$/i.test(String(t)))throw new TypeError("a bounded store kind is required");if(typeof r!="function"||typeof o!="function")throw new TypeError("initialData and validateData are required");if(!Number.isSafeInteger(i)||i<1024)throw new TypeError("maxBytes must be at least 1024");if(!Number.isSafeInteger(l)||l<1e3)throw new TypeError("lockStaleMs must be at least 1000");if(!Number.isSafeInteger(d)||d<0||d>3e4)throw new TypeError("lockWaitMs must be between 0 and 30000");let T=`${e}.lock`;function x(){let a=r();return o(a),{schemaVersion:ae,kind:t,generation:0,data:a}}function O(a){let y;try{y=JSON.parse(a)}catch(c){throw new j(`corrupt ${t} snapshot: invalid JSON (${c.message})`,"STORE_CORRUPT")}if(!y||typeof y!="object"||Array.isArray(y))throw new j(`corrupt ${t} snapshot: root must be an object`,"STORE_CORRUPT");if(y.schemaVersion!==ae)throw new j(`unsupported ${t} schemaVersion ${String(y.schemaVersion)}`,"STORE_SCHEMA");if(y.kind!==t||!Number.isSafeInteger(y.generation)||y.generation<0)throw new j(`corrupt ${t} snapshot metadata`,"STORE_CORRUPT");let{integrity:s,...u}=y;if(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||xe(u)!==s)throw new j(`corrupt ${t} snapshot: checksum mismatch`,"STORE_CORRUPT");try{o(y.data)}catch(c){throw new j(`corrupt ${t} snapshot: ${c.message}`,"STORE_CORRUPT")}return u}function k(){if(!R.existsSync(e))return x();let a=R.statSync(e);if(!a.isFile()||a.size>i)throw new j(`${t} snapshot is not a bounded regular file`,"STORE_BOUNDS");try{R.chmodSync(e,384)}catch{}return O(R.readFileSync(e,"utf8"))}function I(){_e(oe.dirname(e));let a=se(n),y=String(E()),s=`${JSON.stringify({schemaVersion:1,lockId:y,pid:process.pid,acquiredAt:a})}
|
|
2
|
+
`,u=()=>{let f;try{return f=R.openSync(T,"wx",384),R.writeFileSync(f,s,"utf8"),R.fsyncSync(f),R.closeSync(f),{lockId:y}}catch(h){let b=f!==void 0;if(b)try{R.closeSync(f)}catch{}if(b)try{R.unlinkSync(T)}catch{}if(h?.code!=="EEXIST")throw h;return null}},m=se(n)+d,p=new Int32Array(new SharedArrayBuffer(4));for(;;){let f=u();if(f)return f;let h=se(n),b=me(T),w=!1;if(b){let _=h-Number(b.acquiredAt??b.mtimeMs);w=Number.isFinite(_)&&_>=l}else try{w=h-R.statSync(T).mtimeMs>=l}catch{w=!1}if(w){let _=me(T);if(b?_?.lockId===b.lockId:_===null){try{R.unlinkSync(T)}catch(v){if(v?.code!=="ENOENT")throw v}continue}}let g=m-h;if(g<=0)throw new j(`${t} store is busy`,"STORE_BUSY");Atomics.wait(p,0,0,Math.min(10,g))}}function N(a){if(me(T)?.lockId===a.lockId)try{R.unlinkSync(T)}catch(s){if(s?.code!=="ENOENT")throw s}}function B(a){o(a.data);let y={...a,integrity:xe(a)},s=`${L(y)}
|
|
3
|
+
`;if(Buffer.byteLength(s)>i)throw new j(`${t} snapshot exceeds ${i} bytes`,"STORE_BOUNDS");let u=oe.dirname(e);_e(u);let c=oe.join(u,`.${oe.basename(e)}.${process.pid}.${Te()}.tmp`),m;try{m=R.openSync(c,"wx",384),R.writeFileSync(m,s,"utf8"),R.fsyncSync(m),R.closeSync(m),m=void 0,R.renameSync(c,e);try{R.chmodSync(e,384)}catch{}try{let p=R.openSync(u,"r");try{R.fsyncSync(p)}finally{R.closeSync(p)}}catch{}}finally{if(m!==void 0)try{R.closeSync(m)}catch{}try{R.unlinkSync(c)}catch(p){if(p?.code!=="ENOENT")throw p}}}function H(){return ie(k().data)}function Z(){let a=k();return{schemaVersion:a.schemaVersion,kind:a.kind,generation:a.generation,data:ie(a.data)}}function W(a){if(typeof a!="function")throw new TypeError("mutator must be a function");let y=I();try{let s=k(),u=ie(s.data),c=a(u,{generation:s.generation,now:se(n)});return o(u),B({schemaVersion:ae,kind:t,generation:s.generation+1,data:u}),ie(c)}finally{N(y)}}return Object.freeze({filePath:e,read:H,inspect:Z,mutate:W})}import{createHash as ht}from"node:crypto";var he=Object.freeze(["price","wallet","risk","execution","security","nft","governance","system"]),Qe=new Set(he);function et(e){if(!Qe.has(e))throw new TypeError(`Unknown watch category: ${String(e)}`);return e}function tt(e={}){let t=e.subscribedCategories??[];if(!Array.isArray(t))throw new TypeError("subscribedCategories must be an array");return t}function rt(){return{subscribedCategories:[]}}function nt(e,t){return!(!t||t.notify!==!0||t.category!==e.category||e.watchId!==void 0&&t.id!==e.watchId)}function Ne(e,t=rt(),r){if(!e||typeof e!="object")throw new TypeError("alert must be an object");return et(e.category),tt(t).includes(e.category)?{deliver:!0,reason:"category-subscribed"}:nt(e,r)?{deliver:!0,reason:"watch-opt-in"}:{deliver:!1,reason:"not-subscribed"}}var ot=(process.env.ORACLE_REDACT_SECRETS??"true").toLowerCase(),st=["1","true","yes","on"].includes(ot),it=[/sk-[A-Za-z0-9_-]{10,}/g,/sk_live_[A-Za-z0-9]{10,}/g,/sk_test_[A-Za-z0-9]{10,}/g,/ghp_[A-Za-z0-9]{10,}/g,/github_pat_[A-Za-z0-9_]{10,}/g,/gho_[A-Za-z0-9]{10,}/g,/ghs_[A-Za-z0-9]{10,}/g,/xox[baprs]-[A-Za-z0-9-]{10,}/g,/AIza[A-Za-z0-9_-]{30,}/g,/AKIA[A-Z0-9]{16}/g,/pplx-[A-Za-z0-9]{10,}/g,/hf_[A-Za-z0-9]{10,}/g,/xai-[A-Za-z0-9]{30,}/g,/gsk_[A-Za-z0-9]{10,}/g,/npm_[A-Za-z0-9]{10,}/g,/tvly-[A-Za-z0-9]{10,}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi],at=/\b0x[a-fA-F0-9]{64}\b/g,ct=/-----BEGIN (?:RSA |EC |OPENSSH |ENCRYPTED )?PRIVATE KEY-----[\s\S]*?-----END (?:RSA |EC |OPENSSH |ENCRYPTED )?PRIVATE KEY-----/g,ut=/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,dt=/\b([A-Z][A-Z0-9_]{0,40}(?:API_?KEY|TOKEN|SECRET|PASSWORD|PASSWD|PRIVATE_?KEY|MNEMONIC|SEED|AUTH)[A-Z0-9_]{0,20})\s*=\s*(['"]?)(\S+)\2/g,ft=/^(?:export\s+)?((?:api[_-]?key|token|secret|password|private[_-]?key|mnemonic|seed[_-]?phrase|authorization))\s*[:=]\s*(['"]?)([^\s&]+)\2/gim,lt=/("(?:api[_-]?key|apiKey|access[_-]?token|refresh[_-]?token|client[_-]?secret|private[_-]?key|privateKey|secret|password|authorization|bearer|mnemonic|seedPhrase)"\s*:\s*")([^"]{6,})(")/gi,pt=new Set(["access_token","refresh_token","id_token","token","api_key","apikey","client_secret","password","auth","jwt","session","secret","key","code","signature","x-amz-signature","private_key","authorization"]),Gt=new Set([...pt].map(e=>e.replace(/[^a-z0-9]/gi,"").toLowerCase()));function yt(e){let t=String(e??"");return t.length<18?"[REDACTED]":`${t.slice(0,6)}\u2026${t.slice(-4)}`}function mt(e){return`\xABredacted:${String(e??"").slice(0,4)}\u2026\xBB`}function Ie(e,t={}){if(e==null)return e;let r=typeof e=="string"?e:String(e);if(!r||!(t.force||st))return r;let o=t.fileRead?mt:yt;r=r.replace(ct,"[REDACTED_PRIVATE_KEY]"),r=r.replace(at,"[REDACTED_EVM_KEY]"),r=r.replace(ut,n=>o(n));for(let n of it)n.lastIndex=0,r=r.replace(n,i=>o(i));return r=r.replace(dt,(n,i,l,d)=>/^(?:os\.(?:getenv|environ)|process\.env|\$ENV\{)/.test(d)?`${i}=${l||""}${d}${l||""}`:`${i}=${l||""}${o(d)}${l||""}`),r=r.replace(ft,(n,i,l,d)=>n.replace(d,o(d))),r=r.replace(lt,(n,i,l,d)=>`${i}${o(l)}${d}`),r}var M=1,ke=Object.freeze(["alert","prepare"]),Oe=Object.freeze(["LIVE","STALE","UNAVAILABLE","UNKNOWN"]),wt=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,126}[A-Za-z0-9])?$/,gt=new Set(["secret","webhooksecret","password","passphrase","privatekey","mnemonic","seed","authorization","apikey","accesstoken","bearertoken","signingkey"]);function $(e,t){for(let[r,o]of[["tenantId",e],["workflowId",t]])if(typeof o!="string"||!wt.test(o))throw new TypeError(`${r} must be a bounded, non-wildcard scope id`);return{tenantId:e,workflowId:t}}function S(e,t,{min:r=1,max:o=256}={}){if(typeof t!="string"||t.length<r||t.length>o||/[\u0000-\u001f\u007f]/.test(t))throw new TypeError(`${e} must be a string between ${r} and ${o} characters without control bytes`);return t}function P(e){if(!he.includes(e))throw new TypeError(`Unknown watch category: ${String(e)}`);return e}function ce(e){if(!ke.includes(e))throw new TypeError(`notification work kind must be alert or prepare, got ${String(e)}`);return e}function Q(e,t="value",r=new Set){if(e!=null){if(typeof e=="function"||typeof e=="symbol"||typeof e=="bigint")throw new TypeError(`${t} must be JSON-safe`);if(typeof e=="number"&&!Number.isFinite(e))throw new TypeError(`${t} must contain finite numbers`);if(typeof e=="object"){if(r.has(e))throw new TypeError(`${t} must not contain cycles`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new TypeError(`${t} must contain plain JSON objects only`);if(r.add(e),Array.isArray(e))e.forEach((o,n)=>Q(o,`${t}[${n}]`,r));else for(let[o,n]of Object.entries(e)){let i=o.toLowerCase().replace(/[^a-z0-9]/g,"");if(gt.has(i))throw new TypeError(`${t}.${o} may contain secret material and is rejected`);Q(n,`${t}.${o}`,r)}r.delete(e)}}}function we(e,t,r){if(e==null)return e;if(typeof e=="string"){let n=Ie(e,{force:!0});if(n!==e)throw new TypeError(`${t} may contain secret material and is rejected`);return n}if(typeof e!="object")return e;if(r.has(e))throw new TypeError(`${t} must not contain cycles`);if(r.add(e),Array.isArray(e)){let n=e.map((i,l)=>we(i,`${t}[${l}]`,r));return r.delete(e),n}let o={};for(let[n,i]of Object.entries(e))o[n]=we(i,`${t}.${n}`,r);return r.delete(e),o}function U(e,{name:t="payload",maxBytes:r=64*1024}={}){Q(e,t);let o=we(e,t,new Set),n;try{n=L(o)}catch(i){throw new TypeError(`${t} must be JSON-safe: ${i.message}`)}if(Buffer.byteLength(n)>r)throw new TypeError(`${t} exceeds ${r} bytes`);return JSON.parse(n)}function q(e){let t=typeof e=="string"?e.toUpperCase():e?.status?.toUpperCase?.();return Oe.includes(t)?t:"UNKNOWN"}function te(e){return ht("sha256").update(L(e)).digest("hex")}function re({category:e,preferences:t,watch:r,watchId:o}={}){P(e);let n=Ne({category:e,...o===void 0?{}:{watchId:o}},t,r);if(!n.deliver){let i=new Error(`notification category ${e} is not opted in`);throw i.name="NotificationOptInError",i.code="NOTIFICATION_NOT_OPTED_IN",i}return n}function A(e){if(!Number.isFinite(e))throw new TypeError("time must be finite");return new Date(Math.trunc(e)).toISOString()}function C(e){let t=e(),r=t instanceof Date?t.getTime():typeof t=="string"?Date.parse(t):Number(t);if(!Number.isFinite(r))throw new TypeError("clock must return epoch milliseconds, an ISO string, or a Date");return Math.trunc(r)}function Et(e,{onError:t=()=>{}}={}){if(typeof e!="function")throw new TypeError("event append function is required");return Object.freeze({append(r){try{let o=e(Object.freeze({...r}));o&&typeof o.then=="function"&&o.catch(t)}catch(o){t(o)}}})}function z(e,t){if(e){if(typeof e.append!="function")throw new TypeError("eventSink must expose append(event)");e.append(t)}}import Re from"node:path";import{homedir as bt}from"node:os";import{randomUUID as $e}from"node:crypto";var ge=1,Ce=new Set(["pending","leased","completed"]),At=5*366*24*60;function St(e=process.env){let t=e.ORACLE_CONFIG_DIR||Re.join(bt(),".config","oracle");return Re.join(t,"notification-schedules.v1.json")}function ue(e,t,r,o){if(!/^\d+$/.test(e))throw new TypeError(`invalid ${o} cron field`);let n=Number(e);if(!Number.isSafeInteger(n)||n<t||n>r)throw new TypeError(`${o} cron field is out of range`);return n}function ne(e,t,r,o,{weekday:n=!1}={}){let i=new Set,l=e==="*";if(!e||e.length>80)throw new TypeError(`invalid ${o} cron field`);for(let d of e.split(",")){if(!d)throw new TypeError(`invalid ${o} cron field`);let[E,T,x]=d.split("/");if(x!==void 0)throw new TypeError(`invalid ${o} cron step`);let O=T===void 0?1:ue(T,1,r-t+1,`${o} step`),k,I;if(E==="*")k=t,I=r;else if(E.includes("-")){let N=E.split("-");if(N.length!==2)throw new TypeError(`invalid ${o} cron range`);if(k=ue(N[0],t,r,o),I=ue(N[1],t,r,o),I<k)throw new TypeError(`invalid descending ${o} cron range`)}else if(k=ue(E,t,r,o),I=k,T!==void 0)throw new TypeError(`cron step requires * or a range in ${o}`);for(let N=k;N<=I;N+=O)i.add(n&&N===7?0:N)}if(i.size===0)throw new TypeError(`empty ${o} cron field`);return{values:i,wildcard:l}}function fe(e){if(typeof e!="string"||e.length>160)throw new TypeError("schedule must be a bounded string");let t=e.trim().toLowerCase();if(!t)throw new TypeError("schedule is required");if(t==="hourly")return Object.freeze({type:"interval",intervalMs:36e5,source:t});if(t==="daily")return Object.freeze({type:"interval",intervalMs:864e5,source:t});let r=t.match(/^every\s+([1-9]\d{0,5})\s*([mhd])$/);if(r){let l=r[2]==="m"?6e4:r[2]==="h"?36e5:864e5,d=Number(r[1])*l;if(!Number.isSafeInteger(d)||d<6e4||d>366*864e5)throw new TypeError("schedule interval must be between one minute and 366 days");return Object.freeze({type:"interval",intervalMs:d,source:t})}let o=t.match(/^at\s+(.+)$/);if(o){let l=o[1];if(!/^\d{4}-\d{2}-\d{2}t\d{2}:\d{2}:\d{2}(?:\.\d{3})?z$/.test(l))throw new TypeError("one-time schedule must use an ISO-8601 UTC time");let d=Date.parse(l);if(!Number.isFinite(d))throw new TypeError("invalid one-time schedule time");return Object.freeze({type:"at",atMs:d,source:`at ${new Date(d).toISOString()}`})}let n=t.split(/\s+/);if(n.length!==5)throw new TypeError(`invalid schedule: ${e}`);let i={minute:ne(n[0],0,59,"minute"),hour:ne(n[1],0,23,"hour"),day:ne(n[2],1,31,"day-of-month"),month:ne(n[3],1,12,"month"),weekday:ne(n[4],0,7,"day-of-week",{weekday:!0})};return Object.freeze({type:"cron",fields:i,source:t})}function de(e,t){let r=typeof e=="string"?fe(e):e,o=t instanceof Date?t.getTime():typeof t=="string"?Date.parse(t):Number(t);if(!Number.isFinite(o))throw new TypeError("after must be a valid time");if(r.type==="interval")return Math.trunc(o)+r.intervalMs;if(r.type==="at")return r.atMs>o?r.atMs:null;if(r.type!=="cron")throw new TypeError("unknown parsed schedule type");let n=Math.floor(o/6e4)*6e4+6e4;for(let i=0;i<At;i+=1,n+=6e4){let l=new Date(n),d=r.fields,E=d.day.values.has(l.getUTCDate()),T=d.weekday.values.has(l.getUTCDay()),x=d.day.wildcard&&d.weekday.wildcard?!0:d.day.wildcard?T:d.weekday.wildcard?E:E||T;if(d.minute.values.has(l.getUTCMinutes())&&d.hour.values.has(l.getUTCHours())&&d.month.values.has(l.getUTCMonth()+1)&&x)return n}throw new RangeError("cron schedule has no occurrence within five years")}function Tt(e){if(!e||e.schemaVersion!==M)throw new TypeError("invalid schedule record version");if($(e.tenantId,e.workflowId),S("schedule id",e.id,{max:128}),S("idempotencyKey",e.idempotencyKey,{max:160}),S("schedule name",e.name,{max:160}),ce(e.kind),P(e.category),fe(e.schedule),e.startAt!==null&&!Number.isFinite(Date.parse(e.startAt)))throw new TypeError("invalid schedule startAt");if(typeof e.enabled!="boolean")throw new TypeError("schedule enabled must be boolean");if(e.nextRunAt!==null&&!Number.isFinite(Date.parse(e.nextRunAt)))throw new TypeError("invalid schedule nextRunAt");if(!Number.isFinite(Date.parse(e.createdAt))||!Number.isFinite(Date.parse(e.updatedAt)))throw new TypeError("invalid schedule timestamps");if(U(e.payload),!/^[a-f0-9]{64}$/.test(e.definitionFingerprint))throw new TypeError("invalid schedule fingerprint")}function xt(e){if(!e||e.schemaVersion!==M)throw new TypeError("invalid scheduled work version");if($(e.tenantId,e.workflowId),S("work id",e.id,{max:128}),S("schedule id",e.scheduleId,{max:128}),S("work idempotencyKey",e.idempotencyKey,{max:512}),ce(e.kind),P(e.category),!Ce.has(e.status))throw new TypeError("invalid scheduled work status");if(!Number.isSafeInteger(e.attempts)||e.attempts<0)throw new TypeError("invalid scheduled work attempts");if(e.executionAllowed!==!1||e.custody!=="none")throw new TypeError("scheduled work crossed the custody boundary");if(!Number.isFinite(Date.parse(e.scheduledFor))||!Number.isFinite(Date.parse(e.createdAt)))throw new TypeError("invalid work time");if(e.lease!==null&&(S("lease owner",e.lease.owner,{max:128}),S("lease token",e.lease.token,{max:160}),!Number.isFinite(Date.parse(e.lease.until))))throw new TypeError("invalid work lease");U(e.payload)}function _t(e,t){return r=>{if(!r||r.schemaVersion!==ge||!Array.isArray(r.schedules)||!Array.isArray(r.work))throw new TypeError("invalid schedule store schema");if(r.schedules.length>e||r.work.length>t)throw new TypeError("schedule store record bound exceeded");let o=new Set,n=new Set;for(let d of r.schedules){if(Tt(d),o.has(d.id))throw new TypeError("duplicate schedule id");let E=`${d.tenantId}\0${d.workflowId}\0${d.idempotencyKey}`;if(n.has(E))throw new TypeError("duplicate scoped schedule idempotency key");o.add(d.id),n.add(E)}let i=new Set,l=new Set;for(let d of r.work){if(xt(d),i.has(d.id)||l.has(d.idempotencyKey))throw new TypeError("duplicate scheduled work identity");i.add(d.id),l.add(d.idempotencyKey)}}}function V(e,t,r){return e.tenantId===t&&e.workflowId===r}function De(e,t,r){if(e.status!=="leased"||!e.lease||e.lease.token!==t)throw new Error("scheduled work lease token does not match");if(Date.parse(e.lease.until)<=r)throw new Error("scheduled work lease expired")}function Nt({filePath:e=St(),clock:t=()=>Date.now(),idFactory:r=()=>$e(),leaseTokenFactory:o=()=>$e(),eventSink:n,maxSchedules:i=1e3,maxWork:l=5e3,maxBytes:d=8*1024*1024}={}){if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(l)||l<1)throw new TypeError("schedule record bounds must be positive integers");let E=J({filePath:e,kind:"oracle-notification-schedules",clock:t,maxBytes:d,initialData:()=>({schemaVersion:ge,schedules:[],work:[]}),validateData:_t(i,l)});function T(a={},y={}){let s=C(t),{tenantId:u,workflowId:c}=$(a.tenantId,a.workflowId),m=S("idempotencyKey",a.idempotencyKey,{max:160}),p=S("schedule name",a.name??m,{max:160}),f=ce(a.kind??a.mode),h=P(a.category),b=fe(a.schedule),w=U(a.payload??{});f==="alert"&&re({category:h,preferences:y.preferences??a.preferences,watch:y.watch??a.watch,watchId:a.watchId});let g={tenantId:u,workflowId:c,idempotencyKey:m,name:p,kind:f,category:h,schedule:b.source,payload:w,startAt:a.startAt??null},_=te(g),D=de(b,s);if(a.startAt!==void 0){if(typeof a.startAt!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(a.startAt))throw new TypeError("startAt must be an ISO-8601 UTC time");if(D=Date.parse(a.startAt),!Number.isFinite(D)||D<=s)throw new TypeError("startAt must be in the future")}if(D===null||D<=s)throw new TypeError("schedule must have a future occurrence");let v=E.mutate(Y=>{let G=Y.schedules.find(F=>V(F,u,c)&&F.idempotencyKey===m);if(G){if(G.definitionFingerprint!==_){let F=new Error("schedule idempotency key was reused with different content");throw F.code="IDEMPOTENCY_CONFLICT",F}return{...G,duplicate:!0}}if(Y.schedules.length>=i)throw new Error("schedule capacity reached");let X=A(s),ee={schemaVersion:M,id:S("generated schedule id",String(r()),{max:128}),...g,definitionFingerprint:_,enabled:a.enabled!==!1,createdAt:X,updatedAt:X,lastMaterializedAt:null,nextRunAt:A(D)};return Y.schedules.push(ee),ee});return v.duplicate||z(n,{type:"notification.schedule.created",at:A(s),tenantId:u,workflowId:c,scheduleId:v.id,kind:f,category:h}),v}function x({tenantId:a,workflowId:y}={}){return $(a,y),E.read().schedules.filter(s=>V(s,a,y))}function O({tenantId:a,workflowId:y,id:s,enabled:u}={}){if($(a,y),typeof u!="boolean")throw new TypeError("enabled must be boolean");let c=C(t),m=E.mutate(p=>{let f=p.schedules.find(h=>V(h,a,y)&&h.id===s);if(!f)return null;if(f.enabled=u,f.updatedAt=A(c),u&&f.nextRunAt===null){let h=de(f.schedule,c);if(h===null)throw new Error("a completed one-time schedule cannot be re-enabled");f.nextRunAt=A(h)}return f});return m&&z(n,{type:"notification.schedule.enabled",at:A(c),tenantId:a,workflowId:y,scheduleId:s,enabled:u}),m}function k({tenantId:a,workflowId:y,id:s}={}){$(a,y);let u=C(t),c=E.mutate(m=>{let p=m.schedules.findIndex(f=>V(f,a,y)&&f.id===s);return p<0?!1:(m.schedules.splice(p,1),!0)});return c&&z(n,{type:"notification.schedule.removed",at:A(u),tenantId:a,workflowId:y,scheduleId:s}),c}function I({tenantId:a,workflowId:y,limit:s=100,until:u}={}){if($(a,y),!Number.isSafeInteger(s)||s<1||s>1e3)throw new TypeError("limit must be between 1 and 1000");let c=u===void 0?C(t):typeof u=="string"?Date.parse(u):Number(u);if(!Number.isFinite(c))throw new TypeError("until must be a valid time");let m=E.mutate(p=>{let f=[],h=new Set(p.work.map(w=>w.idempotencyKey)),b=p.schedules.filter(w=>V(w,a,y)&&w.enabled&&w.nextRunAt!==null&&Date.parse(w.nextRunAt)<=c).sort((w,g)=>w.nextRunAt.localeCompare(g.nextRunAt)||w.id.localeCompare(g.id));for(let w of b){for(;w.enabled&&w.nextRunAt!==null&&Date.parse(w.nextRunAt)<=c&&f.length<s;){let g=w.nextRunAt,_=`${a}:${y}:${w.id}:${g}`;if(!h.has(_)){if(p.work.length>=l)throw new Error("scheduled work capacity reached");let v={schemaVersion:M,id:S("generated work id",String(r()),{max:128}),tenantId:a,workflowId:y,scheduleId:w.id,idempotencyKey:_,kind:w.kind,category:w.category,payload:w.payload,evidence:q(w.payload?.evidence),scheduledFor:g,createdAt:A(c),status:"pending",attempts:0,lease:null,completedAt:null,custody:"none",executionAllowed:!1};p.work.push(v),f.push(v),h.add(_)}w.lastMaterializedAt=g;let D=de(w.schedule,Date.parse(g));w.nextRunAt=D===null?null:A(D),D===null&&(w.enabled=!1),w.updatedAt=A(c)}if(f.length>=s)break}return f});for(let p of m)z(n,{type:"notification.schedule.work.created",at:A(c),tenantId:a,workflowId:y,scheduleId:p.scheduleId,workId:p.id,kind:p.kind,evidence:p.evidence});return m}function N({tenantId:a,workflowId:y,status:s}={}){if($(a,y),s!==void 0&&!Ce.has(s))throw new TypeError("invalid work status");return E.read().work.filter(u=>V(u,a,y)&&(s===void 0||u.status===s))}function B({tenantId:a,workflowId:y}={}){$(a,y);let s=C(t);return E.mutate(u=>{let c=0;for(let m of u.work)V(m,a,y)&&m.status==="leased"&&Date.parse(m.lease.until)<=s&&(m.status="pending",m.lease=null,c+=1);return c})}function H({tenantId:a,workflowId:y,workerId:s,limit:u=1,leaseMs:c=3e4}={}){if($(a,y),S("workerId",s,{max:128}),!Number.isSafeInteger(u)||u<1||u>100)throw new TypeError("claim limit must be between 1 and 100");if(!Number.isSafeInteger(c)||c<1e3||c>36e5)throw new TypeError("leaseMs must be between 1000 and 3600000");let m=C(t),p=E.mutate(f=>{let h=f.work.filter(b=>V(b,a,y)&&(b.status==="pending"||b.status==="leased"&&Date.parse(b.lease.until)<=m)).sort((b,w)=>b.scheduledFor.localeCompare(w.scheduledFor)||b.id.localeCompare(w.id)).slice(0,u);for(let b of h)b.status="leased",b.attempts+=1,b.lease={owner:s,token:S("generated lease token",String(o()),{max:160}),until:A(m+c)};return h});for(let f of p)z(n,{type:"notification.schedule.work.claimed",at:A(m),tenantId:a,workflowId:y,workId:f.id,attempt:f.attempts});return p}function Z({tenantId:a,workflowId:y,id:s,leaseToken:u}={}){$(a,y);let c=C(t),m=E.mutate(p=>{let f=p.work.find(h=>V(h,a,y)&&h.id===s);return f?(De(f,u,c),f.status="completed",f.lease=null,f.completedAt=A(c),f):null});return m&&z(n,{type:"notification.schedule.work.completed",at:A(c),tenantId:a,workflowId:y,workId:s}),m}function W({tenantId:a,workflowId:y,id:s,leaseToken:u}={}){$(a,y);let c=C(t);return E.mutate(m=>{let p=m.work.find(f=>V(f,a,y)&&f.id===s);return p?(De(p,u,c),p.status="pending",p.lease=null,p):null})}return Object.freeze({filePath:e,createSchedule:T,listSchedules:x,setEnabled:O,removeSchedule:k,materializeDue:I,listWork:N,recoverExpiredWork:B,claimWork:H,completeWork:Z,releaseWork:W,inspect:E.inspect})}import ve from"node:path";import{homedir as It}from"node:os";import{randomUUID as Fe}from"node:crypto";var Ee=1,je=Object.freeze(["pending","leased","delivered","dead_letter"]),Me=new Set(je);function kt(e=process.env){let t=e.ORACLE_CONFIG_DIR||ve.join(It(),".config","oracle");return ve.join(t,"notification-outbox.v1.json")}function Ot(e){if(!e||e.schemaVersion!==M)throw new TypeError("invalid outbox record version");if($(e.tenantId,e.workflowId),S("message id",e.id,{max:128}),S("idempotencyKey",e.idempotencyKey,{max:200}),S("channel",e.channel,{max:32}),e.channel!=="webhook")throw new TypeError("P1 outbox supports webhook only");if(P(e.category),!Me.has(e.status))throw new TypeError("invalid outbox state");if(!Number.isSafeInteger(e.attempts)||e.attempts<0)throw new TypeError("outbox attempts must be monotonic non-negative integers");if(!Number.isSafeInteger(e.maxAttempts)||e.maxAttempts<1||e.maxAttempts>100)throw new TypeError("invalid outbox maxAttempts");if(!Number.isFinite(Date.parse(e.createdAt))||!Number.isFinite(Date.parse(e.updatedAt))||!Number.isFinite(Date.parse(e.nextAttemptAt)))throw new TypeError("invalid outbox timestamp");if(e.destinationId!==null&&S("destinationId",e.destinationId,{max:160}),!/^[a-f0-9]{64}$/.test(e.contentFingerprint))throw new TypeError("invalid outbox fingerprint");if(e.lease!==null&&(S("lease owner",e.lease.owner,{max:128}),S("lease token",e.lease.token,{max:160}),!Number.isFinite(Date.parse(e.lease.until))))throw new TypeError("invalid outbox lease");if(e.lastError!==null&&S("lastError",e.lastError,{max:512}),e.replayOf!==null&&S("replayOf",e.replayOf,{max:128}),!Array.isArray(e.failures)||e.failures.length>100)throw new TypeError("invalid outbox failure records");for(let t of e.failures){if(!t||!Number.isSafeInteger(t.attempt)||t.attempt<1)throw new TypeError("invalid outbox failure attempt");if(!Number.isFinite(Date.parse(t.at)))throw new TypeError("invalid outbox failure time");if(S("failure code",t.code,{max:512}),typeof t.retryable!="boolean")throw new TypeError("failure retryable must be boolean");if(t.terminal!==!0&&t.terminal!==!1)throw new TypeError("failure terminal must be boolean")}if(e.executionAllowed!==!1||e.custody!=="none")throw new TypeError("outbox crossed the custody boundary");U(e.payload)}function Rt(e){return t=>{if(!t||t.schemaVersion!==Ee||!Array.isArray(t.messages))throw new TypeError("invalid outbox store schema");if(t.messages.length>e)throw new TypeError("outbox record bound exceeded");let r=new Set,o=new Set;for(let n of t.messages){Ot(n);let i=`${n.tenantId}\0${n.workflowId}\0${n.idempotencyKey}`;if(r.has(n.id)||o.has(i))throw new TypeError("duplicate outbox identity");r.add(n.id),o.add(i)}}}function K(e,t,r){return e.tenantId===t&&e.workflowId===r}function $t(e){let t=e&&typeof e=="object"?e.code:null;if(typeof t=="string"&&/^[A-Z][A-Z0-9_.:-]{0,63}$/.test(t))return`delivery failed: ${t}`;let r=e&&typeof e=="object"?Number(e.status??e.statusCode):NaN;return Number.isInteger(r)&&r>=100&&r<=599?`delivery failed: HTTP_${r}`:"delivery failed"}function ze(e,t,r){if(e.status!=="leased"||!e.lease||e.lease.token!==t)throw new Error("outbox lease token does not match");if(Date.parse(e.lease.until)<=r)throw new Error("outbox lease expired")}function Dt({filePath:e=kt(),clock:t=()=>Date.now(),idFactory:r=()=>Fe(),leaseTokenFactory:o=()=>Fe(),eventSink:n,maxRecords:i=1e4,maxBytes:l=16*1024*1024,maxAttempts:d=5,baseBackoffMs:E=1e3,maxBackoffMs:T=36e5}={}){for(let[s,u,c,m]of[["maxRecords",i,1,1e5],["maxAttempts",d,1,100],["baseBackoffMs",E,1,864e5],["maxBackoffMs",T,1,7*864e5]])if(!Number.isSafeInteger(u)||u<c||u>m)throw new TypeError(`${s} is out of range`);if(E>T)throw new TypeError("baseBackoffMs cannot exceed maxBackoffMs");let x=J({filePath:e,kind:"oracle-notification-outbox",clock:t,maxBytes:l,initialData:()=>({schemaVersion:Ee,messages:[]}),validateData:Rt(i)}),O=s=>Math.min(T,E*2**Math.min(30,Math.max(0,s-1)));function k(s,u){return re({category:s.category,preferences:u?.preferences??s.preferences,watch:u?.watch??s.watch,watchId:s.watchId})}function I(s){let{tenantId:u,workflowId:c}=$(s.tenantId,s.workflowId),m=P(s.category),p=S("idempotencyKey",s.idempotencyKey,{max:200}),f=s.channel??"webhook";if(f!=="webhook")throw new TypeError("P1 outbox supports webhook only; fiat/P2 channels are not available");let h=s.destinationId==null?null:S("destinationId",s.destinationId,{max:160}),b=U(s.payload??{}),w=q(s.evidence??s.payload?.evidence),g={tenantId:u,workflowId:c,idempotencyKey:p,category:m,channel:f,destinationId:h,payload:b,evidence:w};return{...g,contentFingerprint:te(g)}}function N(s={},u={}){k(s,u);let c=I(s),m=C(t),p=x.mutate(f=>{let h=f.messages.find(g=>K(g,c.tenantId,c.workflowId)&&g.idempotencyKey===c.idempotencyKey);if(h){if(h.contentFingerprint!==c.contentFingerprint){let g=new Error("outbox idempotency key was reused with different content");throw g.code="IDEMPOTENCY_CONFLICT",g}return{...h,duplicate:!0}}if(f.messages.length>=i)throw new Error("outbox capacity reached");let b=A(m),w={schemaVersion:M,id:S("generated message id",String(r()),{max:128}),...c,status:"pending",attempts:0,maxAttempts:s.maxAttempts===void 0?d:Number(s.maxAttempts),nextAttemptAt:b,lease:null,lastError:null,failures:[],createdAt:b,updatedAt:b,deliveredAt:null,deadLetteredAt:null,replayOf:null,custody:"none",executionAllowed:!1};if(!Number.isSafeInteger(w.maxAttempts)||w.maxAttempts<1||w.maxAttempts>d)throw new TypeError(`message maxAttempts must be between 1 and ${d}`);return f.messages.push(w),w});return p.duplicate||z(n,{type:"notification.outbox.enqueued",at:A(m),tenantId:c.tenantId,workflowId:c.workflowId,messageId:p.id,category:c.category,evidence:c.evidence}),p}function B({tenantId:s,workflowId:u,status:c}={}){if($(s,u),c!==void 0&&!Me.has(c))throw new TypeError("invalid outbox status");return x.read().messages.filter(m=>K(m,s,u)&&(c===void 0||m.status===c))}function H({tenantId:s,workflowId:u}={}){$(s,u);let c=C(t),m=x.mutate(p=>{let f=[];for(let h of p.messages)!K(h,s,u)||h.status!=="leased"||Date.parse(h.lease.until)>c||(h.lease=null,h.updatedAt=A(c),h.attempts>=h.maxAttempts?(h.status="dead_letter",h.lastError="delivery lease expired after final attempt",h.deadLetteredAt=A(c)):(h.status="pending",h.lastError="delivery lease expired before acknowledgement",h.nextAttemptAt=A(c+O(h.attempts))),f.push(h));return f});for(let p of m)z(n,{type:"notification.outbox.lease_recovered",at:A(c),tenantId:s,workflowId:u,messageId:p.id,status:p.status,attempt:p.attempts});return m}function Z({tenantId:s,workflowId:u,workerId:c,limit:m=1,leaseMs:p=3e4}={}){if($(s,u),S("workerId",c,{max:128}),!Number.isSafeInteger(m)||m<1||m>100)throw new TypeError("claim limit must be between 1 and 100");if(!Number.isSafeInteger(p)||p<1e3||p>36e5)throw new TypeError("leaseMs must be between 1000 and 3600000");let f=C(t),h=x.mutate(b=>{for(let g of b.messages)!K(g,s,u)||g.status!=="leased"||Date.parse(g.lease.until)>f||(g.lease=null,g.updatedAt=A(f),g.attempts>=g.maxAttempts?(g.status="dead_letter",g.lastError="delivery lease expired after final attempt",g.deadLetteredAt=A(f)):(g.status="pending",g.lastError="delivery lease expired before acknowledgement",g.nextAttemptAt=A(f)));let w=b.messages.filter(g=>K(g,s,u)&&g.status==="pending"&&Date.parse(g.nextAttemptAt)<=f&&g.attempts<g.maxAttempts).sort((g,_)=>g.nextAttemptAt.localeCompare(_.nextAttemptAt)||g.createdAt.localeCompare(_.createdAt)||g.id.localeCompare(_.id)).slice(0,m);for(let g of w)g.status="leased",g.attempts+=1,g.updatedAt=A(f),g.lease={owner:c,token:S("generated lease token",String(o()),{max:160}),until:A(f+p)};return w});for(let b of h)z(n,{type:"notification.outbox.claimed",at:A(f),tenantId:s,workflowId:u,messageId:b.id,attempt:b.attempts});return h}function W({tenantId:s,workflowId:u,id:c,leaseToken:m}={}){$(s,u);let p=C(t),f=x.mutate(h=>{let b=h.messages.find(w=>K(w,s,u)&&w.id===c);return b?(ze(b,m,p),b.status="delivered",b.lease=null,b.updatedAt=A(p),b.deliveredAt=A(p),b):null});return f&&z(n,{type:"notification.outbox.delivered",at:A(p),tenantId:s,workflowId:u,messageId:c,attempt:f.attempts}),f}function a({tenantId:s,workflowId:u,id:c,leaseToken:m,error:p,retryable:f=!0}={}){if($(s,u),typeof f!="boolean")throw new TypeError("retryable must be boolean");let h=C(t),b=$t(p),w=x.mutate(g=>{let _=g.messages.find(v=>K(v,s,u)&&v.id===c);if(!_)return null;ze(_,m,h),_.lease=null,_.lastError=b;let D=!f||_.attempts>=_.maxAttempts;return _.failures=[..._.failures??[],{attempt:_.attempts,at:A(h),code:b,retryable:f,terminal:D}],_.updatedAt=A(h),D?(_.status="dead_letter",_.deadLetteredAt=A(h)):(_.status="pending",_.nextAttemptAt=A(h+O(_.attempts))),_});return w&&z(n,{type:w.status==="dead_letter"?"notification.outbox.dead_lettered":"notification.outbox.retry_scheduled",at:A(h),tenantId:s,workflowId:u,messageId:c,attempt:w.attempts,nextAttemptAt:w.nextAttemptAt}),w}function y({tenantId:s,workflowId:u,id:c,idempotencyKey:m}={},p={}){$(s,u);let f=S("replay idempotencyKey",m,{max:200}),b=x.read().messages.find(_=>K(_,s,u)&&_.id===c);if(!b)return null;if(b.status!=="dead_letter"&&b.status!=="delivered")throw new Error("only delivered or dead-letter messages may be replayed");k({...b,preferences:p.preferences,watch:p.watch},p);let w=C(t),g=x.mutate(_=>{let D=_.messages.find(F=>K(F,s,u)&&F.id===c);if(!D||D.status!=="dead_letter"&&D.status!=="delivered")throw new Error("replay source changed state");let v=_.messages.find(F=>K(F,s,u)&&F.idempotencyKey===f),Y={tenantId:s,workflowId:u,idempotencyKey:f,category:D.category,channel:D.channel,destinationId:D.destinationId,payload:D.payload,evidence:D.evidence},G=te(Y);if(v){if(v.contentFingerprint!==G||v.replayOf!==c){let F=new Error("replay idempotency key was reused with different content");throw F.code="IDEMPOTENCY_CONFLICT",F}return{...v,duplicate:!0}}if(_.messages.length>=i)throw new Error("outbox capacity reached");let X=A(w),ee={schemaVersion:M,id:S("generated message id",String(r()),{max:128}),...Y,contentFingerprint:G,status:"pending",attempts:0,maxAttempts:D.maxAttempts,nextAttemptAt:X,lease:null,lastError:null,failures:[],createdAt:X,updatedAt:X,deliveredAt:null,deadLetteredAt:null,replayOf:c,custody:"none",executionAllowed:!1};return _.messages.push(ee),ee});return g.duplicate||z(n,{type:"notification.outbox.replayed",at:A(w),tenantId:s,workflowId:u,messageId:g.id,replayOf:c}),g}return Object.freeze({filePath:e,enqueue:N,list:B,claim:Z,acknowledge:W,fail:a,recoverExpiredLeases:H,replay:y,backoffForAttempt:O,inspect:x.inspect})}import Pe from"node:path";import{homedir as zt}from"node:os";import{createHash as Ue,createHmac as Ve,randomUUID as jt,timingSafeEqual as Mt}from"node:crypto";import pe from"node:net";import Ct from"node:dns";var vt=new Set(["localhost","metadata.google.internal","metadata.goog"]);function le(e){let t=String(e).toLowerCase().split("%")[0];if((t.match(/::/g)||[]).length>1)return null;let r=x=>{if(!x)return[];let O=x.split(":"),k=O.at(-1);if(k?.includes(".")){let I=k.split(".").map(Number);if(I.length!==4||I.some(N=>!Number.isInteger(N)||N<0||N>255))return null;O.splice(O.length-1,1,(I[0]<<8|I[1]).toString(16),(I[2]<<8|I[3]).toString(16))}return O.some(I=>!/^[0-9a-f]{1,4}$/.test(I))?null:O.map(I=>Number.parseInt(I,16))},[o,n]=t.split("::"),i=r(o),l=r(n);if(!i||!l)return null;let d=t.includes("::"),E=8-i.length-l.length;if(!d&&E!==0||d&&E<1)return null;let T=[...i,...Array(Math.max(0,E)).fill(0),...l];return T.length!==8?null:Uint8Array.from(T.flatMap(x=>[x>>8,x&255]))}function be(e,t,r){let o=Math.floor(r/8),n=r%8;for(let l=0;l<o;l+=1)if(e[l]!==t[l])return!1;if(!n)return!0;let i=255<<8-n;return(e[o]&i)===(t[o]&i)}function Ae(e){if(pe.isIPv4(e)){let t=e.split(".").map(Number);return!(t[0]===0||t[0]===10||t[0]===127||t[0]>=224||t[0]===100&&t[1]>=64&&t[1]<=127||t[0]===169&&t[1]===254||t[0]===172&&t[1]>=16&&t[1]<=31||t[0]===192&&(t[1]===0||t[1]===2||t[1]===168)||t[0]===192&&t[1]===88&&t[2]===99||t[0]===198&&(t[1]===18||t[1]===19||t[1]===51)||t[0]===203&&t[1]===0&&t[2]===113)}if(pe.isIPv6(e)){let t=le(e);if(!t)return!1;let r=le("::ffff:0:0");return be(t,r,96)?Ae([...t.slice(12)].join(".")):be(t,le("2000::"),3)?![["2001::",23],["2001:db8::",32],["2001:10::",28],["2001:2::",48],["2002::",16],["3fff::",20]].some(([n,i])=>be(t,le(n),i)):!1}return!1}function Ft(e){let t;try{t=new URL(String(e))}catch{return{ok:!1,error:`not a valid URL: ${String(e).slice(0,120)}`}}if(t.protocol!=="http:"&&t.protocol!=="https:")return{ok:!1,error:`refused protocol ${t.protocol} (only http/https)`};let r=t.hostname.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.+$/,"");if(vt.has(r)||r.endsWith(".localhost")||r.endsWith(".internal"))return{ok:!1,error:`refused internal host ${r}`};let o=pe.isIP(r);return o!==0&&!Ae(r)?{ok:!1,error:`refused private address ${r}`}:{ok:!0,url:t,host:r,isLiteralIp:o!==0}}async function Le(e,{lookupFn:t=Ct.promises.lookup}={}){let r=Ft(e);if(!r.ok)return r;if(r.isLiteralIp)return{ok:!0,url:r.url,addresses:[{address:r.host,family:pe.isIPv6(r.host)?6:4}]};let o;try{o=await t(r.host,{all:!0,verbatim:!0})}catch{return{ok:!1,error:`refused: ${r.host} did not resolve`}}return!Array.isArray(o)||o.length===0||o.some(n=>!Ae(n.address))?{ok:!1,error:`refused: ${r.host} resolves to a non-public address`}:{ok:!0,url:r.url,addresses:o}}var Se=1,Lt="hmac-sha256",Ke="x-oracle-signature",He="x-oracle-timestamp",Be="x-oracle-delivery-id",Ze="x-oracle-key-id";function ye(e,t){if(e&&typeof e.get=="function")return e.get(t);let r=t.toLowerCase();for(let[o,n]of Object.entries(e??{}))if(o.toLowerCase()===r)return n}function Pt(e){let t=e&&typeof e=="object"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array),r=t?e.secret:e,o=t?e.keyId??null:null,n;if(typeof r=="string")n=Buffer.from(r,"utf8");else if(Buffer.isBuffer(r)||r instanceof Uint8Array)n=Buffer.from(r),(Buffer.isBuffer(r)||r instanceof Uint8Array)&&r.fill(0);else throw new TypeError("secretProvider must return a string, bytes, or { secret, keyId }");if(n.length<32||n.length>4096)throw n.fill(0),new TypeError("webhook signing secret must contain 32 to 4096 bytes");return o!==null&&S("webhook keyId",o,{max:128}),{bytes:n,keyId:o}}async function We(e,t){if(typeof e!="function")throw new TypeError("an injected secretProvider is required");return Pt(await e(Object.freeze({...t})))}function Je(e,t,r){return`${e??""}.${t}.${r}`}function qe(e){if(!e||e.schemaVersion!==Se)throw new TypeError("unsupported webhook envelope version");if(S("deliveryId",e.deliveryId,{max:128}),S("eventId",e.eventId,{max:160}),$(e.tenantId,e.workflowId),P(e.category),e.destinationId!==null&&S("destinationId",e.destinationId,{max:160}),!Number.isFinite(Date.parse(e.occurredAt))||!Number.isFinite(Date.parse(e.createdAt)))throw new TypeError("invalid webhook envelope time");if(e.executionAllowed!==!1||e.custody!=="none")throw new TypeError("webhook envelope crossed the custody boundary");return U(e.payload),e}async function Ye(e,{lookupFn:t,assertPublicUrlFn:r=Le,pin:o}={}){if(typeof e!="string"||e.length<1||e.length>2048)throw new TypeError("webhook URL must be a bounded string");let n;try{n=new URL(e)}catch{throw new TypeError("webhook destination is not a valid URL")}if(n.protocol!=="https:")throw new TypeError("webhook destination must use HTTPS");if(n.username||n.password)throw new TypeError("webhook destination must not contain URL credentials");if(n.hash)throw new TypeError("webhook destination must not contain a fragment");let i=await r(n.toString(),t?{lookupFn:t}:{});if(!i?.ok)throw new Error(i?.error||"webhook destination was refused");if(!Array.isArray(i.addresses)||i.addresses.length===0)throw new Error("webhook destination did not return pinned addresses");let l=i.addresses.map(({address:d,family:E})=>Object.freeze({address:d,family:E}));if(o!==void 0){if(typeof o!="function")throw new TypeError("pin must be a function");await o(i.url.hostname,l)}return Object.freeze({url:i.url.toString(),host:i.url.hostname,addresses:Object.freeze(l)})}async function Ge(e={},{secretProvider:t,clock:r=()=>Date.now(),deliveryId:o=jt(),destinationId:n=e.destinationId??null}={}){let i=C(r),{tenantId:l,workflowId:d}=$(e.tenantId,e.workflowId),E=P(e.category),T={schemaVersion:Se,deliveryId:S("deliveryId",String(o),{max:128}),eventId:S("eventId",String(e.eventId??e.id??""),{max:160}),tenantId:l,workflowId:d,category:E,destinationId:n==null?null:S("destinationId",n,{max:160}),occurredAt:e.occurredAt===void 0?A(i):A(Date.parse(e.occurredAt)),createdAt:A(i),evidence:q(e.evidence??e.payload?.evidence),payload:U(e.payload??{}),custody:"none",executionAllowed:!1};qe(T),Q(T,"webhook envelope");let x=L(T);if(Buffer.byteLength(x)>64*1024)throw new TypeError("webhook body exceeds 65536 bytes");let O=String(Math.floor(i/1e3)),k=await We(t,{tenantId:l,workflowId:d,destinationId:T.destinationId,purpose:"sign",keyId:null}),I;try{I=`sha256=${Ve("sha256",k.bytes).update(Je(k.keyId,O,x)).digest("hex")}`}finally{k.bytes.fill(0)}let N={"content-type":"application/json",[Be]:T.deliveryId,[He]:O,[Ke]:I,...k.keyId===null?{}:{[Ze]:k.keyId}};return Object.freeze({body:x,headers:Object.freeze(N),envelope:Object.freeze(T)})}async function Ut({body:e,headers:t}={},{secretProvider:r,clock:o=()=>Date.now(),maxAgeMs:n=5*6e4,maxFutureSkewMs:i=3e4,replayGuard:l,expectedTenantId:d,expectedWorkflowId:E,expectedDestinationId:T}={}){if(typeof e!="string"||Buffer.byteLength(e)>64*1024)return{ok:!1,reason:"invalid-body"};if(!Number.isSafeInteger(n)||n<1e3||!Number.isSafeInteger(i)||i<0)throw new TypeError("invalid webhook verification window");let x=ye(t,He),O=ye(t,Ke);if(!/^\d{1,16}$/.test(String(x))||!/^sha256=[a-f0-9]{64}$/.test(String(O)))return{ok:!1,reason:"invalid-signature-headers"};let k=Number(x)*1e3,I=C(o);if(k>I+i)return{ok:!1,reason:"future-signature"};if(I-k>n)return{ok:!1,reason:"expired-signature"};let N;try{if(N=JSON.parse(e),qe(N),L(N)!==e)return{ok:!1,reason:"non-canonical-body"}}catch{return{ok:!1,reason:"invalid-envelope"}}if(ye(t,Be)!==N.deliveryId)return{ok:!1,reason:"delivery-id-mismatch"};if(d!==void 0&&N.tenantId!==d)return{ok:!1,reason:"scope-mismatch"};if(E!==void 0&&N.workflowId!==E)return{ok:!1,reason:"scope-mismatch"};if(T!==void 0&&N.destinationId!==T)return{ok:!1,reason:"destination-mismatch"};let B=ye(t,Ze)??null,H;try{H=await We(r,{tenantId:N.tenantId,workflowId:N.workflowId,destinationId:N.destinationId,purpose:"verify",keyId:B})}catch{return{ok:!1,reason:"secret-unavailable"}}let Z=!1;try{let a=Ve("sha256",H.bytes).update(Je(B,String(x),e)).digest(),y=Buffer.from(String(O).slice(7),"hex");Z=y.length===a.length&&Mt(y,a)}finally{H.bytes.fill(0)}if(!Z)return{ok:!1,reason:"signature-mismatch"};let W=!1;if(l!==void 0){if(!l||typeof l.consume!="function")throw new TypeError("replayGuard must expose consume(record)");if(W=!0,!await l.consume({tenantId:N.tenantId,workflowId:N.workflowId,deliveryId:N.deliveryId,expiresAt:A(k+n+i)}))return{ok:!1,reason:"replay"}}return{ok:!0,envelope:N,replayProtected:W}}function Vt({clock:e=()=>Date.now(),maxEntries:t=1e4}={}){if(!Number.isSafeInteger(t)||t<1)throw new TypeError("maxEntries must be positive");let r=new Map;return Object.freeze({consume({tenantId:o,workflowId:n,deliveryId:i,expiresAt:l}={}){$(o,n),S("deliveryId",i,{max:128});let d=Date.parse(l),E=C(e);if(!Number.isFinite(d)||d<=E)return!1;for(let[x,O]of r)O<=E&&r.delete(x);let T=Ue("sha256").update(`${o}\0${n}\0${i}`).digest("hex");if(r.has(T))return!1;if(r.size>=t)throw new Error("webhook replay guard capacity reached");return r.set(T,d),!0},get size(){return r.size}})}function Kt(e=process.env){let t=e.ORACLE_CONFIG_DIR||Pe.join(zt(),".config","oracle");return Pe.join(t,"webhook-replay.v1.json")}function Ht({filePath:e=Kt(),clock:t=()=>Date.now(),maxEntries:r=1e4,maxBytes:o=4*1024*1024}={}){if(!Number.isSafeInteger(r)||r<1||r>1e5)throw new TypeError("maxEntries is out of range");let i=J({filePath:e,kind:"oracle-webhook-replay",clock:t,maxBytes:o,initialData:()=>({schemaVersion:1,entries:[]}),validateData:l=>{if(!l||l.schemaVersion!==1||!Array.isArray(l.entries)||l.entries.length>r)throw new TypeError("invalid webhook replay store schema");let d=new Set;for(let E of l.entries){if(!E||!/^[a-f0-9]{64}$/.test(E.key)||d.has(E.key))throw new TypeError("invalid webhook replay key");if(!Number.isFinite(Date.parse(E.expiresAt))||!Number.isFinite(Date.parse(E.consumedAt)))throw new TypeError("invalid webhook replay time");d.add(E.key)}}});return Object.freeze({filePath:e,consume({tenantId:l,workflowId:d,deliveryId:E,expiresAt:T}={}){$(l,d),S("deliveryId",E,{max:128});let x=Date.parse(T),O=C(t);if(!Number.isFinite(x)||x<=O)return!1;let k=Ue("sha256").update(`${l}\0${d}\0${E}`).digest("hex");return i.mutate(I=>{if(I.entries=I.entries.filter(N=>Date.parse(N.expiresAt)>O),I.entries.some(N=>N.key===k))return!1;if(I.entries.length>=r)throw new Error("webhook replay guard capacity reached");return I.entries.push({schemaVersion:M,key:k,consumedAt:A(O),expiresAt:A(x)}),!0})},inspect:i.inspect})}async function Bt(e,{destinationUrl:t,destinationId:r=e?.destinationId??null,secretProvider:o,transport:n,pin:i,lookupFn:l,assertPublicUrlFn:d,clock:E=()=>Date.now(),deliveryId:T}={}){if(typeof n!="function")throw new TypeError("an injected webhook transport is required");if(typeof i!="function")throw new TypeError("an injected pinned-resolution hook is required");let x=await Ye(t,{lookupFn:l,assertPublicUrlFn:d,pin:i}),O=await Ge(e,{secretProvider:o,clock:E,deliveryId:T,destinationId:r}),k=await n(Object.freeze({url:x.url,host:x.host,addresses:x.addresses,method:"POST",redirect:"error",headers:O.headers,body:O.body}));return{deliveryId:O.envelope.deliveryId,response:k}}export{j as DurableStoreError,Oe as NOTIFICATION_EVIDENCE,ke as NOTIFICATION_KINDS,M as NOTIFICATION_SCHEMA_VERSION,je as OUTBOX_STATES,Ee as OUTBOX_STORE_SCHEMA_VERSION,ge as SCHEDULE_STORE_SCHEMA_VERSION,ae as SNAPSHOT_SCHEMA_VERSION,Se as WEBHOOK_ENVELOPE_SCHEMA_VERSION,Lt as WEBHOOK_SIGNATURE_ALGORITHM,Q as assertNoNotificationSecrets,$ as assertNotificationScope,L as canonicalNotificationJson,Nt as createDurableScheduler,J as createDurableSnapshotStore,Ht as createDurableWebhookReplayGuard,Vt as createMemoryWebhookReplayGuard,Et as createNotificationEventSink,Dt as createNotificationOutbox,Ge as createSignedWebhookDelivery,Bt as deliverWebhook,de as nextScheduleTime,q as normalizeNotificationEvidence,fe as parseDurableSchedule,re as requireNotificationOptIn,Ye as resolveWebhookDestination,Ut as verifyWebhookDelivery};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{wordlists as Z}from"ethers";var ee=new Set(["privatekey","privkey","secretkey","seedphrase","seed","mnemonic","passphrase","password","keystore","keymaterial","wif","xprv","xpriv","bearer","authorization","signature","apikey","credential"]),te=[/\b[5KL][1-9A-HJ-NP-Za-km-z]{50,51}\b/,/\bxprv[0-9A-Za-z]{50,}\b/],re=new Set([12,15,18,21,24]);function oe(t){let r=String(t).trim().toLowerCase().split(/\s+/).filter(Boolean);return re.has(r.length)&&r.every(e=>Z.en.getWordIndex(e)>=0)}var ne=/^\s*(?:0x)?[0-9a-fA-F]{64}\s*$/,ie=/(hash|digest|root|salt|nonce|proof|commitment|sig|id)(?:e?s)?$/i,se=new Set(["calldata","data","publickey","pubkey","message","payload","input","extradata"]);function ae(t){let r=L(t);return se.has(r)||ie.test(r)}var B=class extends Error{constructor(r){super(`action receipt refused: secret-bearing field at ${r}`),this.name="ActionReceiptSecretError",this.code="ACTION_RECEIPT_SECRET"}};function L(t){return String(t).replace(/[^a-z0-9]/gi,"").toLowerCase()}function ce(t){let r=L(t);return[...ee].some(e=>r.includes(e))}function le(t,r,e){if(typeof r=="string"){if(te.some(n=>n.test(r))||oe(r))throw new B(e);if(ne.test(r)&&!ae(t))throw new B(e)}}function x(t,r="$",e=""){if(t==null||typeof t=="boolean")return t;if(typeof t=="string")return le(e,t,r),t;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`action receipt: non-finite number at ${r}`);return t}if(typeof t=="bigint")return t.toString();if(Array.isArray(t))return t.map((o,s)=>x(o,`${r}[${s}]`,e));if(typeof t!="object"||Object.getPrototypeOf(t)!==Object.prototype)throw new TypeError(`action receipt: JSON-like value required at ${r}`);let n={};for(let o of Object.keys(t).sort()){let s=`${r}.${o}`;if(ce(o))throw new B(s);t[o]!==void 0&&(n[o]=x(t[o],s,o))}return n}function g(t){return x(t)}function P(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(P).join(",")}]`:`{${Object.keys(t).map(r=>`${JSON.stringify(r)}:${P(t[r])}`).join(",")}}`}function M(t){return P(x(t))}var V=1,J="Alert findings only; not an execution signal and not a live oracle.",Me=18,Ce="1000000000000000000",de=Object.freeze(["aave-v3","morpho","compound","solend","spark","farming","generic"]),C=Object.freeze({criticalHealthFactorWad:"1050000000000000000",warningHealthFactorWad:"1250000000000000000"}),ue=new Set(de),fe=Object.freeze({aave:"aave-v3",aavev3:"aave-v3","aave-v3":"aave-v3",morpho:"morpho",compound:"compound","compound-v2":"compound","compound-v3":"compound",solend:"solend",save:"solend",spark:"spark","spark-lend":"spark",farming:"farming",farm:"farming",yield:"farming",generic:"generic",lending:"generic"}),me=new Set(["complete","incomplete","unknown","stale"]),pe=/[\u0000-\u001f\u007f]/,E=10n**18n,R=36,v=64,j=128,F=class extends Error{constructor(r,e="POSITION_HEALTH_INVALID"){super(`position health: ${r}`),this.name="PositionHealthValidationError",this.code=e}};function d(t,r){throw new F(t,r)}function w(t,r){return t<r?-1:t>r?1:0}function I(t){if(t&&typeof t=="object"&&!Object.isFrozen(t)){for(let r of Object.values(t))I(r);Object.freeze(t)}return t}function p(t,r){return(!t||typeof t!="object"||Array.isArray(t)||Object.getPrototypeOf(t)!==Object.prototype)&&d(`${r} must be a plain object`),t}function S(t,r,{optional:e=!1,lower:n=!1}={}){if(t==null&&e)return null;typeof t!="string"&&d(`${r} must be a string`);let o=t.trim();return o||d(`${r} is required`),pe.test(o)&&d(`${r} contains control characters`),o.length>512&&d(`${r} is too long`),n?o.toLowerCase():o}function A(t,r,{optional:e=!1,positive:n=!1}={}){if(t==null&&e)return null;typeof t=="number"&&d(`${r} must be an exact decimal string or BigInt; Number coercion is refused`,"POSITION_HEALTH_UNSAFE_NUMBER");let o;typeof t=="bigint"?o=t.toString():typeof t=="string"?o=t.trim():d(`${r} must be an exact decimal string or BigInt`),/^\d+$/.test(o)||d(`${r} must be a non-negative base-10 integer string`);let s=BigInt(o);return n&&s===0n&&d(`${r} must be positive`),s.toString()}function Q(t,r){t==null&&d(`${r} is required`,"POSITION_HEALTH_MISSING_DECIMALS"),typeof t=="number"&&d(`${r} must be an exact decimal string or BigInt; Number coercion is refused`,"POSITION_HEALTH_UNSAFE_NUMBER");let e=A(t,r),n=BigInt(e);return n>BigInt(R)&&d(`${r} exceeds ${R}`),Number(n)}function $(t,r){return t==null?null:S(t,r)}function he(t,r){return t==null&&d(`${r} is required`),typeof t=="bigint"?t.toString():typeof t=="number"?((!Number.isInteger(t)||!Number.isSafeInteger(t)||t<0)&&d(`${r} must be a safe non-negative integer, decimal string, or slug`),String(t)):S(String(t),r,{lower:!0})}function c(t,r){for(let e of r)if(t[e]!==void 0)return t[e]}function be(t,r="protocol"){if(t==null)return"generic";let e=S(t,r,{lower:!0}),n=fe[e]||e;return ue.has(n)||d(`${r} must be a supported lending or yield protocol`),n}function K(t){return t.protocol!=null?be(t.protocol):t.marketId!=null||t.lltv!=null||t.loanAsset&&t.collateralAsset?"morpho":t.cToken!=null||t.underlying_symbol!=null||t.collateralFactor!=null?"compound":t.borrowedAmountWads!=null||t.lendingMarket!=null||t.mintDecimals!=null?"solend":t.recipe!=null||t.farmingMethod!=null||t.methodId!=null?"farming":t.spark!=null||t.savingsVault!=null?"spark":t.userReserves!=null||t.reserves!=null||t.liquidationThreshold!=null?"aave-v3":"generic"}function ye(t,r="evidence"){if(t==null)return I({status:"unknown",references:[]});let e=p(t,r),n=S(e.status??"unknown",`${r}.status`,{lower:!0});me.has(n)||d(`${r}.status must be complete, incomplete, unknown, or stale`),e.references!=null&&!Array.isArray(e.references)&&d(`${r}.references must be an array`);let o=(e.references||[]).map((a,i)=>{let l=p(a,`${r}.references[${i}]`);return{kind:S(l.kind??l.type,`${r}.references[${i}].kind`,{lower:!0}),id:S(l.id??l.receiptId??l.txHash,`${r}.references[${i}].id`)}}).sort((a,i)=>w(a.kind,i.kind)||w(a.id,i.id)),s=[];for(let a of o)s.some(i=>i.kind===a.kind&&i.id===a.id)||s.push(a);return I({status:n,references:s})}function G(t,r){if(t==null)return null;if(typeof t=="number"&&d(`${r} must be an exact integer string or BigInt; Number coercion is refused`,"POSITION_HEALTH_UNSAFE_NUMBER"),typeof t=="object"){let o=p(t,r);if(o.bps!=null)return G(o.bps,`${r}.bps`);if(o.ray!=null)return q(o.ray,`${r}.ray`);if(o.wad!=null)return W(o.wad,`${r}.wad`);if(o.raw!=null)return q(o.raw,`${r}.raw`);o.value!=null&&d(`${r}.value is not an exact integer threshold; supply bps, wad, or ray`,"POSITION_HEALTH_UNSAFE_NUMBER"),d(`${r} must include bps, wad, or ray`)}let e=typeof t=="bigint"?t.toString():String(t).trim();/^\d+$/.test(e)||d(`${r} must be a non-negative base-10 integer string`);let n=BigInt(e);return n<=10000n?n.toString():n<=E?W(n,r):q(n,r)}function W(t,r){let n=BigInt(A(t,r))*10000n/E;return n>10000n&&d(`${r} exceeds 100%`),n.toString()}function q(t,r){let e=BigInt(A(t,r)),n=10n**27n,o=e*10000n/n;return o>10000n&&d(`${r} exceeds 100%`),o.toString()}function z(t,r,e){let n=`${e}[${r}]`,o=p(t,n),s=S(c(o,["asset","symbol","coin","underlying","underlyingToken","name"])??o.underlyingToken?.symbol??o.liquidityToken?.symbol,`${n}.asset`),a=$(c(o,["address","token","mint","underlyingAddress"])??o.underlyingToken?.address??o.liquidityToken?.mint,`${n}.address`),i=A(c(o,["amount","balance","aTokenBalance","supplyBalance","supplyAssets","collateral","deposited","shares"]),`${n}.amount`),l=Q(c(o,["decimals","tokenDecimals","mintDecimals"])??o.underlyingToken?.decimals??o.liquidityToken?.decimals,`${n}.decimals`),m=A(c(o,["price","priceQuoteMinor","oraclePrice","marketPrice"]),`${n}.price`),u=Q(c(o,["priceDecimals","oraclePriceDecimals","quoteDecimals"]),`${n}.priceDecimals`),b=null;if(e==="collateral"){let f=c(o,["liquidationThresholdBps","liquidationThreshold","lltv","ltvBps","collateralFactor","collateralFactorBps"])??o.supplyInfo?.liquidationThreshold;f==null&&d(`${n}.liquidationThresholdBps is required`,"POSITION_HEALTH_MISSING_THRESHOLD"),b=G(f,`${n}.liquidationThreshold`)}return I({asset:s,address:a,amount:i,decimals:String(l),price:m,priceDecimals:String(u),liquidationThresholdBps:b})}function N(t,r){return t==null?[]:(Array.isArray(t)||d(`${r} must be an array`),t.length>v&&d(`${r} exceeds ${v} assets`),t)}function ge(t){let r=c(t,["chain","chainId","network"]),e=t.market&&typeof t.market=="object"?t.market.chain?.chainId??(typeof t.market.chain=="string"||typeof t.market.chain=="bigint"?t.market.chain:null):null,n=he(r??e,"chain"),o=S(c(t,["account","address","owner","user","wallet"]),"account"),s=c(t,["marketId","pool","vault"]);return typeof t.market=="string"||typeof t.market=="bigint"?s=s??t.market:t.market&&typeof t.market=="object"&&(s=s??t.market.address??t.market.name??t.market.marketId??null),{chain:n,account:o,market:s==null?null:S(String(s),"market")}}function Ae(t,r){let e=A(r.asOf??t.asOf,"asOf"),n=A(c(t,["observedAt","fetchedAt","updatedAt","lastUpdate","asOfObserved"]),"observedAt"),o=A(c(t,["expiresAt","validUntil","staleAfter"]),"expiresAt");return{asOf:e,observedAt:n,expiresAt:o}}function Ie(t,r,e,n){return BigInt(n)<BigInt(r)?{status:"unknown",reason:"FUTURE_EVIDENCE"}:BigInt(n)>=BigInt(e)?{status:"stale",reason:"STALE_EVIDENCE"}:t.status==="stale"?{status:"stale",reason:"STALE_EVIDENCE"}:t.status==="unknown"?{status:"unknown",reason:"UNKNOWN_EVIDENCE"}:t.status==="incomplete"?{status:"incomplete",reason:"INCOMPLETE_EVIDENCE"}:{status:"complete",reason:null}}function _(t,r,e,n={}){return I({code:t,severity:r,message:e,...n})}function X(t){let r={critical:0,warning:1,info:2};return[...t].sort((e,n)=>{let o=(r[e.severity]??9)-(r[n.severity]??9);return o||w(e.code,n.code)||w(e.message,n.message)})}function U(t,r,e,n,o,s){return BigInt(t)*BigInt(e)*10n**BigInt(o-r)*10n**BigInt(s-n)}function Te(t,r){let e=[...t,...r],n=e.reduce((h,O)=>Math.max(h,Number(O.decimals)),0),o=e.reduce((h,O)=>Math.max(h,Number(O.priceDecimals)),0),s=0n,a=0n,i=0n;for(let h of t){let O=U(h.amount,Number(h.decimals),h.price,Number(h.priceDecimals),n,o);a+=O,s+=O*BigInt(h.liquidationThresholdBps)}for(let h of r)i+=U(h.amount,Number(h.decimals),h.price,Number(h.priceDecimals),n,o);let l=10n**BigInt(n),m={tokenDecimals:String(n),priceDecimals:String(o),unit:"quote-minor = floor(scaledValue / 10^tokenDecimals) at priceDecimals"},u=(a/l).toString(),b=(i/l).toString(),f=(s/10000n/l).toString();if(i===0n)return I({healthFactorWad:null,healthFactorStatus:a===0n?"empty":"no-debt",totalCollateralQuoteMinor:u,totalDebtQuoteMinor:"0",weightedCollateralQuoteMinor:f,liquidationBufferQuoteMinor:f,quote:m});let T=(s*E/(i*10000n)).toString(),k=s/10000n-i,H=k<0n?"-":"",D=k<0n?-k:k;return I({healthFactorWad:T,healthFactorStatus:BigInt(T)<E?"liquidatable":"priced",totalCollateralQuoteMinor:u,totalDebtQuoteMinor:b,weightedCollateralQuoteMinor:f,liquidationBufferQuoteMinor:`${H}${(D/l).toString()}`,quote:m})}function y(t,r={}){g(t),g(r);let e=p(t,"snapshot");p(r,"options");let n=K(e),{chain:o,account:s,market:a}=ge(e),i=ye(e.evidence),{asOf:l,observedAt:m,expiresAt:u}=Ae(e,r),b=S(e.id??e.positionId??`${n}:${o}:${s}:${a??"default"}`,"id"),f=$(e.tenantId,"tenantId"),T=N(e.collateral??e.supplies??e.deposits,"collateral").map((D,h)=>z(D,h,"collateral")),k=N(e.debt??e.borrows??e.liabilities,"debt").map((D,h)=>z(D,h,"debt")),H={id:b,protocol:n,chain:o,account:s,market:a,observedAt:m,expiresAt:u,asOf:l,evidence:i,collateral:T,debt:k};return f&&(H.tenantId=f),I(H)}function Se(t){return c(t,["liquidationThresholdBps","liquidationThreshold","lltv"])??t.market?.lltv??t.state?.lltv}function we(t,r={}){return c(r,["collateralFactorBps","collateralFactor","liquidationThresholdBps","liquidationThreshold"])??c(t,["collateralFactorBps","collateralFactor","liquidationThresholdBps"])}function ke(t){return c(t,["price","priceQuoteMinor","oraclePrice","marketPrice"])}function Oe(t,r={}){g(t);let e=p(t,"snapshot");if(Array.isArray(e.collateral)||Array.isArray(e.debt))return y({...e,protocol:"aave-v3"},r);let n=e.userReserves??e.reserves??e.market?.reserves;if(!Array.isArray(n))return y({...e,protocol:"aave-v3"},r);let o=[],s=[];for(let a of n){let i=p(a,"reserve"),l=p(i.underlyingToken??i.token??i,"reserve.token"),m={asset:l.symbol??i.symbol,address:l.address??i.address,decimals:l.decimals??i.decimals,price:c(i,["price","priceQuoteMinor","oraclePrice"])??i.size?.usd,priceDecimals:c(i,["priceDecimals","oraclePriceDecimals"]),liquidationThreshold:i.liquidationThresholdBps??i.liquidationThreshold??i.supplyInfo?.liquidationThreshold},u=c(i,["aTokenBalance","supplyBalance","collateral","amount","supplied"]),b=c(i,["variableDebtTokenBalance","stableDebtTokenBalance","borrowBalance","debt","borrowed"]);u!=null&&u!=="0"&&o.push({...m,amount:u}),b!=null&&b!=="0"&&s.push({...m,amount:b})}return y({...e,protocol:"aave-v3",collateral:e.collateral??o,debt:e.debt??s},r)}function Ee(t,r={}){g(t);let e=p(t,"snapshot");if(Array.isArray(e.collateral)||Array.isArray(e.debt))return y({...e,protocol:"morpho"},r);let n=Se(e),o=e.collateralAsset??e.market?.collateralAsset??{},s=e.loanAsset??e.market?.loanAsset??{},a=e.position??e.state??{},i=[{asset:o.symbol??e.collateralSymbol,address:o.address,decimals:o.decimals??e.collateralDecimals,amount:c(e,["collateral","collateralAmount","supplyAssets"])??a.collateral??a.supplyAssets,price:c(e,["collateralPrice","price","priceQuoteMinor"])??o.price,priceDecimals:c(e,["collateralPriceDecimals","priceDecimals"])??o.priceDecimals,liquidationThreshold:n}],l=e.debt??[{asset:s.symbol??e.loanSymbol,address:s.address,decimals:s.decimals??e.loanDecimals,amount:c(e,["borrowAssets","debt","borrowAmount"])??a.borrowAssets,price:c(e,["loanPrice","debtPrice"])??s.price,priceDecimals:c(e,["loanPriceDecimals","debtPriceDecimals"])??s.priceDecimals}],m=(Array.isArray(l)?l:[l]).filter(u=>u&&u.amount!=null&&u.amount!=="0"&&u.amount!==0n);return y({...e,protocol:"morpho",market:e.marketId??e.market?.marketId??e.market,collateral:Array.isArray(i)?i:[i],debt:m},r)}function De(t,r={}){g(t);let e=p(t,"snapshot"),n=e.markets??e.cTokens??(e.cToken||e.underlying?[e]:null);if(e.collateral||e.debt)return y({...e,protocol:"compound"},r);let o=[],s=[];for(let a of N(n??[],"markets")){let i=p(a,"market"),l={asset:i.underlying??i.underlying_symbol??i.symbol??i.asset,address:i.address??i.cToken,decimals:i.decimals??i.underlyingDecimals,price:i.price??i.priceQuoteMinor??i.oraclePrice,priceDecimals:i.priceDecimals,liquidationThreshold:we(e,i)},m=c(i,["supplyBalance","balance","amount","totalSupply"]),u=c(i,["borrowBalance","borrow","debt","totalBorrow"]);m!=null&&m!=="0"&&o.push({...l,amount:m}),u!=null&&u!=="0"&&s.push({...l,amount:u})}return y({...e,protocol:"compound",collateral:o,debt:s},r)}function Be(t,r={}){g(t);let e=p(t,"snapshot");if(e.stale===!0||e.reserve?.lastUpdate?.stale===1)return y({...e,protocol:"solend",evidence:{...e.evidence||{},status:"stale"}},r);if(e.collateral||e.debt)return y({...e,protocol:"solend"},r);let n=e.reserves??e.obligation?.deposits??(e.mint||e.mintDecimals!=null?[e]:[]),o=[],s=[];for(let a of N(n,"reserves")){let i=p(a,"reserve"),l={asset:i.symbol??i.asset??i.liquidityToken?.symbol,address:i.mint??i.address??i.liquidityToken?.mint,decimals:i.mintDecimals??i.decimals??i.liquidityToken?.decimals,price:ke(i),priceDecimals:i.priceDecimals??i.oraclePriceDecimals,liquidationThreshold:i.liquidationThresholdBps??i.liquidationThreshold??i.loanToValueRatio??e.liquidationThresholdBps},m=c(i,["depositedAmount","collateral","amount","availableAmount"]),u=c(i,["borrowedAmount","borrowBalance","debt"]);if(u==null&&i.borrowedAmountWads!=null){let b=A(i.borrowedAmountWads,"borrowedAmountWads");u=(BigInt(b)/10n**18n).toString()}m!=null&&m!=="0"&&o.push({...l,amount:m}),u!=null&&u!=="0"&&s.push({...l,amount:u})}return y({...e,protocol:"solend",collateral:o,debt:s},r)}function _e(t,r={}){g(t);let e=p(t,"snapshot");if(e.collateral||e.debt)return y({...e,protocol:"spark"},r);let n=e.vault??e.savingsVault??e.data?.vault??e,o=p(n,"vault"),s=[{asset:o.symbol??o.asset??e.token??"savings",address:o.address??e.address,decimals:o.decimals??e.decimals,amount:c(e,["amount","shares","balance"])??o.amount??o.shares,price:c(e,["price","priceQuoteMinor"])??o.price,priceDecimals:c(e,["priceDecimals"])??o.priceDecimals,liquidationThreshold:c(e,["liquidationThresholdBps","liquidationThreshold"])??"10000"}],a=c(e,["debt","borrowed","borrowAmount"]),i=a==null||a==="0"?[]:[{asset:e.debtAsset??e.borrowSymbol??"debt",address:e.debtAddress,decimals:e.debtDecimals??o.decimals??e.decimals,amount:a,price:e.debtPrice??e.price,priceDecimals:e.debtPriceDecimals??e.priceDecimals??o.priceDecimals}];return y({...e,protocol:"spark",collateral:s,debt:i},r)}function $e(t,r={}){g(t);let e=p(t,"snapshot");if(e.tvlUsd!=null&&typeof e.tvlUsd=="number"&&d("farming tvlUsd Number is refused; supply exact collateral and debt amounts","POSITION_HEALTH_UNSAFE_NUMBER"),Array.isArray(e.collateral)||Array.isArray(e.debt)){let l=y({...e,protocol:"farming"},r),m=$(e.recipe??e.farmingMethod??e.methodId,"recipe");return I(m?{...l,recipe:m}:l)}let n=$(e.recipe??e.farmingMethod??e.methodId,"recipe"),o=[{asset:e.symbol??e.asset??e.project??"farm",address:e.pool??e.address,decimals:e.decimals,amount:c(e,["amount","deposited","shares","collateral"]),price:c(e,["price","priceQuoteMinor"]),priceDecimals:e.priceDecimals,liquidationThreshold:c(e,["liquidationThresholdBps","liquidationThreshold","lltv"])??"10000"}],s=c(e,["debt","borrowed","borrowAmount"]),a=s==null||s==="0"?[]:[{asset:e.debtAsset??e.borrowSymbol??"debt",decimals:e.debtDecimals??e.decimals,amount:s,price:e.debtPrice??e.price,priceDecimals:e.debtPriceDecimals??e.priceDecimals}],i=y({...e,protocol:"farming",collateral:o,debt:a},r);return I(n?{...i,recipe:n}:i)}var He=Object.freeze({"aave-v3":Oe,morpho:Ee,compound:De,solend:Be,spark:_e,farming:$e,generic:y});function xe(t,r={}){g(t);let e=p(t,"snapshot"),n=K(e);return He[n]({...e,protocol:n},r)}function Ne(t){let r=t==null?{}:p(t,"thresholds"),e=A(r.criticalHealthFactorWad??C.criticalHealthFactorWad,"thresholds.criticalHealthFactorWad",{positive:!0}),n=A(r.warningHealthFactorWad??C.warningHealthFactorWad,"thresholds.warningHealthFactorWad",{positive:!0});BigInt(n)<BigInt(e)&&d("thresholds.warningHealthFactorWad must be >= criticalHealthFactorWad");let o=A(r.minLiquidationBufferQuoteMinor,"thresholds.minLiquidationBufferQuoteMinor",{optional:!0});return I({criticalHealthFactorWad:e,warningHealthFactorWad:n,minLiquidationBufferQuoteMinor:o})}function Pe(t,r,e){let n=[];if(e.status!=="complete"){let i=e.reason||"UNKNOWN_EVIDENCE";return n.push(_(i,"critical","Position evidence is not current and complete; health fails closed.")),{healthStatus:e.status==="stale"?"stale":"unknown",findings:n,metrics:{healthFactorWad:null,totalCollateralQuoteMinor:null,totalDebtQuoteMinor:null,weightedCollateralQuoteMinor:null,liquidationBufferQuoteMinor:null,quote:null}}}let o=t;if(t.healthFactorStatus==="empty")return{healthStatus:"empty",findings:n,metrics:o};if(t.healthFactorStatus==="no-debt")return{healthStatus:"no-debt",findings:n,metrics:o};let s=BigInt(t.healthFactorWad);s<E?n.push(_("LIQUIDATABLE","critical","Health factor is below 1.0 wad; the position is at or past liquidation.")):s<BigInt(r.criticalHealthFactorWad)?n.push(_("HEALTH_FACTOR_CRITICAL","critical","Health factor is below the configured critical threshold.")):s<BigInt(r.warningHealthFactorWad)&&n.push(_("HEALTH_FACTOR_WARNING","warning","Health factor is below the configured warning threshold.")),r.minLiquidationBufferQuoteMinor!=null&&BigInt(t.liquidationBufferQuoteMinor)<BigInt(r.minLiquidationBufferQuoteMinor)&&n.push(_("LIQUIDATION_BUFFER_LOW",s<E?"critical":"warning","Liquidation buffer is below the configured quote-minor minimum."));let a="healthy";return n.some(i=>i.code==="LIQUIDATABLE")?a="liquidatable":n.some(i=>i.severity==="critical")?a="critical":n.length&&(a="warning"),{healthStatus:a,findings:n,metrics:o}}function Y(t={},r={}){g(t),g(r),p(t,"input"),p(r,"options"),r.asOf==null&&t.asOf==null&&d("explicit asOf required","POSITION_HEALTH_MISSING_ASOF");let e=xe(t,r),n=Ne(r.thresholds??t.thresholds),o=Ie(e.evidence,e.observedAt,e.expiresAt,e.asOf),s=Pe(o.status==="complete"?Te(e.collateral,e.debt):{healthFactorStatus:"unknown"},n,o),a={recordVersion:V,recordType:"position-health",label:J,posture:"alert-only",executionReady:!1,signingReady:!1,broadcastReady:!1,id:e.id,protocol:e.protocol,chain:e.chain,account:e.account,market:e.market,observedAt:e.observedAt,expiresAt:e.expiresAt,asOf:e.asOf,evidence:e.evidence,collateral:e.collateral,debt:e.debt,thresholds:n,healthStatus:s.healthStatus,healthFactorWad:s.metrics.healthFactorWad,totalCollateralQuoteMinor:s.metrics.totalCollateralQuoteMinor,totalDebtQuoteMinor:s.metrics.totalDebtQuoteMinor,weightedCollateralQuoteMinor:s.metrics.weightedCollateralQuoteMinor,liquidationBufferQuoteMinor:s.metrics.liquidationBufferQuoteMinor,quote:s.metrics.quote,findings:X(s.findings)};return e.tenantId&&(a.tenantId=e.tenantId),e.recipe&&(a.recipe=e.recipe),I(a)}var Re=Y;function ve(t={},r={}){g(t),g(r);let e=Array.isArray(t)?{snapshots:t}:p(t,"input"),n=e.snapshots??e.positions;Array.isArray(n)||d("snapshots must be an array"),n.length>j&&d(`snapshots exceed ${j}`);let o=A(r.asOf??e.asOf,"asOf"),s=r.thresholds??e.thresholds,a=$(e.tenantId,"tenantId"),i=n.map((f,T)=>Y(a&&f?.tenantId==null?{...f,tenantId:a}:f,{...r,asOf:o,thresholds:s,index:T})).sort((f,T)=>w(f.chain,T.chain)||w(f.account,T.account)||w(f.id,T.id)),l=X(i.flatMap(f=>f.findings.map(T=>({...T,positionId:f.id})))),m=i.filter(f=>f.healthStatus==="unknown"||f.healthStatus==="stale").length,u=i.filter(f=>f.findings.length>0).length,b={recordVersion:V,recordType:"position-health-book",label:J,posture:"alert-only",asOf:o,positionCount:String(i.length),alertCount:String(u),failClosedCount:String(m),positions:i,findings:l};return a&&(b.tenantId=a),I(b)}function je(t){return`${M(t)}
|
|
2
|
+
`}export{C as DEFAULT_POSITION_HEALTH_THRESHOLDS,J as POSITION_HEALTH_LABEL,V as POSITION_HEALTH_VERSION,Ce as POSITION_HEALTH_WAD,Me as POSITION_HEALTH_WAD_DECIMALS,F as PositionHealthValidationError,de as SUPPORTED_POSITION_PROTOCOLS,je as canonicalPositionHealthJson,ve as evaluatePositionBook,Y as evaluatePositionHealth,Oe as normalizeAavePositionSnapshot,De as normalizeCompoundPositionSnapshot,$e as normalizeFarmingPositionSnapshot,Ee as normalizeMorphoPositionSnapshot,xe as normalizePositionSnapshot,Be as normalizeSolendPositionSnapshot,_e as normalizeSparkPositionSnapshot,Re as summarizePositionHealth};
|