@oakagentkit/addon 0.0.0-stage → 0.1.1

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.
Files changed (62) hide show
  1. package/LICENSE +18 -0
  2. package/README.md +12 -2
  3. package/build/dist/action-result.d.ts +3 -0
  4. package/build/dist/action-result.js +1 -0
  5. package/build/dist/bridge.d.ts +65 -0
  6. package/build/dist/bridge.js +1 -0
  7. package/build/dist/chunks/2NJCYRBM.js +1 -0
  8. package/build/dist/chunks/44YOYZLT.js +1 -0
  9. package/build/dist/chunks/4B2GMIK7.js +1 -0
  10. package/build/dist/chunks/4LWKW7PM.js +2 -0
  11. package/build/dist/chunks/67E2KBUQ.js +1 -0
  12. package/build/dist/chunks/GONTF7K4.js +1 -0
  13. package/build/dist/chunks/I5LKYO3W.js +3 -0
  14. package/build/dist/chunks/IVR4JOHU.js +1 -0
  15. package/build/dist/chunks/OB7JDPFV.js +1 -0
  16. package/build/dist/chunks/QIDB35RS.js +1 -0
  17. package/build/dist/chunks/RDCN3YPX.js +5 -0
  18. package/build/dist/chunks/RGOGWTRI.js +1 -0
  19. package/build/dist/chunks/U3IXRJH7.js +5 -0
  20. package/build/dist/chunks/U5VW3XSD.js +2 -0
  21. package/build/dist/chunks/UTTRLIY5.js +1 -0
  22. package/build/dist/chunks/VZCMAMZL.js +2 -0
  23. package/build/dist/chunks/YR4WKA4P.js +1 -0
  24. package/build/dist/chunks/YVAFJM4Y.js +1 -0
  25. package/build/dist/cli.d.ts +67 -0
  26. package/build/dist/cli.js +6 -0
  27. package/build/dist/confirm.d.ts +120 -0
  28. package/build/dist/confirm.js +1 -0
  29. package/build/dist/execution-trace.d.ts +30 -0
  30. package/build/dist/execution-trace.js +1 -0
  31. package/build/dist/identity.d.ts +48 -0
  32. package/build/dist/identity.js +1 -0
  33. package/build/dist/journal.d.ts +53 -0
  34. package/build/dist/journal.js +1 -0
  35. package/build/dist/module-destinations.d.ts +4 -0
  36. package/build/dist/module-destinations.js +1 -0
  37. package/build/dist/onboarding.d.ts +38 -0
  38. package/build/dist/onboarding.js +1 -0
  39. package/build/dist/private-files.d.ts +5 -0
  40. package/build/dist/private-files.js +1 -0
  41. package/build/dist/recipes.d.ts +26 -0
  42. package/build/dist/recipes.js +1 -0
  43. package/build/dist/redact.d.ts +4 -0
  44. package/build/dist/redact.js +1 -0
  45. package/build/dist/renew.d.ts +2 -0
  46. package/build/dist/renew.js +1 -0
  47. package/build/dist/schema/recipe.schema.json +1 -0
  48. package/build/dist/sender.d.ts +141 -0
  49. package/build/dist/sender.js +1 -0
  50. package/build/dist/session.d.ts +45 -0
  51. package/build/dist/session.js +1 -0
  52. package/build/dist/setup.d.ts +26 -0
  53. package/build/dist/setup.js +1 -0
  54. package/build/dist/subscribe.d.ts +347 -0
  55. package/build/dist/subscribe.js +1 -0
  56. package/build/dist/terminal-confirm.d.ts +7 -0
  57. package/build/dist/terminal-confirm.js +1 -0
  58. package/build/dist/version.d.ts +1 -0
  59. package/build/dist/version.js +1 -0
  60. package/build/dist/wallet.d.ts +11 -0
  61. package/build/dist/wallet.js +12 -0
  62. package/package.json +49 -3
package/LICENSE ADDED
@@ -0,0 +1,18 @@
1
+ Oak — Free to use, no copying
2
+ Copyright (c) 2026 Oak. All rights reserved.
3
+
4
+ Anyone may install and use this package, including in their own agents and
5
+ commercial products, free of charge. You may make the copies technically
6
+ necessary to install, run and back up the package for that use.
7
+
8
+ You may not otherwise copy, modify, distribute, resell, sublicense or rehost
9
+ the package code, whether in original, minified or derived form. Products
10
+ may depend on the official package; this does not permit redistributing its
11
+ code inside another package, bundle, service download or hosted mirror.
12
+
13
+ Keep this license with permitted copies. Third-party dependencies are
14
+ separate works governed by their own licenses; these restrictions do not
15
+ replace their terms. This license grants no trademark rights.
16
+
17
+ The package is provided as is, without warranty. To the extent permitted
18
+ by law, Oak is not liable for claims or damages arising from its use.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # @oakagentkit/addon
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The local Oak CLI and MCP bridge. It keeps wallet signing on your computer and connects AI agents to Oak on Robinhood Chain.
4
+
5
+ Install:
6
+
7
+ ```sh
8
+ npm install -g @oakagentkit/addon
9
+ ```
10
+
11
+ See [setup](https://oakagentkit.org/setup.html) and [documentation](https://oakagentkit.org/docs.html). Oak is not affiliated with Robinhood. Not financial advice. Onchain actions involve risk; Oak never promises returns. Run `oak init` and `oak export` yourself in your own terminal, never through an agent. Never share recovery words or private keys.
12
+
13
+ On first use, `oak mcp` or `oak address` creates the local wallet automatically without prompts. `account` returns its address, network, ETH/USDG funding message and optional backup guidance. The agent re-checks balances after funding, then uses `oak_setup` and `oak_subscribe` with user authorization. Mainnet defaults include service/RPC URLs and public contract discovery. Run `oak backup` for guidance; export/recovery remain owner-terminal operations.
@@ -0,0 +1,3 @@
1
+ import type { SenderResult } from '@oakagentkit/core/types';
2
+ export declare function executionSummary(hashes: readonly string[], status: string, details?: string): string;
3
+ export declare function actionResult(data: Record<string, unknown>, sent: SenderResult): Record<string, unknown>;
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunks/IVR4JOHU.js";export{b as actionResult,a as executionSummary};
@@ -0,0 +1,65 @@
1
+ import { type ConfirmMode } from './confirm.js';
2
+ import { createModule as kyberswap } from '@oakagentkit/core/modules/kyberswap/index';
3
+ import { createModule as velora } from '@oakagentkit/core/modules/velora/index';
4
+ import { createModule as spark } from '@oakagentkit/core/modules/spark/index';
5
+ import { createModule as netnet } from '@oakagentkit/core/modules/netnet/index';
6
+ import { createModule as longbow } from '@oakagentkit/core/modules/longbow/index';
7
+ import { createModule as beefy } from '@oakagentkit/core/modules/beefy/index';
8
+ import { createModule as orbio } from '@oakagentkit/core/modules/orbio/index';
9
+ import { createModule as hoodlock } from '@oakagentkit/core/modules/hoodlock/index';
10
+ import { createModule as uniswap } from '@oakagentkit/core/modules/uniswap/index';
11
+ import { createModule as hookr } from '@oakagentkit/core/modules/hookr/index';
12
+ import { createModule as poolstrade } from '@oakagentkit/core/modules/poolstrade/index';
13
+ export declare const MODULE_FACTORIES: readonly [typeof kyberswap, typeof velora, import("@oakagentkit/core/types").CreateModule, typeof spark, typeof netnet, typeof longbow, import("@oakagentkit/core/types").CreateModule, typeof beefy, import("@oakagentkit/core/types").CreateModule, typeof orbio, typeof hoodlock, import("@oakagentkit/core/types").CreateModule, import("@oakagentkit/core/types").CreateModule, import("@oakagentkit/core/types").CreateModule, import("@oakagentkit/core/types").CreateModule, import("@oakagentkit/core/types").CreateModule, import("@oakagentkit/core/types").CreateModule, import("@oakagentkit/core/types").CreateModule, import("@oakagentkit/core/types").CreateModule, typeof uniswap, typeof hookr, import("@oakagentkit/core/types").CreateModule, import("@oakagentkit/core/types").CreateModule, import("@oakagentkit/core/types").CreateModule, typeof poolstrade];
14
+ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
15
+ import { type OakNetwork } from '@oakagentkit/core/addresses';
16
+ import type { Address, Recipe, ToolArgs } from '@oakagentkit/core/types';
17
+ import { type RecipeReadClient } from './recipes.js';
18
+ import { createSender } from './sender.js';
19
+ import { type IdentityClient } from './identity.js';
20
+ import type { SetupRequest } from './setup.js';
21
+ import type { LifecycleResult } from './subscribe.js';
22
+ import type { WalletSigner } from './wallet.js';
23
+ export interface ListedTool {
24
+ name: string;
25
+ description: string;
26
+ inputSchema: {
27
+ type: 'object';
28
+ [key: string]: unknown;
29
+ };
30
+ }
31
+ export declare const READ_TOOLS: ReadonlySet<string>;
32
+ export declare function toolManifest(network?: OakNetwork): ListedTool[];
33
+ export declare function jsonArgs(value: unknown): ToolArgs;
34
+ export declare function serverAddress(value: string): URL;
35
+ export declare const PREVIEW_TTL_SECONDS = 12;
36
+ export interface BridgeOptions {
37
+ confirmMode?: ConfirmMode;
38
+ oakTokenAddress?: Address;
39
+ startupInstructions?: () => Promise<string>;
40
+ launchOnly?: boolean;
41
+ privateTestMode?: boolean;
42
+ identity?: Pick<IdentityClient, 'sessions' | 'requireVerified'> & Partial<Pick<IdentityClient, 'unlink'>>;
43
+ signOwner?: import('./identity.js').OwnerSign;
44
+ setup?: (request: SetupRequest) => Promise<unknown>;
45
+ subscribe?: (plan: 'holder' | 'nohold') => Promise<unknown>;
46
+ network?: OakNetwork;
47
+ serverUrl: string;
48
+ signer: WalletSigner;
49
+ sender?: Pick<ReturnType<typeof createSender>, 'send' | 'signTypedData'> & Partial<Pick<ReturnType<typeof createSender>, 'blockNumber' | 'withAction'>>;
50
+ display(text: string): void | Promise<void>;
51
+ ensureSubscribed(): Promise<LifecycleResult>;
52
+ fetch?: typeof fetch;
53
+ recipes?: () => Promise<Recipe[]>;
54
+ recipeClient?: RecipeReadClient;
55
+ now?: () => number;
56
+ previewTtlSeconds?: number;
57
+ }
58
+ export declare function createBridge(options: BridgeOptions): {
59
+ listTools: () => Promise<ListedTool[]>;
60
+ postTool: (name: string, args: ToolArgs) => Promise<unknown>;
61
+ callTool: (name: string, original: ToolArgs) => Promise<unknown>;
62
+ start: (transport?: Transport) => Promise<void>;
63
+ stop: () => Promise<void>;
64
+ confirmSignature: import("./confirm.js").Confirm;
65
+ };
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g}from"./chunks/RDCN3YPX.js";import"./chunks/RGOGWTRI.js";import"./chunks/4LWKW7PM.js";import"./chunks/U5VW3XSD.js";import"./chunks/VZCMAMZL.js";import"./chunks/GONTF7K4.js";import"./chunks/YVAFJM4Y.js";import"./chunks/IVR4JOHU.js";import"./chunks/U3IXRJH7.js";import"./chunks/2NJCYRBM.js";import"./chunks/YR4WKA4P.js";import"./chunks/4B2GMIK7.js";import"./chunks/QIDB35RS.js";import"./chunks/67E2KBUQ.js";export{a as MODULE_FACTORIES,f as PREVIEW_TTL_SECONDS,b as READ_TOOLS,g as createBridge,d as jsonArgs,e as serverAddress,c as toolManifest};
@@ -0,0 +1 @@
1
+ import{hasErrorCode as m}from"@oakagentkit/core/errors";import{isAddress as p,toHex as c}from"viem";function s(e){throw new Error(`Local transaction guard: ${e}; nothing was signed.`)}function C(e,r,i){let d=(n,f=!1)=>{(!n||typeof n!="object"||Array.isArray(n))&&s("local execution trace is unavailable");let t=n,a=typeof t.type=="string"?t.type.toUpperCase():"";["CALL","STATICCALL","DELEGATECALL","CALLCODE","CREATE","CREATE2","SELFDESTRUCT"].includes(a)||s("malformed local execution trace"),(typeof t.to!="string"||!p(t.to,{strict:!1}))&&s("malformed local execution trace"),f&&(a!=="CALL"||typeof t.from!="string"||t.from.toLowerCase()!==r.account.toLowerCase()||t.to.toLowerCase()!==r.to.toLowerCase()||typeof t.input!="string"||t.input.toLowerCase()!==r.data.toLowerCase()||typeof t.value!="string"||!/^0x[0-9a-f]+$/i.test(t.value)||BigInt(t.value)!==r.value||t.error!==void 0)&&s("execution trace differs from the simulated transaction"),(a==="DELEGATECALL"||a==="CALLCODE")&&!i.some(u=>u.toLowerCase()===t.to.toLowerCase())&&s("delegatecall destination is outside the module contract set"),t.calls!==void 0&&!Array.isArray(t.calls)&&s("malformed local execution trace");for(let u of t.calls??[])d(u)};d(e,!0)}function g(e){return{method:"debug_traceCall",params:[{from:e.account,to:e.to,data:e.data,value:c(e.value),...e.gas!==void 0?{gas:c(e.gas)}:{},...e.nonce!==void 0?{nonce:c(e.nonce)}:{},...e.maxFeePerGas!==void 0?{maxFeePerGas:c(e.maxFeePerGas)}:{},...e.maxPriorityFeePerGas!==void 0?{maxPriorityFeePerGas:c(e.maxPriorityFeePerGas)}:{}},e.blockNumber!==void 0?c(e.blockNumber):"latest",{tracer:"callTracer"}]}}function w(e){let r;return async(i,d,n)=>{[...d,...n?[n]:[]].some(o=>o.toLowerCase()===i.to.toLowerCase())||s("destination is outside the module contract set");let f,t=!r;r||(r=(async()=>{if(!e)return!1;try{return f=await e(i),!0}catch(o){let l=o instanceof Error?o.message:"";if(m(o,-32601,-32004)||m(o,-32602)&&/tracer.*(unsupported|not supported|not found|unknown)|(?:unsupported|unknown).*tracer/i.test(l))return!1;throw o}})());let a=r,u;try{u=await a}catch(o){throw r===a&&(r=void 0),o}return u?(t||(f=await e(i)),C(f,i,d),"callTracer"):"simulation-only"}}export{C as a,g as b,w as c};
@@ -0,0 +1 @@
1
+ import{e as y}from"./VZCMAMZL.js";import{c as l}from"./YVAFJM4Y.js";import{a}from"./IVR4JOHU.js";import{c as d,e as g}from"./YR4WKA4P.js";import{getAddress as c}from"viem";import{buildIdentityLinkTypedData as p,buildIdentityTuple as w,canonicalSessionIdentity as f}from"@oakagentkit/core/identity-link";function E(t){return async o=>{let r,i=[],s="not_submitted";try{if(o.mode==="register"){let e=await t.callTool("erc8004_register",{profile:o.profile??y,tag:o.tag??!0});if(!e||typeof e.agentId!="string"||!Array.isArray(e.hashes)||!e.hashes.length&&e.registrationResumed!==!0)throw new Error("Registration is not confirmed. Wait for the mined receipt before running oak setup again.");if(i=e.hashes,s=typeof e.status=="string"?e.status:i.length?"mined":"not_submitted",r=w(e.agentId,t.network),e.chainId!==r.chainId||e.registry!==r.registry)throw new Error(g);if(typeof e.owner!="string"||c(e.owner)!==t.signer.address)throw new Error(d);await t.identity.accept(r)}else{let e=w(o.agentId,t.network),n=await t.callTool("erc8004_identity",{agentId:o.agentId});if(n.chainId!==e.chainId||n.registry!==e.registry)throw new Error(g);let m=typeof n.owner=="string"&&c(n.owner)===t.signer.address?u=>t.signer.signTypedData(p(u)):t.signOwner??(async()=>{throw new Error(d)});r=await t.identity.link(e,m)}r=f(r,t.network);try{await t.save(r)}catch{throw t.identity.sessions.setIdentity(),new Error("Could not save identity. Run oak setup again after fixing local configuration.")}return{summary:a(i,s,`Agent ${r.agentId} verified on chain ${r.chainId}. Identity setup is complete; run oak subscribe --plan holder or oak subscribe --plan nohold next.`),identity:r,hashes:i,status:s}}catch(e){let n=l(e);throw i.length&&(n.message=a(i,s,`Identity setup stopped. ${n.message}`)),n}}}export{E as a};
@@ -0,0 +1 @@
1
+ import{createHash as p,randomBytes as x}from"node:crypto";import{canonicalSessionIdentity as w}from"@oakagentkit/core/identity-link";import{generatePrivateKey as b,privateKeyToAccount as N}from"viem/accounts";import{getAddress as h,recoverMessageAddress as K}from"viem";import{loadSigner as P}from"#oak-wallet";var a=()=>new Error("Invalid or expired Oak session."),l=()=>Math.floor(Date.now()/1e3);function k(e,t){let n={expires:e.expires,wallet:h(e.wallet)};if(e.identity!==void 0){if(n.identity=w(e.identity,t),typeof e.nonce!="string"||!/^0x[0-9a-f]{64}$/.test(e.nonce))throw a();n.nonce=e.nonce}return e.sessionKey!==void 0&&(n.sessionKey=h(e.sessionKey)),JSON.stringify(n)}async function v(e={}){let t=(e.now??l)(),n=e.lifetime??900;if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(n)||n<1||n>900||!Number.isSafeInteger(t+n))throw a();try{let r=e.signer??await P(),o=k({expires:t+n,wallet:r.address,...e.sessionKey?{sessionKey:e.sessionKey}:{},...e.identity?{identity:e.identity,nonce:`0x${x(32).toString("hex")}`}:{}},e.network??"mainnet"),s=await r.signMessage({message:o}),i=`${Buffer.from(o,"utf8").toString("base64url")}.${s}`;return await O(i,t,e.network??"mainnet"),i}catch{throw new Error("Local session signing failed.")}}async function O(e,t=l(),n="mainnet"){try{if(!Number.isSafeInteger(t)||t<0||typeof e!="string"||e.length>1024)throw a();let r=/^([A-Za-z0-9_-]+)\.(0x[0-9a-fA-F]{130})$/.exec(e);if(!r)throw a();let o=r[1],s=Buffer.from(o,"base64url").toString("utf8");if(Buffer.from(s,"utf8").toString("base64url")!==o)throw a();let i=JSON.parse(s);if(!i||!Number.isSafeInteger(i.expires)||i.expires<=t||i.expires-t>900||typeof i.wallet!="string"||k(i,n)!==s)throw a();let u=await K({message:s,signature:r[2]});if(h(u)!==i.wallet)throw a();return i}catch{throw a()}}function R(e){let t=e.network??"mainnet",n=e.now??l,r=e.identity&&w(e.identity,t),o,s,i=0;function u(){i++,o=void 0,s=void 0}let S={get identity(){return r&&{...r}},setIdentity(c){r=c&&w(c,t),u()},clear:u,async get(){if(o&&o.expires-n()>60)return o.token;if(!s){let c=i,m=n(),y=r&&{...r},f=N(b()),d=Promise.resolve().then(async()=>{let g=y&&e.refreshIdentity?await e.refreshIdentity(y):y;if(i!==c)throw new Error("Identity changed while signing; retry the action.");return r=g,v({...e,network:t,identity:g,sessionKey:f.address,now:()=>m})}).then(g=>{if(i!==c)throw new Error("Identity changed while signing; retry the action.");return o={token:g,expires:m+900,key:f},g}).finally(()=>{s===d&&(s=void 0)});s=d}return s},async headers(c,m,y){let f=await S.get(),d=o;if(!d||d.token!==f)throw a();let g=i,I=await $({token:f,signer:d.key,method:c,path:m,body:y,expires:Math.min(n()+60,d.expires)});if(i!==g)throw new Error("Identity changed while signing; retry the action.");return{"X-Oak-Session":f,"X-Oak-Request":I}}};return S}async function $(e){let t=r=>p("sha256").update(r).digest("hex"),n=JSON.stringify({session:t(e.token),method:e.method,path:e.path,bodyHash:t(e.body),nonce:e.nonce??`0x${x(32).toString("hex")}`,expires:e.expires});return`${Buffer.from(n).toString("base64url")}.${await e.signer.signMessage({message:n})}`}export{v as a,O as b,R as c,$ as d};
@@ -0,0 +1,2 @@
1
+ import{a as w,b as C,d as R}from"./GONTF7K4.js";import{c as U}from"./YVAFJM4Y.js";import ne from"ajv";import{constants as l}from"node:fs";import{lstat as I,mkdir as ie,open as Z,readdir as N,rmdir as oe,unlink as ae}from"node:fs/promises";import{homedir as se}from"node:os";import{basename as J,dirname as q,isAbsolute as W,join as E,parse as ce,relative as pe,resolve as A,sep as Y}from"node:path";import{Readable as fe,Transform as de}from"node:stream";import{pipeline as le}from"node:stream/promises";import{createGunzip as ue}from"node:zlib";import me from"tar-stream";import{createPublicClient as we,decodeFunctionResult as he,encodeFunctionData as O,getAddress as V,http as ye,isAddress as z}from"viem";var F={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://oakagentkit.org/schema/recipe.schema.json",title:"Oak declarative recipe v1",type:"object",additionalProperties:!1,required:["schema","project","name","description","chainId","contract","function","inputs","kind"],properties:{schema:{const:"oak-recipe/v1"},project:{$ref:"#/definitions/slug"},name:{$ref:"#/definitions/slug"},description:{type:"string"},chainId:{const:4663},contract:{type:"string",format:"eip55"},function:{type:"object",additionalProperties:!1,required:["type","name","stateMutability","inputs","outputs"],properties:{type:{const:"function"},name:{type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]*$"},stateMutability:{enum:["view","pure","nonpayable","payable"]},inputs:{type:"array",maxItems:128,items:{$ref:"#/definitions/parameter"}},outputs:{type:"array",maxItems:128,items:{$ref:"#/definitions/parameter"}}}},inputs:{type:"array",maxItems:128,items:{type:"object",additionalProperties:!1,required:["name","type","description"],properties:{name:{type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]*$"},type:{type:"string",pattern:"^(address|bool|string|bytes([1-9]|[12][0-9]|3[0-2])?|u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?|tuple)(\\[([1-9][0-9]*)?\\])*$"},description:{type:"string"},default:{}}}},kind:{enum:["read","tx"]},value:{type:"object",additionalProperties:!1,required:["fromInput"],properties:{fromInput:{type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]*$"}}},approve:{type:"object",additionalProperties:!1,required:["token","amountFromInput"],properties:{token:{type:"string",format:"eip55"},amountFromInput:{type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]*$"}}}},definitions:{slug:{type:"string",pattern:"^[a-z0-9-]{1,40}$"},parameter:{type:"object",additionalProperties:!1,required:["type"],properties:{name:{type:"string",pattern:"^([A-Za-z_][A-Za-z0-9_]*)?$"},type:{type:"string",pattern:"^(address|bool|string|bytes([1-9]|[12][0-9]|3[0-2])?|u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?|tuple)(\\[([1-9][0-9]*)?\\])*$"},internalType:{type:"string"},components:{type:"array",minItems:1,maxItems:128,items:{$ref:"#/definitions/parameter"}}}}}};var d=64*1024,S=4*1024*1024,H=100,v=/^[a-z0-9-]{1,40}$/,X=/^package\/recipes\/[a-z0-9-]{1,40}\.recipe\.json$/,ge="as-is, not reviewed by Oak",L=new ne({strict:!0,allErrors:!0});L.addFormat("eip55",{type:"string",validate:e=>z(e,{strict:!1})&&V(e)===e});var M=L.compile(F),T=(e,t)=>Object.hasOwn(e,t);function B(e,t=0){if(t>16)throw new Error("Recipe ABI nesting exceeds 16 levels.");let r=/^tuple(?:\[|$)/.test(e.type),o="components"in e?e.components:void 0;if(r!==!!o)throw new Error("Recipe tuple components must match its ABI type.");for(let n of o??[])B(n,t+1);for(let n of e.type.matchAll(/\[(\d+)\]/g))if(!Number.isSafeInteger(Number(n[1])))throw new Error("Invalid ABI array length.")}function G(e,t=256){if(typeof e!="string"||!/^(0|[1-9][0-9]*)$/.test(e))throw new Error("Expected an unsigned decimal base-unit string.");let r=BigInt(e);if(r>=1n<<BigInt(t))throw new Error("Unsigned integer exceeds its ABI type.");return r}function g(e,t){let r=/^(.*)\[([0-9]*)\]$/.exec(e.type);if(r){if(!Array.isArray(t)||r[2]!==""&&t.length!==Number(r[2]))throw new Error("Expected an ABI array of the declared length.");return t.map(n=>g({...e,type:r[1]},n))}if(e.type==="tuple"&&"components"in e){if(Array.isArray(t)){if(t.length!==e.components.length)throw new Error("Tuple input length mismatch.");return e.components.map((i,a)=>g(i,t[a]))}if(t===null||typeof t!="object")throw new Error("Expected a tuple input.");let n=e.components.map(i=>i.name);if(n.some(i=>!i)||new Set(n).size!==n.length||Object.keys(t).length!==n.length)throw new Error("Use positional values for this tuple.");return e.components.map(i=>{if(!T(t,i.name))throw new Error("Missing tuple input.");return g(i,t[i.name])})}let o=/^(u?int)(\d*)$/.exec(e.type);if(o){let n=Number(o[2]||256);if(o[1]==="uint")return G(t,n);if(typeof t!="string"||!/^(0|-?[1-9][0-9]*)$/.test(t))throw new Error("Expected a signed decimal string.");let i=BigInt(t),a=1n<<BigInt(n-1);if(i<-a||i>=a)throw new Error("Signed integer exceeds its ABI type.");return i}if(e.type==="address"){if(typeof t!="string"||!z(t))throw new Error("Expected an address input.");return V(t)}if(e.type==="bool"&&typeof t=="boolean"||e.type==="string"&&typeof t=="string")return t;if(/^bytes\d*$/.test(e.type)&&typeof t=="string"&&/^0x(?:[0-9a-fA-F]{2})*$/.test(t)){let n=e.type.slice(5);if(!n||(t.length-2)/2===Number(n))return t}throw new Error(`Invalid typed input for ${e.type}.`)}function b(e){let t=typeof e=="string"?e:e instanceof Uint8Array?Buffer.from(e).toString("utf8"):JSON.stringify(e);if(t===void 0||Buffer.byteLength(t)>d)throw new Error("Recipe exceeds 64 KiB or is not JSON.");let r=JSON.parse(t);if(!M(r))throw new Error(`Invalid recipe schema: ${L.errorsText(M.errors)}.`);let o=r;if(o.function.inputs.length!==o.inputs.length)throw new Error("Recipe inputs must match ABI inputs by position and type.");let n=new Set;o.inputs.forEach((a,c)=>{if(n.has(a.name))throw new Error("Duplicate recipe input name.");n.add(a.name);let s=o.function.inputs[c];if(s.type!==a.type)throw new Error("Recipe inputs must match ABI inputs by position and type.");B(s),T(a,"default")&&g(s,a.default)}),o.function.outputs.forEach(a=>B(a));let i=o.function.stateMutability;if(o.kind==="read"?!["view","pure"].includes(i):!["nonpayable","payable"].includes(i))throw new Error("Recipe kind does not match function stateMutability.");if(o.approve&&o.kind!=="tx")throw new Error("Recipe approve requires kind tx.");for(let a of[o.value?.fromInput,o.approve?.amountFromInput])if(a!==void 0&&!o.inputs.some(c=>c.name===a&&/^uint(\d*)$/.test(c.type)))throw new Error("Recipe value/approve must reference an unsigned integer input.");if(o.value&&i!=="payable")throw new Error("Recipe value requires a payable function.");return o}function Q(e,t){if(t===null||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(r=>!e.inputs.some(o=>o.name===r)))throw new Error("Unexpected recipe inputs.");return e.inputs.map((r,o)=>{let n=T(t,r.name)?t[r.name]:r.default;if(n===void 0)throw new Error(`Missing recipe input: ${r.name}.`);return g(e.function.inputs[o],n)})}function $(e){if(typeof e=="bigint"||typeof e=="number")return String(e);if(e==null)return null;if(typeof e=="string"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map($);if(typeof e=="object")return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,$(r)]));throw new Error("Unexpected decoded recipe result.")}async function ze(e,t,r={}){try{if(e=b(e),e.kind!=="read")throw new Error("Expected a read recipe.");let o=O({abi:[e.function],functionName:e.function.name,args:Q(e,t)});if(!r.client&&!process.env.OAK_RPC_URL)throw new Error("Set OAK_RPC_URL before reading a recipe.");let n=r.client??we({transport:ye(process.env.OAK_RPC_URL),cacheTime:0});if(await n.getChainId()!==e.chainId)throw new Error("RPC chain does not match recipe chain.");let i=await n.call({to:e.contract,data:o});if(!i.data)throw new Error("Recipe read returned no data.");return $(he({abi:[e.function],functionName:e.function.name,data:i.data}))}catch(o){throw U(o)}}function Le(e,t,r){if(e=b(e),e.kind!=="tx")throw new Error("Expected a tx recipe.");if(!z(r))throw new Error("Invalid wallet address.");let o=Q(e,t),n=s=>String(o[e.inputs.findIndex(f=>f.name===s)]),i=`${e.project}/${e.name} \u2014 ${ge}`,a={to:e.contract,data:O({abi:[e.function],functionName:e.function.name,args:o}),value:e.value?n(e.value.fromInput):"0",chainId:e.chainId,description:i};return e.approve?[{to:e.approve.token,data:O({abi:[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{type:"address"},{type:"uint256"}],outputs:[{type:"bool"}]}],functionName:"approve",args:[e.contract,G(n(e.approve.amountFromInput))]}),value:"0",chainId:e.chainId,description:`Approve exact amount for ${i}`},a]:[a]}function j(e){if(!e||e.startsWith("/")||/^[A-Za-z]:/.test(e)||e.includes("\\")||[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127)||e.split("/").some(t=>t===".."||t==="."))throw new Error("Unsafe archive path.")}var P=class extends de{total=0;entries=0;header=Buffer.alloc(512);filled=0;remaining=0;zeroBlocks=0;_transform(t,r,o){try{if(this.total+=t.length,this.total>S)throw new Error("Archive exceeds 4 MiB decompressed limit.");let n=0;for(;n<t.length;){if(this.remaining){let m=Math.min(this.remaining,t.length-n);this.remaining-=m,n+=m;continue}let i=Math.min(512-this.filled,t.length-n);if(t.copy(this.header,this.filled,n,n+i),this.filled+=i,n+=i,this.filled!==512)continue;if(this.filled=0,this.header.every(m=>m===0)){this.zeroBlocks++;continue}if(this.zeroBlocks)throw new Error("Archive contains trailing entries after its terminator.");if(++this.entries>H)throw new Error("Archive exceeds 100 entries.");let a=(m,te)=>this.header.subarray(m,m+te).toString("utf8").split("\0")[0],c=this.header.subarray(257,263).equals(Buffer.from("ustar\0"))?a(345,155):"",s=`${c?`${c}/`:""}${a(0,100)}`;j(s);let f=this.header[156];if(f!==0&&f!==48&&f!==53)throw new Error("Unsupported archive entry type (links and extensions forbidden).");if(a(157,100))throw new Error("Unsupported archive link type.");let p=a(124,12).trim();if(!/^[0-7]+$/.test(p))throw new Error("Invalid archive size.");let y=Number.parseInt(p,8);if(!Number.isSafeInteger(y)||y>S)throw new Error("Archive exceeds 4 MiB decompressed limit.");if(f===53&&y!==0)throw new Error("Archive directory must have no payload.");if((X.test(s)||s==="package/package.json")&&y>d)throw new Error("Selected recipe or metadata exceeds 64 KiB.");this.remaining=Math.ceil(y/512)*512}o(null,t)}catch(n){o(n)}}_flush(t){t(this.filled||this.remaining||this.zeroBlocks<2?new Error("Truncated archive or missing terminator."):null)}};async function D(e){let t=[],r,o=me.extract();if(o.on("entry",(i,a,c)=>{let s=X.test(i.name)||i.name==="package/package.json";try{if(j(i.name),i.type!=="file"&&i.type!=="directory")throw new Error("Unsupported archive entry type.");if(s&&(i.size??0)>d)throw new Error("Selected recipe or metadata exceeds 64 KiB.")}catch(p){c(p);return}let f=[];a.on("data",p=>{s&&Buffer.isBuffer(p)&&f.push(p)}),a.on("end",()=>{try{if(j(i.name),i.type!=="file"&&i.type!=="directory")throw new Error("Unsupported archive entry type.");if(i.type==="file"&&s){let p=Buffer.concat(f);if(p.length>d)throw new Error("Selected recipe or metadata exceeds 64 KiB.");if(i.name==="package/package.json"){if(r)throw new Error("Duplicate package metadata.");r=p}else t.push({name:J(i.name),data:p})}c()}catch(p){c(p)}}),a.on("error",p=>o.destroy(p))}),await le(e,ue(),new P,o),!r)throw new Error("Missing package metadata.");let n=JSON.parse(r.toString("utf8"));if(!n||typeof n!="object"||!("oakProject"in n)||typeof n.oakProject!="string"||!v.test(n.oakProject))throw new Error("Invalid package oakProject metadata.");for(let i of t)if(b(i.data).project!==n.oakProject)throw new Error("Recipe project differs from package oakProject.");return t}async function h(e){try{return await I(e)}catch(t){if(t.code==="ENOENT")return;throw t}}async function u(e){let t=A(e),r=ce(t).root;for(let o of t.slice(r.length).split(Y).filter(Boolean)){r=E(r,o);let n=await h(r);if(!n)return;if(n.isSymbolicLink())throw new Error("Recipe paths must not contain links.");if(r!==t&&!n.isDirectory())throw new Error("Recipe ancestor is not a directory.")}}async function Ee(e,t=!1){let r=t?await R(e,l.O_RDONLY,d):await Z(e,l.O_RDONLY|l.O_NOFOLLOW|l.O_NONBLOCK);try{let o=await r.stat();if(!o.isFile())throw new Error("Recipe source must be a regular file.");if(o.size>d)throw new Error("Recipe exceeds 64 KiB.");let n=Buffer.alloc(d+1),i=0;for(;i<n.length;){let{bytesRead:a}=await r.read(n,i,n.length-i,null);if(!a)break;i+=a}if(i>d)throw new Error("Recipe exceeds 64 KiB.");return n.subarray(0,i)}finally{await r.close()}}async function ee(e,t=!1){let r=[],o=0,n=0,i=async a=>{if(++o>H)throw new Error("Local import exceeds 100 entries.");let c=await I(a);if(c.isSymbolicLink())throw new Error("Local imports must not follow links.");if(c.isDirectory()){t&&await w(a);for(let s of(await N(a)).sort())await i(E(a,s))}else if(c.isFile()){if(a.endsWith(".recipe.json")){let s=await Ee(a,t);if(n+=s.length,n>S)throw new Error("Local import exceeds 4 MiB.");r.push({name:J(a),data:s})}}else throw new Error("Unsupported local file type.")};return await i(e),r}var x=e=>A(e.directory??E(se(),".oak/recipes"));function k(e,t,r){if(!v.test(t))throw new Error("Invalid recipe project.");if(r!==void 0&&!v.test(r))throw new Error("Invalid recipe name.");let o=A(e,t,...r===void 0?[]:[`${r}.recipe.json`]),n=pe(e,o);if(!n||n.startsWith(`..${Y}`)||n===".."||W(n))throw new Error("Recipe destination escapes store.");return o}async function _(e){await u(e);let t=await h(e);if(t){if(!t.isDirectory())throw new Error("Recipe store path is not a directory.");return}await _(q(e));try{await ie(e,{mode:448})}catch(r){if(r.code!=="EEXIST")throw r}if(await u(e),!(await I(e)).isDirectory())throw new Error("Recipe store path is not a directory.")}async function K(e,t){let r=await t(e,{headers:{"User-Agent":"Oak-Recipe-Importer/1"},signal:AbortSignal.timeout(3e4)});if(!r.ok||!r.body)throw await r.body?.cancel(),new Error(`Recipe fetch failed (${r.status}).`);return fe.fromWeb(r.body)}async function be(e,t){let r=/^(@[a-z0-9-]+\/[a-z0-9._-]+|[a-z0-9][a-z0-9._-]*)(?:@([a-zA-Z0-9._-]+))?$/.exec(e);if(!r)throw new Error("Invalid npm recipe source.");let o=r[1].replace("/","%2F"),n=await K(`https://registry.npmjs.org/${o}/${r[2]??"latest"}`,t),i=[],a=0;for await(let f of n){if(a+=f.length,a>d)throw new Error("Registry metadata exceeds 64 KiB.");i.push(f)}let c=JSON.parse(Buffer.concat(i).toString("utf8"));if(typeof c?.dist?.tarball!="string")throw new Error("Missing npm tarball metadata.");let s=new URL(c.dist.tarball);if(s.protocol!=="https:"||s.username||s.password)throw new Error("Invalid npm tarball URL.");return K(s.href,t)}async function Te(e,t={}){let r=A(e);await u(r);let o=await h(r),n;if(o)if(o.isFile()&&/\.(tgz|tar\.gz)$/.test(r)){let s=await Z(r,l.O_RDONLY|l.O_NOFOLLOW|l.O_NONBLOCK);try{n=await D(s.createReadStream())}finally{await s.close()}}else n=await ee(r);else{if(W(e)||e.startsWith("."))throw new Error("Local recipe source does not exist.");n=await D(await be(e,t.fetch??fetch))}let i=x(t),a=new Set,c=n.map(s=>{let f=b(s.data);if(`${f.name}.recipe.json`!==s.name)throw new Error("Recipe filename must match its name.");let p=k(i,f.project,f.name);if(a.has(p))throw new Error("Recipe has a duplicate destination.");return a.add(p),f});if(!c.length)throw new Error("No recipe files selected.");for(let s of a)if(await u(s),await h(s))throw new Error("Recipe destination already exists.");await _(i),await w(i);for(let s of c){let f=k(i,s.project,s.name);await _(q(f)),await u(f);let p=await R(f,l.O_WRONLY|l.O_CREAT|l.O_EXCL,d);try{await p.writeFile(`${JSON.stringify(s,null,2)}
2
+ `),await C(p,d),await p.sync()}finally{await p.close()}}return c}async function Ue(e={}){let t=x(e);if(await u(t),!await h(t))return[];await w(t);let r=[];for(let o of(await N(t)).sort()){let n=k(t,o);await u(n);for(let i of await ee(n,!0)){let a=b(i.data);if(a.project!==o||i.name!==`${a.name}.recipe.json`)throw new Error("Stored recipe namespace/filename mismatch.");r.push(a)}}return r}async function Ce(e,t={}){let r=k(x(t),e);if(await u(r),!await h(r))return;await w(x(t)),await w(r);let o=await N(r);for(let n of o){let i=E(r,n);if(await u(i),!/^[a-z0-9-]{1,40}\.recipe\.json$/.test(n)||!(await I(i)).isFile())throw new Error("Recipe project contains an unexpected file.");await(await R(i,l.O_RDONLY,d)).close()}for(let n of o)await ae(E(r,n));await oe(r)}export{b as a,ze as b,Le as c,Te as d,Ue as e,Ce as f};
@@ -0,0 +1 @@
1
+ import{getAddress as d,parseAbi as n}from"viem";import{ADDRESSES as p,NETWORKS as i}from"@oakagentkit/core/addresses";import{relayOriginDepository as u}from"@oakagentkit/core/modules/relay/inbound";function c(r,o=4663){if(r.recipe)return`${r.recipe.project}.${r.recipe.name}`!==r.name||r.recipe.chainId!==o?[]:[r.recipe.contract];let e=p[4663];if(["erc8004_register","erc8004_update"].includes(r.name))return o===46630?[i.testnet.identityRegistry]:o===4663?[i.mainnet.identityRegistry]:[];if(r.name==="relay_bridge_in"||r.name==="relay_bridge_out"){let s=r.name==="relay_bridge_in"?u(o):o===4663?e.relay.depository.address:void 0;return s?[s]:[]}if(o!==4663)return[];let t=[...{steakhouse:[e.vaults.steakhouse.address],spark:[e.vaults.spark.address],netnet:[e.vaults.netnet.address],grove:[e.vaults.groveAlm.address],beefy:[e.vaults.beefyTestedLpVault.address],longbow:[e.vaults.longbowCore.address,e.vaults.longbowFrontier.address,e.vaults.longbowEth.address],orbio:[e.orbio.exchange.address],priors:[e.priors.pool.address],morpho:[e.morpho.morpho_blue.address],hoodag:[e.hoodag.registrarController.address,e.hoodag.reverseRegistrar.address],hoodlock:[e.hoodlock.locker.address,e.hoodlock.burner.address,e.hoodlock.airdrop.address,e.hoodlock.liquidityLocker.address],hookr:[e.hookr.HookrLimitOrders.address],merkl:[e.merkl.distributor.address],meridian:[e.meridian.PredictionMarketEscrow.address,e.meridian.SecondaryMarketEscrow.address],tickerspring:[e.tickerSpring.limitOrderHook.address,e.tickerSpring.gridStrategy.address,e.tickerSpring.ladderStrategy.address,e.tickerSpring.basketZap.address],uniswap:[e.uniswap.v3_position_manager.address,e.uniswap.v4_position_manager.address,e.uniswap.permit2.address,e.ponsTrade.universal_router.address],pons:[e.pons.factory.address,e.pons.launchAndBuyRouter.address,e.pons.memeHook.address,e.pons.feeEscrow.address,e.ponsTrade.universal_router.address,e.ponsTrade.permit2.address],clanker:[e.clanker.factory.address,e.clanker.fee_locker.address,e.clanker.locker.address,e.clanker.legacy_locker_v1.address,e.clanker.fee_static_hook_v2.address,e.clanker.fee_dynamic_hook_v2.address],poolstrade:[e.poolsTrade.liquidityLauncher.address,e.poolsTrade.universalRouter.address,e.poolsTrade.permit2.address,e.poolsTrade.uerc20BeneficiaryVault.address,e.poolsTrade.feeSplitterFeesOn.address,e.poolsTrade.feeSplitterFeesOff.address]}[r.name.split("_")[0]]??[]];return(r.name==="longbow_deposit"&&r.args.wrapEth===!0||r.name.startsWith("morpho_")&&r.args.wrapNative===!0||r.name==="uniswap_add"&&r.args.wrapNative===!0)&&t.push(i.mainnet.weth),t}async function f(r,o,e=4663){let a=c(r,e);if(e!==4663)return a;let t=p[4663];if(["pons_buy","pons_sell","pons_claim"].includes(r.name)&&r.args.token){let s=await o.readContract({address:t.pons.factory.address,abi:n(["function getLaunchedToken(address) view returns ((address token,address curve,address deployer,address creatorFeeRecipient,address pairToken,uint256 graduationThreshold,uint24 poolFee,int24 tickSpacing,uint16 creatorTaxBps,bool buybackEnabled,uint8 phase,uint256 sweptQuote,uint256 sweptTokens,uint256 sweptAt,bool exists))"]),functionName:"getLaunchedToken",args:[d(String(r.args.token))]});if(!s.exists||s.token.toLowerCase()!==String(r.args.token).toLowerCase())throw new Error("Local transaction guard: token has no matching Pons factory record; nothing was signed.");if(a.push(d(s.curve)),r.name==="pons_claim"){let l=await o.readContract({address:s.curve,abi:n(["function feeEscrow() view returns (address)"]),functionName:"feeEscrow"});a.push(d(l))}}if(r.name==="clanker_claim"&&r.args.poolId&&r.args.token){let s=await o.readContract({address:t.clanker.factory.address,abi:n(["function tokenDeploymentInfo(address) view returns ((address token,address hook,address locker,address[] extensions))"]),functionName:"tokenDeploymentInfo",args:[d(String(r.args.token))]});if(s.token.toLowerCase()!==String(r.args.token).toLowerCase())throw new Error("Local transaction guard: token has no matching Clanker factory record; nothing was signed.");a.push(d(s.hook),d(s.locker))}return a}export{c as a,f as b};
@@ -0,0 +1 @@
1
+ import{constants as o}from"node:fs";import{lstat as w,mkdir as m,open as a}from"node:fs/promises";import{platform as n}from"node:os";import{dirname as d}from"node:path";async function s(e,r=!1){r&&await m(e,{recursive:!0,mode:448});let i=await w(e);if(!i.isDirectory()||i.isSymbolicLink()||n()!=="win32"&&((i.mode&63)!==0||i.uid!==process.getuid?.()))throw new Error("Unsafe local Oak directory. Use an owner-only directory without links.")}async function f(e,r){let i=await e.stat();if(!i.isFile()||i.nlink!==1||i.size>r||n()!=="win32"&&((i.mode&511)!==384||i.uid!==process.getuid?.()))throw new Error("Unsafe local Oak file. Use an owner-owned 0600 file without links.")}async function v(e){if(n()==="win32")return;await s(e);let r=await a(e,o.O_RDONLY|o.O_NOFOLLOW);try{await r.sync()}finally{await r.close()}}async function F(e,r,i,c=!1){await s(d(e),c);let t=await a(e,r|o.O_NOFOLLOW|o.O_NONBLOCK,384);try{return await f(t,i),t}catch(l){throw await t.close(),l}}export{s as a,f as b,v as c,F as d};
@@ -0,0 +1,3 @@
1
+ import{b as a}from"./U3IXRJH7.js";import{createInterface as u}from"node:readline/promises";function g(o="ask",r={}){if(o!=="ask"&&o!=="auto")throw new Error("Set confirm to ask or auto.");return async s=>{if(o==="auto")return;if(!(r.isTTY??(()=>process.stdin.isTTY===!0&&process.stdout.isTTY===!0))())throw new Error("Human confirmation requires interactive stdin and stdout. Run this command in your own terminal, or set oak config set confirm auto there first. Nothing was signed.");let m=Array.from(s.summary,n=>{let t=n.charCodeAt(0);return t<32&&t!==10||t>=127&&t<=159||t>=8232&&t<=8238||t>=8294&&t<=8297?`\\u${t.toString(16).padStart(4,"0")}`:n}).join(""),c=JSON.stringify(s.hash);(r.write??(n=>{process.stdout.write(`${n}
2
+ `)}))(`${m}
3
+ Unsigned signing hash: ${c}`);let e="Sign and submit this action? [y/N] ",i;if(r.ask)i=await r.ask(e);else{let n=u({input:process.stdin,output:process.stdout});try{i=await n.question(e,{signal:AbortSignal.timeout(a*1e3)})}catch{throw new Error("Human confirmation timed out or was unavailable; nothing was signed.")}finally{n.close()}}if(i.trim().toLowerCase()!=="y")throw new Error("Human confirmation declined; nothing was signed.")}}export{g as a};
@@ -0,0 +1 @@
1
+ function m(n,e,r=""){return`${n.length?`${e==="final"?"Final":e==="mined"?"Mined":"Submitted"}: ${n.join(", ")}. Status: ${e}.`:"Not submitted."}${r?` ${r}`:""}`}function u(n){return n.replace(/No transaction was sent\.?/gi,"").replace(/Not submitted\.?/gi,"").replace(/Simulation only[:;]?/gi,"Preview note: simulation").replace(/\s+/g," ").trim().replace(/^Preview note:\s*/i,"")}function a(n,e){let r=t=>Array.isArray(t)?t.map(r):t===null||typeof t!="object"?t:Object.fromEntries(Object.entries(t).map(([o,s])=>[o,o==="summary"&&typeof s=="string"?`Preview note: ${u(s)}`:r(s)])),i=typeof n.summary=="string"?u(n.summary):"";return{summary:`${e.summary}${i?` Preview note: ${i}`:""}`,...Object.fromEntries(Object.entries(r(n)).filter(([t])=>!["summary","hashes","status"].includes(t))),hashes:e.hashes,status:e.status??(e.hashes.length?"mined":"not_submitted")}}export{m as a,a as b};
@@ -0,0 +1 @@
1
+ import{c as o}from"./UTTRLIY5.js";async function i(r){return r.action(async e=>{let s=await r.authoritative();if(!s||s.plan===0)return{ok:!1,access:!1,hashes:[],summary:"No subscription. Use oak subscribe --plan holder or oak subscribe --plan nohold."};if(s.paidUntil-await r.now()>o){let a=await r.access(s);return{ok:a,access:a,hashes:[],summary:a?"Subscription is paid; renewal is not due.":`Buy back ${s.count} OAK base units (token ${r.deployment.oak}, decimals 18) to restore access.`}}if(s.retired){let a=s.plan===1?await r.proof(s):null;return a?r.holderPayment(e,s,a):{ok:!1,access:await r.access(s),hashes:[],summary:"Retired subscription has no eligible grandfather proof; once the old paid days expire, use oak subscribe for a fresh subscription on the successor."}}return s.plan===1?r.holderPayment(e,s):r.pricedPayment(e,s.contract,"nohold",!0)},!0)}export{i as a};
@@ -0,0 +1 @@
1
+ import{randomUUID as $}from"node:crypto";import{constants as P}from"node:fs";import{lstat as S,mkdir as D,open as k,readdir as M,rename as L,rmdir as O,unlink as A}from"node:fs/promises";import{homedir as R}from"node:os";import{join as u}from"node:path";import{getAddress as g,keccak256 as b,parseTransaction as _,recoverTransactionAddress as F}from"viem";var j=()=>u(R(),".oak"),h=i=>i?.code,W=i=>new Promise(t=>setTimeout(t,i)),l=()=>new Error("Wallet journal is unreadable or invalid; resolve it before a new action."),v=i=>new Error(i),N=i=>typeof i=="string"&&/^0x(?:[0-9a-fA-F]{2})+$/.test(i),H=i=>typeof i=="string"&&/^(0|[1-9]\d*)$/.test(i),m=(i,t)=>Number.isSafeInteger(i)&&i>=t,K=i=>[i.hash,...(i.previous??[]).map(t=>b(t))];async function I(i){await D(i,{recursive:!0,mode:448});let t=await S(i);if(!t.isDirectory()||t.isSymbolicLink()||process.platform!=="win32"&&((t.mode&63)!==0||t.uid!==process.getuid?.()))throw new Error("Unsafe wallet state directory.")}async function Y(i){if(process.platform==="win32")return;let t=await k(i,P.O_RDONLY);try{await t.sync()}finally{await t.close()}}async function Q(i,t,a={}){let e=a.directory??j();await I(e);let r=g(i).toLowerCase(),n=u(e,`${r}.lock`),o=`${process.pid}-${$()}`,s=u(e,`${r}.lock-${o}`);await D(s,{mode:448}),await(await k(u(s,o),"wx",384)).close();let c=!1,f=Date.now();try{for(;!c;)try{await L(s,n),c=!0}catch(E){if(!["EEXIST","ENOTEMPTY"].includes(h(E)??""))throw v("Wallet lock cannot be acquired.");let w=await S(n).catch(p=>{if(h(p)!=="ENOENT")throw p});if(!w)continue;if(!w.isDirectory()||w.isSymbolicLink())throw v("Invalid wallet lock.");let x=await M(n).catch(p=>{if(h(p)==="ENOENT")return[];throw p});if(x.length===1){let p=x[0],T=/^(\d+)-[0-9a-f-]{36}$/.exec(p)?.[1];if(!T||Number(T)<1)throw v("Invalid wallet lock owner.");let C=!0;try{process.kill(Number(T),0)}catch(y){h(y)==="ESRCH"&&(C=!1)}if(!C){await A(u(n,p)).catch(y=>{if(h(y)!=="ENOENT")throw y}),await O(n).catch(y=>{if(!["ENOENT","ENOTEMPTY","EEXIST"].includes(h(y)??""))throw y});continue}}else if(x.length>1)throw v("Invalid wallet lock owner.");if(Date.now()-f>=(a.timeoutMs??3e4))throw v("Wallet is busy; retry after the current action finishes.");await W(a.pollMs??25)}return await t()}finally{let E=c?n:s;await A(u(E,o)).catch(w=>{if(h(w)!=="ENOENT")throw w}),await O(E).catch(w=>{if(!["ENOENT","ENOTEMPTY","EEXIST"].includes(h(w)??""))throw w})}}var J=class{constructor(t,a=j()){this.address=t;this.directory=a;let e=g(t).toLowerCase();this.path=u(a,`${e}.pending.json`),this.approvalsPath=u(a,`${e}.approvals.json`),this.clearedPath=u(a,`${e}.cleared.json`)}address;directory;path;clearedPath;approvalsPath;async signedCall(t){let a=_(t);if(g(await F({serializedTransaction:t}))!==g(this.address))throw l();return{chainId:a.chainId,nonce:a.nonce,gas:a.gas,call:[a.to?.toLowerCase(),a.data??"0x",a.value??0n,a.gas].join(":")}}async validate(t){if(!Array.isArray(t))throw l();let a=new Set;for(let e of t){if(!e||!m(e.nonce,0)||!m(e.chainId,1)||!m(e.sentAt,0)||e.notAfter!==void 0&&(!m(e.notAfter,0)||e.notAfter<e.sentAt)||!H(e.blockNumber)||!["approval","main","burn"].includes(e.kind)||!N(e.rawTx)||b(e.rawTx)!==e.hash||e.previous!==void 0&&(!Array.isArray(e.previous)||!e.previous.every(N)))throw l();let r=await this.signedCall(e.rawTx);if(r.chainId!==e.chainId||r.nonce!==e.nonce||e.kind==="burn"&&(r.gas===void 0||r.gas<21000n||r.call!==[this.address.toLowerCase(),"0x",0n,r.gas].join(":")))throw l();let n=new Set([e.hash]),o=e.kind==="burn"?void 0:r.call;for(let d of e.previous??[]){let c=await this.signedCall(d),f=b(d);if(c.chainId!==r.chainId||c.nonce!==r.nonce||n.has(f))throw l();if(o===void 0)o=c.call;else if(c.call!==o&&c.call!==r.call)throw l();n.add(f)}let s=`${e.chainId}:${e.nonce}`;if(a.has(s))throw l();a.add(s)}return t}validateCleared(t){if(!Array.isArray(t))throw l();for(let a of t)if(!a||!N(a.hash)||a.hash.length!==66||!m(a.nonce,0)||!m(a.chainId,1)||!["approval","main","burn"].includes(a.kind)||!m(a.sentAt,0)||!H(a.blockNumber)||a.reason!=="nonce_consumed"||!m(a.clearedAt,0))throw l();return t}async load(t,a){try{await I(this.directory);let e=await k(t,P.O_RDONLY|(P.O_NOFOLLOW??0));try{let r=await e.stat();if(!r.isFile()||r.nlink!==1||r.size>16*1024*1024||process.platform!=="win32"&&((r.mode&63)!==0||r.uid!==process.getuid?.()))throw l();return await a(JSON.parse(await e.readFile("utf8")))}finally{await e.close()}}catch(e){if(h(e)==="ENOENT")return;throw l()}}async store(t,a,e){let r=`${t}.${$()}.tmp`;await I(this.directory);try{await e(a);let n=await k(r,"wx",384);try{await n.writeFile(JSON.stringify(a)),await n.sync()}finally{await n.close()}await L(r,t),await Y(this.directory)}catch{throw l()}finally{await A(r).catch(n=>{if(h(n)!=="ENOENT")throw l()})}}async approvals(){return await this.load(this.approvalsPath,t=>this.validate(t))??[]}async retainApproval(t){let a=await this.approvals();a.some(e=>e.hash===t.hash)||await this.store(this.approvalsPath,[...a,t],e=>this.validate(e))}async forgetApproval(t){await this.store(this.approvalsPath,(await this.approvals()).filter(a=>a.hash!==t),a=>this.validate(a))}async read(){return await this.load(this.path,t=>this.validate(t))??[]}async cleared(){return await this.load(this.clearedPath,t=>this.validateCleared(t))??[]}async write(t){await this.store(this.path,t,a=>this.validate(a))}async append(t){await this.write([...await this.read(),t])}async replace(t,a,e,r){let n=await this.read(),o=n.findIndex(c=>c.hash===t);if(o<0)throw l();let s=n[o],d={...s,rawTx:a,hash:b(a),blockNumber:e,sentAt:r,previous:[...s.previous??[],s.rawTx]};return n[o]=d,await this.write(n),d}async burn(t,a,e,r,n){let o=await this.read(),s=o.findIndex(f=>f.hash===t);if(s<0)throw l();let d=o[s],c={...d,kind:"burn",rawTx:a,hash:b(a),blockNumber:e,sentAt:r,...n!==void 0?{notAfter:n}:{},previous:[...d.previous??[],d.rawTx]};return o[s]=c,await this.write(o),c}async clear(t,a){let e=await this.read(),r=e.find(n=>n.hash===t);if(r&&a){let n=await this.cleared();if(!n.some(o=>o.hash===t)){let{nonce:o,chainId:s,kind:d,sentAt:c,blockNumber:f}=r;await this.store(this.clearedPath,[...n,{hash:t,nonce:o,chainId:s,kind:d,sentAt:c,blockNumber:f,reason:a,clearedAt:Math.floor(Date.now()/1e3)}],E=>this.validateCleared(E))}}await this.write(e.filter(n=>n.hash!==t))}};export{j as a,K as b,Q as c,J as d};
@@ -0,0 +1,5 @@
1
+ import{a as Ne}from"./RGOGWTRI.js";import{b as Ue,c as pe,e as Be}from"./4LWKW7PM.js";import{a as me,c as $e}from"./U5VW3XSD.js";import{a as De,c as Le}from"./VZCMAMZL.js";import{a as fe,b as Ce,c as K}from"./YVAFJM4Y.js";import{a as W,b as ne}from"./IVR4JOHU.js";import{c as Me,h as je}from"./U3IXRJH7.js";import{i as He}from"./YR4WKA4P.js";import{assertQuoteBinding as Ye,snapshotQuote as Ze}from"@oakagentkit/core/swap";import{isReadDiscovery as ie}from"@oakagentkit/core/tool-policy";import{LAUNCH_ACTION as et,LAUNCH_TOOLS as Qe}from"@oakagentkit/core/launch";import{rejectWalletSecrets as tt}from"@oakagentkit/core/secret-fields";import{untrustedText as Fe}from"@oakagentkit/core/untrusted";import{createModule as rt}from"@oakagentkit/core/modules/kyberswap/index";import{createModule as nt}from"@oakagentkit/core/modules/velora/index";import{createModule as it}from"@oakagentkit/core/modules/steakhouse/index";import{createModule as ot}from"@oakagentkit/core/modules/spark/index";import{createModule as st}from"@oakagentkit/core/modules/netnet/index";import{createModule as at}from"@oakagentkit/core/modules/longbow/index";import{createModule as dt}from"@oakagentkit/core/modules/grove/index";import{createModule as ut}from"@oakagentkit/core/modules/beefy/index";import{createModule as ct}from"@oakagentkit/core/modules/pons/index";import{createModule as lt}from"@oakagentkit/core/modules/orbio/index";import{createModule as ft}from"@oakagentkit/core/modules/hoodlock/index";import{createModule as pt}from"@oakagentkit/core/modules/merkl/index";import{createModule as mt}from"@oakagentkit/core/modules/relay/index";import{createModule as ht}from"@oakagentkit/core/modules/lighter/index";import{createModule as Ve}from"@oakagentkit/core/modules/erc8004/index";import{createModule as wt}from"@oakagentkit/core/modules/hoodag/index";import{createModule as yt}from"@oakagentkit/core/modules/heyresearch/index";import{createModule as gt}from"@oakagentkit/core/modules/priors/index";import{createModule as bt}from"@oakagentkit/core/modules/morpho/index";import{createModule as kt}from"@oakagentkit/core/modules/uniswap/index";import{createModule as vt}from"@oakagentkit/core/modules/hookr/index";import{createModule as xt}from"@oakagentkit/core/modules/meridian/index";import{createModule as At}from"@oakagentkit/core/modules/tickerspring/index";import{createModule as Tt}from"@oakagentkit/core/modules/clanker/index";import{createModule as qt}from"@oakagentkit/core/modules/poolstrade/index";import{isDeepStrictEqual as he}from"node:util";import{createPublicClient as St,custom as It,encodeAbiParameters as we,keccak256 as ye,parseAbiParameters as ge,zeroAddress as Je}from"viem";import{Server as Pt}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as Et}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as Ot,ListToolsRequestSchema as Rt}from"@modelcontextprotocol/sdk/types.js";import{ADDRESSES as Ae,CHAIN_ID as Te,NETWORKS as Mt,resolveNetwork as jt}from"@oakagentkit/core/addresses";import{createModuleContext as Nt,createModuleRegistry as Ct}from"@oakagentkit/core/module";import{unsignedTx as qe}from"@oakagentkit/core/tx";var _t=[rt,nt,it,ot,st,at,dt,ut,ct,lt,ft,pt,mt,ht,Ve,wt,yt,gt,bt,kt,vt,xt,At,Tt,qt],be="as-is, not reviewed by Oak",oe=new Set(["balances","find_token","price","quote","preview","history","positions","account","kyberswap_quote","velora_quote","steakhouse_list","spark_list","netnet_list","longbow_list","grove_list","beefy_list","pons_browse","pons_status","pons_launch_options","orbio_credit_status","hoodlock_list_locks","merkl_rewards","relay_status","lighter_funding","erc8004_identity","hoodag_resolve","hoodag_name_info","heyresearch_research_project","heyresearch_chain_activity","priors_status","morpho_status","uniswap_list_positions","meridian_browse","meridian_positions","tickerspring_orders","clanker_browse"]),se="Action tools and recipe transactions are paused. Run oak status, top up the required funds, then run oak renew; if you have no subscription, run oak subscribe --plan holder or oak subscribe --plan nohold.",X=()=>{throw new Error("Manifest construction must not execute a tool.")};function Ut(e="mainnet"){let c=St({transport:It({request:X})}),h=Nt({network:e,clientFor:()=>c,http:X,preview:X,quoteSwap:X,buildSwap:X}),y=(p,T={},E=[])=>({name:p,description:`Oak ${p}`,inputSchema:{type:"object",additionalProperties:!1,properties:T,required:E}}),l=[y("find_token",{query:{type:"string",minLength:1,description:"Token name, symbol or address on Robinhood Chain. Pons and pools.trade require an address."}},["query"]),y("balances"),y("price",{token:{type:"string"}},["token"]),y("quote",{from:{type:"string",description:"Token address or verified symbol; use find_token for discovery."},to:{type:"string",description:"Token address or verified symbol; use find_token for discovery."},amountIn:{type:"string",description:"Positive decimal integer in input token base units, not a human amount."},slippageBps:{type:"integer"}},["from","to","amountIn"]),y("swap",{quoteId:{type:"string"}},["quoteId"]),y("preview",{txs:{type:"array"}},["txs"]),y("history",{limit:{type:"integer",minimum:1}}),y("positions"),y("account")],k=Ct(h,e==="testnet"?[Ve]:_t);if(k.errors.length)throw new Error("Oak module manifest could not be loaded.");return[...l,...k.tools.map(p=>({name:p.name,description:`Oak ${p.name}`,inputSchema:p.inputSchema}))]}function m(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function P(e,c){return typeof e=="string"&&typeof c=="string"&&e.toLowerCase()===c.toLowerCase()}function R(e){if(typeof e!="string"||!/^[0-9]+$/.test(e)||e.length>78||BigInt(e)>=2n**256n)throw new Error("Invalid project integer.");return BigInt(e)}function ae(e){if(!m(e))throw new Error("Provide a JSON object.");return tt(e),e}function Bt(e){let c=new URL(e);if(c.protocol!=="https:"&&!(c.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(c.hostname))||c.username||c.password||c.search||c.hash)throw new Error("Use an HTTPS Oak server URL, or HTTP on loopback for local testing.");return c}var ke=Ae[Te].meridian,$t=[{name:"predictionHash",type:"bytes32"},{name:"signer",type:"address"},{name:"collateral",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],Ht=[{name:"tradeHash",type:"bytes32"},{name:"signer",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}];function ve(e,c,h,y,l,k,p){let T=e==="meridian_buy";if(!T&&e!=="meridian_sell")throw new Error("Unexpected project continuation.");let E=(T?ke.PredictionMarketEscrow:ke.SecondaryMarketEscrow).address;if(l.chainId!==Te||!P(l.wallet,h)||!P(l.escrowContract,E)||typeof l.requestId!="string"||!l.requestId)throw new Error("Project chain, domain or wallet mismatch.");if(k&&l.requestId!==k.requestId)throw new Error("Project exchange changed during continuation.");let M=k?.stage;if(l.stage==="prerequisites"){if(M!==void 0&&M!=="prerequisites"||!y.length||y.some(I=>I.kind!=="tx"))throw new Error("Unexpected prerequisite step order.");return}if(y.length!==1||y[0]?.kind!=="typedData"||!m(l.request)||!he(l.request,y[0].request))throw new Error("Project must return exactly its current typed-data step.");if(T?l.stage!=="primary_accept"||M!==void 0&&M!=="prerequisites":l.stage==="secondary_start"?M!==void 0&&M!=="prerequisites":l.stage!=="secondary_accept"||M!=="secondary_start")throw new Error("Unexpected project step order.");let O=y[0].request,Y=T?"MintApproval":"TradeApproval";if(!he(O.domain,{name:T?"PredictionMarketEscrow":"SecondaryMarketEscrow",version:"1",chainId:Te,verifyingContract:E})||O.primaryType!==Y||!he(O.types,{[Y]:T?$t:Ht})||!P(O.message.signer,h))throw new Error("Project typed-data domain, type or wallet mismatch.");let U=[R(O.message.deadline)];if(R(O.message.nonce),l.stage!=="secondary_start"){if(!m(l.winningBid)||typeof l.auctionId!="string"||!l.auctionId||l.winningBid.auctionId!==l.auctionId)throw new Error("Project winning bid or auction mismatch.");U.push(R(l.acceptDeadline)),T?U.push(R(l.winningBid.counterpartyDeadline)):l.winningBid.buyerDeadline!==void 0&&U.push(R(l.winningBid.buyerDeadline))}if(U.some(I=>BigInt(p)>=I))throw new Error("Meridian exchange expired. Start a fresh auction.");let S=l.winningBid,Q;if(T){let I=c.picks,F=ye(we(ge("(address conditionResolver,bytes conditionId,uint8 predictedOutcome)[]"),[I]));if(Q=ye(we(ge("bytes32,uint256,uint256,address,address,address,bytes"),[F,R(c.stake),R(S?.counterpartyCollateral),h,S?.counterparty,Je,"0x"])),O.message.collateral!==c.stake)throw new Error("Project collateral differs from the requested stake.")}else if(Q=ye(we(ge("address,address,address,address,uint256,uint256"),[c.token,ke.CollateralToken_USDe.address,h,l.stage==="secondary_start"?Je:S?.buyer,R(c.amount),l.stage==="secondary_start"?0n:R(S?.price)])),k?.stage==="secondary_start"){let I=k.request;if(I.message.nonce!==O.message.nonce||I.message.deadline!==O.message.deadline)throw new Error("Project changed its signing nonce or deadline.")}if(O.message[T?"predictionHash":"tradeHash"]!==Q)throw new Error("Project hash does not match the current winning terms.")}var Dt=12;function b(e){return e>1e11?Math.floor(e/1e3):Math.floor(e)}function V(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return b(e);if(typeof e=="bigint"&&e>=0n)return b(Number(e));if(typeof e=="string"&&e.trim()){if(/^[0-9]+$/.test(e.trim()))return b(Number(e.trim()));let c=Date.parse(e);if(Number.isFinite(c)&&c>=0)return b(c)}}function de(e){if(typeof e=="bigint"&&e>=0n)return e;if(typeof e=="number"&&Number.isSafeInteger(e)&&e>=0)return BigInt(e);if(typeof e=="string"&&/^(?:0|[1-9][0-9]*|0x[0-9a-fA-F]+)$/.test(e.trim()))return BigInt(e.trim())}function L(e,c){for(let h of c?["sender","wallet","from","account"]:["sender","wallet","account"])if(typeof e[h]=="string")return e[h]}function xe(e){if(!(!Array.isArray(e)||!e.length))try{return e.map(c=>{if(!m(c))throw new Error("Invalid preview transaction.");let h=typeof c.description=="string"&&c.description.trim()?c.description:"preview";return qe({...c,description:h})})}catch{return}}function We(e,c){return e.length===c.length&&e.every((h,y)=>{let l=c[y];return P(h.to,l.to)&&P(h.data,l.data)&&h.value===l.value&&h.chainId===l.chainId})}function Cr(e){let c=Bt(e.serverUrl),h=jt(e.network),{chainId:y}=Mt[h];if(h==="testnet"&&!e.sender)throw new Error("Configure a testnet sender before starting the bridge.");let l=e.fetch??fetch,k=e.identity??He({base:c,signer:e.signer,network:h,fetch:l,now:e.now}),p=e.now??(()=>Math.floor(Date.now()/1e3)),T=e.previewTtlSeconds??Dt,E=e.sender??$e({signer:e.signer,preview:D,now:e.now,confirm:t=>Q(t)});if((e.launchOnly||e.privateTestMode)&&h!=="mainnet")throw new Error("Launch bootstrap requires mainnet chain 4663.");let M=Ut(h).filter(t=>!e.launchOnly||Qe.has(t.name)),O=new Set(M.map(t=>t.name)),Y=e.recipes??(()=>Be()),U=async()=>e.launchOnly?[]:(await Y()).filter(t=>t.chainId===y),S,Q=Me(e.confirmMode,()=>S),I=new Map,F=new Map,B,z,Z=!1,ee;async function _e(t){try{if(typeof E.blockNumber=="function")return await E.blockNumber(t);let o=e.recipeClient;if(typeof o?.getBlockNumber=="function")return await o.getBlockNumber();if(typeof o?.getBlock=="function")return(await o.getBlock({blockTag:"latest"})).number}catch{return}}async function G(t,o){if(t==="account"){if(ae(o),Object.keys(o).length)throw new Error("Provide an empty JSON object.");let u=Le(e.signer.address,h);try{let{data:r}=await C(t,o);if(!m(r))throw new Error("Invalid account status.");return{...r,...u}}catch{return{...u,statusUnavailable:!0,summary:"Subscription status is unavailable. Retry account when the Oak service is reachable; do not assume action access."}}}return(await C(t,ae(o))).data}async function C(t,o,u=!1){if(!O.has(t))throw new Error("Unknown Oak tool.");let r=JSON.stringify(o);if(Buffer.byteLength(r)>(t==="pons_launch"?8388608:1048576))throw new Error("Tool arguments are too large.");!oe.has(t)&&!ie(t,o)&&t!=="erc8004_register"&&await J(t,u);let i=t==="preview"||!oe.has(t)&&!ie(t,o),v=t==="relay_bridge_in"&&typeof o.originChainId=="number"?o.originChainId:t==="preview"&&Array.isArray(o.txs)&&m(o.txs[0])&&typeof o.txs[0].chainId=="number"?o.txs[0].chainId:y,w=b(p()),x=i?await _e(v):void 0,g=`/v1/tools/${t}`,a=await k.sessions.headers("POST",g,r),s;try{s=await l(new URL(g,c),{method:"POST",redirect:"error",headers:{"content-type":"application/json",...a},body:r,signal:AbortSignal.timeout(18e4)})}catch{throw new Error("Oak server request failed. Check connectivity; any project exchange may need a fresh auction.")}let n;try{n=await s.json()}catch{throw new Error("Oak server returned invalid JSON.")}if(!m(n)||typeof n.ok!="boolean")throw new Error("Oak server returned an invalid tool envelope.");if(!n.ok)throw new Error(typeof n.error=="string"?fe(n.error):"Oak tool failed.");if(!s.ok||!Object.hasOwn(n,"data"))throw new Error("Oak server returned an invalid tool response.");if(t==="preview"&&m(n.data)&&typeof n.data.summary=="string"&&(!("changes"in n.data)||Array.isArray(n.data.changes))){let f=xe(o.txs),A=n.data.txs!==void 0?xe(n.data.txs):f,d=Array.isArray(n.data.txs)?n.data.txs:Array.isArray(o.txs)?o.txs:[];f&&A&&We(f,A)&&(ee={preview:n.data,txs:A,rawTxs:d,sender:L(n.data,!0)??e.signer.address,at:V(n.data.timestamp??n.data.createdAt??n.data.simulatedAt)??w,blockNumber:de(n.data.blockNumber??n.data.block)??x})}return{data:n.data,meta:{at:w,blockNumber:x}}}async function D(t){t=fe(t),await e.display(t),S?.getClientCapabilities()&&await S.sendLoggingMessage({level:"info",logger:"oak-preview",data:t}).catch(()=>{})}async function Se(){try{return await ze()}catch(t){throw K(t)}}async function ze(){return e.launchOnly?M:[...M,...k.unlink?[{name:"oak_identity_unlink",description:"Remove an identity link as the linked agent or with a current-owner signature. No transaction.",inputSchema:{type:"object",additionalProperties:!1,properties:{actor:{enum:["agent","owner"]},linkId:{type:"string"}}}}]:[],...e.subscribe?[{name:"oak_subscribe",description:"Start a recurring USDG subscription after the user approves the plan and price. Requires verified identity; previews and signs locally.",inputSchema:{type:"object",additionalProperties:!1,required:["plan"],properties:{plan:{enum:["holder","nohold"]}}}},{name:"oak_renew",description:"Reconcile or renew the current subscription using local signing.",inputSchema:{type:"object",additionalProperties:!1,properties:{}}}]:[],...e.setup?[{name:"oak_setup",description:"Register a public identity with a default profile (costs gas), or link an existing ID. An external owner signs in their terminal.",inputSchema:{type:"object",additionalProperties:!1,required:["mode"],properties:{mode:{enum:["register","link"]},agentId:{type:"string"},profile:{type:"object"},tag:{type:"boolean"}}}}]:[],...(await U()).map(t=>({name:`${t.project}.${t.name}`,description:`Third-party recipe; ${be}. Description: ${Fe(t.description)}`,inputSchema:{type:"object",additionalProperties:!1,properties:Object.fromEntries(t.inputs.map(o=>[o.name,{description:`${o.type}; ${Fe(o.description)}`}])),required:t.inputs.filter(o=>o.default===void 0).map(o=>o.name)}}))]}async function Ge(t,o,u,r,i){let v=ee;ee=void 0;let w=e.signer.address;if(r){let s=L(r,!1);if(s!==void 0&&!P(s,w))return}for(let s of t)if(m(s)){let n=L(s,!0);if(n!==void 0&&!P(n,w))return}let x=[];if(r&&m(r.preview)&&typeof r.preview.summary=="string"&&(!("changes"in r.preview)||Array.isArray(r.preview.changes))){let s=xe(r.preview.txs);if(s){let n=de(r.preview.blockNumber??r.preview.block),f=de(r.blockNumber??r.block);(n===void 0||f===void 0||n===f)&&x.push({preview:r.preview,txs:s,rawTxs:r.preview.txs,sender:L(r.preview,!0)??L(r,!1)??w,at:V(r.preview.timestamp??r.preview.createdAt??r.preview.simulatedAt??r.timestamp??r.createdAt)??i?.at,blockNumber:n??f??i?.blockNumber})}}if(v&&(!r||r.preview===void 0)&&x.push(v),!x.length)return;let g=b(p()),a=r?de(r.blockNumber??r.block):void 0;for(let s of x){if(s.preview.stale===!0||r?.stale===!0||!P(s.sender,w)||s.preview.chainId!==void 0&&s.preview.chainId!==u||s.rawTxs.some(A=>m(A)&&L(A,!0)!==void 0&&!P(L(A,!0),w))||!We(s.txs,o)||s.at===void 0||!Number.isFinite(s.at)||g<s.at||g-s.at>T)continue;let n=V(s.preview.expiresAt??r?.expiresAt);if(n!==void 0&&g>=n||s.blockNumber===void 0)continue;let f=a??await _e(u);if(!(f===void 0||s.blockNumber!==f))return s.preview}}async function te(t,o,u,r,i,v,w=E){let x=u.map(n=>m(n)?{...n}:n),g=u.map(n=>qe(n)),a=typeof o.quoteId=="string"?I.get(o.quoteId):void 0,s=t==="relay_bridge_in"?o.originChainId:y;if(g.some(n=>n.chainId!==s)||t==="relay_bridge_in"&&i?.originChainId!==void 0&&i.originChainId!==s)throw new Error("Transaction chain differs from the requested project or Relay origin chain.");if(g.length){let n=await Ge(x,g,s,i,v),f=n?v?.at??b(p()):b(p());n||(n=await G("preview",{txs:g}),f=b(p())),ee=void 0;let A=(N,$)=>{let H=[V(N?.expiresAt),V(i?.expiresAt),a?Number(a.expiresAt):void 0,$].filter(le=>le!==void 0);return H.length?Math.min(...H):void 0},d=A(n),q=d!==void 0?Math.min(f+T,d):f+T;if(await D(`${r}
2
+ ${JSON.stringify(n)}
3
+ ${JSON.stringify(g)}`),t!=="erc8004_register"&&await J(t),b(p())>q||d!==void 0&&b(p())>=d){if(d!==void 0&&b(p())>=d)throw new Error("Prepared transaction expired before signing; request a fresh quote and preview.");if(n=await G("preview",{txs:g}),f=b(p()),d=A(n,d),q=d!==void 0?Math.min(f+T,d):f+T,await D(`${r}
4
+ ${JSON.stringify(n)}
5
+ ${JSON.stringify(g)}`),t!=="erc8004_register"&&await J(t),b(p())>q||d!==void 0&&b(p())>=d)throw new Error("Prepared transaction expired before signing; request a fresh quote and preview.")}q=Math.min(b(p())+me,(d??1/0)-1);for(let N of g)Object.defineProperty(N,"notAfter",{value:q,configurable:!0});let _=a;if(_&&b(p())>=Number(_.expiresAt))throw new Error("Quote expired; request a fresh quote.");_&&i?.quote&&m(i.quote)&&Ye(i.quote,_);let j=t.includes(".")?(await U()).find(N=>`${N.project}.${N.name}`===t):void 0,Ee={name:t,args:o,...j?{recipe:j}:{},oakTokenAddress:e.oakTokenAddress,..._?{quote:_,quoteArgs:F.get(o.quoteId)}:{}},Xe=async()=>{j&&await J(t,!0);let N=structuredClone(o),$=_;if(_){let re=F.get(o.quoteId);if(!re)throw new Error("Quote request is unavailable; request a fresh quote.");let Re=await ue(t==="kyberswap_swap"?"kyberswap_quote":t==="velora_swap"?"velora_quote":"quote",re);if(N.quoteId=Re.quoteId,$=I.get(Re.quoteId),!$)throw new Error("Fresh quote is unavailable.")}let H=j?{txs:pe(j,N,e.signer.address)}:(await C(t,N,!0)).data;if(!m(H)||!Array.isArray(H.txs)||H.continuation!==void 0)throw new Error("Action requires a fresh project exchange; start it again.");let le=Math.min(b(p())+me,(V(H.expiresAt)??1/0)-1,$?Number($.expiresAt)-1:1/0);return{txs:H.txs.map(re=>({...qe(re),notAfter:le})),action:{...Ee,args:N,...$?{quote:$}:{}}}},Oe=await w.send(g,Ee,Xe);return{...Oe,status:Oe.status??"mined"}}return{hashes:[],status:"not_submitted",summary:"Not submitted."}}async function Ie(t,o){try{let u=await ue(t,o);if(t==="preview"&&m(u))return ne(u,{hashes:[],status:"not_submitted",summary:"Not submitted. Preview only."});if(["oak_subscribe","oak_renew"].includes(t)&&m(u)&&Array.isArray(u.hashes)){let r=u.hashes,i=typeof u.summary=="string"?u.summary:"",v=r.length?"submitted":"not_submitted";return{summary:!r.length&&/^(?:Submitted|Mined|Final|Submission unknown)[:.]/.test(i)?i:W(r,v,i),...Object.fromEntries(Object.entries(u).filter(([x])=>x!=="summary"))}}return u}catch(u){let r=K(u);throw!oe.has(t)&&!ie(t,o)&&!/^(?:Not submitted|Submitted|Mined|Final|Submission unknown)[:.]/.test(r.message)&&(r.message=`Not submitted. ${r.message}`),r}}async function ue(t,o,u){if(t==="erc8004_register"&&!u&&E.withAction){let a=await E.withAction(async s=>{try{return{ok:!0,value:await ue(t,o,s)}}catch(n){return{ok:!1,error:K(n)}}});if(!a.ok)throw a.error;return a.value}if(e.launchOnly&&!Qe.has(t))throw new Error("Only Pons launch tools are available before deployment.");let r=ae(JSON.parse(JSON.stringify(ae(o))));if(r.continuation!==void 0||r.signature!==void 0)throw new Error("Start a fresh tool call; the local bridge owns project continuations.");if(t==="oak_identity_unlink"&&k.unlink){if(Object.keys(r).some(a=>!["actor","linkId"].includes(a))||r.actor!==void 0&&r.actor!=="agent"&&r.actor!=="owner"||r.linkId!==void 0&&typeof r.linkId!="string")throw new Error("Provide actor (agent or owner) and an optional linkId.");return k.unlink({actor:r.actor==="owner"?"owner":"agent",linkId:r.linkId},e.signOwner)}if(t==="oak_subscribe"&&e.subscribe){if(Object.keys(r).length!==1||r.plan!=="holder"&&r.plan!=="nohold")throw new Error("Choose plan holder or nohold.");return await k.requireVerified(),e.subscribe(r.plan)}if(t==="oak_renew"&&e.subscribe){if(Object.keys(r).length)throw new Error("Provide an empty JSON object.");return await k.requireVerified(),e.ensureSubscribed()}if(t==="oak_setup"&&e.setup){if(Object.keys(r).some(a=>!["mode","agentId","profile","tag"].includes(a)))throw new Error("Provide only documented setup arguments.");if(r.mode==="link"&&typeof r.agentId=="string"&&r.profile===void 0&&r.tag===void 0)return e.setup({mode:"link",agentId:r.agentId});if(r.mode==="register"&&(r.profile===void 0||m(r.profile))&&r.agentId===void 0&&(r.tag===void 0||typeof r.tag=="boolean"))return e.setup({mode:"register",profile:r.profile,tag:r.tag});throw new Error("Choose register (profile optional), or link with an agentId.")}if(t.includes(".")){let a=(await U()).find(f=>`${f.project}.${f.name}`===t);if(!a)throw new Error("Unknown or disabled recipe.");if(a.kind==="read")return Ue(a,r,{client:e.recipeClient});await J();let s=pe(a,r,e.signer.address),n=await te(t,r,s,be);return ne({summary:be},{...n,summary:W(n.hashes,n.status)})}if(t==="account")return G(t,r);let{data:i,meta:v}=await C(t,r);if(oe.has(t)||ie(t,r)){if(["quote","kyberswap_quote","velora_quote"].includes(t)&&m(i)&&typeof i.quoteId=="string"){let a=i,s=a.from??a.input?.token.address,n=a.to??a.output?.token.address;if(!s||!n||(a.amountIn??a.input?.amount)!==r.amountIn||a.wallet!==void 0&&!P(a.wallet,e.signer.address))throw new Error("Quote does not match the requested amount or wallet.");for(let[d,q,_]of[[r.from,a.input?.token,s],[r.to,a.output?.token,n]])if(typeof d!="string"||(d.startsWith("0x")?!P(d,_):!m(q)||!P(d.replace(/^\$/,""),q.symbol)))throw new Error("Quote token does not match the requested token.");let f=Number(a.expiresAt);if(!Number.isSafeInteger(f)||f<=b(p()))throw new Error("Quote expired or has an invalid expiry; request a fresh quote.");let A=Ze({...a,expiresAt:String(Math.min(f,b(p())+60)),from:s,to:n,amountIn:r.amountIn,wallet:e.signer.address,chainId:y,minAmountOut:a.minAmountOut??a.minimumOutput?.amount??""});if(t==="kyberswap_quote"&&!P(A.router,Ae[4663].routes.kyberswap.address)||t==="velora_quote"&&!P(A.router,Ae[4663].routes.velora.address))throw new Error("Quote router differs from the requested module.");if(I.size>=1e3){let d=I.keys().next().value;I.delete(d),F.delete(d)}I.set(a.quoteId,A),F.set(a.quoteId,structuredClone(r))}return i}let w=[],x=[],g=(a,s="")=>{let n=w.length?x.every(f=>f==="final")?"final":x.every(f=>f==="mined"||f==="final")?"mined":"submitted":"not_submitted";return ne(a,{hashes:w,status:n,summary:W(w,n,s)})};try{let a,s;for(;;){if(!m(i)||!Array.isArray(i.txs)&&!Array.isArray(i.steps))return m(i)&&(w.length||t==="erc8004_register")?g(i):i;if(typeof i.summary!="string"||Array.isArray(i.txs)&&Array.isArray(i.steps))throw new Error("Invalid project action result.");if(Array.isArray(i.txs)){if(i.continuation!==void 0)throw new Error("Continuation requires project steps.");let d=await te(t,r,i.txs,i.summary,i,v,u);if(w.push(...d.hashes),d.hashes.length&&x.push(d.status),t==="pons_launch"&&d.hashes.length){let _=d.hashes.at(-1);try{let j=await G(t,{transactionHash:_});if(!m(j)||j.txs!==void 0||j.steps!==void 0)throw new Error("Invalid Pons launch confirmation.");return g({...j,summary:[i.summary,j.summary].filter(Boolean).join(" ")})}catch{return{summary:W(w,d.status,"Token lookup is unavailable. Call pons_launch with only transactionHash to read it; do not launch again."),hashes:w,status:d.status,transactionHash:_,confirmationPending:!0}}}if(t==="erc8004_register"&&d.hashes.length){if(d.hashes.length!==1)throw new Error("Unexpected ERC-8004 registration sequence.");if(i.registrationResumed===!0){if({data:i,meta:v}=await C(t,r),m(i)&&Array.isArray(i.txs))throw new Error("Registrar metadata is not confirmed; retry oak setup register.")}else if(!s)s=d.hashes[0],{data:i,meta:v}=await C(t,{...r,transactionHash:s});else if({data:i,meta:v}=await C(t,{...r,transactionHash:s,metadataTransactionHash:d.hashes[0]}),m(i)&&(Array.isArray(i.txs)||Array.isArray(i.steps)))throw new Error("Unexpected ERC-8004 confirmation response.");if(m(i)&&!Array.isArray(i.txs))return g(i);continue}let q=Object.fromEntries(Object.entries(i).filter(([_])=>_!=="txs"));return!i.txs.length&&(t==="meridian_buy"||t==="meridian_sell")&&i.status==="mined"&&Array.isArray(i.hashes)?(w.push(...i.hashes),x.push("mined"),g(Object.fromEntries(Object.entries(q).filter(([_])=>_!=="summary")),i.summary)):g(q)}let n=i.steps;if(!m(i.continuation)){if(n.some(q=>q.kind!=="tx"))throw new Error("Typed signing requires a project continuation.");let d=await te(t,r,n.map(q=>q.tx),i.summary,i,v,u);return w.push(...d.hashes),d.hashes.length&&x.push(d.status),g({summary:i.summary})}let f=i.continuation;ve(t,r,e.signer.address,n,f,a,p());let A;if(n[0]?.kind==="typedData")await D(je(n[0].request,{name:t})),await J(),ve(t,r,e.signer.address,n,f,a,p()),A=await E.signTypedData(n[0].request,{name:t}),ve(t,r,e.signer.address,n,f,a,p());else{let d=await te(t,r,n.map(q=>q.tx),i.summary,i,v,u);w.push(...d.hashes),d.hashes.length&&x.push(d.status)}a=f,{data:i,meta:v}=await C(t,{...r,continuation:f,...A?{signature:A}:{}})}}catch(a){let s=K(a);throw w.length&&(s.message=W(w,"submitted",`Action stopped. ${s.message}`)),s}}function ce(){let t="Wallet reconciliation failed. Wait for the pending transaction or check local wallet and RPC availability.";return z||(z=Promise.resolve().then(async()=>(typeof E.withAction=="function"&&await E.withAction(async()=>{}),t="Subscription check failed.",e.ensureSubscribed())).then(async o=>{let u=o.ok===!0&&o.access===!0;return await D(u?o.summary:`${o.summary} ${se}`),u}).catch(async()=>(await D(`${t} ${se}`).catch(()=>{}),!1)).finally(()=>{z=void 0})),z}async function J(t,o=!1){if(e.privateTestMode||e.launchOnly&&t===et){let u=e.privateTestMode?"/v1/private-access":"/v1/launch-access",r="{}",i=await l(new URL(u,c),{method:"POST",redirect:"error",headers:{"content-type":"application/json",...await k.sessions.headers("POST",u,r)},body:r,signal:AbortSignal.timeout(3e4)}),v=await i.json();if(!i.ok||v?.ok!==!0||v.data?.allowed!==!0)throw new Error(e.privateTestMode?"This wallet is not on the server private test allow-list. Ask the operator to configure private test access or use the normal paid setup.":"This wallet is not on the server launch allow-list. Ask the operator to configure launch access or use the normal paid setup.");return}if(await k.requireVerified(),o){let{data:u}=await C("account",{});if(!m(u)||!["holder","nohold"].includes(String(u.plan))||R(u.paidUntil)<BigInt(b(p()))||u.plan==="holder"&&R(u.oakHeld)<R(u.oakRequired))throw new Error(se);return}if(!await ce())throw new Error(se)}async function Pe(){Z=!0,B&&globalThis.clearInterval(B),B=void 0,await S?.close(),await z,k.sessions.clear()}async function Ke(t=new Et){if(S||Z)throw new Error("MCP bridge has already started or closed.");!e.launchOnly&&!e.privateTestMode&&await k.requireVerified().then(()=>ce()).catch(async()=>{await D("Run oak setup to register or link your identity first. Reads remain available.")}),S=new Pt({name:"oak",version:Ne},{capabilities:{tools:{},logging:{}},instructions:e.startupInstructions?await e.startupInstructions():De(e.signer.address,h)}),S.setRequestHandler(Rt,async()=>({tools:await Se()})),S.setRequestHandler(Ot,async o=>{try{return{content:[{type:"text",text:JSON.stringify(await Ie(o.params.name,o.params.arguments??{}))}]}}catch(u){return{isError:!0,content:[{type:"text",text:Ce(u,"Oak tool failed.")}]}}}),S.onclose=()=>{Z=!0,B&&globalThis.clearInterval(B),B=void 0};try{await S.connect(t)}catch(o){throw await Pe(),o}!Z&&!e.launchOnly&&!e.privateTestMode&&(B=globalThis.setInterval(()=>{k.requireVerified().then(()=>ce()).catch(()=>{})},36e5),B.unref())}return{listTools:Se,postTool:G,callTool:Ie,start:Ke,stop:Pe,confirmSignature:Q}}export{_t as a,oe as b,Ut as c,ae as d,Bt as e,Dt as f,Cr as g};
@@ -0,0 +1 @@
1
+ var o="0.1.1";export{o as a};
@@ -0,0 +1,5 @@
1
+ import{a as H,b as z}from"./67E2KBUQ.js";import{decodeFunctionData as G,encodeFunctionData as ne,erc20Abi as X,getAddress as oe,hashTypedData as K,isAddress as Y,keccak256 as U,parseTransaction as re,parseAbi as Z,serializeTransaction as B,toEventSelector as _,zeroAddress as J}from"viem";import{ADDRESSES as N,NETWORKS as b}from"@oakagentkit/core/addresses";import{assertSwapTransaction as ae,isNativeToken as E}from"@oakagentkit/core/swap";import{normalizeNativeTokenAddress as R,NATIVE_TOKEN_ADDRESS as S}from"@oakagentkit/core/simulate";import{createModuleContext as V}from"@oakagentkit/core/module";import{createModule as se}from"@oakagentkit/core/modules/morpho/index";import{createModule as ie}from"@oakagentkit/core/modules/priors/index";import{createModule as de}from"@oakagentkit/core/modules/hookr/index";import{createCurveSwapProvider as ue}from"@oakagentkit/core/modules/pons/trade";import{fetchOfficialStockTokens as ce}from"@oakagentkit/core/tokens";import{DEEPEST_V4_POOL_ID as pe,MEASURED_V4_POOLS as le}from"@oakagentkit/core/modules/uniswap/v4";import{normalize as fe}from"viem/ens";var me="Human confirmation is unavailable. Use an MCP client with form elicitation, or run oak config set confirm auto yourself in your own terminal. Restore confirmations with oak config set confirm ask.",ge=300;function Ue(t="ask",o=()=>{},c=ge*1e3){if(t!=="ask"&&t!=="auto")throw new Error("Set confirm to ask or auto.");return async n=>{if(t==="auto")return;let e=o(),p=e?.getClientCapabilities()?.elicitation;if(!e||!p||!("form"in p)&&Object.keys(p).length!==0)throw new Error(me);let u;try{let l=await Promise.race([e.elicitInput({mode:"form",message:`${n.summary}
2
+ Unsigned signing hash: ${n.hash}
3
+ Approve this signature and the displayed terms and limits?`,requestedSchema:{type:"object",properties:{confirm:{type:"boolean",title:"Sign and submit this action",default:!1}},required:["confirm"]}},{timeout:c}),new Promise((r,m)=>{u=setTimeout(()=>m(new Error("timeout")),c)})]);if(l.action!=="accept"||l.content?.confirm!==!0)throw new Error("Human confirmation declined; nothing was signed.")}catch(l){throw l instanceof Error&&l.message==="Human confirmation declined; nothing was signed."?l:new Error("Human confirmation timed out or was unavailable; nothing was signed.",{cause:l})}finally{u&&clearTimeout(u)}}}function Be(t,o){let c={...re(t)};delete c.r,delete c.s,delete c.v,delete c.yParity;let n=U(B({...o,type:"eip1559"}));if(U(B(c))!==n)throw new Error("Signed transaction bytes differ from the human-confirmed transaction.")}async function Ne(t,o,c){let n=Object.freeze({...o}),e=()=>U(B({...n,type:"eip1559"})),p=e();if(await t(Object.freeze({hash:p,summary:c})),e()!==p)throw new Error("Transaction changed after confirmation; confirm again.");return n}function we(t){return JSON.parse(JSON.stringify(t,(o,c)=>typeof c=="bigint"?c.toString():c))}async function je(t,o,c){let n=we(o),e=K(n);if(await t({hash:e,summary:ye(n,c)}),K(n)!==e)throw new Error("Typed action changed after confirmation; confirm again.");return n}function ye(t,o){let c=u=>{let l=String(u);return l.length>512&&d("typed action field exceeds 512 characters"),JSON.stringify(l).replace(/[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g,r=>`\\u${r.charCodeAt(0).toString(16).padStart(4,"0")}`)},n=[`Typed action ${c(o?.name??t.primaryType)}`],e=(u,l,r=0)=>{if((r>8||n.length>=100)&&d("typed action summary is too large"),u!==null&&typeof u=="object")for(let[m,f]of Object.entries(u))e(f,`${l}[${c(m)}]`,r+1);else n.push(`${l}: ${c(u)}`)};e(t.domain,"Domain"),n.push(`Primary type: ${c(t.primaryType)}`),e(t.types,"Types"),e(t.message,"Message"),n.push("Signature only; external settlement remains pending.");let p=n.join(`
4
+ `);return p.length>16384&&d("typed action summary is too large"),p}var he=_("Transfer(address,address,uint256)").toLowerCase(),ve=_("TransferSingle(address,address,address,uint256,uint256)").toLowerCase(),ee=(1n<<256n)-1n;function d(t){throw new Error(`Local transaction guard: ${t}; nothing was signed.`)}function A(t){return typeof t!="string"||!Y(t,{strict:!1})?d("cannot establish the requested asset address"):oe(t)}function T(t){return typeof t!="string"||!/^\d+$/.test(t)||BigInt(t)>ee?d("cannot establish the requested base-unit amount"):BigInt(t)}function M(t){return!t||typeof t!="object"||Array.isArray(t)?d("malformed local transfer trace"):t}function ke(t,o){let c=[];for(let n of t){Array.isArray(n.logs)||d("local transfer trace is unavailable");for(let e of n.logs){let p=M(e);(!Array.isArray(p.topics)||typeof p.topics[0]!="string")&&d("malformed local transfer trace");let u=p.topics,l=u[0].toLowerCase();if(l===ve&&d("ERC-1155 asset transfers cannot yet be matched to this action"),l!==he)continue;(u.length!==3&&u.length!==4||!u.slice(1,3).every(h=>/^0x0{24}[0-9a-f]{40}$/i.test(h))||typeof p.data!="string")&&d("malformed local transfer trace");let r=A(`0x${u[1].slice(-40)}`),m=A(`0x${u[2].slice(-40)}`);if(r.toLowerCase()!==o.toLowerCase()&&m.toLowerCase()!==o.toLowerCase())continue;let f=u.length===4;(f?/^0x[0-9a-f]{64}$/i.test(u[3])&&p.data==="0x":/^0x[0-9a-f]{64}$/i.test(p.data))||d("malformed local transfer amount"),c.push({token:R(A(p.address)),from:r,to:m,amount:f?1n:BigInt(p.data),...f?{id:BigInt(u[3])}:{}})}}return c}var be=new Set(["increaseAllowance(address,uint256)","increaseApproval(address,uint256)","permit(address,address,uint256,uint256,uint8,bytes32,bytes32)","permit(address,address,uint256,uint256,bool,uint8,bytes32,bytes32)","permit(address,((address,uint160,uint48,uint48),address,uint256),bytes)","permit(address,((address,uint160,uint48,uint48)[],address,uint256),bytes)","permitTransferFrom(((address,uint256),uint256,uint256),(address,uint256),address,bytes)","permitTransferFrom(((address,uint256)[],uint256,uint256),(address,uint256)[],address,bytes)","permitWitnessTransferFrom(((address,uint256),uint256,uint256),(address,uint256),address,bytes32,string,bytes)","permitWitnessTransferFrom(((address,uint256)[],uint256,uint256),(address,uint256)[],address,bytes32,string,bytes)"].map(t=>_(t).slice(0,10).toLowerCase())),$=1n<<128n,te=720*60*60;function D(t,o,c=Math.floor(Date.now()/1e3)){t>=$&&d("unlimited or effectively unlimited approval"),o!==void 0&&o>c+te&&d("Permit2 approval expiration exceeds 30 days")}function j(t,o,c,n=!0){let e=[],p=_("Approval(address,address,uint256)").toLowerCase(),u=_("ApprovalForAll(address,address,bool)").toLowerCase(),l=_("Approval(address,address,address,uint160,uint48)").toLowerCase(),r=_("Permit(address,address,address,uint160,uint48,uint48)").toLowerCase();for(let m of t){Array.isArray(m.logs)||d("local approval trace is unavailable");for(let f of m.logs){let h=M(f);(!Array.isArray(h.topics)||!h.topics.every(x=>typeof x=="string"))&&d("malformed approval trace");let a=h.topics,g=a[0]?.toLowerCase();if(![p,u,l,r].includes(g??""))continue;let s=x=>/^0x0{24}[0-9a-f]{40}$/i.test(a[x]??"")?A(`0x${a[x].slice(-40)}`):d("malformed approval trace");if(s(1).toLowerCase()!==o.toLowerCase())continue;g===u&&d("operator-wide approval is not an exact approval");let y=g===l||g===r;((y?a.length!==4:![3,4].includes(a.length))||typeof h.data!="string")&&d("malformed approval trace");let i=!y&&a.length===4,w=i?a[3]:h.data,C=y?g===r?3:2:1;(!new RegExp(`^0x[0-9a-f]{${C*64}}$`,"i").test(w)||i&&h.data!=="0x")&&d("malformed approval trace");let v=BigInt(`0x${w.slice(2,66)}`),k=y?Number(BigInt(`0x${w.slice(66,130)}`)):void 0;g===r&&BigInt(`0x${w.slice(130,194)}`)>=1n<<48n&&d("malformed approval trace"),y&&(v>=1n<<160n||!Number.isSafeInteger(k)||k>=2**48)&&d("malformed approval trace"),n&&D(v,k,c),e.push({...i?{nft:!0}:{},token:y?s(2):A(h.address),spender:s(y?3:2),amount:v,...y?{expiration:k,permit2:A(h.address),...g===r?{kind:"permit"}:{}}:{}})}}return e}function I(t,o){let c=t.data.slice(0,10).toLowerCase();if(c==="0xa22cb465"&&d("operator-wide approval is not an exact approval"),be.has(c)&&d("allowance grant requires an absolute exact approve; incremental approvals and permits are unsupported"),c==="0x87517c45"){BigInt(t.value)!==0n&&d("approval carries native value");let u;try{u=G({abi:Z(["function approve(address token,address spender,uint160 amount,uint48 expiration)"]),data:t.data})}catch{return d("malformed approval")}let[l,r,m,f]=u.args;return D(m,f,o),{token:l,spender:r,amount:m,expiration:f,permit2:t.to}}if(c!=="0x095ea7b3")return;let n;try{n=G({abi:X,data:t.data})}catch{return d("malformed approval")}(n.functionName!=="approve"||BigInt(t.value)!==0n)&&d("malformed approval");let[e,p]=n.args;return D(p),{token:t.to,spender:e,amount:p}}function We(t,o,c){return j(t,o,c)}var L=t=>`${t.token.toLowerCase()}:${t.spender.toLowerCase()}`,Ae=(t,o)=>L(t)===L(o)&&t.amount===o.amount&&t.expiration===o.expiration&&t.permit2?.toLowerCase()===o.permit2?.toLowerCase()&&t.kind===o.kind&&t.nft===o.nft;function He(t,o){return{account:o,to:t.token,data:ne({abi:X,functionName:"allowance",args:[o,t.spender]}),value:0n,gas:100000n}}var Q=t=>Array.isArray(t)?JSON.stringify(t.map(o=>{let c=M(o);return{address:c.address,topics:c.topics,data:c.data}})):void 0,q=t=>t.status==="success"||t.status==="0x1";function Ce(t,o,c,n,e=new Map,p=[],u=[]){t.length!==c.length&&d("local approval simulation returned an unexpected result");let l=new Map(e);return t.flatMap((r,m)=>{q(r)||d("approval simulation reverted or did not execute successfully");let f=j([r],o,n,!1),h=I(c[m],n),a=p[m],g=new Map(l),s=new Map;for(let i of ke([r],o))if(i.id===void 0&&i.from.toLowerCase()===o.toLowerCase()&&i.to.toLowerCase()!==o.toLowerCase()){let w=i.token.toLowerCase();s.set(w,(s.get(w)??0n)+i.amount)}let y=!1;for(let i of f){let w=L(i);if(h&&!y&&Ae(i,h))D(i.amount,i.expiration,n),y=!0;else{let C=g.get(w),v=l.get(w),k=a?.get(w),x=s.get(i.token.toLowerCase())??0n,W=u.some(F=>F.toLowerCase()===i.spender.toLowerCase())&&u.some(F=>F.toLowerCase()===c[m].to.toLowerCase())&&x>0n,O=v!==void 0&&v>=x?v-x:void 0;(i.permit2||i.nft||C===void 0||i.amount>=C||v===void 0||k===void 0||k>=v||!W||O===void 0||k>O)&&d("simulated approvals differ from decoded expected approvals"),(i.amount===$||k===$)&&d("unlimited or effectively unlimited approval"),(i.amount>$||k>$)&&(!W||k!==O)&&d("unlimited or effectively unlimited approval")}!i.permit2&&!i.nft&&g.set(w,i.amount)}if(h&&!y&&d("simulated approvals differ from decoded expected approvals"),a)for(let[i,w]of a){let C=l.get(i);C===void 0&&d("pre-state allowance is unavailable"),w>C&&(!h||L(h)!==i||h.permit2||w!==h.amount)&&d("post-state allowance differs from decoded expected approval"),g.has(i)&&f.some(v=>!v.permit2&&!v.nft&&L(v)===i)&&w!==g.get(i)&&d("post-state allowance differs from approval logs")}return l=new Map(a??g),f})}async function ze(t,o,c,n,e,p,u,l=[]){t.length!==c.length&&d("local approval simulation returned an unexpected result");let r=new Map;for(let[g,s]of t.entries()){q(s)||d("approval simulation reverted or did not execute successfully");let y=I(c[g],p);for(let i of[...j([s],o,p,!1),...y?[y]:[]])!i.permit2&&!i.nft&&r.set(L(i),i)}let[m,f]=await Promise.allSettled([Promise.all([...r].map(async([g,s])=>{let y=await n(s.token,s.spender,e);return(typeof y!="bigint"||y<0n||y>ee)&&d("pre-state allowance is unavailable"),[g,y]})),Promise.all(t.map(async(g,s)=>{if(!r.size)return new Map;if(!u)return d("post-state allowance simulation is unavailable");let y=[...r.values()],i=await u(s,y);i.length!==s+1+y.length&&d("post-state allowance simulation is incomplete");for(let w=0;w<=s;w++)(!q(i[w])||Q(i[w].logs)!==Q(t[w].logs))&&d("post-state allowance simulation changed the transaction");return new Map(y.map((w,C)=>{let v=i[s+1+C],k=v.returnData??v.data;return(!q(v)||typeof k!="string"||!/^0x[0-9a-f]{64}$/i.test(k))&&d("post-state allowance is unavailable"),[L(w),BigInt(k)]}))}))]);if(m.status==="rejected")throw m.reason;if(f.status==="rejected")throw f.reason;let h=new Map(m.value),a=f.value;return Ce(t,o,c,p,h,a,l)}var P=t=>`${R(t.token).toLowerCase()}:${t.id??""}`;function Ge(t,o,c,n=new Map,e=[]){let p=new Map;for(let r of c)p.set(P(r),(p.get(P(r))??0n)+r.amount);let u=new Map(n),l=e.filter(r=>r.chainId===4663&&r.to.toLowerCase()===b.mainnet.weth.toLowerCase()&&r.data.toLowerCase()==="0xd0e30db0").reduce((r,m)=>r+BigInt(m.value),0n);if(l>0n){t.filter(f=>E(f.token)&&f.from.toLowerCase()===o.toLowerCase()&&f.to.toLowerCase()===b.mainnet.weth.toLowerCase()).reduce((f,h)=>f+h.amount,0n)!==l&&d("wrapped ETH transfer does not match the explicit wrap");let m=P({token:b.mainnet.weth});u.set(m,(u.get(m)??0n)-l)}for(let r of t){if(r.from.toLowerCase()!==o.toLowerCase()||r.to.toLowerCase()===o.toLowerCase())continue;let m=P(r),f=(u.get(m)??0n)+r.amount;f>(p.get(m)??0n)&&d(`simulation outflow of ${r.token} (${f} base units) does not match requested inputs`),u.set(m,f)}return u}function xe(t,o){let c=o.destinations??H(o,t[0]?.chainId??4663),n=e=>c.some(p=>p.toLowerCase()===e.toLowerCase());for(let e of t){let p=I(e);p?(!n(p.spender)||e.data.slice(0,10).toLowerCase()==="0x87517c45"&&!n(e.to))&&d("approval spender or Permit2 destination is outside the module contract set"):n(e.to)||d("destination is outside the module contract set")}}function Ke(t,o,c,n){let e=["swap","kyberswap_swap","velora_swap"].includes(o.name)||["pons_buy","pons_sell"].includes(o.name)&&o.quote!==void 0,p=o.quote;e&&!p&&d("quote is not held locally; request a fresh quote in this session"),(o.name==="kyberswap_swap"&&p?.router.toLowerCase()!==N[4663].routes.kyberswap.address.toLowerCase()||o.name==="velora_swap"&&p?.router.toLowerCase()!==N[4663].routes.velora.address.toLowerCase())&&d("swap router differs from the requested module"),e||xe(t,o);let u=0;for(let m of t){let f=I(m);if(f){let h=t.filter(s=>s.chainId===4663&&s.to.toLowerCase()===b.mainnet.weth.toLowerCase()&&s.data.toLowerCase()==="0xd0e30db0").reduce((s,y)=>s+BigInt(y.value),0n),g=(h>0n?[...n,{token:b.mainnet.weth,amount:h}]:n).find(s=>s.token.toLowerCase()===f.token.toLowerCase());if(f.expiration!==void 0){let s=o.name.startsWith("pons_")?300:o.name.startsWith("poolstrade_")?600:o.name==="uniswap_add"?1800:te,y=o.args.deadline===void 0?void 0:T(String(o.args.deadline)),i=o.args.permit2Expiration===void 0?void 0:T(String(o.args.permit2Expiration)),w=BigInt(f.expiration);(f.expiration>Math.floor(Date.now()/1e3)+s||y!==void 0&&w>y||i!==void 0&&w!==i)&&d("Permit2 approval expiration differs from the module builder lifetime")}(!g||(g.id!==void 0?f.amount!==g.id:p?f.amount!==g.amount:f.amount>g.amount))&&d("approval token or amount differs from the requested input"),p&&(f.spender.toLowerCase()!==(p.spender??p.router).toLowerCase()||f.token.toLowerCase()!==p.from?.toLowerCase())&&d("swap approval spender is outside the module router set")}else e&&(u++,ae(m,{...p,wallet:c}))}e&&u!==1&&d("a swap must contain exactly one execution");let l=t.reduce((m,f)=>m+BigInt(f.value),0n),r=n.filter(m=>E(m.token)).reduce((m,f)=>m+f.amount,0n);l>r&&d("native value differs from the requested input")}function Te(t){return JSON.stringify(t).replace(/[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g,o=>`\\u${o.charCodeAt(0).toString(16).padStart(4,"0")}`)}function Je(t,o,c,n,e,p=[]){let u=[`Action: ${Te(t)}`,`Destination contract: ${o.to}`,`Native value: ${o.value} wei`,`Estimated gas limit: ${o.gas}; maximum gas cost: ${o.gas*o.maxFeePerGas} wei`,`Chain: ${o.chainId}; nonce: ${o.nonce}; max fee: ${o.maxFeePerGas}; priority fee: ${o.maxPriorityFeePerGas}`];for(let l of c)u.push(`${l.from.toLowerCase()===n.toLowerCase()?"OUT":"IN"} ${l.amount} base units of ${l.token}${l.id!==void 0?` token ID ${l.id}`:""}: ${l.from} -> ${l.to}`);for(let l of e){let r=I(l);r&&u.push(`Approval: ${r.token}, spender ${r.spender}, exact amount ${r.amount} base units${r.expiration!==void 0?`, Permit2 ${r.permit2}, expiration ${r.expiration} (${new Date(r.expiration*1e3).toISOString()})`:""}`)}for(let l of p)u.push(`Simulated approval: ${l.token}, spender ${l.spender}, exact amount ${l.amount} base units${l.expiration!==void 0?`, Permit2 ${l.permit2}, expiration ${l.expiration} (${new Date(l.expiration*1e3).toISOString()})`:""}`);return u.push("The maximum gas cost above is the most you approve for network gas (gas limit times max fee per gas). A refresh must stay within this cost, gas limit and priority fee cap; decreases are allowed. Decoded terms and the shown minimum stay unchanged; a swap receipt may vary above that minimum. A nonce change requires RPC proof that previously journaled own transactions mined and the new nonce is current pending. Any other change requires confirmation again, at most once per action, including retries."),u.join(`
5
+ `)}async function Ve(t,o,c){let{name:n,args:e,quote:p}=t,u=N[4663];t.destinations=await z(t,c,t.chainId);let l=[],r=(a,g,s)=>l.push({token:R(A(a)),amount:typeof g=="bigint"?g:T(g),...s!==void 0?{id:s}:{}}),m=async(a,g,s,y=[])=>c.readContract({address:A(a),abi:Z([g]),functionName:s,args:y}),f=a=>r(S,a);if(t.recipe){let a=t.recipe,g=s=>e[s]??a.inputs.find(y=>y.name===s)?.default;return a.approve&&r(a.approve.token,g(a.approve.amountFromInput)),a.value&&f(g(a.value.fromInput)),l}if(["swap","kyberswap_swap","velora_swap"].includes(n)){if(p?.from){let a=t.quoteArgs,g={ETH:S,USDG:b.mainnet.usdg,WETH:b.mainnet.weth,USDE:u.meridian.CollateralToken_USDe.address,...t.oakTokenAddress?{OAK:t.oakTokenAddress}:{}};for(let[s,y]of[[a?.from,p.from],[a?.to,p.to]]){typeof s!="string"&&d("quote request is not held locally");let i=Y(s,{strict:!1})?s:g[s.replace(/^\$/,"").toUpperCase()];if(!i){let w=(await ce()).filter(C=>C.symbol.toUpperCase()===s.toUpperCase());w.length===1&&(i=w[0].address)}(!i||R(A(i)).toLowerCase()!==y?.toLowerCase())&&d("quote asset cannot be bound locally; quote an explicit token address")}if(a?.amountIn!==p.amountIn&&d("quote amount differs from the request"),p.provider==="pons"){let s=await m(u.pons.factory.address,"function getLaunchedToken(address) view returns ((address token,address curve,address deployer,address creatorFeeRecipient,address pairToken,uint256 graduationThreshold,uint24 poolFee,int24 tickSpacing,uint16 creatorTaxBps,bool buybackEnabled,uint8 phase,uint256 sweptQuote,uint256 sweptTokens,uint256 sweptAt,bool exists))","getLaunchedToken",[p.ponsCurveToken]);(!s.exists||s.phase!==0||s.curve.toLowerCase()!==p.router.toLowerCase())&&d("Pons curve does not match its factory record")}r(p.from,p.amountIn)}return l}let h=n==="morpho_repay"&&(e.repayAll||e.shares)?se:n==="priors_repay"?ie:n==="hookr_create"&&e.bounty===void 0?de:void 0;if(h){let a=()=>d("input reconstruction requires an unavailable local read"),g=V({network:"mainnet",clientFor:()=>c,http:a,quoteSwap:a,buildSwap:a,preview:async i=>({txs:i,changes:[],summary:"Local input reconstruction only."})}),s=h(g).tools.find(i=>i.name===n);s||d("local action builder is unavailable");let y=M(await s.execute(e,o));Array.isArray(y.txs)||d("local action builder returned no inputs");for(let i of y.txs){let w=I(i);w&&r(w.token,w.amount),BigInt(i.value)>0n&&f(i.value)}if(n==="hookr_create"&&!l.some(i=>!E(i.token))){let i=e.key,w=e.tokenIn??(e.zeroForOne?i?.currency0:i?.currency1);E(A(w))||r(w,e.amountIn)}return l}if(n==="pons_buy"||n==="pons_sell"){let a=()=>d("local Pons input reconstruction is unavailable"),g=V({network:"mainnet",clientFor:()=>c,http:a,preview:a,quoteSwap:a,buildSwap:a});try{t.quote=await ue(g).quote({from:n==="pons_buy"?S:A(e.token),to:n==="pons_buy"?A(e.token):S,amountIn:String(e.amountIn),slippageBps:e.slippageBps},o)}catch(s){if(!(s instanceof Error)||!s.message.includes("Pons curve quotes are only available before graduation."))throw s}r(n==="pons_buy"?S:e.token,e.amountIn)}else if(n==="pons_launch"){let a=await m(u.pons.factory.address,"function launchFee() view returns (uint256)","launchFee");f(a),r(e.pairToken??J,e.initialBuy??"0")}else if(n==="pons_buy"||n==="poolstrade_buy")f(e.amountIn);else if(n==="pons_sell"||n==="poolstrade_sell")r(e.token,e.amountIn);else if(n==="clanker_launch")f(e.initialBuy??"0");else if(n==="poolstrade_launch")f(e.initialBuy??"0");else if(n==="orbio_buy_credit")r(b.mainnet.usdg,e.usdgIn);else if(n==="meridian_buy")r(u.meridian.CollateralToken_USDe.address,e.stake);else if(n==="meridian_sell")r(e.token,e.amount);else if(["steakhouse_deposit","spark_deposit","netnet_deposit","grove_deposit","priors_lend"].includes(n))r(b.mainnet.usdg,e.assets??e.amount);else if(n==="beefy_deposit")r(e.token,e.amount);else if(n==="longbow_deposit"){let a=e.wrapEth===!0;r(a?S:e.vault==="eth"||String(e.vault).toLowerCase()===u.vaults.longbowEth.address.toLowerCase()?b.mainnet.weth:b.mainnet.usdg,e.amount)}else if(n==="hoodag_register"){let a=fe(String(e.name).replace(/\.hood$/i,""));r(b.mainnet.usdg,await m(u.hoodag.registrarController.address,"function priceUSDG(string,uint256) view returns (uint256)","priceUSDG",[a,T(e.duration??"31536000")]))}else if(n==="hoodlock_airdrop_create"){let a=e.entries,g=e.total===void 0?a.reduce((s,y)=>s+T(y.amount),0n):T(e.total);r(e.token,g),f(await m(u.hoodlock.airdrop.address,"function quote(uint32) view returns (uint256)","quote",[Number(e.maxClaims??a.length)]))}else if(n==="hoodlock_burn"||n==="hoodlock_lock")e.tokenId!==void 0?(r(e.manager,1n,T(e.tokenId)),f(await m(u.hoodlock.liquidityLocker.address,"function fixedFee() view returns (uint256)","fixedFee"))):(r(e.token,e.amount),f(await m(n==="hoodlock_burn"?u.hoodlock.burner.address:u.hoodlock.locker.address,"function fee() view returns (uint256)","fee")));else if(n==="hookr_create"){let a=e.key;r(e.tokenIn??(e.zeroForOne?a?.currency0:a?.currency1),e.amountIn),e.bounty===void 0&&d("supply an explicit Hookr bounty to bind its native value"),f(e.bounty)}else if(n==="tickerspring_create")r(e.side==="buy"?b.mainnet.usdg:e.token,e.amount);else if(n==="relay_bridge_in"||n==="relay_bridge_out")e.swap&&d("combined Relay swaps require separate locally quoted swap and bridge actions"),r(e.originCurrency??J,e.amount);else if(n==="uniswap_add"){let a=e.poolKey??e.key??(e.currency0&&e.currency1?{currency0:e.currency0,currency1:e.currency1}:void 0),g=String(e.poolId??pe);if(e.version==="v4"&&!a&&(a=le.find(s=>s.poolId.toLowerCase()===g.toLowerCase())?.key),e.version==="v4"&&!a){let s=await m(u.uniswap.v4_position_manager.address,"function poolKeys(bytes25) view returns (address currency0,address currency1,uint24 fee,int24 tickSpacing,address hooks)","poolKeys",[g.slice(0,52)]);a={currency0:s[0],currency1:s[1]}}r(e.token0??a?.currency0,e.amount0Desired??e.amount0Max),r(e.token1??a?.currency1,e.amount1Desired??e.amount1Max)}else if(n==="morpho_supply_collateral"||n==="morpho_repay"){let a=e.marketParams;if(!a){let y=await m(u.morpho.morpho_blue.address,"function idToMarketParams(bytes32) view returns (address loanToken,address collateralToken,address oracle,address irm,uint256 lltv)","idToMarketParams",[e.marketId]),[i,w]=y;a={loanToken:i,collateralToken:w}}let g=n==="morpho_repay"?a.loanToken:a.collateralToken,s=e.assets??e.amount;r(g,s),e.wrapNative===!0&&f(s)}else if(/_(withdraw|withdraw_collateral)$/.test(n)&&(e.vault||["spark","steakhouse","netnet","grove","longbow"].some(a=>n.startsWith(`${a}_`)))){let a=u.vaults,g=n.startsWith("spark_")?a.spark.address:n.startsWith("steakhouse_")?a.steakhouse.address:n.startsWith("netnet_")?a.netnet.address:n.startsWith("grove_")?a.groveAlm.address:e.vault,s=e.vault??g,y={core:a.longbowCore.address,frontier:a.longbowFrontier.address,eth:a.longbowEth.address},i=A(n==="longbow_withdraw"?y[String(s??"core")]??s:s),w=e.shares;w==="all"||e.amount==="max"?w=await m(i,"function balanceOf(address) view returns (uint256)","balanceOf",[o]):w===void 0&&(w=await m(i,"function previewWithdraw(uint256) view returns (uint256)","previewWithdraw",[T(e.amount)])),r(i,w)}return l}export{me as a,ge as b,Ue as c,Be as d,Ne as e,we as f,je as g,ye as h,ke as i,te as j,I as k,We as l,L as m,He as n,Ce as o,ze as p,Ge as q,xe as r,Ke as s,Te as t,Je as u,Ve as v};
@@ -0,0 +1,2 @@
1
+ import{a as ia}from"./YVAFJM4Y.js";import{a as xe}from"./IVR4JOHU.js";import{b as Ve,c as Ze,d as de,e as ke,f as ea,g as aa,h as ta,i as K,k as ve,n as na,p as ra,q as Te,s as sa,u as M,v as oa}from"./U3IXRJH7.js";import{b as ca,c as da}from"./2NJCYRBM.js";import{b as Y,c as la,d as ua}from"./QIDB35RS.js";import{a as Qe}from"./67E2KBUQ.js";import{createPublicClient as Aa,decodeFunctionData as Sa,encodeFunctionData as Fa,erc20Abi as j,getAddress as ma,http as Na,keccak256 as Ra,parseTransaction as X,recoverTypedDataAddress as Ga,TransactionNotFoundError as fa,TransactionReceiptNotFoundError as wa}from"viem";import{CHAIN_ID as Fe,OAK_FINALITY as La}from"@oakagentkit/core/addresses";import{hasErrorCode as Ie}from"@oakagentkit/core/errors";import{affordableSimulationGas as ha,gasShortage as qa,simulationGasLimit as le}from"@oakagentkit/core/gas";import{unsignedTx as Ae}from"@oakagentkit/core/tx";import{loadSigner as $a}from"#oak-wallet";var Ea=Ve,d=class extends Error{},I=()=>new d("Wallet journal is unresolved; wait for the pending transaction before a new action."),E=()=>new d("Local signing failed."),Q=()=>new d("Transaction reverted; the remaining sequence was stopped."),B=(l,x,k,N)=>new d(qa(l,x,k,N)),Se=(l,x,k)=>new d(`Transaction ${l+1} of ${x} cannot be estimated on chain ${k}; it was not signed.`),W=()=>new d("Prepared transaction expired before signing; preview and retry with a fresh quote."),ue=l=>l instanceof d?l:l instanceof Error&&["Wallet journal is unreadable or invalid; resolve it before a new action.","Unsafe wallet state directory.","Wallet is busy; retry after the current action finishes.","Invalid wallet lock.","Invalid wallet lock owner.","Wallet lock cannot be acquired."].includes(l.message)?new d(l.message):new d("Wallet action failed; check local custody and RPC availability. Any pending journal remains unresolved."),me=l=>l+l/4n,fe=l=>l+l/10n+1n,H=(l,x)=>l>x?l:x;function Ba(){let l=process.env.OAK_FINALITY??String(La);if(l==="safe"||l==="finalized")return l;if(/^[1-9]\d*$/.test(l)&&Number.isSafeInteger(Number(l)))return Number(l);throw new d("Invalid OAK_FINALITY setting.")}function Ha(l){if(l!==Fe)throw new d("Configure an RPC for the transaction chain.");let x=process.env.OAK_RPC_URL;if(!x)throw new d("Set OAK_RPC_URL before sending a transaction.");return Aa({transport:Na(x),cacheTime:0})}function Oa(l,x){let k=`${l} transaction${l===1?"":"s"}`;return x===l?`${k} mined and final.`:x===0?`${k} mined, awaiting finality.`:`${k} mined; ${x} final, ${l-x} awaiting finality.`}function Ne(l={}){let x=new Set(l.allowedChainIds??[Fe]),k=l.finality??Ba();if(typeof k=="number"&&(!Number.isSafeInteger(k)||k<1))throw new d("Invalid finality block count.");let N=l.notAfterSeconds??Ea;if(!Number.isSafeInteger(N)||N<1)throw new d("Invalid transaction not-after window.");let A=()=>{let t=(l.now??(()=>Math.floor(Date.now()/1e3)))(),e=t>1e11?Math.floor(t/1e3):Math.floor(t);if(!Number.isSafeInteger(e)||e<0)throw new d("Invalid local timestamp; check the system clock.");return e},we=async t=>{try{await(l.confirm??Ze())(t)}catch(e){throw new d(e.message)}},V=l.preview?t=>l.preview(ia(t)):void 0,Re=new Map,Z=new Map,Ge=()=>new d("Action terms or signing limits changed again after the second confirmation; request a fresh human-reviewed action. Nothing further was signed.");function Le(t,e){let a=[JSON.stringify(t.map(({to:n,data:o,value:c,chainId:m})=>({to:n.toLowerCase(),data:o.toLowerCase(),value:c,chainId:m})))];if(e?.quote){let n=e.quote;a.push(JSON.stringify({from:n.from?.toLowerCase(),to:n.to?.toLowerCase(),amountIn:n.amountIn,chainId:n.chainId}))}return a}async function pa(t,e,a,n){let o=n.transaction;if(a.nonce===o.nonce)return!0;if(a.chainId!==o.chainId||a.nonce<o.nonce)return!1;let c=n.journaled.filter(s=>s.chainId===o.chainId&&s.nonce>=o.nonce&&s.nonce<a.nonce);if(c.length!==a.nonce-o.nonce)return!1;let[m,f,u]=await Promise.all([t.getTransactionCount({address:e.address,blockTag:"pending"}),t.getTransactionCount({address:e.address,blockTag:"latest"}),Promise.all(c.map(s=>Ee(t,Y(s))))]);return m===a.nonce&&f>=a.nonce&&u.every(s=>s!==void 0)}async function q(t){if(!Number.isSafeInteger(t)||!x.has(t))throw new d("Unsupported transaction chain.");let e=(l.clientFor??Ha)(t),a;try{a=await e.getChainId()}catch{throw new d(`Wallet action failed: RPC getChainId on chain ${t}. Check RPC availability; any pending journal remains unresolved.`)}if(a!==t)throw new d("RPC chain does not match the requested chain; nothing was signed.");return new Proxy(e,{get(n,o){let c=o==="traceCall"&&!n.traceCall&&"request"in n?m=>n.request(ca(m)):Reflect.get(n,o);return typeof c!="function"?c:async(...m)=>{try{return await c.apply(n,m)}catch(f){if((o==="simulateBlocks"||o==="traceCall")&&Ie(f,-32601,-32004,-32602)||f instanceof fa||f instanceof wa||f instanceof d)throw f;let u=f?.code,s=typeof u=="number"?` (RPC code ${u})`:"";throw new d(`Wallet action failed: RPC ${String(o)} on chain ${t}${s}. Check RPC availability; any pending journal remains unresolved.`)}}}})}async function R(t,e){let a=await t.getBlock(e);if(a.number===null)throw new d("RPC returned a block without a height; retry when the node is synchronized.");return{...a,number:a.number}}async function O(t){let[e,a]=await Promise.all([R(t,{blockTag:"latest"}),t.estimateMaxPriorityFeePerGas()]),n=e.baseFeePerGas;if(typeof n!="bigint"||n<0n||a<0n||n*2n+a<=0n)throw new d("Network fee data is unavailable; nothing was signed.");return{baseFee:n,maxFeePerGas:n*2n+a,maxPriorityFeePerGas:a,blockNumber:e.number,gasLimit:e.gasLimit}}async function qe(t,e,a,n,o,c,m){let f=o,u=a.map(r=>{let i=BigInt(r.value),w;try{w=ha(le(c.gasLimit),f,i,c.maxFeePerGas,e,n)}catch(b){throw new d(b.message)}return f-=i,{account:e,to:r.to,data:r.data,value:i,gas:w,gasPrice:c.baseFee+c.maxPriorityFeePerGas}}),s;try{s=(await t.simulateBlocks({blocks:[{calls:u}],validation:!1,traceTransfers:!0,blockNumber:c.blockNumber}))[0]?.calls??[]}catch(r){if(!Ie(r,-32601,-32004))throw r;return Promise.all(u.map((i,w)=>t.estimateGas(i).catch(()=>{throw Se(w,u.length,n)})))}if(await m?.(s,u),s.length!==u.length)throw new d(`Simulation on chain ${n} returned an unexpected result; nothing was signed.`);return s.map((r,i)=>{if(r.status!=="success"&&r.gasUsed>=u[i].gas)throw B(e,n,a.reduce((b,h)=>b+BigInt(h.value),0n)+me(r.gasUsed+1n)*c.maxFeePerGas,o);if(r.status!=="success")throw new d(`Transaction ${i+1} of ${u.length} would revert on chain ${n}; nothing was signed.`);let w=H(r.gasUsed,r.maxUsedGas??0n);if(w<=0n)throw new d("Gas estimate is unavailable.");return w})}async function he(t,e,a){let n=A(),o=t.map(s=>{let r=Ae(s);try{ve(r)}catch(b){throw new d(b.message)}let i=s.notAfter;if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<0))throw new d("Invalid transaction not-after timestamp.");let w=i??n+N;if(n>w)throw W();return{tx:r,notAfter:w}}),c=new Map;for(let{tx:s}of o){let r=c.get(s.chainId)??{client:await q(s.chainId),txs:[]};r.txs.push(s),c.set(s.chainId,r)}let m=new Map,f=new Map,u=new Map;for(let[s,r]of c){let[i,w]=await Promise.all([r.client.getBalance({address:e.address,blockTag:"pending"}),O(r.client)]),b=r.txs.reduce((y,C)=>y+BigInt(C.value),0n),h=b+BigInt(r.txs.length)*21000n*w.maxFeePerGas;if(i<h)throw B(e.address,s,h,i);let P;if(a)try{let y={...a,chainId:s};P=await oa(y,e.address,r.client),sa(r.txs,y,e.address,P),f.set(s,P),u.set(s,y.quote?[y.quote.router,y.quote.spender??y.quote.router]:y.destinations??Qe(y,s))}catch(y){throw new d(y.message)}let g=!1,T=await qe(r.client,e.address,r.txs,s,i,w,async(y,C)=>{if(P){g=!0;try{Te(K(y,e.address),e.address,P,void 0,r.txs),await ae(r.client,y,e.address,r.txs,w.blockNumber,C,u.get(s)??[])}catch(re){throw new d(re.message)}}});if(P&&!g)throw new d("Local transfer simulation is unavailable; nothing was signed.");if(r.txs.forEach((y,C)=>{m.set(y,T[C]),b+=me(T[C])*w.maxFeePerGas}),i<b)throw B(e.address,s,b,i)}return o.map(({tx:s,notAfter:r})=>({tx:s,notAfter:r,client:c.get(s.chainId).client,value:BigInt(s.value),simulated:m.get(s),inputs:f.get(s.chainId),pins:u.get(s.chainId)??[s.to]}))}async function $e(t,e,a=!1){let{blockNumber:n}=e;try{return e.blockHash&&(await R(t,{blockNumber:n})).hash!==e.blockHash?!1:typeof k=="number"?(await R(t,{blockTag:"latest"})).number-n+1n>=BigInt(k):(await R(t,{blockTag:k})).number>=n}catch(o){if(a)throw o;return!1}}async function ee(t,e,a,n=t.hash){let o=await e.waitForTransactionReceipt({hash:n,confirmations:1,timeout:l.receiptTimeoutMs??12e4});if(!Y(t).some(m=>m.toLowerCase()===o.transactionHash.toLowerCase()))throw I();let c=await $e(e,o);if(c&&await a.clear(t.hash),o.status!=="success")throw Q();return c}async function Ee(t,e){for(let a of e)try{let n=await t.getTransactionReceipt({hash:a});if(n.transactionHash.toLowerCase()!==a.toLowerCase())throw I();return n}catch(n){if(!(n instanceof wa))throw n}}async function Be(t,e){for(let a of e)try{if((await t.getTransaction({hash:a})).hash.toLowerCase()===a.toLowerCase())return a}catch(n){if(!(n instanceof fa))throw n}}async function ae(t,e,a,n,o,c,m){return ra(e,a,n,(f,u,s)=>t.readContract({address:f,abi:j,functionName:"allowance",args:[a,u],blockNumber:s}),o,A(),async(f,u)=>{let s=await t.simulateBlocks({blocks:[{calls:[...c.slice(0,f+1),...u.map(r=>na(r,a))]}],validation:!1,traceTransfers:!0,blockNumber:o});if(s.length!==1)throw new d("Local post-state allowance simulation is unavailable; nothing was signed.");return s[0].calls},m)}async function pe(t,e,a){let n=e.chainId??await t.getChainId(),o=Re.get(n);o||(o=da(t.traceCall?.bind(t)),Re.set(n,o));try{let c=ve({...e,chainId:n,value:e.value.toString(),description:"Local execution check"});await o(e,a,c?e.to:void 0)}catch(c){throw new d(`Local transaction guard: execution trace failed (${c.message}); nothing was signed.`)}}function He(t,e,a,n,o,c,m){let f=m?.quote,u=f?.to?a.filter(r=>r.id===void 0&&r.token.toLowerCase()===f.to.toLowerCase()&&r.to.toLowerCase()===n.toLowerCase()&&r.from.toLowerCase()!==n.toLowerCase()):[],s=a;if(u.length===1){let r=u[0],i=BigInt(f.minAmountOut);if(r.amount<i)throw new d("Swap receipt is below the confirmed minimum output; nothing was signed.");s=a.map(w=>w===r?{...w,amount:i}:w)}return M(t,{...e,gas:0n,nonce:0,maxFeePerGas:0n,maxPriorityFeePerGas:0n},s,n,o,c)}async function Oe(t,e,a,n,o,c,m,f,u=!1){let{chainId:s,...r}=a,[,i,w,b]=await Promise.all([q(s),O(t),t.getBalance({address:e.address,blockTag:"pending"}),t.getTransactionCount({address:e.address,blockTag:"pending"})]);if(!u&&b!==a.nonce||i.baseFee+i.maxPriorityFeePerGas>a.maxFeePerGas||i.maxPriorityFeePerGas>a.maxPriorityFeePerGas)return!1;if(w<a.value+a.gas*a.maxFeePerGas)throw B(e.address,s,a.value+a.gas*a.maxFeePerGas,w);let[h]=await Promise.all([t.simulateBlocks({blocks:[{calls:[{...r,account:e.address}]}],validation:!1,traceTransfers:!0,blockNumber:i.blockNumber}),pe(t,{...a,account:e.address,blockNumber:i.blockNumber},m)]);if(h.length!==1||h[0]?.calls.length!==1||h[0].calls[0]?.status!=="success")throw Q();try{let P={...a,value:a.value.toString(),description:o},g=await ae(t,h[0].calls,e.address,[P],i.blockNumber,[{...r,account:e.address}],m),T=K(h[0].calls,e.address);return f?He(o,a,T,e.address,c,g,f)===n:M(o,a,T,e.address,c,g)===n}catch(P){throw new d(P.message)}}async function Je(t,e,a,n){let{chainId:o,...c}=a,m=await R(t,{blockTag:"latest"}),f=await t.simulateBlocks({blocks:[{calls:[{...c,account:e.address}]}],validation:!1,traceTransfers:!0,blockNumber:m.number});if(f.length!==1||f[0]?.calls.length!==1||f[0].calls[0]?.status!=="success")throw Q();let u;try{u=K(f[0].calls,e.address)}catch(b){throw new d(b.message)}let s={to:a.to,data:a.data,chainId:o,value:a.value.toString(),description:n},r=await ae(t,f[0].calls,e.address,[s],m.number,[{...c,account:e.address}],[s.to]);await pe(t,{...c,account:e.address,blockNumber:m.number},[s.to]);let i=M(n,a,u,e.address,[s],r),w=await ke(we,a,i);if(!await Oe(t,e,w,i,n,[s],[s.to],void 0,!0))throw new d("Recovery simulation changed; confirm a fresh preview.");return w}async function ga(t,e,a,n){let o=X(t.rawTx),c=o.maxFeePerGas??o.gasPrice??0n,m=await O(e),f=t;if(c<m.baseFee){if(!o.to||o.gas===void 0)throw I();let s=o.value??0n,r=H(m.maxPriorityFeePerGas,fe(o.maxPriorityFeePerGas??0n)),i=H(m.baseFee*2n+r,fe(c)),w=await e.getBalance({address:a.address,blockTag:"pending"}),b=s+o.gas*i;if(w<b)throw B(a.address,t.chainId,b,w);let h=await Je(e,a,{chainId:t.chainId,nonce:t.nonce,to:o.to,data:o.data??"0x",value:s,gas:o.gas,maxFeePerGas:i,maxPriorityFeePerGas:r},"Recover pending action with a fee replacement"),P;try{P=await a.signTransaction(h),de(P,h)}catch{throw E()}f=await n.replace(t.hash,P,m.blockNumber.toString(),A())}if((await e.sendRawTransaction({serializedTransaction:f.rawTx})).toLowerCase()!==f.hash.toLowerCase())throw I();return f}async function ba(t,e,a,n){let o=X(t.rawTx),c=o.maxFeePerGas??o.gasPrice??0n,m=await O(e),f=await e.estimateGas({account:a.address,to:a.address,data:"0x",value:0n,gas:le()}),u=H(21000n,f),s=H(m.maxPriorityFeePerGas,fe(o.maxPriorityFeePerGas??o.gasPrice??0n)),r=H(m.baseFee*2n+s,fe(c)),i=await e.getBalance({address:a.address,blockTag:"pending"});if(i<u*r){let C=await Be(e,Y(t));if(!C)throw B(a.address,t.chainId,u*r,i);if(!await ee(t,e,n,C))throw I();return}let w=r,b=s,h=await Je(e,a,{chainId:t.chainId,nonce:t.nonce,to:a.address,data:"0x",value:0n,gas:u,maxFeePerGas:w,maxPriorityFeePerGas:b},"Cancel expired pending action using a zero-value self-transfer"),P;try{P=await a.signTransaction(h),de(P,h);let C=X(P);if(!C.to||C.to.toLowerCase()!==a.address.toLowerCase()||(C.data??"0x")!=="0x"||(C.value??0n)!==0n||C.chainId!==t.chainId||C.nonce!==t.nonce||C.gas!==u)throw E()}catch{throw E()}let g=A(),T=await n.burn(t.hash,P,m.blockNumber.toString(),g,g+N);if((await e.sendRawTransaction({serializedTransaction:T.rawTx})).toLowerCase()!==T.hash.toLowerCase())throw I();return T}async function ya(t,e){for(let a of await e.read()){let n=te(a);n&&n.amount>0n&&await e.retainApproval(a);let o=await q(a.chainId),c=Y(a),[m,f]=await Promise.all([o.getTransactionCount({address:t.address,blockTag:"latest"}),o.getTransactionCount({address:t.address,blockTag:"pending"})]),u=await Ee(o,c);if(u){if(!await $e(o,u,!0))throw I();if(await e.clear(a.hash),u.status!=="success")throw Q();continue}let s=a.notAfter??a.sentAt+N,r=await R(o,{blockTag:"latest"});if(r.timestamp<0n||r.timestamp>BigInt(Number.MAX_SAFE_INTEGER))throw new d("Invalid block timestamp; check RPC availability.");let i=A()>s||r.timestamp>BigInt(s);if(!i||a.kind==="burn"){let P=await Be(o,c);if(P){if(!await ee(a,o,e,P))throw I();continue}}let w=typeof k=="number"?r:await R(o,{blockTag:k}),b=BigInt(a.blockNumber)+BigInt(typeof k=="number"?k:1);if(!i&&w.number<b)throw I();if(m>a.nonce){if(w.number<b)throw I();let P=typeof k=="number"?r.number-BigInt(k)+1n:w.number;if(P<0n||await o.getTransactionCount({address:t.address,blockNumber:P})<=a.nonce)throw I();await e.clear(a.hash,"nonce_consumed");continue}if(m!==a.nonce||f<a.nonce||!i&&f!==a.nonce)throw I();let h=i&&a.kind!=="burn"?await ba(a,o,t,e):await ga(a,o,t,e);if(h&&!await ee(h,o,e))throw I()}}function te(t){let e=X(t.rawTx);if(!(!e.to||(e.value??0n)!==0n))try{let a=Sa({abi:j,data:e.data??"0x"});return a.functionName!=="approve"?void 0:{token:ma(e.to),spender:ma(a.args[0]),amount:a.args[1]}}catch{return}}async function ge(t){let e=[];for(let a of await t.approvals()){let n=te(a);if(!n)throw I();e.push(`Submitted approval: token ${n.token}, spender ${n.spender}, amount ${n.amount} base units, chain ${a.chainId}. It may remain active. Retry an Oak action to reconcile and revoke it before new work, or clear it in your wallet by calling approve(${n.spender}, 0) on ${n.token} on chain ${a.chainId}.`)}return e.join(" ")}async function De(t,e,a,n,o){n=n?JSON.parse(JSON.stringify(n)):void 0,t=t.map(r=>({...Ae(r),notAfter:r.notAfter}));let m=Le(t,n).map(r=>Z.get(r)).find(r=>r!==void 0)??{steps:new Map,reprompts:0},f=()=>{for(let r of Le(t,n))Z.set(r,m)};f();let u=[],s;try{if(m.reprompts>1)throw Ge();let r=await he(t,e,n),i=new Map,w=0;for(let h=0;h<r.length;h++){let P=0;for(;;){if(++P>5)throw new d("Action keeps changing; request a fresh preview. Nothing further was signed.");let{tx:g,notAfter:T,client:y,value:C,simulated:re,inputs:Me,pins:be}=r[h],We=async()=>{let p=A()>T;if(p&&!o&&t.some(F=>F.notAfter!==void 0))throw W();let S=p&&o?await o():{txs:t.map(F=>({...F,notAfter:p?A()+N:F.notAfter})),action:n};if(p&&!o&&n?.quote&&A()>=Number(n.quote.expiresAt))throw W();if(S.txs.length!==r.length||r.slice(0,h).some((F,Ce)=>{let Ia=Ae(S.txs[Ce]);return JSON.stringify(Ia)!==JSON.stringify(F.tx)}))throw new d("Prepared sequence changed after submission; request a fresh action.");n=S.action?JSON.parse(JSON.stringify(S.action)):void 0,t=S.txs.map(F=>({...F})),f(),r=await he(t,e,n)};if(A()>T)throw W();await q(g.chainId);let[v,U,ye]=await Promise.all([O(y),y.getTransactionCount({address:e.address,blockTag:"pending"}),y.getBalance({address:e.address,blockTag:"pending"})]),Ue;try{Ue=ha(le(v.gasLimit,re),ye,C,v.baseFee+v.maxPriorityFeePerGas,e.address,g.chainId)}catch(p){throw new d(p.message)}let Ca=await y.estimateGas({account:e.address,to:g.to,data:g.data,value:C,gas:Ue}).catch(()=>{throw Se(h,r.length,g.chainId)});if(A()>T)throw W();let G=me(H(Ca,re)),xa=r.slice(h+1).filter(p=>p.tx.chainId===g.chainId).reduce((p,S)=>p+S.value+me(S.simulated)*v.maxFeePerGas,0n),_e=C+G*v.maxFeePerGas+xa;if(ye<_e)throw B(e.address,g.chainId,_e,ye);if(G>le(v.gasLimit))throw Se(h,r.length,g.chainId);let _=[],se=[],ze=!1,Pe=i.get(g.chainId)??new Map;try{let p=await y.simulateBlocks({blocks:[{calls:[{account:e.address,to:g.to,data:g.data,value:C,gas:G,nonce:U,maxFeePerGas:v.maxFeePerGas,maxPriorityFeePerGas:v.maxPriorityFeePerGas}]}],validation:!1,traceTransfers:!0,blockNumber:v.blockNumber});if(p.length!==1||p[0]?.calls.length!==1||p[0].calls[0]?.status!=="success")throw Q();try{_=K(p[0].calls,e.address),se=await ae(y,p[0].calls,e.address,[g],v.blockNumber,[{account:e.address,to:g.to,data:g.data,value:C,gas:G,nonce:U,maxFeePerGas:v.maxFeePerGas,maxPriorityFeePerGas:v.maxPriorityFeePerGas}],be),ze=!0,Me&&(Pe=Te(_,e.address,Me,Pe,[g]))}catch(S){throw new d(S.message)}}catch(p){if(!Ie(p,-32601,-32004))throw p}if(A()>T)throw W();if(!ze)throw new d("Local transfer simulation is unavailable; nothing was signed.");let $={chainId:g.chainId,to:g.to,data:g.data,value:C,gas:G,nonce:U,maxFeePerGas:v.maxFeePerGas,maxPriorityFeePerGas:v.maxPriorityFeePerGas};await pe(y,{...$,account:e.address,blockNumber:v.blockNumber},be);let oe=n?.name??g.description,z=r.map(p=>p.tx),ka=M(oe,$,_,e.address,z,se)+(n?.quote?`
2
+ Minimum receipt: ${n.quote.minAmountOut} base units of ${n.quote.to}. The simulated receipt may vary above this minimum.`:""),Ke=He(oe,$,_,e.address,z,se,n),Ye=JSON.stringify({txs:z.map(({to:p,data:S,value:F,chainId:Ce})=>({to:p,data:S,value:F,chainId:Ce})),summary:Ke,minimumReceipt:n?.quote?{token:n.quote.to,amount:n.quote.minAmountOut}:void 0}),L=m.steps.get(h),va=L!==void 0&&Ye===L.terms&&G<=L.transaction.gas&&G*v.maxFeePerGas<=L.transaction.gas*L.transaction.maxFeePerGas&&v.maxPriorityFeePerGas<=L.transaction.maxPriorityFeePerGas&&await pa(y,e,$,L),J;if(va)J=Object.freeze({...$});else{if(L&&++m.reprompts>1)throw Ge();let p=await a.read();J=await ke(we,$,ka),m.steps.set(h,{terms:Ye,transaction:J,journaled:p})}if(A()>T){await We();continue}if(!await Oe(y,e,J,n?Ke:M(oe,$,_,e.address,z,se),oe,z,be,n))continue;if(A()>T){await We();continue}let D;try{D=await e.signTransaction(J),de(D,J);let p=X(D);if(!p.to||p.to.toLowerCase()!==g.to.toLowerCase()||(p.data??"0x").toLowerCase()!==g.data.toLowerCase()||(p.value??0n)!==C||p.chainId!==g.chainId||p.nonce!==U||p.gas!==G||p.maxFeePerGas!==v.maxFeePerGas||(p.maxPriorityFeePerGas??0n)!==v.maxPriorityFeePerGas)throw E()}catch{throw E()}let ie=Ra(D),je=A(),Ta=je<=T?je:T,ce={nonce:U,hash:ie,rawTx:D,kind:g.data.startsWith("0x095ea7b3")?"approval":"main",sentAt:Ta,notAfter:T,chainId:g.chainId,blockNumber:v.blockNumber.toString()},Xe=te(ce);if(Xe&&Xe.amount>0n&&await a.retainApproval(ce),await a.append(ce),s=ie,(await y.sendRawTransaction({serializedTransaction:D})).toLowerCase()!==ie.toLowerCase())throw I();u.push(ie),s=void 0,await ee(ce,y,a)&&w++,i.set(g.chainId,Pe);break}}let b=u.length?w===u.length?"final":"mined":"not_submitted";for(let[h,P]of Z)P===m&&Z.delete(h);return{summary:xe(u,b,u.length?Oa(u.length,w):""),hashes:u,status:b}}catch(r){let i=ue(r).message,w=s?`Submission unknown: ${s}. Broadcast acknowledgement unavailable; reconcile the wallet journal.`:"";throw new d(u.length?xe(u,"submitted",`Action stopped. ${w} ${i}`.trim()):s?`${w} ${i}`:`Not submitted. ${i}`)}}async function Pa(t,e){for(let a of await e.approvals()){let n=te(a);if(!n)throw I();let o=await q(a.chainId),c=await o.readContract({address:n.token,abi:j,functionName:"allowance",args:[t.address,n.spender]});if(typeof c!="bigint"||c<0n)throw I();if(c>0n){let m={to:n.token,data:Fa({abi:j,functionName:"approve",args:[n.spender,0n]}),value:"0",chainId:a.chainId,description:`Revoke remaining ${c} base-unit approval to ${n.spender}`};if(!V)throw new d("Approval cleanup requires a preview display. Clear the recorded approval in your wallet before retrying.");let f=await O(o),u=await o.getBalance({address:t.address,blockTag:"pending"}),s;if(await qe(o,t.address,[m],a.chainId,u,f,async i=>{s=i}),await V(`Remaining approval: token ${n.token}, spender ${n.spender}, amount ${c} base units, chain ${a.chainId}. Revoke to zero. Simulation: ${JSON.stringify(s,(i,w)=>typeof w=="bigint"?w.toString():w)}`),await De([m],t,e),(await e.read()).length||await o.readContract({address:n.token,abi:j,functionName:"allowance",args:[t.address,n.spender]})!==0n)throw I()}await e.forgetApproval(a.hash)}}async function ne(t){try{let e=l.signer??await $a();return await la(e.address,async()=>{let a=new ua(e.address,l.directory);try{await ya(e,a),await Pa(e,a)}catch(s){let r=await ge(a);throw new d(`${ue(s).message}${r?` ${r}`:""}`)}let n=!0,o=!1,c,m;function f(s){if(!n||o||c)return Promise.reject(new d("Wallet action must be awaited inside its lock."));o=!0;let r=s().catch(async i=>{c=ue(i);let w=await ge(a);throw w&&(c=new d(`${c.message} ${w}`)),c}).finally(()=>{o=!1});return m=r.then(()=>{},()=>{}),r}let u={approvalStatus:()=>ge(a),assertCanPayGas:s=>f(async()=>{await he(s,e)}),send:(s,r,i)=>f(()=>De(s,e,a,r,i)),signTypedData:(s,r)=>f(async()=>{if(!V)throw new d("No preview display is configured; nothing was signed.");let i=ea(s);await q(i.domain.chainId??0),await V(ta(i,r));let w=await aa(we,i,r);for(let b of["deadline","expiresAt","validBefore"]){let h=w.message[b];if(typeof h=="string"&&/^\d+$/.test(h)&&BigInt(A())>=BigInt(h))throw new d("Typed action expired before signing; request fresh terms.")}try{let b=await e.signTypedData(w);if((await Ga({...i,signature:b})).toLowerCase()!==e.address.toLowerCase())throw E();return b}catch{throw E()}})};try{let s=await t(u);if(n=!1,await m,c)throw c;return s}finally{n=!1,await m}},{directory:l.directory})}catch(e){throw ue(e)}}return{withAction:ne,send:(t,e,a)=>ne(n=>n.send(t,e,a)),signTypedData:(t,e)=>ne(a=>a.signTypedData(t,e)),assertCanPayGas:t=>ne(e=>e.assertCanPayGas(t)),blockNumber:async(t=Fe)=>(await R(await q(t),{blockTag:"latest"})).number}}var tt=(l,x)=>Ne(x).send(l),nt=(l,x)=>Ne(x).signTypedData(l),rt=(l,x)=>Ne(x).assertCanPayGas(l);export{Ea as a,d as b,Ne as c,tt as d,nt as e,rt as f};
@@ -0,0 +1 @@
1
+ import{b as v}from"./U5VW3XSD.js";import{a as S}from"./IVR4JOHU.js";import{randomBytes as O}from"node:crypto";import{encodeFunctionData as w,erc20Abi as L,getAddress as T,parseAbi as N,parseSignature as I,zeroAddress as g,zeroHash as $}from"viem";import{ADDRESSES as G,ETH_USDG_POOL as H,NETWORKS as z,assertNetworkUsdg as B}from"@oakagentkit/core/addresses";import{approval as R,unsignedTx as _}from"@oakagentkit/core/tx";import{verifyNoteOffchain as W}from"@oakagentkit/core/pricenote";import{grandfatherProofFor as q,verifyGrandfatherProof as K}from"@oakagentkit/core/grandfather";var u=N(["struct PriceNote { address wallet; uint256 oakPerEthE18; uint64 timestamp; bytes32 nonce; }","function subscribe(uint8 plan,uint256 maxCount,uint256 maxPrice,PriceNote n,bytes sig)","function subscribeWithAuthorization(uint256 maxCount,PriceNote n,bytes sig,bytes usdgAuth)","function subscribeGrandfatheredWithAuthorization(uint256 count,bytes32[] proof,bytes usdgAuth)","function renewWithAuthorization(bytes usdgAuth)","function renewNoHold(uint256 maxPrice,PriceNote n,bytes sig)","function cancel()","function hasRecord(address) view returns (bool)","function previous() view returns (address)","function retired() view returns (bool)","function plan(address) view returns (uint8)","function paidUntil(address) view returns (uint64)","function signupOakCount(address) view returns (uint256)","function grandfatherRoot() view returns (bytes32)","function grandfatherDeadline() view returns (uint64)","function quoteHolder(PriceNote n,bytes sig) view returns (uint256 count,uint256 burn)","function quoteNoHold(PriceNote n,bytes sig) view returns (uint256 price)","error NoteOutsideGuard(uint256 spot,uint256 note)","error OracleUnreadable(address source)","error NoteExpired()","error NoteUsed()","error NoteBadSignature()"]),k=N(["function phase() view returns (uint8)","function priceSigner() view returns (address)","function spotOakPerEthE18() view returns (uint256)"]),x=N(["function authorizationState(address,bytes32) view returns (bool)","function receiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce,uint8 v,bytes32 r,bytes32 s)"]),j={ReceiveWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},F=new Set(Object.values(G[4663]).flatMap(r=>Object.values(r).map(e=>e.address.toLowerCase()))),M={wallet:g,oakPerEthE18:0n,timestamp:0n,nonce:$},b=9000000n,se=3n*86400n,C=r=>(r*101n+99n)/100n,y=(r,e)=>r.toLowerCase()===e.toLowerCase(),i=class extends Error{constructor(t,n=!1){super(t);this.retryNote=n}retryNote};function U(r){if(r.network!=="mainnet"&&r.network!=="testnet")throw new i("Set the subscription deployment network to mainnet or testnet.");let e=z[r.network];if(r.chainId!==e.chainId)throw new i("Network does not match the subscription deployment chain.");return B(r.network,r.usdg),{...e.usdgDomain}}function J(r){U(r);for(let e of["subscription","usdg","oak","oracle","ethUsdgPool"]){let t=T(r[e]);if(t===g)throw new i(`Configure a non-zero ${e} in the deployment config.`);if(r.network==="testnet"&&F.has(t.toLowerCase()))throw new i(`${e} cannot use a mainnet pin in the testnet deployment config.`)}if(r.network==="mainnet"&&!y(r.ethUsdgPool,H))throw new i("ETH/USDG pool must match the pinned mainnet pool.")}function Q(r){let e=r;for(let t=0;e&&typeof e=="object"&&t<12;t++){let n=e;if(n.data?.errorName)return n.data.errorName;e=n.cause}}var h=(r,e=!1,t=!1,n=[])=>({ok:e,access:t,summary:r,hashes:n}),E=class{constructor(e){this.options=e;J(e.deployment),T(e.wallet)}options;get deployment(){return this.options.deployment}get wallet(){return this.options.wallet}async now(){return(await this.options.client.getBlock({blockTag:"latest"})).timestamp}async authoritative(){let e=new Set,t=this.deployment.subscription;for(let n=0;t!==g&&n<256;n++){if(e.has(t.toLowerCase()))throw new i("Invalid subscription lineage.");e.add(t.toLowerCase());let a=o=>this.options.client.readContract({address:t,abi:u,functionName:o,args:[this.wallet]});if(await a("hasRecord")){let[o,s,c,d]=await Promise.all([a("plan"),a("paidUntil"),a("signupOakCount"),this.options.client.readContract({address:t,abi:u,functionName:"retired"})]);return{contract:t,plan:Number(o),paidUntil:BigInt(s),count:BigInt(c),retired:d}}t=await this.options.client.readContract({address:t,abi:u,functionName:"previous"})}if(t!==g)throw new i("Subscription lineage is too deep.");return null}async proof(e){let t=await this.options.grandfatherList?.();if(!t)return null;let n=q(t,this.wallet);if(!n||!y(n.source,e.contract)||BigInt(n.count)!==e.count)return null;let a=await this.options.client.readContract({address:this.deployment.subscription,abi:u,functionName:"grandfatherRoot"});if(!K(a,n.entry,n.proof))throw new i("Grandfather proof does not match the successor root.");return n}async balance(e){return this.options.client.readContract({address:e,abi:L,functionName:"balanceOf",args:[this.wallet]})}async access(e){return!e||e.plan===0||e.paidUntil<await this.now()?!1:e.plan===2||e.plan===1&&await this.balance(this.deployment.oak)>=e.count}plain(e){if(e instanceof i)return e;if(e instanceof v)return new i(e.message);let t=Q(e);return t==="OracleUnreadable"?new i(`Price unavailable: check the ETH/USDG pool ${this.deployment.ethUsdgPool}; try again when the oracle recovers.`):t?.startsWith("Note")?new i(`Price note rejected (${t}); retry with a fresh note.`,!0):new i("Subscription action failed; check funds and RPC availability, then retry with oak renew or oak subscribe.")}async action(e,t=!1){let n=[],a=o=>{let s=[...new Set([...n,...o.hashes])];return s.length?{...o,hashes:s,summary:S(s,"submitted",o.summary)}:o};for(let o=0;o<(t?2:1);o++){let s;try{let c=await this.options.sender.withAction(async d=>{try{if(await this.options.client.getChainId()!==this.deployment.chainId)throw new i("RPC chain does not match the subscription deployment; nothing was signed.");return await e({...d,send:async(...l)=>{let p=await d.send(...l);return n.push(...p.hashes),p}})}catch(l){s=this.plain(l);let p=await d.approvalStatus?.();return h(`${s.message}${p?` ${p}`:""}`)}});if(s?.retryNote&&o===0&&t)continue;return a(c)}catch(c){return c instanceof v?a(h(c.message)):a(h("Payment failed or remains pending; tools are paused. Run oak renew to reconcile the wallet journal before another payment."))}}return h("Price note unavailable; retry with a fresh note.")}tx(e,t,n){return _({to:e,data:t,value:"0",chainId:this.deployment.chainId,description:n})}async funds(e,t=0n){if(await this.options.client.getBalance({address:this.wallet,blockTag:"pending"})===0n)throw new i(`Needs ETH for network fees: send ETH to ${this.wallet} on chain ${this.deployment.chainId}.`);if(await this.balance(this.deployment.usdg)<e)throw new i(`Renewal/payment needs ${e} USDG base units (token ${this.deployment.usdg}, decimals 6). Top up and run oak renew; tools are paused until payment succeeds.`);if(t>0n&&await this.balance(this.deployment.oak)<t)throw new i(`Needs ${t} OAK base units (token ${this.deployment.oak}, decimals 18). Buy back OAK and retry.`)}async authorization(e,t){let n=`0x${O(32).toString("hex")}`;if(await this.options.client.readContract({address:this.deployment.usdg,abi:x,functionName:"authorizationState",args:[this.wallet,n]}))throw new i("USDG authorization nonce is used or cancelled; retry with a new nonce.");let a=await this.now()+300n,o={domain:U(this.deployment),types:j,primaryType:"ReceiveWithAuthorization",message:{from:this.wallet,to:t,value:b.toString(),validAfter:"0",validBefore:a.toString(),nonce:n}},s=I(await e.signTypedData(o));return w({abi:x,functionName:"receiveWithAuthorization",args:[this.wallet,t,b,0n,a,n,Number(s.v??BigInt(s.yParity??0)+27n),s.r,s.s]})}async note(e){for(let t=0;t<2;t++){let n=await this.options.issueNote({for:"subscription",wallet:this.wallet});if("reason"in n)throw n.reason==="eth_usd_unreadable"&&/price source is stale|freshness is unavailable/.test(n.error)?new i(`Price unavailable: ETH/USDG pool ${this.deployment.ethUsdgPool} needs a readable observation within 30 minutes. Retry after the pool updates.`):n.reason==="history_too_thin"&&/OAK price source is stale/.test(n.error)?new i("Price unavailable: refresh the stale OAK 30-minute trade history before retrying."):n.reason==="eth_usd_unreadable"?new i(`Price unavailable: ETH/USDG pool ${this.deployment.ethUsdgPool} is unreadable.`):n.reason==="history_too_thin"?new i("Price warmup: wait until the pool has 30 minutes of history, then retry."):new i(`Price unavailable (${n.reason}); retry in a minute.`);if(!y(n.consumer,e)||!y(n.note.wallet,this.wallet))throw new i("Price note consumer or wallet does not match this subscription.");let a=await this.now();if(BigInt(n.note.timestamp)+300n-a<60n)continue;let[o,s]=await Promise.all([this.options.client.readContract({address:this.deployment.oracle,abi:k,functionName:"priceSigner"}),this.options.client.readContract({address:this.deployment.oracle,abi:k,functionName:"spotOakPerEthE18"})]),c=await W({note:n.note,signature:n.signature,consumer:e,wallet:this.wallet,signer:o,spotOakPerEthE18:s,now:a,expiresAt:n.expiresAt,chainId:this.deployment.chainId});if(!c.ok)throw new i(`Price note rejected (${c.reason}); retry with a fresh note.`,c.reason==="outside_guard"||c.reason==="expired");return n}throw new i("Price note has less than 60 seconds remaining; retry with a fresh note.")}async fresh(e){if(e&&BigInt(e.note.timestamp)+300n-await this.now()<60n)throw new i("Price note is too close to expiry; retry with a fresh note.",!0)}async pricedPayment(e,t,n,a=!1){let o=await this.options.client.readContract({address:this.deployment.oracle,abi:k,functionName:"phase"});if(o!==0&&o!==1)throw new i("Unknown subscription phase; nothing was signed.");if(o===0&&n==="holder")throw new i("Holder plan is closed during the curve; use oak subscribe --plan nohold.");let s=o===1?await this.note(t):null,c=s?{...s.note,timestamp:BigInt(s.note.timestamp),oakPerEthE18:BigInt(s.note.oakPerEthE18)}:M,d=s?.signature??"0x",l=[];if(n==="holder"){let[m,f]=await this.options.client.readContract({address:t,abi:u,functionName:"quoteHolder",args:[c,d],account:this.wallet}),P=C(m);await this.funds(b,m),await this.fresh(s);let D=await this.authorization(e,t);l.push(R(this.deployment.oak,t,f.toString(),this.deployment.chainId)),l.push(this.tx(t,w({abi:u,functionName:"subscribeWithAuthorization",args:[P,c,d,D]}),`Subscribe holder: 9000000 USDG base units (decimals 6); exact OAK burn ${f} (decimals 18).`))}else{let m=o===0?12333333n:await this.options.client.readContract({address:t,abi:u,functionName:"quoteNoHold",args:[c,d],account:this.wallet}),f=o===0?m:C(m);await this.funds(m),l.push(R(this.deployment.usdg,t,f.toString(),this.deployment.chainId));let P=a?w({abi:u,functionName:"renewNoHold",args:[f,c,d]}):w({abi:u,functionName:"subscribe",args:[2,0n,f,c,d]});l.push(this.tx(t,P,`${a?"Renew":"Subscribe"} nohold: at most ${f} USDG base units (token ${this.deployment.usdg}, decimals 6).`))}await this.fresh(s),await e.assertCanPayGas(l);let p=await e.send(l.slice(0,-1));await this.fresh(s),s&&(n==="holder"?await this.options.client.readContract({address:t,abi:u,functionName:"quoteHolder",args:[c,d],account:this.wallet}):await this.options.client.readContract({address:t,abi:u,functionName:"quoteNoHold",args:[c,d],account:this.wallet}));let A=await e.send(l.slice(-1));return h(A.summary,!0,await this.access(await this.authoritative()),[...p.hashes,...A.hashes])}async holderPayment(e,t,n){let a=n?this.deployment.subscription:t.contract;if(n&&await this.options.client.readContract({address:a,abi:u,functionName:"grandfatherDeadline"})<await this.now())return h("Grandfather deadline has passed; once the old paid days expire, use oak subscribe for a fresh subscription.",!1,await this.access(t));await this.funds(b,n?t.count:0n);let o=await this.authorization(e,a),s=n?w({abi:u,functionName:"subscribeGrandfatheredWithAuthorization",args:[BigInt(n.count),n.proof,o]}):w({abi:u,functionName:"renewWithAuthorization",args:[o]}),c=await e.send([this.tx(a,s,`Renew holder: 9000000 USDG base units (token ${this.deployment.usdg}, decimals 6); no OAK burn.`)]);return h(c.summary,!0,await this.access(await this.authoritative()),c.hashes)}subscribe(e){return this.action(async t=>{if(e!=="holder"&&e!=="nohold")throw new i("Choose oak subscribe --plan holder or --plan nohold.");let n=await this.authoritative();if(n?.plan===1&&!y(n.contract,this.deployment.subscription)&&n.paidUntil>=await this.now()&&await this.proof(n))throw new i("your paid days carry over with `oak renew` when it is due");if(n&&y(n.contract,this.deployment.subscription)&&n.plan!==0)throw new i("Already subscribed; use oak renew, or oak cancel before switching plans.");if(await this.options.client.readContract({address:this.deployment.subscription,abi:u,functionName:"retired"}))throw new i("Subscription deployment is retired; configure its successor before signing up.");return this.pricedPayment(t,this.deployment.subscription,e)},!0)}cancel(){return this.action(async e=>{let t=await this.authoritative();if(!t||t.plan===0)return h("No active subscription to cancel.",!0);let n=await e.send([this.tx(t.contract,w({abi:u,functionName:"cancel"}),"Cancel subscription; all remaining paid days are forfeited immediately.")]);return h("Subscription cancelled; remaining paid days forfeited.",!0,!1,n.hashes)})}async register(e=!1){return this.options.callTool?this.options.callTool("erc8004_register",{noTag:e}):{ok:!1,error:"Configure the authenticated ERC-8004 tool bridge before oak register."}}};export{u as a,b,se as c,U as d,J as e,E as f};
@@ -0,0 +1,2 @@
1
+ import{c as s,d as c}from"./GONTF7K4.js";import{getAddress as p}from"viem";import{NETWORKS as u}from"@oakagentkit/core/addresses";import{constants as i}from"node:fs";import{homedir as d}from"node:os";import{join as l}from"node:path";function h(t,e){return`Wallet ${t} on Robinhood Chain ${e} (chain ${u[e].chainId}); ask for balances anytime.`}async function b(t,e,a=l(d(),".oak")){let r;try{r=await c(l(a,"first-start-shown"),i.O_WRONLY|i.O_CREAT|i.O_EXCL,2,!0)}catch(n){if(n.code==="EEXIST")return h(t,e);throw new Error("Could not save the first-start notice marker. Check local Oak directory permissions and restart MCP.",{cause:n})}try{await r.writeFile(`1
2
+ `),await r.sync()}finally{await r.close()}await s(a);let o=m(t,e);return`Tell the user: ${o.message} ${o.backup} ${o.notice} Never run oak init or oak export through an agent, read wallet files, or ask for keys, recovery words or passphrases. After funding, explain that ERC-8004 registration publishes a profile and costs gas; get user authorization before oak_setup registration. External identity owners sign in their own terminal. Read account for phase and price and get approval for the recurring subscription before oak_subscribe. Both plans wait during warmup. Never subscribe automatically just because funds arrived. Read tools stay available without paid access.`}function m(t,e){let{chainId:a,usdg:r}=u[e];return{wallet:t,address:t,network:e,chainId:a,funding:{gas:{address:"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",symbol:"ETH",decimals:18,chainId:a},payment:{address:p(r),symbol:"USDG",decimals:6,chainId:a}},message:`Fund this address ${t} with a little ETH for gas and USDG on Robinhood Chain ${e} (chain ${a}). Re-check balances after funding.`,backup:"When you hold more than pocket change, run oak export in your own terminal. Run oak backup for guidance. Oak cannot recover a lost key.",notice:"Availability varies by region; check the terms of each service. Oak is independent and is not affiliated with Robinhood."}}var O="Backups are optional. When you hold more than pocket change, run oak export in your own terminal, never through an agent. Keep the exported private key offline and private. Restore it with oak init --recover in your own terminal. Automatic wallets have no recovery phrase. Oak cannot recover a lost key.",x={type:"https://eips.ethereum.org/EIPS/eip-8004#registration-v1",name:"Oak agent",description:"A local Oak agent wallet.",image:"https://oakagentkit.org/favicon.svg",services:[],x402Support:!1,active:!0,registrations:[]};export{h as a,b,m as c,O as d,x as e};
@@ -0,0 +1 @@
1
+ import{a as E,c as S}from"./4B2GMIK7.js";import{getAddress as b}from"viem";import{buildIdentityLinkTypedData as x,canonicalSessionIdentity as k}from"@oakagentkit/core/identity-link";var w="Identity changed, expired or link revoked. Run oak setup link <agentId> with the current owner to verify or link it again. Reads remain available; actions are paused.",y="Identity status is unavailable. Please try again. Reads remain available; actions are paused.",g=class extends Error{constructor(){super(w)}};function R(e){return e.verified===!1&&typeof e.status=="string"&&["revoked","unlinked","transferred","burned"].includes(e.status)}var h="This wallet does not own that agent ID. Ask the current owner to sign the link in oak setup link <agentId>.",l="The identity challenge expired. Run oak setup link <agentId> again for a fresh owner signature.",I="Wrong identity network or registry. Set OAK_NETWORK and OAK_CHAIN_ID to match the owner\u2019s agent, then run oak setup again.",v="Owner signing cancelled. Run the identity command again when ready.",O="Owner signing requires your terminal. Run oak setup link <agentId> or oak identity unlink --owner <linkId> there.";function f(e){if(e instanceof g)return e;let a=e instanceof Error?e.message:typeof e=="string"?e:"";return/cancelled|canceled/i.test(a)?new Error(v):[w,y,h,l,I,O].includes(a)?new Error(a):/identity changed|link revoked|reads remain available/i.test(a)?new Error(w):/challenge.*expir/i.test(a)?new Error(l):/network|registry|chain/i.test(a)?new Error(I):/owner|signature|proof/i.test(a)?new Error(h):new Error(w)}function B(e){let a=S({...e,refreshIdentity:async o=>{let n=await E({signer:e.signer,network:e.network,now:e.now});try{let t=await m(new URL("/v1/identity/status",e.base),{method:"POST",redirect:"error",headers:{"content-type":"application/json","X-Oak-Session":n},body:JSON.stringify({identity:o}),signal:AbortSignal.timeout(3e4)}),r=await t.json();if(t.ok&&r?.ok===!0&&r.data&&R(r.data)){await e.clearIdentity?.();return}}catch{}return o}}),m=e.fetch??fetch,c=e.now??(()=>Math.floor(Date.now()/1e3));async function u(o,n){try{let t=`/v1/identity/${o}`,r=JSON.stringify(n),d=await m(new URL(t,e.base),{method:"POST",redirect:"error",headers:{"content-type":"application/json",...await a.headers("POST",t,r)},body:r,signal:AbortSignal.timeout(3e4)}),i=await d.json();if(!d.ok||!i||i.ok!==!0||!i.data||typeof i.data!="object"){if(o==="status"){let s=typeof i?.error=="string"?/Failed registry RPC: (eth_[a-zA-Z0-9]+)\./.exec(i.error)?.[1]:void 0;throw new Error(`${y} Failed server identity status (HTTP ${d.status})${s?`: registry RPC ${s}`:""}.`)}throw f(i?.error)}return i.data}catch(t){throw o!=="status"?f(t):t instanceof Error&&t.message.startsWith(y)?t:new Error(`${y} Failed server identity status: transport or invalid response.`,{cause:t})}}async function p(o){let n=await u("status",{identity:o});if(R(n))throw new g;if(n.verified!==!0){let t=typeof n.message=="string"?/Failed registry RPC: (eth_[a-zA-Z0-9]+)\./.exec(n.message)?.[1]:void 0;throw new Error(`${y} Failed server identity status${t?`: registry RPC ${t}`:""}.`)}return n}return{sessions:a,async requireVerified(){if(e.loadIdentity){let n=await e.loadIdentity();JSON.stringify(n)!==JSON.stringify(a.identity)&&a.setIdentity(n)}let o=a.identity;if(!o)throw new Error("Run oak setup to register or link an ERC-8004 identity first. Reads remain available; actions are paused.");try{await p(o)}catch(n){throw n instanceof g&&(a.setIdentity(void 0),await e.clearIdentity?.()),n}},async unlink(o={actor:"agent"},n){let t=o.linkId??a.identity?.linkId;if(!t||!/^0x[0-9a-f]{64}$/.test(t))throw new Error("Provide the linkId to unlink, or link an identity first.");if(!["agent","owner"].includes(o.actor))throw new Error("Choose agent or owner to unlink.");let r;if(o.actor==="owner"){if(!n)throw new Error("Owner signing is unavailable. Run oak identity unlink --owner <linkId> in your terminal.");let i=await u("challenge",{linkId:t});try{if(x(i),k({chainId:i.chainId,registry:i.registry,agentId:i.agentId},e.network),i.audience!==JSON.stringify([e.base.origin,"unlink",t]))throw new Error(I);if(BigInt(i.issuedAt)>BigInt(c())||BigInt(i.expiresAt)<=BigInt(c()))throw new Error(l);let s=await n({...i});if(BigInt(i.expiresAt)<=BigInt(c()))throw new Error(l);if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(s))throw new Error(h);r={link:i,signature:s}}catch(s){throw f(s)}}if((await u("unlink",{linkId:t,...r?{proof:r}:{}})).unlinked!==!0)throw new Error(w);return a.identity?.linkId===t&&(a.setIdentity(void 0),await e.clearIdentity?.()),{unlinked:!0,summary:"Identity link removed. Reads remain available; linked actions are paused."}},async accept(o){let n=k(o,e.network);return await p(n),a.setIdentity(n),n},async link(o,n){let t=k(o,e.network);if(t.linkId)throw new Error("Request a fresh identity link without an old linkId.");let r=await u("challenge",{identity:t});try{if(x(r),r.chainId!==t.chainId||r.registry!==t.registry||r.agentId!==t.agentId||b(r.agentWallet)!==e.signer.address||r.audience!==e.base.origin)throw new Error(I);if(BigInt(r.issuedAt)>BigInt(c())||BigInt(r.expiresAt)<=BigInt(c()))throw new Error(l);let d=await n({...r});if(BigInt(r.expiresAt)<=BigInt(c()))throw new Error(l);if(typeof d!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(d))throw new Error(h);let i=await u("link",{proof:{link:r,signature:d}}),s=k(i.identity,e.network);if(!s.linkId||s.agentId!==t.agentId)throw new Error(w);return await p(s),a.setIdentity(s),s}catch(d){throw f(d)}}}}export{w as a,y as b,h as c,l as d,I as e,v as f,O as g,f as h,B as i};
@@ -0,0 +1 @@
1
+ import{BaseError as i}from"viem";function a(e){return e.replace(/\b(?:https?|wss?):(?:\/\/|\\\/\\\/)[^\s<>"'`]+/gi,"[redacted URL]").replace(/((?:^|[\r\n])[ \t]*(?:set-)?cookie\s*[:=][ \t]*)[^\r\n]+/gi,"$1[redacted]").replace(/((?:^|[^a-z0-9_-])["']?(?:proxy[-_])?authorization["']?\s*[:=]\s*)([a-z]+[ \t]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\r\n,;}"']+))/gi,"$1[redacted]").replace(/\?[^\s<>"'`]+/g,"[redacted query]").replace(/((?:^|[^a-z0-9_-])["']?(?:(?:x[-_])?api[-_ ]?key|(?:access|auth|refresh)[-_ ]?token|(?:proxy[-_])?authorization|password|(?:client[-_])?secret|(?:set[-_])?cookie|token)["']?\s*[:=]\s*)("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|(?![\s{[])(?:(?![ \t]+["']?[a-z][\w-]*["']?\s*[:=])[^\r\n,;}[\]<>"'{])+)/gi,(r,t,n)=>{let s=n.trim().replace(/^["']|["']$/g,""),o=/^\$?[A-Z][A-Za-z0-9.]{0,11}$/.test(s)||/^0x[0-9a-f]{40}$/i.test(s);return/(?:^|[^a-z0-9_-])["']?token["']?\s*[:=]\s*$/i.test(t)&&o?r:`${t}[redacted]`}).replace(/\b(?:Bearer|Basic)\s+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,"'}]+)/gi,"[redacted authorization]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,"[redacted token]")}function c(e,r="Oak request failed. Check connectivity and retry."){return e instanceof i?a(e.shortMessage):a(e instanceof Error?e.message:r)}var d=e=>new Error(c(e)),g=()=>new Error("Cannot read local Oak configuration. Check file ownership, links and 0600 permissions.");export{a,c as b,d as c,g as d};