@oracle-agent/oracle 0.28.14 → 0.28.15
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/dist/assets/skills/oracle-action-semantics/SKILL.md +3 -1
- package/dist/assets/skills/oracle-desk-product/SKILL.md +1 -1
- package/dist/bin/desk-server.mjs +26 -26
- package/dist/cli/commands/chat.mjs +131 -131
- package/dist/cli/commands/doctor.mjs +3 -3
- package/dist/cli/commands/eval.mjs +73 -74
- package/dist/cli/commands/model.mjs +134 -134
- package/dist/cli/commands/receipt.mjs +2 -2
- package/dist/cli/commands/sign.mjs +11 -11
- package/dist/cli/commands/signer.mjs +13 -13
- package/dist/cli/commands/venues.mjs +2 -2
- package/dist/data/desk-data.mjs +24 -24
- package/dist/index.mjs +29 -29
- package/dist/local-signer/anvil-attestation-worker.mjs +1 -1
- package/dist/local-signer/index.mjs +3 -3
- package/dist/local-signer/runtime.mjs +10 -10
- package/dist/public-api/agent-grants.mjs +2 -2
- package/package.json +1 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
var He=Object.defineProperty;var pe=(e,t)=>{for(var n in t)He(e,n,{get:t[n],enumerable:!0})};var be={};pe(be,{GRANT_VERSION:()=>_,GrantValidationError:()=>S,MAX_ACTIONS:()=>re,MAX_GRANT_TTL_SECONDS:()=>ee,MAX_NONCE_LENGTH:()=>te,MAX_REVOCATION_KEY_LENGTH:()=>ne,MAX_SLIPPAGE_BPS:()=>Q,MAX_TARGETS:()=>se,READONLY_ACTION_VERBS:()=>ye,REQUIRED_FIELDS:()=>Z,canonicalizeGrant:()=>H,grantId:()=>w,isExpired:()=>L,isReadonlyAction:()=>j,normalizeGrant:()=>G,validateGrant:()=>T});import{createHash as Xe}from"node:crypto";var _=1,Z=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]),ye=Object.freeze(["read","simulate"]),Q=1e4,ee=1440*60,te=128,ne=256,re=64,se=256,ge=/^0x[0-9a-fA-F]{40}$/,Ye=/^[a-z][a-z0-9_-]*:[a-z0-9._-]+$/,Je=/^[a-z][a-z0-9_-]*:\*$/,Ze=/^[A-Za-z0-9._:-]+$/,Qe=/^[A-Za-z0-9._:-]+$/,xe=/^(0|[1-9][0-9]*)$/,S=class extends Error{constructor(t){let n=t.map(r=>`${r.field}: ${r.message}`);super(`invalid grant (${t.length} error${t.length===1?"":"s"}): ${n.join("; ")}`),this.name="GrantValidationError",this.errors=t}};function Ae(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function et(e){if(typeof e=="bigint")return e>=0n?e.toString(10):null;if(typeof e=="number")return!Number.isSafeInteger(e)||e<0?null:String(e);if(typeof e=="string"){let t=e.trim();return xe.test(t)?t:null}return null}function k(e){if(typeof e=="bigint")return e<0n||e>BigInt(Number.MAX_SAFE_INTEGER)?null:Number(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0?null:e;if(typeof e=="string"){let t=e.trim();if(!xe.test(t))return null;let n=Number(t);return Number.isSafeInteger(n)?n:null}return null}function j(e){let t=String(e).split(":")[0];return ye.includes(t)}function T(e,t={}){let n=[],r=(i,c)=>n.push({field:i,message:c});if(!Ae(e))return r("grant","grant must be a plain object"),{ok:!1,errors:n,grant:null};for(let i of Object.keys(e))Z.includes(i)||r(i,"unknown field is not allowed");for(let i of Z)(!(i in e)||e[i]==null)&&r(i,"required field is missing");if(n.length)return{ok:!1,errors:n,grant:null};let s={},o=k(e.chainId);o==null||o<=0?r("chainId","must be a positive integer chain id"):s.chainId=o;for(let i of["agentAddress","accountAddress"]){let c=e[i];typeof c!="string"||!ge.test(c.trim())?r(i,"must be a 0x-prefixed 20-byte hex address"):s[i]=c.trim().toLowerCase()}if(!Array.isArray(e.actions)||e.actions.length===0)r("actions","must be a non-empty array of action scopes");else if(e.actions.length>re)r("actions",`too many actions (max ${re})`);else{let i=[];for(let c of e.actions){let m=typeof c=="string"?c.trim():null;if(!m){r("actions","action entries must be non-empty strings");continue}if(m.includes("*")){t.allowWildcardActions===!0&&Je.test(m)?i.push(m):r("actions",`broad wildcard action "${m}" is rejected (fail closed)`);continue}if(!Ye.test(m)){r("actions",`malformed action "${m}" (expected verb:resource)`);continue}i.push(m)}s.actions=[...new Set(i)].sort()}if(!Array.isArray(e.targets))r("targets","must be an array of contract addresses");else if(e.targets.length>se)r("targets",`too many targets (max ${se})`);else{let i=[];for(let c of e.targets){let m=typeof c=="string"?c.trim():null;if(!m||!ge.test(m)){r("targets",`target "${c}" must be a 0x-prefixed 20-byte hex address (wildcards not allowed)`);continue}i.push(m.toLowerCase())}if(s.targets=[...new Set(i)].sort(),s.targets.length===0&&Array.isArray(s.actions)){let c=s.actions.filter(m=>!j(m));(c.length>0||s.actions.length===0)&&r("targets",`empty targets are only allowed for read/simulate scopes (blocked by: ${c.join(", ")||"no valid actions"})`)}}for(let i of["maxValueWei","maxGasWei"]){let c=et(e[i]);c==null?r(i,"must be a non-negative integer wei amount"):s[i]=c}let a=k(e.maxSlippageBps);a==null||a>Q?r("maxSlippageBps",`must be an integer between 0 and ${Q}`):s.maxSlippageBps=a;let u=864e10,f=k(e.expiresAt);if(f==null||f<=0)r("expiresAt","must be a positive unix-seconds timestamp");else if(f>u)r("expiresAt","exceeds the max unix-seconds timestamp (pass seconds, not milliseconds)");else if(s.expiresAt=f,t.now!=null){let i=k(t.now);i==null?r("expiresAt","opts.now must be a unix-seconds integer"):f<=i?r("expiresAt",`grant is expired (expiresAt ${f} <= now ${i})`):f-i>ee&&r("expiresAt",`grant exceeds the hard 24-hour TTL (${ee} seconds)`)}let d=typeof e.nonce=="string"?e.nonce.trim():k(e.nonce)!=null?String(k(e.nonce)):null;!d||d.length>te||!Ze.test(d)?r("nonce",`must be a non-empty string (max ${te} chars, [A-Za-z0-9._:-])`):s.nonce=d;let l=typeof e.revocationKey=="string"?e.revocationKey.trim():null;return!l||l.length>ne||!Qe.test(l)?r("revocationKey",`must be a non-empty public identifier (max ${ne} chars, [A-Za-z0-9._:-])`):s.revocationKey=l,n.length?{ok:!1,errors:n,grant:null}:{ok:!0,errors:[],grant:s}}function G(e,t={}){let{ok:n,errors:r,grant:s}=T(e,t);if(!n)throw new S(r);return s}function H(e,t={}){let n=G(e,t),s=Object.keys(n).sort().map(o=>`${JSON.stringify(o)}:${JSON.stringify(n[o])}`);return`{"version":${_},${s.join(",")}}`}function w(e,t={}){return Xe("sha256").update(H(e,t),"utf8").digest("hex")}function L(e,t){let n=k(t),r=k(Ae(e)?e.expiresAt:null);return n==null||r==null?!0:r<=n}var tt="oracle-connect-request",nt="oracle-unsigned-grant",Se="oracle-grant-canonical-json-utf8-v1",W=class extends Error{constructor(t,n){super(`secret material must never appear in a public API object (at ${t}, rule: ${n})`),this.name="SecretLeakError",this.path=t,this.rule=n}},rt=/(private[_-]?key|secret|bearer|keystore|mnemonic|seed[_-]?phrase|passphrase|password|api[_-]?key|access[_-]?token|auth[_-]?token|session[_-]?token|signer[_-]?url|signature)/i,st=Object.freeze(["privkey","wif","xprv","seed"]);function he(e){let t=String(e),n=t.toLowerCase().replace(/[\s._-]+/g,"");return rt.test(t)||st.includes(n)}var it=Object.freeze([{rule:"raw-32-byte-hex-key",re:/^0x[0-9a-fA-F]{64}$/},{rule:"raw-32-byte-hex-bare",re:/^[0-9a-fA-F]{64}$/},{rule:"extended-private-key",re:/\b(?:xprv|tprv|yprv|zprv)[1-9A-HJ-NP-Za-km-z]{107}\b/},{rule:"bitcoin-wif",re:/\b[59KLc][1-9A-HJ-NP-Za-km-z]{50,51}\b/},{rule:"bip39-mnemonic",re:/\b(?:[a-z]{3,8}\s+){11,23}[a-z]{3,8}\b/},{rule:"bearer-token",re:/bearer\s+[A-Za-z0-9._~+/=-]+/i},{rule:"pem-private-key",re:/-----BEGIN[A-Z ]*PRIVATE KEY-----/},{rule:"keystore-path",re:/keystore/i},{rule:"signer-url",re:/https?:\/\/\S*sign/i},{rule:"authorization-header",re:/authorization\s*:/i}]),ot=Object.freeze(["grantid","id","hash","sha256","sha256hex","checksum","txhash","transactionhash","blockhash","digest","userophash","commithash","prevhash","intenthash","canonicalhash","payloadhash","requestid"]);function E(e,t="$",n=new Set,r=""){if(e==null)return e;if(typeof e=="string"){let s=ot.includes(String(r).toLowerCase().replace(/[_-]/g,""));for(let{rule:o,re:a}of it)if(!(s&&o.startsWith("raw-32-byte-hex"))&&a.test(e))throw new W(t,o);return e}if(typeof e!="object"||n.has(e)||(n.add(e),ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e;if(e instanceof Map){for(let[s,o]of e.entries()){if(typeof s=="string"&&he(s))throw new W(`${t}[${JSON.stringify(s)}]`,"forbidden-key-name");E(s,`${t}[key]`,n),E(o,`${t}[${String(s)}]`,n)}return e}if(e instanceof Set){let s=0;for(let o of e.values())E(o,`${t}[${s++}]`,n);return e}if(Array.isArray(e))return e.forEach((s,o)=>E(s,`${t}[${o}]`,n)),e;for(let[s,o]of Object.entries(e)){if(he(s))throw new W(`${t}.${s}`,"forbidden-key-name");E(o,`${t}.${s}`,n,s)}return e}function X(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))X(t)}return e}function at(e,t){let n=Number(typeof e=="string"?e.trim():e);if(!Number.isSafeInteger(n)||n<=0)throw new S([{field:t,message:"must be a positive unix-seconds integer"}]);return n}function ct(e){if(e?.now==null)throw new S([{field:"opts.now",message:"explicit reference time is required for live grant construction"}]);return at(e.now,"opts.now")}function ut(e){return new Date(e*1e3).toISOString()}function dt(e,t){let n=e.actions.every(r=>j(r));return["ORACLE \u2014 CONNECT AGENT (unsigned grant, you sign it, we never do)","=================================================================",`Grant ID: ${t}`,`Version: ${_}`,`Chain: ${e.chainId}`,`Agent: ${e.agentAddress}`,`Your account: ${e.accountAddress}`,`Actions: ${e.actions.join(", ")}`,`Targets: ${e.targets.length?e.targets.join(", "):"(none \u2014 read/simulate only)"}`,`Max value: ${e.maxValueWei} wei`,`Max gas: ${e.maxGasWei} wei`,`Max slippage: ${e.maxSlippageBps} bps`,`Expires: ${ut(e.expiresAt)} (unix ${e.expiresAt})`,`Nonce: ${e.nonce}`,`Revocation: ${e.revocationKey}`,"-----------------------------------------------------------------",n?"Scope: read/simulate only \u2014 this grant cannot move funds.":"Scope: includes state-changing actions bounded by the caps above.","Self-custodial: this payload is UNSIGNED and contains public data only.","Sign the bytes below with YOUR wallet; Oracle never holds your keys."].join(`
|
|
2
|
-
`)}function ie(e={},t={}){let n=ct(t),r=e&&e.kind===tt?e.grant:e,s=G(r,{now:n,allowWildcardActions:t.allowWildcardActions===!0}),o=H(s),a=w(s),u=Buffer.from(o,"utf8"),f=X({kind:nt,unsigned:!0,payload:X({version:_,grantId:a,grant:s,canonical:o}),signing:X({scheme:Se,message:o,bytesHex:`0x${u.toString("hex")}`,byteLength:u.length,sha256:a}),render:dt(s,a)});return E(f)}var M=Object.freeze({ACTIVE:"active",EXPIRED:"expired",REVOKED:"revoked",INVALID:"invalid"});function we(e){if(e==null)return[];if(Array.isArray(e))return e;if(e instanceof Map)return[...e.values()];if(typeof e[Symbol.iterator]=="function")return[...e];throw new TypeError("grant store must be an array, Map, or iterable of grant records")}function ft(e){return e&&typeof e=="object"&&!Array.isArray(e)&&e.grant!=null?{grant:e.grant,revoked:e.revoked===!0||e.revokedAt!=null}:{grant:e,revoked:!1}}function oe(e){let t=Number(typeof e=="string"?e.trim():e);if(!Number.isSafeInteger(t)||t<0)throw new TypeError("an explicit unix-seconds `now` is required (deterministic liveness, no wall-clock fallback)");return t}function lt(e,t,n){if(e==null)return!1;if(typeof e=="function")return e(t,n)===!0;let r=[t,n.revocationKey];return e instanceof Set?r.some(s=>e.has(s)):Array.isArray(e)?r.some(s=>e.includes(s)):typeof e.has=="function"?r.some(s=>e.has(s)):!1}function ae(e,{now:t,revoked:n}={}){let r=oe(t),{grant:s,revoked:o}=ft(e),{ok:a,grant:u}=T(s);if(!a)return{status:M.INVALID,id:null,grant:null};let f=w(u);return o||lt(n,f,u)?{status:M.REVOKED,id:f,grant:u}:L(u,r)?{status:M.EXPIRED,id:f,grant:u}:{status:M.ACTIVE,id:f,grant:u}}function mt(e,{now:t,revoked:n,agentAddress:r,accountAddress:s,chainId:o}={}){let a=oe(t),u=r!=null?String(r).trim().toLowerCase():null,f=s!=null?String(s).trim().toLowerCase():null,d=o!=null?Number(o):null,l=[];for(let i of we(e)){let{status:c,id:m,grant:x}=ae(i,{now:a,revoked:n});c===M.ACTIVE&&(u!=null&&x.agentAddress!==u||f!=null&&x.accountAddress!==f||d!=null&&x.chainId!==d||l.push(Object.freeze({id:m,grant:x})))}return l.sort((i,c)=>i.id<c.id?-1:i.id>c.id?1:0),E(Object.freeze(l))}function pt(e,t,{now:n,revoked:r}={}){let s=oe(n),o=String(t??"").trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(o))return null;for(let a of we(e)){let u=ae(a,{now:s,revoked:r});if(u.status!==M.INVALID&&u.id===o)return E(Object.freeze({id:u.id,status:u.status,grant:u.grant}))}return null}var gt=Object.freeze(["grantCreated","grantActivated","grantRevoked","grantExpired"]),z=Object.freeze({ACTIVE:"active",PENDING:"pending",REVOKED:"revoked",EXPIRED:"expired",UNKNOWN:"unknown",INVALID:"invalid"}),yt=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]);function Ee(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Ie(e){return typeof e=="bigint"?Number(e):typeof e=="number"&&Number.isFinite(e)?e:typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e.trim()))?Number(e.trim()):null}function Ne(e,t=512){if(typeof e!="string")return null;let n=e.trim();return n?n.length>t?n.slice(0,t):n:null}function xt(e){let t={};for(let n of yt)t[n]=e[n];return t}function At(e,t){if(!Ee(e))return{ok:!1,error:{type:null,at:null,grantId:null,message:"event must be a plain object"}};let n=typeof e.type=="string"?e.type:null,r=Ie(e.at),s=typeof e.grantId=="string"&&e.grantId.trim()?e.grantId.trim():null;if(!gt.includes(n))return{ok:!1,error:{type:n,at:r,grantId:s,message:`unknown event type "${String(n)}"`}};if(r==null)return{ok:!1,error:{type:n,at:null,grantId:s,message:"event.at must be a unix-seconds number"}};if(n==="grantCreated"){if(!Ee(e.grant))return{ok:!1,error:{type:n,at:r,grantId:s,message:"grantCreated requires a grant payload"}};let a;try{a=G(e.grant,{allowWildcardActions:t.allowWildcardActions})}catch(f){let d=f instanceof S?f.message:String(f?.message||f);return{ok:!1,error:{type:n,at:r,grantId:s,message:d}}}let u=w(e.grant,{allowWildcardActions:t.allowWildcardActions});return s&&s!==u?{ok:!1,error:{type:n,at:r,grantId:s,message:"grantId does not match content-derived grant identity (fail closed)"}}:{ok:!0,event:{type:n,at:r,grantId:u,grant:a}}}if(!s)return{ok:!1,error:{type:n,at:r,grantId:null,message:`${n} requires a grantId`}};let o=n==="grantRevoked"?Ne(e.reason):null;return{ok:!0,event:{type:n,at:r,grantId:s,reason:o}}}function ce(e){return e.length?e.reduce((t,n)=>Math.min(t,n)):null}function Oe(e,t={}){let n=Ie(t.now);if(n==null)throw new Error("grant-indexer: opts.now (unix seconds) is required");if(!Array.isArray(e))throw new Error("grant-indexer: events must be an array");let r=[],s=new Map;function o(d){return s.has(d)||s.set(d,{created:[],activated:[],revoked:[],expired:[]}),s.get(d)}for(let d of e){let l=At(d,t);if(!l.ok){r.push(l.error);continue}let i=l.event;if(i.at>n)continue;let c=o(i.grantId);if(i.type==="grantCreated"){let m=c.created[0];(!m||i.at<m.at)&&(c.created=[i])}else i.type==="grantActivated"?c.activated.push(i):i.type==="grantRevoked"?c.revoked.push(i):i.type==="grantExpired"&&c.expired.push(i)}let a=[];for(let[d,l]of s.entries()){let i=l.created[0]||null,c=i?i.at:null,m=ce(l.activated.map(g=>g.at)),x=ce(l.revoked.map(g=>g.at)),I=ce(l.expired.map(g=>g.at)),b=i?i.grant:null,V=b?L(b,n):!1,C=I??(V?b.expiresAt:null),N;i?l.revoked.length>0?N=z.REVOKED:I!=null||V?N=z.EXPIRED:l.activated.length>0?N=z.ACTIVE:N=z.PENDING:N=z.UNKNOWN;let h={grantId:d,status:N,createdAt:c,activatedAt:m,revokedAt:x,expiredAt:C,reason:l.revoked.length>0?Ne(l.revoked.map(g=>g.reason).find(Boolean)||null):null,grant:b?xt(b):null};a.push(h)}a.sort((d,l)=>d.grantId<l.grantId?-1:d.grantId>l.grantId?1:0),r.sort((d,l)=>{let i=(d.at??-1/0)-(l.at??-1/0);if(i!==0)return i;let c=d.grantId||"",m=l.grantId||"";return c<m?-1:c>m?1:0});let u=a.filter(d=>d.status===z.ACTIVE),f=a.filter(d=>d.status!==z.ACTIVE);return Object.freeze({active:Object.freeze(u),historical:Object.freeze(f),all:Object.freeze(a),invalidEvents:Object.freeze(r)})}import{createHash as wt}from"node:crypto";function bt(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 $e(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 n=bt(e,t);if(n==="")throw new Error(`${t} is required`);if(!/^-?\d+$/.test(n)&&!/^0x[0-9a-fA-F]+$/.test(n))throw new Error(`${t} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(n)}`);try{return BigInt(n)}catch{throw new Error(`${t} must be an integer, got ${JSON.stringify(n)}`)}}function ht(e,t,n="guard"){let r=Number(t);if(t==null||!Number.isFinite(r))throw new Error(`${n}: current time must be a finite number (got ${St(t)})`);let s=Number(e?.issuedAtMs),o=Number(e?.expiresAtMs);if(!Number.isFinite(o))throw new Error(`${n}: expiresAtMs is required and must be a finite number`);if(r>o)throw new Error(`${n} expired at ${o}, now ${r}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(s))throw new Error(`${n}: issuedAtMs must be a finite number when present`);if(o<=s)throw new Error(`${n}: expiry must be after issuance`)}return{now:r,issuedAtMs:s,expiresAtMs:o}}function ke(e,t,{inclusive:n=!1}={}){try{let{now:r,expiresAtMs:s}=ht(e,t);return!(n&&r>=s)}catch{return!1}}function St(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var de=Object.freeze({SAFE:"safe",KERNEL_ZERODEV:"kernel-zerodev",BICONOMY_NEXUS:"biconomy-nexus",PERMISSIONLESS_VIEM:"permissionless-viem"}),Ge=Object.freeze(Object.values(de)),P=Object.freeze({ACTIVE:"active",EXPIRED:"expired",REVOKED:"revoked"}),Re=1440*60*1e3,Et=["read:","simulate:"],It=/^0x[0-9a-fA-F]{40}$/;function Nt(e){let t=String(e||"");return Et.some(n=>t.startsWith(n))}function y(e){throw new Error(`session: ${e}`)}function ue(e,t){let n=String(e??"").trim().toLowerCase();return It.test(n)||y(`${t} must be a 0x-prefixed 20-byte address`),n}function Ot(e){let t=String(e??"").trim().toLowerCase();return t||y("action ids must be non-empty strings"),t.length>128&&y("action id too long"),t}function $t(e,t){let n=Number(e);return(!Number.isFinite(n)||!Number.isInteger(n)||n<=0)&&y(`${t} must be a positive integer`),n}function ve(e,t,{allowZero:n=!0}={}){if(e==null||e==="")return"0";let r;try{r=$e(e,t)}catch(s){y(s.message)}return r<0n&&y(`${t} must not be negative`),!n&&r===0n&&y(`${t} must be greater than zero`),r.toString()}function F(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(F).join(",")+"]":"{"+Object.keys(e).sort().map(n=>JSON.stringify(n)+":"+F(e[n])).join(",")+"}"}function fe(e){let t=wt("sha256");return t.update(F(e),"utf8"),`0x${t.digest("hex")}`}function _e({provider:e,owner:t,agent:n,chainId:r,actions:s,targets:o=[],maxValueWei:a="0",maxGasWei:u,expiresAtMs:f,nonce:d=0,issuedAtMs:l=Date.now()}={}){let i=String(e??"").trim().toLowerCase();Ge.includes(i)||y(`provider must be one of ${Ge.join(", ")}`);let c=ue(t,"owner"),m=ue(n,"agent");c===m&&y("agent key must differ from owner wallet");let x=$t(r,"chainId");(!Array.isArray(s)||s.length===0)&&y("actions must be a non-empty array");let I=[...new Set(s.map(Ot))].sort();Array.isArray(o)||y("targets must be an array");let b=[...new Set(o.map(qe=>ue(qe,"target")))].sort(),V=I.every(Nt);b.length===0&&!V&&y("empty target allowlist is only allowed when every action is read/simulate");let C=ve(a,"maxValueWei"),N=u==null?null:ve(u,"maxGasWei"),h=Number(l);Number.isFinite(h)||y("issuedAtMs must be a finite number");let g=Number(f);Number.isFinite(g)||y("expiresAtMs must be a finite number"),g<=h&&y("expiresAtMs must be after issuedAtMs"),g-h>Re&&y(`session grant exceeds the hard 24-hour TTL (${Re} ms)`);let J=String(d??0),v={mode:"oracle-session-grant",version:1,provider:i,owner:c,agent:m,chainId:x,actions:I,targets:b,maxValueWei:C,maxGasWei:N,issuedAtMs:h,expiresAtMs:g,nonce:J},Ue={id:fe(v),...v};return Object.freeze(Ue)}function Te(){let e=new Map;return{revoke(t,{nowMs:n=Date.now(),reason:r=null}={}){return t||y("revoke requires a sessionId"),e.has(t)||e.set(t,{revokedAtMs:Number(n),reason:r}),e.get(t)},isRevoked(t){return e.has(t)},revokedAt(t){return e.get(t)?.revokedAtMs??null},get size(){return e.size}}}function kt(e,t){return t?typeof t.isRevoked=="function"?t.isRevoked(e.id):t instanceof Set?t.has(e.id):Array.isArray(t)?t.includes(e.id):!1:!1}function Me(e,{nowMs:t=Date.now(),revocation:n}={}){return(!e||e.mode!=="oracle-session-grant")&&y("invalid session grant"),kt(e,n)?P.REVOKED:ke({expiresAtMs:e.expiresAtMs},t,{inclusive:!0})?P.ACTIVE:P.EXPIRED}import{encodeFunctionData as De,keccak256 as Gt,stringToHex as Rt,numberToHex as R,isAddress as B,isHex as Y,getAddress as D}from"viem";var vt="0x0000000071727De22E5E9d8BAf0edAc6f37da032",_t=[{type:"function",name:"getNonce",stateMutability:"view",inputs:[{name:"sender",type:"address"},{name:"key",type:"uint192"}],outputs:[{name:"nonce",type:"uint256"}]}],Ve=[{type:"function",name:"installSessionKey",stateMutability:"nonpayable",inputs:[{name:"sessionId",type:"bytes32"},{name:"agent",type:"address"},{name:"validAfter",type:"uint48"},{name:"validUntil",type:"uint48"},{name:"actionsHash",type:"bytes32"},{name:"targets",type:"address[]"},{name:"maxValueWei",type:"uint256"},{name:"maxGasWei",type:"uint256"}],outputs:[]},{type:"function",name:"revokeSessionKey",stateMutability:"nonpayable",inputs:[{name:"sessionId",type:"bytes32"}],outputs:[]}];function p(e){throw new Error(`aa-adapter: ${e}`)}function je(e){return(typeof e!="string"||!B(e))&&p("opts.moduleAddress is required and must be a valid 0x address of the deployed session-key module on the owner's smart account (this adapter never guesses/hardcodes a contract address)"),D(e)}function Ce(e){(!e||e.mode!=="oracle-session-grant")&&p("input is not a valid session-key-model grant (missing/wrong mode)");let{id:t,...n}=e;fe(n)!==t&&p("grant integrity check failed: id does not match grant fields (tampered or hand-built object)")}function Tt(e,t={}){Ce(e);let n=Me(e,t);n!==P.ACTIVE&&p(`refusing to encode calldata for a ${n} session (${e.id})`)}function ze(e,t){let n=Math.floor(Number(e)/1e3);return(!Number.isFinite(n)||n<0||n>0xffffffffffff)&&p(`${t} does not fit a uint48 seconds timestamp`),BigInt(n)}function Le(e,t={}){Tt(e,t);let n=je(t.moduleAddress),r=t.abi??Ve,s=D(e.agent),o=e.targets.map(c=>D(c)),a=ze(e.issuedAtMs,"issuedAtMs"),u=ze(e.expiresAtMs,"expiresAtMs"),f=Gt(Rt(F(e.actions))),d=BigInt(e.maxValueWei),l=e.maxGasWei==null?0n:BigInt(e.maxGasWei),i=De({abi:r,functionName:"installSessionKey",args:[e.id,s,a,u,f,o,d,l]});return{to:n,data:i,value:"0x0"}}function We(e,t={}){let n;typeof e=="string"?n=e:e&&e.mode==="oracle-session-grant"?(Ce(e),n=e.id):p("revokeSessionKey requires a session-key-model grant object or a raw session id string"),(!Y(n)||n.length!==66)&&p("session id must be a 0x-prefixed 32-byte hash (as produced by computeSessionId)");let r=je(t.moduleAddress),s=t.abi??Ve,o=De({abi:s,functionName:"revokeSessionKey",args:[n]});return{to:r,data:o,value:"0x0"}}var Mt=["callGasLimit","verificationGasLimit","preVerificationGas","maxFeePerGas","maxPriorityFeePerGas"];function O(e,t){e==null&&p(`${t} is required`);let n;try{n=typeof e=="bigint"?e:BigInt(e)}catch{p(`${t} must be an integer, bigint, or 0x-hex string`)}return n<0n&&p(`${t} must not be negative`),n}async function Pe(e={}){let{client:t,entryPoint:n=vt,sender:r,callData:s,nonce:o,nonceKey:a=0n,factory:u,factoryData:f,paymaster:d,paymasterVerificationGasLimit:l,paymasterPostOpGasLimit:i,paymasterData:c="0x"}=e;(typeof r!="string"||!B(r))&&p("params.sender must be a valid 0x address"),(typeof s!="string"||!Y(s))&&p("params.callData must be 0x-prefixed hex"),(typeof n!="string"||!B(n))&&p("params.entryPoint must be a valid 0x address");let m=D(r),x=D(n);for(let v of Mt)e[v]==null&&p(`params.${v} is required (this adapter does not estimate gas)`);let I=O(e.callGasLimit,"callGasLimit"),b=O(e.verificationGasLimit,"verificationGasLimit"),V=O(e.preVerificationGas,"preVerificationGas"),C=O(e.maxFeePerGas,"maxFeePerGas"),N=O(e.maxPriorityFeePerGas,"maxPriorityFeePerGas");u==null!=(f==null)&&p("factory and factoryData must both be set (counterfactual deploy) or both omitted"),u!=null&&(typeof u!="string"||!B(u))&&p("params.factory must be a valid 0x address"),f!=null&&(typeof f!="string"||!Y(f))&&p("params.factoryData must be 0x-prefixed hex");let h=d!=null;h&&((typeof d!="string"||!B(d))&&p("params.paymaster must be a valid 0x address"),(l==null||i==null)&&p("paymasterVerificationGasLimit and paymasterPostOpGasLimit are required when paymaster is set")),c!=null&&(typeof c!="string"||!Y(c))&&p("params.paymasterData must be 0x-prefixed hex");let g;if(o!=null)g=O(o,"nonce");else{(!t||typeof t.readContract!="function")&&p("params.nonce was omitted and no usable client was provided \u2014 pass an explicit nonce or a client with an async readContract({address, abi, functionName, args}) method (a real viem PublicClient in production, a mock in tests; this adapter makes no network call itself)");let v=O(a,"nonceKey");g=await t.readContract({address:x,abi:_t,functionName:"getNonce",args:[m,v]}),g=O(g,"resolved nonce")}let J={sender:m,nonce:R(g),factory:u!=null?D(u):null,factoryData:f??null,callData:s,callGasLimit:R(I),verificationGasLimit:R(b),preVerificationGas:R(V),maxFeePerGas:R(C),maxPriorityFeePerGas:R(N),paymaster:h?D(d):null,paymasterVerificationGasLimit:h?R(O(l,"paymasterVerificationGasLimit")):null,paymasterPostOpGasLimit:h?R(O(i,"paymasterPostOpGasLimit")):null,paymasterData:h?c:null,signature:"0x"};return Object.freeze(J)}import{getBytes as zt,verifyMessage as Dt}from"ethers";var K=Object.freeze({PLAN:"oracle-session-plan",ACTIVATION:"oracle-session-activation",REVOCATION:"oracle-session-revocation",DESCRIPTION:"oracle-session-description"});function $(e){throw new Error(`session-orchestrator: ${e}`)}var Vt=Object.freeze(["id","sessionId"]),jt=/^0x[0-9a-fA-F]{64}$/;function le(e,t){if(e==null||typeof e!="object")return typeof e=="string"&&Vt.includes(t)&&jt.test(e)?`session-id:${e.slice(2)}`:e;if(Array.isArray(e))return e.map(r=>le(r,null));let n={};for(let[r,s]of Object.entries(e)){if(r==="signature"){s!=="0x"&&$('refusing to return a userOp whose signature is not the empty "0x" placeholder (this module never signs)');continue}n[r]=le(s,r)}return n}function U(e){return E(le(e,null)),e}function q(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))q(t)}return e}function Ct(e,t={}){let n=T(e,{now:t.now});if(!n.ok)throw new S(n.errors);let r=ie(n.grant,{now:t.now}),s=q({kind:K.PLAN,unsigned:!0,grantId:r.payload.grantId,grant:n.grant,unsignedGrant:r,signingBytes:r.signing,render:r.render});return U(s)}function Lt(e){(typeof e!="string"||e.trim()==="")&&$("ownerSignature is required (the owner must have signed the grant in their own wallet)");let t=e.trim();return(!/^0x[0-9a-fA-F]+$/.test(t)||t==="0x")&&$("ownerSignature must be non-empty 0x-prefixed hex"),t}async function Wt({grant:e,ownerSignature:t,verifyOwnerSignature:n,nowSeconds:r}){let s=Lt(t),o=ie(e,{now:r});if(typeof n=="function"){await n({grant:e,ownerSignature:s,signingBytes:o.signing})!==!0&&$("ownerSignature verification failed");return}try{Dt(zt(o.signing.bytesHex),s).toLowerCase()!==e.accountAddress.toLowerCase()&&$("ownerSignature signer does not match grant accountAddress")}catch(a){if(String(a?.message||"").startsWith("session-orchestrator:"))throw a;$("ownerSignature could not be verified; smart accounts must provide verifyOwnerSignature")}}async function Fe({grant:e,ownerSignature:t,sessionKeyModel:n}={},r){(n==null||typeof n!="object")&&$("sessionKeyModel is required ({ provider?, moduleAddress, issuedAtMs, userOp })");let{provider:s=de.PERMISSIONLESS_VIEM,moduleAddress:o,issuedAtMs:a,abi:u,userOp:f}=n;Number.isFinite(Number(a))||$("sessionKeyModel.issuedAtMs (epoch MILLISECONDS) is required for a deterministic session grant"),(f==null||typeof f!="object")&&$("sessionKeyModel.userOp (gas/fee/nonce params for buildUserOperation) is required");let d=Math.floor(Number(a)/1e3),l=T(e,{now:d});if(!l.ok)throw new S(l.errors);let i=l.grant;await Wt({grant:i,ownerSignature:t,verifyOwnerSignature:r,nowSeconds:d});let c=i.expiresAt*1e3,m=_e({provider:s,owner:i.accountAddress,agent:i.agentAddress,chainId:i.chainId,actions:i.actions,targets:i.targets,maxValueWei:i.maxValueWei,maxGasWei:i.maxGasWei,expiresAtMs:c,nonce:i.nonce,issuedAtMs:Number(a)}),x=Le(m,{moduleAddress:o,abi:u,nowMs:Number(a)}),I=await Pe({...f,sender:i.accountAddress,callData:x.data}),b=q({kind:K.ACTIVATION,unsigned:!0,grantId:w(i),sessionId:m.id,sessionGrant:m,install:x,userOp:I,units:{expiresAtSeconds:i.expiresAt,expiresAtMs:m.expiresAtMs}});return U(b)}async function Pt(e={}){return Fe(e,void 0)}function Ft({verifyOwnerSignature:e}={}){typeof e!="function"&&$("createSessionOrchestrator requires a trusted verifyOwnerSignature function");let t=e;return Object.freeze({activateSession(n={}){return Fe(n,t)}})}function Bt(e,t={}){let n=We(e,{moduleAddress:t.moduleAddress,abi:t.abi}),r=typeof e=="string"?e:e.id,s=t.registry??Te(),o=s.revoke(r,{nowMs:t.nowMs??Date.now(),reason:t.reason??null}),a={kind:K.REVOCATION,sessionId:r,revoke:n,revocation:Object.freeze({revokedAtMs:o.revokedAtMs,reason:o.reason}),registry:s};return Object.freeze(a),q(a.revoke),U(a)}function Kt(e,t){let n=Oe(e,{now:t}),r=q({kind:K.DESCRIPTION,now:t,active:n.active,count:n.active.length,index:n});return U(r)}var Ke={};pe(Ke,{formatBps:()=>Be,formatWei:()=>me,renderGrant:()=>Ht});var Ut=14;function A(e,t){return`${(e+":").padEnd(Ut)}${t}`}function qt(e){return new Date(e*1e3).toISOString()}function Be(e){return`${e} bps (${(e/100).toFixed(2)}%)`}function me(e){return`${String(e).replace(/\B(?=(\d{3})+(?!\d))/g,",")} wei`}function Ht(e,t={}){let n=G(e,t),r=w(n),s=n.actions.every(a=>j(a));return["ORACLE CONTROL GRANT (deterministic authorization)","==================================================",A("Grant ID",r),A("Version",String(_)),A("Chain",String(n.chainId)),A("Agent",n.agentAddress),A("Account",n.accountAddress),A("Actions",n.actions.join(", ")),A("Targets",n.targets.length?n.targets.join(", "):"(none \u2014 read/simulate only)"),A("Max value",me(n.maxValueWei)),A("Max gas",me(n.maxGasWei)),A("Max slippage",Be(n.maxSlippageBps)),A("Expires",`${qt(n.expiresAt)} (unix ${n.expiresAt})`),A("Nonce",n.nonce),A("Revocation",n.revocationKey),"--------------------------------------------------",s?"Scope: read/simulate only \u2014 this grant cannot move funds.":"Scope: includes state-changing actions bounded by the caps above.","Self-custodial: this grant contains public data only and can be revoked at any time via the revocation key."].join(`
|
|
3
|
-
`)}var En=Object.freeze({userSigns:!0,houseCustody:!1,storesPrivateKeys:!1,revocable:!0,timeBoxed:!0,deterministicReads:!0,note:"Oracle prepares and validates grants. The user signs; Oracle never holds a key."});export{En as GRANTS_POSTURE,
|
|
2
|
+
`)}function ie(e={},t={}){let n=ct(t),r=e&&e.kind===tt?e.grant:e,s=G(r,{now:n,allowWildcardActions:t.allowWildcardActions===!0}),o=H(s),a=w(s),u=Buffer.from(o,"utf8"),f=X({kind:nt,unsigned:!0,payload:X({version:_,grantId:a,grant:s,canonical:o}),signing:X({scheme:Se,message:o,bytesHex:`0x${u.toString("hex")}`,byteLength:u.length,sha256:a}),render:dt(s,a)});return E(f)}var z=Object.freeze({ACTIVE:"active",EXPIRED:"expired",REVOKED:"revoked",INVALID:"invalid"});function we(e){if(e==null)return[];if(Array.isArray(e))return e;if(e instanceof Map)return[...e.values()];if(typeof e[Symbol.iterator]=="function")return[...e];throw new TypeError("grant store must be an array, Map, or iterable of grant records")}function ft(e){return e&&typeof e=="object"&&!Array.isArray(e)&&e.grant!=null?{grant:e.grant,revoked:e.revoked===!0||e.revokedAt!=null}:{grant:e,revoked:!1}}function oe(e){let t=Number(typeof e=="string"?e.trim():e);if(!Number.isSafeInteger(t)||t<0)throw new TypeError("an explicit unix-seconds `now` is required (deterministic liveness, no wall-clock fallback)");return t}function lt(e,t,n){if(e==null)return!1;if(typeof e=="function")return e(t,n)===!0;let r=[t,n.revocationKey];return e instanceof Set?r.some(s=>e.has(s)):Array.isArray(e)?r.some(s=>e.includes(s)):typeof e.has=="function"?r.some(s=>e.has(s)):!1}function ae(e,{now:t,revoked:n}={}){let r=oe(t),{grant:s,revoked:o}=ft(e),{ok:a,grant:u}=T(s);if(!a)return{status:z.INVALID,id:null,grant:null};let f=w(u);return o||lt(n,f,u)?{status:z.REVOKED,id:f,grant:u}:L(u,r)?{status:z.EXPIRED,id:f,grant:u}:{status:z.ACTIVE,id:f,grant:u}}function mt(e,{now:t,revoked:n,agentAddress:r,accountAddress:s,chainId:o}={}){let a=oe(t),u=r!=null?String(r).trim().toLowerCase():null,f=s!=null?String(s).trim().toLowerCase():null,d=o!=null?Number(o):null,l=[];for(let i of we(e)){let{status:c,id:m,grant:x}=ae(i,{now:a,revoked:n});c===z.ACTIVE&&(u!=null&&x.agentAddress!==u||f!=null&&x.accountAddress!==f||d!=null&&x.chainId!==d||l.push(Object.freeze({id:m,grant:x})))}return l.sort((i,c)=>i.id<c.id?-1:i.id>c.id?1:0),E(Object.freeze(l))}function pt(e,t,{now:n,revoked:r}={}){let s=oe(n),o=String(t??"").trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(o))return null;for(let a of we(e)){let u=ae(a,{now:s,revoked:r});if(u.status!==z.INVALID&&u.id===o)return E(Object.freeze({id:u.id,status:u.status,grant:u.grant}))}return null}var gt=Object.freeze(["grantCreated","grantActivated","grantRevoked","grantExpired"]),M=Object.freeze({ACTIVE:"active",PENDING:"pending",REVOKED:"revoked",EXPIRED:"expired",UNKNOWN:"unknown",INVALID:"invalid"}),yt=Object.freeze(["chainId","agentAddress","accountAddress","actions","targets","maxValueWei","maxGasWei","maxSlippageBps","expiresAt","nonce","revocationKey"]);function Ee(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Ie(e){return typeof e=="bigint"?Number(e):typeof e=="number"&&Number.isFinite(e)?e:typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e.trim()))?Number(e.trim()):null}function Ne(e,t=512){if(typeof e!="string")return null;let n=e.trim();return n?n.length>t?n.slice(0,t):n:null}function xt(e){let t={};for(let n of yt)t[n]=e[n];return t}function At(e,t){if(!Ee(e))return{ok:!1,error:{type:null,at:null,grantId:null,message:"event must be a plain object"}};let n=typeof e.type=="string"?e.type:null,r=Ie(e.at),s=typeof e.grantId=="string"&&e.grantId.trim()?e.grantId.trim():null;if(!gt.includes(n))return{ok:!1,error:{type:n,at:r,grantId:s,message:`unknown event type "${String(n)}"`}};if(r==null)return{ok:!1,error:{type:n,at:null,grantId:s,message:"event.at must be a unix-seconds number"}};if(n==="grantCreated"){if(!Ee(e.grant))return{ok:!1,error:{type:n,at:r,grantId:s,message:"grantCreated requires a grant payload"}};let a;try{a=G(e.grant,{allowWildcardActions:t.allowWildcardActions})}catch(f){let d=f instanceof S?f.message:String(f?.message||f);return{ok:!1,error:{type:n,at:r,grantId:s,message:d}}}let u=w(e.grant,{allowWildcardActions:t.allowWildcardActions});return s&&s!==u?{ok:!1,error:{type:n,at:r,grantId:s,message:"grantId does not match content-derived grant identity (fail closed)"}}:{ok:!0,event:{type:n,at:r,grantId:u,grant:a}}}if(!s)return{ok:!1,error:{type:n,at:r,grantId:null,message:`${n} requires a grantId`}};let o=n==="grantRevoked"?Ne(e.reason):null;return{ok:!0,event:{type:n,at:r,grantId:s,reason:o}}}function ce(e){return e.length?e.reduce((t,n)=>Math.min(t,n)):null}function Oe(e,t={}){let n=Ie(t.now);if(n==null)throw new Error("grant-indexer: opts.now (unix seconds) is required");if(!Array.isArray(e))throw new Error("grant-indexer: events must be an array");let r=[],s=new Map;function o(d){return s.has(d)||s.set(d,{created:[],activated:[],revoked:[],expired:[]}),s.get(d)}for(let d of e){let l=At(d,t);if(!l.ok){r.push(l.error);continue}let i=l.event;if(i.at>n)continue;let c=o(i.grantId);if(i.type==="grantCreated"){let m=c.created[0];(!m||i.at<m.at)&&(c.created=[i])}else i.type==="grantActivated"?c.activated.push(i):i.type==="grantRevoked"?c.revoked.push(i):i.type==="grantExpired"&&c.expired.push(i)}let a=[];for(let[d,l]of s.entries()){let i=l.created[0]||null,c=i?i.at:null,m=ce(l.activated.map(g=>g.at)),x=ce(l.revoked.map(g=>g.at)),I=ce(l.expired.map(g=>g.at)),b=i?i.grant:null,V=b?L(b,n):!1,C=I??(V?b.expiresAt:null),N;i?l.revoked.length>0?N=M.REVOKED:I!=null||V?N=M.EXPIRED:l.activated.length>0?N=M.ACTIVE:N=M.PENDING:N=M.UNKNOWN;let h={grantId:d,status:N,createdAt:c,activatedAt:m,revokedAt:x,expiredAt:C,reason:l.revoked.length>0?Ne(l.revoked.map(g=>g.reason).find(Boolean)||null):null,grant:b?xt(b):null};a.push(h)}a.sort((d,l)=>d.grantId<l.grantId?-1:d.grantId>l.grantId?1:0),r.sort((d,l)=>{let i=(d.at??-1/0)-(l.at??-1/0);if(i!==0)return i;let c=d.grantId||"",m=l.grantId||"";return c<m?-1:c>m?1:0});let u=a.filter(d=>d.status===M.ACTIVE),f=a.filter(d=>d.status!==M.ACTIVE);return Object.freeze({active:Object.freeze(u),historical:Object.freeze(f),all:Object.freeze(a),invalidEvents:Object.freeze(r)})}import{createHash as wt}from"node:crypto";function bt(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 $e(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 n=bt(e,t);if(n==="")throw new Error(`${t} is required`);if(!/^-?\d+$/.test(n)&&!/^0x[0-9a-fA-F]+$/.test(n))throw new Error(`${t} must be an integer in decimal or 0x-hex form, got ${JSON.stringify(n)}`);try{return BigInt(n)}catch{throw new Error(`${t} must be an integer, got ${JSON.stringify(n)}`)}}function ht(e,t,n="guard"){if(typeof t!="number"||!Number.isFinite(t))throw new Error(`${n}: current time must be a finite number (got ${St(t)})`);let r=t,s=Number(e?.issuedAtMs),o=Number(e?.expiresAtMs);if(!Number.isFinite(o))throw new Error(`${n}: expiresAtMs is required and must be a finite number`);if(r>o)throw new Error(`${n} expired at ${o}, now ${r}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(s))throw new Error(`${n}: issuedAtMs must be a finite number when present`);if(o<=s)throw new Error(`${n}: expiry must be after issuance`)}return{now:r,issuedAtMs:s,expiresAtMs:o}}function ke(e,t,{inclusive:n=!1}={}){try{let{now:r,expiresAtMs:s}=ht(e,t);return!(n&&r>=s)}catch{return!1}}function St(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var de=Object.freeze({SAFE:"safe",KERNEL_ZERODEV:"kernel-zerodev",BICONOMY_NEXUS:"biconomy-nexus",PERMISSIONLESS_VIEM:"permissionless-viem"}),Ge=Object.freeze(Object.values(de)),P=Object.freeze({ACTIVE:"active",EXPIRED:"expired",REVOKED:"revoked"}),Re=1440*60*1e3,Et=["read:","simulate:"],It=/^0x[0-9a-fA-F]{40}$/;function Nt(e){let t=String(e||"");return Et.some(n=>t.startsWith(n))}function y(e){throw new Error(`session: ${e}`)}function ue(e,t){let n=String(e??"").trim().toLowerCase();return It.test(n)||y(`${t} must be a 0x-prefixed 20-byte address`),n}function Ot(e){let t=String(e??"").trim().toLowerCase();return t||y("action ids must be non-empty strings"),t.length>128&&y("action id too long"),t}function $t(e,t){let n=Number(e);return(!Number.isFinite(n)||!Number.isInteger(n)||n<=0)&&y(`${t} must be a positive integer`),n}function ve(e,t,{allowZero:n=!0}={}){if(e==null||e==="")return"0";let r;try{r=$e(e,t)}catch(s){y(s.message)}return r<0n&&y(`${t} must not be negative`),!n&&r===0n&&y(`${t} must be greater than zero`),r.toString()}function F(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(F).join(",")+"]":"{"+Object.keys(e).sort().map(n=>JSON.stringify(n)+":"+F(e[n])).join(",")+"}"}function fe(e){let t=wt("sha256");return t.update(F(e),"utf8"),`0x${t.digest("hex")}`}function _e({provider:e,owner:t,agent:n,chainId:r,actions:s,targets:o=[],maxValueWei:a="0",maxGasWei:u,expiresAtMs:f,nonce:d=0,issuedAtMs:l=Date.now()}={}){let i=String(e??"").trim().toLowerCase();Ge.includes(i)||y(`provider must be one of ${Ge.join(", ")}`);let c=ue(t,"owner"),m=ue(n,"agent");c===m&&y("agent key must differ from owner wallet");let x=$t(r,"chainId");(!Array.isArray(s)||s.length===0)&&y("actions must be a non-empty array");let I=[...new Set(s.map(Ot))].sort();Array.isArray(o)||y("targets must be an array");let b=[...new Set(o.map(qe=>ue(qe,"target")))].sort(),V=I.every(Nt);b.length===0&&!V&&y("empty target allowlist is only allowed when every action is read/simulate");let C=ve(a,"maxValueWei"),N=u==null?null:ve(u,"maxGasWei"),h=Number(l);Number.isFinite(h)||y("issuedAtMs must be a finite number");let g=Number(f);Number.isFinite(g)||y("expiresAtMs must be a finite number"),g<=h&&y("expiresAtMs must be after issuedAtMs"),g-h>Re&&y(`session grant exceeds the hard 24-hour TTL (${Re} ms)`);let J=String(d??0),v={mode:"oracle-session-grant",version:1,provider:i,owner:c,agent:m,chainId:x,actions:I,targets:b,maxValueWei:C,maxGasWei:N,issuedAtMs:h,expiresAtMs:g,nonce:J},Ue={id:fe(v),...v};return Object.freeze(Ue)}function Te(){let e=new Map;return{revoke(t,{nowMs:n=Date.now(),reason:r=null}={}){return t||y("revoke requires a sessionId"),e.has(t)||e.set(t,{revokedAtMs:Number(n),reason:r}),e.get(t)},isRevoked(t){return e.has(t)},revokedAt(t){return e.get(t)?.revokedAtMs??null},get size(){return e.size}}}function kt(e,t){return t?typeof t.isRevoked=="function"?t.isRevoked(e.id):t instanceof Set?t.has(e.id):Array.isArray(t)?t.includes(e.id):!1:!1}function ze(e,{nowMs:t=Date.now(),revocation:n}={}){return(!e||e.mode!=="oracle-session-grant")&&y("invalid session grant"),kt(e,n)?P.REVOKED:ke({expiresAtMs:e.expiresAtMs},t,{inclusive:!0})?P.ACTIVE:P.EXPIRED}import{encodeFunctionData as De,keccak256 as Gt,stringToHex as Rt,numberToHex as R,isAddress as B,isHex as Y,getAddress as D}from"viem";var vt="0x0000000071727De22E5E9d8BAf0edAc6f37da032",_t=[{type:"function",name:"getNonce",stateMutability:"view",inputs:[{name:"sender",type:"address"},{name:"key",type:"uint192"}],outputs:[{name:"nonce",type:"uint256"}]}],Ve=[{type:"function",name:"installSessionKey",stateMutability:"nonpayable",inputs:[{name:"sessionId",type:"bytes32"},{name:"agent",type:"address"},{name:"validAfter",type:"uint48"},{name:"validUntil",type:"uint48"},{name:"actionsHash",type:"bytes32"},{name:"targets",type:"address[]"},{name:"maxValueWei",type:"uint256"},{name:"maxGasWei",type:"uint256"}],outputs:[]},{type:"function",name:"revokeSessionKey",stateMutability:"nonpayable",inputs:[{name:"sessionId",type:"bytes32"}],outputs:[]}];function p(e){throw new Error(`aa-adapter: ${e}`)}function je(e){return(typeof e!="string"||!B(e))&&p("opts.moduleAddress is required and must be a valid 0x address of the deployed session-key module on the owner's smart account (this adapter never guesses/hardcodes a contract address)"),D(e)}function Ce(e){(!e||e.mode!=="oracle-session-grant")&&p("input is not a valid session-key-model grant (missing/wrong mode)");let{id:t,...n}=e;fe(n)!==t&&p("grant integrity check failed: id does not match grant fields (tampered or hand-built object)")}function Tt(e,t={}){Ce(e);let n=ze(e,t);n!==P.ACTIVE&&p(`refusing to encode calldata for a ${n} session (${e.id})`)}function Me(e,t){let n=Math.floor(Number(e)/1e3);return(!Number.isFinite(n)||n<0||n>0xffffffffffff)&&p(`${t} does not fit a uint48 seconds timestamp`),BigInt(n)}function Le(e,t={}){Tt(e,t);let n=je(t.moduleAddress),r=t.abi??Ve,s=D(e.agent),o=e.targets.map(c=>D(c)),a=Me(e.issuedAtMs,"issuedAtMs"),u=Me(e.expiresAtMs,"expiresAtMs"),f=Gt(Rt(F(e.actions))),d=BigInt(e.maxValueWei),l=e.maxGasWei==null?0n:BigInt(e.maxGasWei),i=De({abi:r,functionName:"installSessionKey",args:[e.id,s,a,u,f,o,d,l]});return{to:n,data:i,value:"0x0"}}function We(e,t={}){let n;typeof e=="string"?n=e:e&&e.mode==="oracle-session-grant"?(Ce(e),n=e.id):p("revokeSessionKey requires a session-key-model grant object or a raw session id string"),(!Y(n)||n.length!==66)&&p("session id must be a 0x-prefixed 32-byte hash (as produced by computeSessionId)");let r=je(t.moduleAddress),s=t.abi??Ve,o=De({abi:s,functionName:"revokeSessionKey",args:[n]});return{to:r,data:o,value:"0x0"}}var zt=["callGasLimit","verificationGasLimit","preVerificationGas","maxFeePerGas","maxPriorityFeePerGas"];function O(e,t){e==null&&p(`${t} is required`);let n;try{n=typeof e=="bigint"?e:BigInt(e)}catch{p(`${t} must be an integer, bigint, or 0x-hex string`)}return n<0n&&p(`${t} must not be negative`),n}async function Pe(e={}){let{client:t,entryPoint:n=vt,sender:r,callData:s,nonce:o,nonceKey:a=0n,factory:u,factoryData:f,paymaster:d,paymasterVerificationGasLimit:l,paymasterPostOpGasLimit:i,paymasterData:c="0x"}=e;(typeof r!="string"||!B(r))&&p("params.sender must be a valid 0x address"),(typeof s!="string"||!Y(s))&&p("params.callData must be 0x-prefixed hex"),(typeof n!="string"||!B(n))&&p("params.entryPoint must be a valid 0x address");let m=D(r),x=D(n);for(let v of zt)e[v]==null&&p(`params.${v} is required (this adapter does not estimate gas)`);let I=O(e.callGasLimit,"callGasLimit"),b=O(e.verificationGasLimit,"verificationGasLimit"),V=O(e.preVerificationGas,"preVerificationGas"),C=O(e.maxFeePerGas,"maxFeePerGas"),N=O(e.maxPriorityFeePerGas,"maxPriorityFeePerGas");u==null!=(f==null)&&p("factory and factoryData must both be set (counterfactual deploy) or both omitted"),u!=null&&(typeof u!="string"||!B(u))&&p("params.factory must be a valid 0x address"),f!=null&&(typeof f!="string"||!Y(f))&&p("params.factoryData must be 0x-prefixed hex");let h=d!=null;h&&((typeof d!="string"||!B(d))&&p("params.paymaster must be a valid 0x address"),(l==null||i==null)&&p("paymasterVerificationGasLimit and paymasterPostOpGasLimit are required when paymaster is set")),c!=null&&(typeof c!="string"||!Y(c))&&p("params.paymasterData must be 0x-prefixed hex");let g;if(o!=null)g=O(o,"nonce");else{(!t||typeof t.readContract!="function")&&p("params.nonce was omitted and no usable client was provided \u2014 pass an explicit nonce or a client with an async readContract({address, abi, functionName, args}) method (a real viem PublicClient in production, a mock in tests; this adapter makes no network call itself)");let v=O(a,"nonceKey");g=await t.readContract({address:x,abi:_t,functionName:"getNonce",args:[m,v]}),g=O(g,"resolved nonce")}let J={sender:m,nonce:R(g),factory:u!=null?D(u):null,factoryData:f??null,callData:s,callGasLimit:R(I),verificationGasLimit:R(b),preVerificationGas:R(V),maxFeePerGas:R(C),maxPriorityFeePerGas:R(N),paymaster:h?D(d):null,paymasterVerificationGasLimit:h?R(O(l,"paymasterVerificationGasLimit")):null,paymasterPostOpGasLimit:h?R(O(i,"paymasterPostOpGasLimit")):null,paymasterData:h?c:null,signature:"0x"};return Object.freeze(J)}import{getBytes as Mt,verifyMessage as Dt}from"ethers";var K=Object.freeze({PLAN:"oracle-session-plan",ACTIVATION:"oracle-session-activation",REVOCATION:"oracle-session-revocation",DESCRIPTION:"oracle-session-description"});function $(e){throw new Error(`session-orchestrator: ${e}`)}var Vt=Object.freeze(["id","sessionId"]),jt=/^0x[0-9a-fA-F]{64}$/;function le(e,t){if(e==null||typeof e!="object")return typeof e=="string"&&Vt.includes(t)&&jt.test(e)?`session-id:${e.slice(2)}`:e;if(Array.isArray(e))return e.map(r=>le(r,null));let n={};for(let[r,s]of Object.entries(e)){if(r==="signature"){s!=="0x"&&$('refusing to return a userOp whose signature is not the empty "0x" placeholder (this module never signs)');continue}n[r]=le(s,r)}return n}function U(e){return E(le(e,null)),e}function q(e){if(e&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.values(e))q(t)}return e}function Ct(e,t={}){let n=T(e,{now:t.now});if(!n.ok)throw new S(n.errors);let r=ie(n.grant,{now:t.now}),s=q({kind:K.PLAN,unsigned:!0,grantId:r.payload.grantId,grant:n.grant,unsignedGrant:r,signingBytes:r.signing,render:r.render});return U(s)}function Lt(e){(typeof e!="string"||e.trim()==="")&&$("ownerSignature is required (the owner must have signed the grant in their own wallet)");let t=e.trim();return(!/^0x[0-9a-fA-F]+$/.test(t)||t==="0x")&&$("ownerSignature must be non-empty 0x-prefixed hex"),t}async function Wt({grant:e,ownerSignature:t,verifyOwnerSignature:n,nowSeconds:r}){let s=Lt(t),o=ie(e,{now:r});if(typeof n=="function"){await n({grant:e,ownerSignature:s,signingBytes:o.signing})!==!0&&$("ownerSignature verification failed");return}try{Dt(Mt(o.signing.bytesHex),s).toLowerCase()!==e.accountAddress.toLowerCase()&&$("ownerSignature signer does not match grant accountAddress")}catch(a){if(String(a?.message||"").startsWith("session-orchestrator:"))throw a;$("ownerSignature could not be verified; smart accounts must provide verifyOwnerSignature")}}async function Fe({grant:e,ownerSignature:t,sessionKeyModel:n}={},r){(n==null||typeof n!="object")&&$("sessionKeyModel is required ({ provider?, moduleAddress, issuedAtMs, userOp })");let{provider:s=de.PERMISSIONLESS_VIEM,moduleAddress:o,issuedAtMs:a,abi:u,userOp:f}=n;Number.isFinite(Number(a))||$("sessionKeyModel.issuedAtMs (epoch MILLISECONDS) is required for a deterministic session grant"),(f==null||typeof f!="object")&&$("sessionKeyModel.userOp (gas/fee/nonce params for buildUserOperation) is required");let d=Math.floor(Number(a)/1e3),l=T(e,{now:d});if(!l.ok)throw new S(l.errors);let i=l.grant;await Wt({grant:i,ownerSignature:t,verifyOwnerSignature:r,nowSeconds:d});let c=i.expiresAt*1e3,m=_e({provider:s,owner:i.accountAddress,agent:i.agentAddress,chainId:i.chainId,actions:i.actions,targets:i.targets,maxValueWei:i.maxValueWei,maxGasWei:i.maxGasWei,expiresAtMs:c,nonce:i.nonce,issuedAtMs:Number(a)}),x=Le(m,{moduleAddress:o,abi:u,nowMs:Number(a)}),I=await Pe({...f,sender:i.accountAddress,callData:x.data}),b=q({kind:K.ACTIVATION,unsigned:!0,grantId:w(i),sessionId:m.id,sessionGrant:m,install:x,userOp:I,units:{expiresAtSeconds:i.expiresAt,expiresAtMs:m.expiresAtMs}});return U(b)}async function Pt(e={}){return Fe(e,void 0)}function Ft({verifyOwnerSignature:e}={}){typeof e!="function"&&$("createSessionOrchestrator requires a trusted verifyOwnerSignature function");let t=e;return Object.freeze({activateSession(n={}){return Fe(n,t)}})}function Bt(e,t={}){let n=We(e,{moduleAddress:t.moduleAddress,abi:t.abi}),r=typeof e=="string"?e:e.id,s=t.registry??Te(),o=s.revoke(r,{nowMs:t.nowMs??Date.now(),reason:t.reason??null}),a={kind:K.REVOCATION,sessionId:r,revoke:n,revocation:Object.freeze({revokedAtMs:o.revokedAtMs,reason:o.reason}),registry:s};return Object.freeze(a),q(a.revoke),U(a)}function Kt(e,t){let n=Oe(e,{now:t}),r=q({kind:K.DESCRIPTION,now:t,active:n.active,count:n.active.length,index:n});return U(r)}var Ke={};pe(Ke,{formatBps:()=>Be,formatWei:()=>me,renderGrant:()=>Ht});var Ut=14;function A(e,t){return`${(e+":").padEnd(Ut)}${t}`}function qt(e){return new Date(e*1e3).toISOString()}function Be(e){return`${e} bps (${(e/100).toFixed(2)}%)`}function me(e){return`${String(e).replace(/\B(?=(\d{3})+(?!\d))/g,",")} wei`}function Ht(e,t={}){let n=G(e,t),r=w(n),s=n.actions.every(a=>j(a));return["ORACLE CONTROL GRANT (deterministic authorization)","==================================================",A("Grant ID",r),A("Version",String(_)),A("Chain",String(n.chainId)),A("Agent",n.agentAddress),A("Account",n.accountAddress),A("Actions",n.actions.join(", ")),A("Targets",n.targets.length?n.targets.join(", "):"(none \u2014 read/simulate only)"),A("Max value",me(n.maxValueWei)),A("Max gas",me(n.maxGasWei)),A("Max slippage",Be(n.maxSlippageBps)),A("Expires",`${qt(n.expiresAt)} (unix ${n.expiresAt})`),A("Nonce",n.nonce),A("Revocation",n.revocationKey),"--------------------------------------------------",s?"Scope: read/simulate only \u2014 this grant cannot move funds.":"Scope: includes state-changing actions bounded by the caps above.","Self-custodial: this grant contains public data only and can be revoked at any time via the revocation key."].join(`
|
|
3
|
+
`)}var En=Object.freeze({userSigns:!0,houseCustody:!1,storesPrivateKeys:!1,revocable:!0,timeBoxed:!0,deterministicReads:!0,note:"Oracle prepares and validates grants. The user signs; Oracle never holds a key."});export{En as GRANTS_POSTURE,z as GRANT_STATUS,K as ORCHESTRATOR_KINDS,Pt as activateSession,ae as classifyGrant,Ft as createSessionOrchestrator,Kt as describeActive,pt as getGrant,mt as listActiveGrants,Ct as planConnection,be as policy,Ke as render,Bt as revokeSession,U as scanPublicReturn};
|
package/package.json
CHANGED