@oakagentkit/addon 0.1.0 → 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 (42) hide show
  1. package/build/dist/action-result.d.ts +3 -0
  2. package/build/dist/action-result.js +1 -0
  3. package/build/dist/bridge.d.ts +5 -1
  4. package/build/dist/bridge.js +1 -1
  5. package/build/dist/chunks/2NJCYRBM.js +1 -0
  6. package/build/dist/chunks/44YOYZLT.js +1 -0
  7. package/build/dist/chunks/67E2KBUQ.js +1 -0
  8. package/build/dist/chunks/I5LKYO3W.js +3 -0
  9. package/build/dist/chunks/IVR4JOHU.js +1 -0
  10. package/build/dist/chunks/{U4YOG57X.js → OB7JDPFV.js} +1 -1
  11. package/build/dist/chunks/RDCN3YPX.js +5 -0
  12. package/build/dist/chunks/RGOGWTRI.js +1 -0
  13. package/build/dist/chunks/U3IXRJH7.js +5 -0
  14. package/build/dist/chunks/U5VW3XSD.js +2 -0
  15. package/build/dist/chunks/UTTRLIY5.js +1 -0
  16. package/build/dist/chunks/YR4WKA4P.js +1 -0
  17. package/build/dist/cli.d.ts +7 -3
  18. package/build/dist/cli.js +5 -5
  19. package/build/dist/confirm.d.ts +120 -0
  20. package/build/dist/confirm.js +1 -0
  21. package/build/dist/execution-trace.d.ts +30 -0
  22. package/build/dist/execution-trace.js +1 -0
  23. package/build/dist/identity.js +1 -1
  24. package/build/dist/module-destinations.d.ts +4 -0
  25. package/build/dist/module-destinations.js +1 -0
  26. package/build/dist/renew.js +1 -1
  27. package/build/dist/sender.d.ts +31 -6
  28. package/build/dist/sender.js +1 -1
  29. package/build/dist/setup.d.ts +3 -1
  30. package/build/dist/setup.js +1 -1
  31. package/build/dist/subscribe.js +1 -1
  32. package/build/dist/terminal-confirm.d.ts +7 -0
  33. package/build/dist/terminal-confirm.js +1 -0
  34. package/build/dist/version.js +1 -1
  35. package/build/dist/wallet.js +1 -1
  36. package/package.json +9 -13
  37. package/build/dist/chunks/4X7FLHGQ.js +0 -1
  38. package/build/dist/chunks/5HTX664S.js +0 -1
  39. package/build/dist/chunks/62PM22KQ.js +0 -7
  40. package/build/dist/chunks/HGFLLHB6.js +0 -1
  41. package/build/dist/chunks/HLAZAI2Q.js +0 -4
  42. package/build/dist/chunks/ILJVXWGD.js +0 -1
@@ -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};
@@ -1,3 +1,4 @@
1
+ import { type ConfirmMode } from './confirm.js';
1
2
  import { createModule as kyberswap } from '@oakagentkit/core/modules/kyberswap/index';
2
3
  import { createModule as velora } from '@oakagentkit/core/modules/velora/index';
3
4
  import { createModule as spark } from '@oakagentkit/core/modules/spark/index';
@@ -12,7 +13,7 @@ import { createModule as poolstrade } from '@oakagentkit/core/modules/poolstrade
12
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];
13
14
  import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
14
15
  import { type OakNetwork } from '@oakagentkit/core/addresses';
15
- import type { Recipe, ToolArgs } from '@oakagentkit/core/types';
16
+ import type { Address, Recipe, ToolArgs } from '@oakagentkit/core/types';
16
17
  import { type RecipeReadClient } from './recipes.js';
17
18
  import { createSender } from './sender.js';
18
19
  import { type IdentityClient } from './identity.js';
@@ -33,6 +34,8 @@ export declare function jsonArgs(value: unknown): ToolArgs;
33
34
  export declare function serverAddress(value: string): URL;
34
35
  export declare const PREVIEW_TTL_SECONDS = 12;
35
36
  export interface BridgeOptions {
37
+ confirmMode?: ConfirmMode;
38
+ oakTokenAddress?: Address;
36
39
  startupInstructions?: () => Promise<string>;
37
40
  launchOnly?: boolean;
38
41
  privateTestMode?: boolean;
@@ -58,4 +61,5 @@ export declare function createBridge(options: BridgeOptions): {
58
61
  callTool: (name: string, original: ToolArgs) => Promise<unknown>;
59
62
  start: (transport?: Transport) => Promise<void>;
60
63
  stop: () => Promise<void>;
64
+ confirmSignature: import("./confirm.js").Confirm;
61
65
  };
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g}from"./chunks/62PM22KQ.js";import"./chunks/HLAZAI2Q.js";import"./chunks/4X7FLHGQ.js";import"./chunks/5HTX664S.js";import"./chunks/4B2GMIK7.js";import"./chunks/QIDB35RS.js";import"./chunks/VZCMAMZL.js";import"./chunks/4LWKW7PM.js";import"./chunks/GONTF7K4.js";import"./chunks/YVAFJM4Y.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};
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{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,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};
@@ -1 +1 @@
1
- import{c as o}from"./HGFLLHB6.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};
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,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 @@
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};
@@ -10,6 +10,7 @@ export declare function readConfig(path?: string): Promise<Config>;
10
10
  export declare function createRuntime(config: Config, writeDisplay: (text: string) => void | Promise<void>, recipeDirectory?: string, setupOptions?: {
11
11
  configPath?: string;
12
12
  signOwner?: OwnerSign;
13
+ terminalConfirmation?: boolean;
13
14
  }): Promise<{
14
15
  wallet: `0x${string}`;
15
16
  bridge: {
@@ -18,16 +19,19 @@ export declare function createRuntime(config: Config, writeDisplay: (text: strin
18
19
  callTool: (name: string, original: import("@oakagentkit/core/types").ToolArgs) => Promise<unknown>;
19
20
  start: (transport?: import("@modelcontextprotocol/sdk/shared/transport").Transport) => Promise<void>;
20
21
  stop: () => Promise<void>;
22
+ confirmSignature: import("./confirm.js").Confirm;
21
23
  };
22
24
  readonly lifecycle: SubscriptionLifecycle;
23
25
  subscribe: (plan: "holder" | "nohold") => Promise<import("./subscribe.js").LifecycleResult>;
24
26
  cancel: () => Promise<import("./subscribe.js").LifecycleResult>;
25
27
  renew: () => Promise<import("./subscribe.js").LifecycleResult>;
26
28
  setup: (request: SetupRequest) => Promise<{
27
- identity: import("@oakagentkit/core/identity-link").SessionIdentity;
28
29
  summary: string;
30
+ identity: import("@oakagentkit/core/identity-link").SessionIdentity;
31
+ hashes: string[];
32
+ status: string;
29
33
  }>;
30
- profile: {
34
+ profile: import("@oakagentkit/core/types").ToolArgs | {
31
35
  type: string;
32
36
  name: string;
33
37
  description: string;
@@ -36,7 +40,7 @@ export declare function createRuntime(config: Config, writeDisplay: (text: strin
36
40
  x402Support: boolean;
37
41
  active: boolean;
38
42
  registrations: never[];
39
- } | import("@oakagentkit/core/types").ToolArgs;
43
+ };
40
44
  }>;
41
45
  type Runtime = Pick<Awaited<ReturnType<typeof createRuntime>>, 'wallet' | 'profile' | 'renew'> & {
42
46
  bridge: Pick<ReturnType<typeof createBridge>, 'postTool' | 'callTool' | 'start'>;
package/build/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{a as he}from"./chunks/U4YOG57X.js";import{a as pe}from"./chunks/ILJVXWGD.js";import{e as B,f as ge}from"./chunks/HGFLLHB6.js";import{d as S,e as j,g as we}from"./chunks/62PM22KQ.js";import{c as oe}from"./chunks/HLAZAI2Q.js";import{a as Q}from"./chunks/4X7FLHGQ.js";import{c as J,f as se,g as ae,i as ce}from"./chunks/5HTX664S.js";import"./chunks/4B2GMIK7.js";import"./chunks/QIDB35RS.js";import{b as le,c as de,d as fe,e as ue}from"./chunks/VZCMAMZL.js";import{d as ne,e as $,f as ie}from"./chunks/4LWKW7PM.js";import{a as te,c as re,d as v}from"./chunks/GONTF7K4.js";import{a as W,b as Z,d as ee}from"./chunks/YVAFJM4Y.js";import{buildIdentityLinkTypedData as De,canonicalSessionIdentity as Ae,identityNetwork as Ee}from"@oakagentkit/core/identity-link";import{constants as I}from"node:fs";import{realpath as Ke,rename as Ie,unlink as Ne}from"node:fs/promises";import{randomUUID as ke}from"node:crypto";import{homedir as Pe}from"node:os";import{dirname as _e,join as Ce}from"node:path";import{pathToFileURL as ve}from"node:url";import{createPublicClient as Le,getAddress as y,http as Ue}from"viem";import{ETH_USDG_POOL as He,NETWORKS as N,assertNetworkRpc as xe,assertNetworkUsdg as Oe,resolveNetwork as k}from"@oakagentkit/core/addresses";import{DEFAULT_RPC_URL as We}from"@oakagentkit/core/chain";import{createWallet as $e,exportKey as Je,loadSigner as ye}from"#oak-wallet";var je="oak identity unlink [--owner <linkId>]|setup [register [--no-tag]|link <agentId>]|init [--recover [--replace]]|address|status|backup|export|subscribe --plan <holder|nohold>|renew|cancel|register [--no-tag]|recipes add|remove|list <pkg-or-path>|config set <k> <v>|mcp|call <tool> <json>",Se="The command or its arguments are not valid. Run oak --help and retry with the listed arguments.",me="as-is, not reviewed by Oak",L=()=>Ce(Pe(),".oak","config.json"),Be=new Set(["OAK_PRIVATE_TEST_MODE","OAK_LAUNCH_BOOTSTRAP","OAK_NETWORK","OAK_CHAIN_ID","OAK_SERVER_URL","OAK_RPC_URL","OAK_SUBSCRIPTION_ADDRESS","OAK_RETIRED_SUBSCRIPTION_ADDRESSES","OAK_TOKEN_ADDRESS","OAK_USDG_ADDRESS","OAK_ORACLE_ADDRESS","OAK_ETH_USDG_POOL_ADDRESS","OAK_FINALITY","profile","grandfather","identity"]);function Y(n,i){if(!Be.has(n)&&!/^OAK_RPC_URL_[1-9][0-9]*$/.test(n))throw new Error("Unknown setting. Wallet keys cannot be stored in config.");if(!i.trim()||i.length>1048576)throw new Error("Invalid configuration value.");if(["OAK_LAUNCH_BOOTSTRAP","OAK_PRIVATE_TEST_MODE"].includes(n)&&!["true","false"].includes(i))throw new Error("Set the mode to true or false.");if(n==="OAK_NETWORK")k(i);else{if(n==="OAK_CHAIN_ID"&&!["4663","46630"].includes(i))throw new Error("Set OAK_CHAIN_ID to 4663 or 46630.");if(n==="OAK_SERVER_URL")j(i);else if(n.startsWith("OAK_RPC_URL")){let o=new URL(i);if(!["https:","http:"].includes(o.protocol))throw new Error("RPC URL must use HTTP or HTTPS.")}else if(n.endsWith("_ADDRESS"))y(i);else if(n==="OAK_RETIRED_SUBSCRIPTION_ADDRESSES")i.split(",").forEach(o=>y(o.trim()));else{if(n==="OAK_FINALITY"&&i!=="safe"&&i!=="finalized"&&(!/^[1-9][0-9]*$/.test(i)||!Number.isSafeInteger(Number(i))))throw new Error("Invalid finality setting.");if(n==="identity"){let o=S(JSON.parse(i));Ae(o,Ee(o.chainId))}else(n==="profile"||n==="grandfather")&&S(JSON.parse(i))}}}async function U(n=L()){let i;try{i=await v(n,I.O_RDONLY,2097152)}catch(o){if(o.code==="ENOENT")return{};throw ee()}try{let o=await i.stat();if(!o.isFile()||o.size>2097152)throw new Error("Invalid local Oak configuration.");let f=S(JSON.parse(await i.readFile("utf8")));for(let[w,s]of Object.entries(f)){if(typeof s!="string")throw new Error("Configuration values must be strings.");Y(w,s)}return f}finally{await i.close()}}async function F(n,i,o){if(o!==void 0)Y(i,o);else if(i!=="identity")throw new Error("Only the public identity setting can be cleared.");let f={...await U(n)};o===void 0?delete f[i]:f[i]=o;let w=`${JSON.stringify(f,null,2)}
3
- `;if(Buffer.byteLength(w)>2097152)throw new Error("Local Oak configuration exceeds 2 MiB. Remove unused settings before retrying.");await te(_e(n),!0);let s=`${n}.${ke()}.tmp`,p=await v(s,I.O_WRONLY|I.O_CREAT|I.O_EXCL,2097152);try{try{await p.writeFile(w),await p.sync()}finally{await p.close()}try{await(await v(n,I.O_RDONLY,2097152)).close()}catch(r){if(r.code!=="ENOENT")throw r}await Ie(s,n),await re(_e(n))}finally{await Ne(s).catch(r=>{if(r.code!=="ENOENT")throw r})}}async function Fe(n,i,o,f={}){n={...n};let w=t=>i(W(t)),s=t=>process.env[t]??n[t],p=t=>{let c=s(t);if(!c)throw new Error(`Set ${t} with oak config set before this command.`);return c},r=k(n.OAK_NETWORK);if(process.env.OAK_NETWORK!==void 0&&k(process.env.OAK_NETWORK)!==r)throw new Error("OAK_NETWORK disagrees with the local config; set the network in the config explicitly.");let{chainId:e,usdg:m}=N[r];if((n.OAK_CHAIN_ID??String(N.mainnet.chainId))!==String(e)||process.env.OAK_CHAIN_ID!==void 0&&process.env.OAK_CHAIN_ID!==String(e))throw new Error(`Set OAK_CHAIN_ID to ${e} in the local deployment config.`);let g=(t,c)=>{let d=n[t]??c;if(!d)throw new Error(`Set ${t} in the local deployment config.`);let O=y(d);if(process.env[t]!==void 0&&y(process.env[t])!==O)throw new Error(`${t} disagrees with the local deployment config.`);return O},A=n.OAK_PRIVATE_TEST_MODE==="true",E=n.OAK_LAUNCH_BOOTSTRAP==="true";if(E&&A)throw new Error("Choose private test mode or launch-only bootstrap, then restart Oak.");if((E||A)&&r!=="mainnet")throw new Error("Launch bootstrap requires mainnet chain 4663.");let b=()=>{let t={network:r,chainId:e,subscription:g("OAK_SUBSCRIPTION_ADDRESS"),usdg:g("OAK_USDG_ADDRESS",m),oak:g("OAK_TOKEN_ADDRESS"),oracle:g("OAK_ORACLE_ADDRESS"),ethUsdgPool:g("OAK_ETH_USDG_POOL_ADDRESS")};return Oe(r,t.usdg),B(t),t},T=["OAK_SUBSCRIPTION_ADDRESS","OAK_TOKEN_ADDRESS","OAK_ORACLE_ADDRESS","OAK_ETH_USDG_POOL_ADDRESS"];for(let t of T)if(process.env[t]!==void 0&&n[t]===void 0)throw new Error(`Set ${t} in the local deployment config; environment-only addresses are not accepted.`);!E&&!A&&T.every(t=>n[t])&&b();let D=j(s("OAK_SERVER_URL")??(r==="mainnet"?"https://api.oakagentkit.org":p("OAK_SERVER_URL"))),l=async()=>{if(T.every(O=>n[O])){b();return}let t;try{let O=await fetch(new URL("/v1/config",D),{redirect:"error",signal:AbortSignal.timeout(5e3)}),K=S(await O.json());if(!O.ok||K.ok!==!0)throw new Error;t=S(K.data)}catch{throw new Error("Oak deployment configuration is unavailable. Ask the operator to enable /v1/config or configure the published Oak contract addresses. Your wallet address and read tools remain available.")}if(t.network!==r||t.chainId!==e||typeof t.usdg!="string")throw new Error("The Oak service configuration does not match the selected network.");Oe(r,y(t.usdg));let c={OAK_SUBSCRIPTION_ADDRESS:t.subscription,OAK_TOKEN_ADDRESS:t.oak,OAK_ORACLE_ADDRESS:t.oracle,OAK_ETH_USDG_POOL_ADDRESS:t.ethUsdgPool},d={};for(let[O,K]of Object.entries(c)){if(typeof K!="string")throw new Error("The Oak service deployment configuration is invalid.");let X=y(K);if(n[O]&&y(n[O])!==X)throw new Error(`${O} disagrees with the local deployment config.`);d[O]=X}if(B({network:r,chainId:e,subscription:d.OAK_SUBSCRIPTION_ADDRESS,oak:d.OAK_TOKEN_ADDRESS,oracle:d.OAK_ORACLE_ADDRESS,ethUsdgPool:d.OAK_ETH_USDG_POOL_ADDRESS,usdg:y(t.usdg)}),r==="mainnet"&&d.OAK_ETH_USDG_POOL_ADDRESS!==He)throw new Error("ETH/USDG pool must match the pinned mainnet pool.");Object.assign(n,d),b()},u=new Map,a=t=>{let c=u.get(t);if(!c){let d=t===e?s("OAK_RPC_URL")??(r==="mainnet"?We:p("OAK_RPC_URL")):p(`OAK_RPC_URL_${t}`);c=Le({transport:Ue(d,{timeout:1e4,retryCount:0}),cacheTime:0}),u.set(t,c)}return c},h=[e,...Object.keys({...n,...process.env}).filter(t=>/^OAK_RPC_URL_[1-9][0-9]*$/.test(t)).map(t=>Number(t.slice(12)))];if(h.includes(r==="testnet"?N.mainnet.chainId:N.testnet.chainId))throw new Error("Do not configure the other Robinhood network as an additional RPC. Set OAK_NETWORK and OAK_RPC_URL together.");await Promise.all([...new Set(h)].filter(t=>t!==e||s("OAK_RPC_URL")).map(async t=>{let c=a(t);if(t===e)await xe(r,c);else if(await c.getChainId()!==t)throw new Error(`RPC chain does not match configured chain ${t}.`)}));let _=s("OAK_FINALITY");_&&Y("OAK_FINALITY",_);let P=_===void 0?void 0:_==="safe"||_==="finalized"?_:Number(_),R=await ye(),G=t=>{if(!t)return;let c=JSON.parse(t),d=Ae(c,Ee(c.chainId));return d.chainId===e?d:void 0},H=ce({base:D,signer:R,network:r,identity:E||A?void 0:G(n.identity),clearIdentity:()=>F(f.configPath??L(),"identity"),loadIdentity:async()=>E||A?void 0:G((await U(f.configPath)).identity)}),M=oe({signer:R,clientFor:a,allowedChainIds:h,finality:P,preview:w}),Re={withAction:t=>M.withAction(c=>t({...c,send:async d=>(d.length&&await w(JSON.stringify(await x.postTool("preview",{txs:d}))),c.send(d))}))},be,C=()=>be??=new ge({wallet:R.address,deployment:b(),client:a(e),sender:Re,issueNote:async t=>{try{let c=await fetch(new URL("/v1/price-note",D),{method:"POST",redirect:"error",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(3e4)}),d=await c.json();if(!c.ok&&!("reason"in d))throw new Error;return d}catch{throw new Error("Price note is unavailable. Retry when the server is reachable.")}},...n.grandfather?{grandfatherList:async()=>JSON.parse(n.grandfather)}:{}}),V=async()=>(await l(),he(C())),q=async t=>(await H.requireVerified(),await l(),C().subscribe(t)),Te=async()=>(await l(),C().cancel()),x=we({network:r,launchOnly:E,privateTestMode:A,identity:H,signOwner:f.signOwner,setup:t=>z(t),serverUrl:D.href,signer:R,sender:M,display:w,ensureSubscribed:V,startupInstructions:()=>le(R.address,r),subscribe:q,recipes:()=>$({directory:o}),recipeClient:a(e)}),z=pe({network:r,signer:R,identity:H,callTool:x.callTool,signOwner:f.signOwner,save:t=>F(f.configPath??L(),"identity",JSON.stringify(t))});return{wallet:R.address,bridge:x,get lifecycle(){return C()},subscribe:q,cancel:Te,renew:V,setup:z,profile:n.profile?S(JSON.parse(n.profile)):ue}}async function Ye(n,i={}){let o=i.output??(r=>{process.stdout.write(`${r}
4
- `)}),f=i.error??i.output??(r=>{process.stderr.write(`${r}
5
- `)}),w=r=>f(W(r)),s=r=>o(JSON.stringify(r)),p=()=>{if(!(i.isTTY??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0)))throw new Error("run this in your own terminal, not through the agent")};try{let[r,...e]=n;if(r==="--version"||r==="-v")return o(Q),0;if(r==="--help"||r==="-h")return o(je),0;if(r==="init"&&(!e.length||e[0]==="--recover"&&(e.length===1||e.length===2&&e[1]==="--replace"))){p();let a=i.initialize??$e;return s(await(e.length?a({recover:!0,replace:e[1]==="--replace"}):a())),0}if(r==="export"&&!e.length)return p(),await(i.exportWallet??Je)(),0;if(r==="backup"&&!e.length)return o(fe),0;if(r==="address"&&!e.length){let a=await U(i.configPath),h=k(a.OAK_NETWORK);if(process.env.OAK_NETWORK!==void 0&&k(process.env.OAK_NETWORK)!==h)throw new Error("OAK_NETWORK disagrees with the local config; set the network in the config explicitly.");let _=N[h].chainId;if(a.OAK_CHAIN_ID!==void 0&&a.OAK_CHAIN_ID!==String(_)||process.env.OAK_CHAIN_ID!==void 0&&process.env.OAK_CHAIN_ID!==String(_))throw new Error(`Set OAK_CHAIN_ID to ${_} for the selected network.`);return s(de(await(i.address??(async()=>(await ye()).address))(),h)),0}if(r==="config"&&e.length===3&&e[0]==="set")return await F(i.configPath??L(),e[1],e[2]),o(`Saved ${e[1]}.`),0;if(r==="recipes"){let a={directory:i.recipeDirectory};if(e[0]==="add"&&e.length===2)s({recipes:await ne(e[1],a),label:me});else if(e[0]==="remove"&&e.length===2)await ie(e[1],a),o("Recipe project removed.");else if(e[0]==="list"&&e.length<=2)s({recipes:(await $(a)).filter(h=>!e[1]||h.project===e[1]),label:me});else throw new Error(Se);return 0}let m=r==="identity"&&e[0]==="unlink"&&(e.length===1||e.length===3&&e[1]==="--owner"&&/^0x[0-9a-f]{64}$/.test(e[2])),g=r==="setup"&&(!e.length||e[0]==="register"&&(e.length===1||e.length===2&&e[1]==="--no-tag")||e[0]==="link"&&e.length===2),A=["status","renew","cancel","mcp"].includes(r??"")&&!e.length,E=r==="subscribe"&&e.length===2&&e[0]==="--plan"&&["holder","nohold"].includes(e[1]),b=r==="register"&&(!e.length||e.length===1&&e[0]==="--no-tag"),T=r==="call"&&e.length===2;if(!m&&!g&&!A&&!E&&!b&&!T)throw new Error(Se);let D=T?S(JSON.parse(e[1])):void 0,l=await(i.runtime??(async()=>Fe(await U(i.configPath),w,i.recipeDirectory,{configPath:i.configPath,signOwner:i.signOwner??(["setup","identity","mcp","call"].includes(r??"")?Ge(w):void 0)})))(),u;switch(r){case"identity":u=await l.bridge.callTool("oak_identity_unlink",e[1]==="--owner"?{actor:"owner",linkId:e[2]}:{actor:"agent"});break;case"setup":{if(!l.setup)throw new Error("Identity setup is unavailable in this runtime.");let a=e[0],h=e[1];if(!a){let P=(i.chooseSetup?await i.chooseSetup():"register").trim().split(/\s+/);a=P[0],h=P[1]}if(a==="link"&&h)u=await l.setup({mode:a,agentId:h});else if(a==="register"){if(!l.profile)throw new Error("Set a registration-v1 profile with oak config set profile <json>, then run oak setup register.");u=await l.setup({mode:a,profile:l.profile,tag:h!=="--no-tag"})}else throw new Error("Choose register or link <agentId> with oak setup.");break}case"status":u={wallet:l.wallet,...S(await l.bridge.postTool("account",{}))};break;case"subscribe":u=await(l.subscribe??(a=>l.lifecycle.subscribe(a)))(e[1]);break;case"renew":u=await l.renew();break;case"cancel":u=await(l.cancel??(()=>l.lifecycle.cancel()))();break;case"register":if(!l.profile)throw new Error("Set a registration-v1 profile with oak config set profile <json>, then run oak register.");u=await l.bridge.callTool("erc8004_register",{profile:l.profile,tag:e[0]!=="--no-tag"});break;case"call":u=await l.bridge.callTool(e[0],D);break;case"mcp":return await l.bridge.start(),0}return s(u),u&&typeof u=="object"&&"ok"in u&&u.ok===!1?1:0}catch(r){return w(r instanceof SyntaxError?"The JSON is not valid. Use a JSON object with double-quoted field names and strings, then retry.":Z(r,"Oak command failed. Run oak status and retry when the server is reachable.")),1}}function Ge(n){return async i=>{if(!process.stdin.isTTY||!process.stderr.isTTY)throw new Error(ae);return n("In the current owner\u2019s wallet, sign this EIP-712 identity request (the audience identifies link or unlink). Paste only the signature below; input is hidden. Never paste a key or recovery words."),n(JSON.stringify(De(i),(o,f)=>typeof f=="bigint"?f.toString():f)),new Promise((o,f)=>{let w=process.stdin.isRaw,s="",p=m=>{process.stdin.off("data",e),process.stdin.off("end",r),process.stdin.setRawMode(w===!0),process.stdin.pause(),m?f(m):/^0x(?:[0-9a-fA-F]{2})+$/.test(s)?o(s):f(new Error(J))},r=()=>p(new Error(se)),e=m=>{for(let g of m.toString("utf8")){if(g===""||g===""){r();return}if(g==="\r"||g===`
6
- `){p();return}if(g==="\x7F"?s=s.slice(0,-1):s+=g,s.length>131072){p(new Error(J));return}}};process.stdin.setRawMode(!0),process.stdin.on("data",e),process.stdin.once("end",r),process.stdin.resume()})}}process.argv[1]&&import.meta.url===ve(await Ke(process.argv[1])).href&&(process.exitCode=await Ye(process.argv.slice(2)));export{Fe as createRuntime,U as readConfig,Ye as runCli,Ge as terminalOwnerSign};
2
+ import{a as _e}from"./chunks/I5LKYO3W.js";import{a as he}from"./chunks/OB7JDPFV.js";import{e as F,f as ge}from"./chunks/UTTRLIY5.js";import{a as pe}from"./chunks/44YOYZLT.js";import{d as O,e as B,g as we}from"./chunks/RDCN3YPX.js";import{a as Q}from"./chunks/RGOGWTRI.js";import{d as ne,e as J,f as ie}from"./chunks/4LWKW7PM.js";import{c as oe}from"./chunks/U5VW3XSD.js";import{b as le,c as de,d as fe,e as ue}from"./chunks/VZCMAMZL.js";import{a as te,c as re,d as L}from"./chunks/GONTF7K4.js";import{a as $,b as Z,d as ee}from"./chunks/YVAFJM4Y.js";import"./chunks/IVR4JOHU.js";import"./chunks/U3IXRJH7.js";import"./chunks/2NJCYRBM.js";import{c as j,f as se,g as ae,i as ce}from"./chunks/YR4WKA4P.js";import"./chunks/4B2GMIK7.js";import"./chunks/QIDB35RS.js";import"./chunks/67E2KBUQ.js";import{buildIdentityLinkTypedData as Ke,canonicalSessionIdentity as Ee,identityNetwork as ye}from"@oakagentkit/core/identity-link";import{constants as k}from"node:fs";import{realpath as ke,rename as Ie,unlink as Ne}from"node:fs/promises";import{randomUUID as Pe}from"node:crypto";import{homedir as Ce}from"node:os";import{dirname as me,join as ve}from"node:path";import{pathToFileURL as Le}from"node:url";import{createPublicClient as Ue,getAddress as y,http as He}from"viem";import{ETH_USDG_POOL as xe,NETWORKS as I,assertNetworkRpc as We,assertNetworkUsdg as Oe,resolveNetwork as N}from"@oakagentkit/core/addresses";import{DEFAULT_RPC_URL as $e}from"@oakagentkit/core/chain";import{createWallet as Je,exportKey as je,loadSigner as Re}from"#oak-wallet";var Be="oak identity unlink [--owner <linkId>]|setup [register [--no-tag]|link <agentId>]|init [--recover [--replace]]|address|status|backup|export|subscribe --plan <holder|nohold>|renew|cancel|register [--no-tag]|recipes add|remove|list <pkg-or-path>|config set <k> <v>|mcp|call <tool> <json>",Se="The command or its arguments are not valid. Run oak --help and retry with the listed arguments.",Ae="as-is, not reviewed by Oak",U=()=>ve(Ce(),".oak","config.json"),Fe=new Set(["OAK_PRIVATE_TEST_MODE","OAK_LAUNCH_BOOTSTRAP","OAK_NETWORK","OAK_CHAIN_ID","OAK_SERVER_URL","OAK_RPC_URL","OAK_SUBSCRIPTION_ADDRESS","OAK_RETIRED_SUBSCRIPTION_ADDRESSES","OAK_TOKEN_ADDRESS","OAK_USDG_ADDRESS","OAK_ORACLE_ADDRESS","OAK_ETH_USDG_POOL_ADDRESS","OAK_FINALITY","profile","grandfather","identity","confirm"]);function G(n,i){if(!Fe.has(n)&&!/^OAK_RPC_URL_[1-9][0-9]*$/.test(n))throw new Error("Unknown setting. Wallet keys cannot be stored in config.");if(!i.trim()||i.length>1048576)throw new Error("Invalid configuration value.");if(["OAK_LAUNCH_BOOTSTRAP","OAK_PRIVATE_TEST_MODE"].includes(n)&&!["true","false"].includes(i))throw new Error("Set the mode to true or false.");if(n==="confirm"&&i!=="ask"&&i!=="auto")throw new Error("Set confirm to ask or auto.");if(n==="OAK_NETWORK")N(i);else{if(n==="OAK_CHAIN_ID"&&!["4663","46630"].includes(i))throw new Error("Set OAK_CHAIN_ID to 4663 or 46630.");if(n==="OAK_SERVER_URL")B(i);else if(n.startsWith("OAK_RPC_URL")){let o=new URL(i);if(!["https:","http:"].includes(o.protocol))throw new Error("RPC URL must use HTTP or HTTPS.")}else if(n.endsWith("_ADDRESS"))y(i);else if(n==="OAK_RETIRED_SUBSCRIPTION_ADDRESSES")i.split(",").forEach(o=>y(o.trim()));else{if(n==="OAK_FINALITY"&&i!=="safe"&&i!=="finalized"&&(!/^[1-9][0-9]*$/.test(i)||!Number.isSafeInteger(Number(i))))throw new Error("Invalid finality setting.");if(n==="identity"){let o=O(JSON.parse(i));Ee(o,ye(o.chainId))}else(n==="profile"||n==="grandfather")&&O(JSON.parse(i))}}}async function H(n=U()){let i;try{i=await L(n,k.O_RDONLY,2097152)}catch(o){if(o.code==="ENOENT")return{};throw ee()}try{let o=await i.stat();if(!o.isFile()||o.size>2097152)throw new Error("Invalid local Oak configuration.");let l=O(JSON.parse(await i.readFile("utf8")));for(let[p,s]of Object.entries(l)){if(typeof s!="string")throw new Error("Configuration values must be strings.");G(p,s)}return l}finally{await i.close()}}async function Y(n,i,o){if(o!==void 0)G(i,o);else if(i!=="identity")throw new Error("Only the public identity setting can be cleared.");let l={...await H(n)};o===void 0?delete l[i]:l[i]=o;let p=`${JSON.stringify(l,null,2)}
3
+ `;if(Buffer.byteLength(p)>2097152)throw new Error("Local Oak configuration exceeds 2 MiB. Remove unused settings before retrying.");await te(me(n),!0);let s=`${n}.${Pe()}.tmp`,w=await L(s,k.O_WRONLY|k.O_CREAT|k.O_EXCL,2097152);try{try{await w.writeFile(p),await w.sync()}finally{await w.close()}try{await(await L(n,k.O_RDONLY,2097152)).close()}catch(r){if(r.code!=="ENOENT")throw r}await Ie(s,n),await re(me(n))}finally{await Ne(s).catch(r=>{if(r.code!=="ENOENT")throw r})}}async function Ye(n,i,o,l={}){n={...n};let p=t=>i($(t)),s=t=>process.env[t]??n[t],w=t=>{let c=s(t);if(!c)throw new Error(`Set ${t} with oak config set before this command.`);return c},r=N(n.OAK_NETWORK);if(process.env.OAK_NETWORK!==void 0&&N(process.env.OAK_NETWORK)!==r)throw new Error("OAK_NETWORK disagrees with the local config; set the network in the config explicitly.");let{chainId:e,usdg:S}=I[r];if((n.OAK_CHAIN_ID??String(I.mainnet.chainId))!==String(e)||process.env.OAK_CHAIN_ID!==void 0&&process.env.OAK_CHAIN_ID!==String(e))throw new Error(`Set OAK_CHAIN_ID to ${e} in the local deployment config.`);let g=(t,c)=>{let f=n[t]??c;if(!f)throw new Error(`Set ${t} in the local deployment config.`);let m=y(f);if(process.env[t]!==void 0&&y(process.env[t])!==m)throw new Error(`${t} disagrees with the local deployment config.`);return m},A=n.OAK_PRIVATE_TEST_MODE==="true",E=n.OAK_LAUNCH_BOOTSTRAP==="true";if(E&&A)throw new Error("Choose private test mode or launch-only bootstrap, then restart Oak.");if((E||A)&&r!=="mainnet")throw new Error("Launch bootstrap requires mainnet chain 4663.");let T=()=>{let t={network:r,chainId:e,subscription:g("OAK_SUBSCRIPTION_ADDRESS"),usdg:g("OAK_USDG_ADDRESS",S),oak:g("OAK_TOKEN_ADDRESS"),oracle:g("OAK_ORACLE_ADDRESS"),ethUsdgPool:g("OAK_ETH_USDG_POOL_ADDRESS")};return Oe(r,t.usdg),F(t),t},b=["OAK_SUBSCRIPTION_ADDRESS","OAK_TOKEN_ADDRESS","OAK_ORACLE_ADDRESS","OAK_ETH_USDG_POOL_ADDRESS"];for(let t of b)if(process.env[t]!==void 0&&n[t]===void 0)throw new Error(`Set ${t} in the local deployment config; environment-only addresses are not accepted.`);!E&&!A&&b.every(t=>n[t])&&T();let D=B(s("OAK_SERVER_URL")??(r==="mainnet"?"https://api.oakagentkit.org":w("OAK_SERVER_URL"))),d=async()=>{if(b.every(m=>n[m])){T();return}let t;try{let m=await fetch(new URL("/v1/config",D),{redirect:"error",signal:AbortSignal.timeout(5e3)}),K=O(await m.json());if(!m.ok||K.ok!==!0)throw new Error;t=O(K.data)}catch{throw new Error("Oak deployment configuration is unavailable. Ask the operator to enable /v1/config or configure the published Oak contract addresses. Your wallet address and read tools remain available.")}if(t.network!==r||t.chainId!==e||typeof t.usdg!="string")throw new Error("The Oak service configuration does not match the selected network.");Oe(r,y(t.usdg));let c={OAK_SUBSCRIPTION_ADDRESS:t.subscription,OAK_TOKEN_ADDRESS:t.oak,OAK_ORACLE_ADDRESS:t.oracle,OAK_ETH_USDG_POOL_ADDRESS:t.ethUsdgPool},f={};for(let[m,K]of Object.entries(c)){if(typeof K!="string")throw new Error("The Oak service deployment configuration is invalid.");let X=y(K);if(n[m]&&y(n[m])!==X)throw new Error(`${m} disagrees with the local deployment config.`);f[m]=X}if(F({network:r,chainId:e,subscription:f.OAK_SUBSCRIPTION_ADDRESS,oak:f.OAK_TOKEN_ADDRESS,oracle:f.OAK_ORACLE_ADDRESS,ethUsdgPool:f.OAK_ETH_USDG_POOL_ADDRESS,usdg:y(t.usdg)}),r==="mainnet"&&f.OAK_ETH_USDG_POOL_ADDRESS!==xe)throw new Error("ETH/USDG pool must match the pinned mainnet pool.");Object.assign(n,f),T()},u=new Map,a=t=>{let c=u.get(t);if(!c){let f=t===e?s("OAK_RPC_URL")??(r==="mainnet"?$e:w("OAK_RPC_URL")):w(`OAK_RPC_URL_${t}`);c=Ue({transport:He(f,{timeout:1e4,retryCount:0}),cacheTime:0}),u.set(t,c)}return c},h=[e,...Object.keys({...n,...process.env}).filter(t=>/^OAK_RPC_URL_[1-9][0-9]*$/.test(t)).map(t=>Number(t.slice(12)))];if(h.includes(r==="testnet"?I.mainnet.chainId:I.testnet.chainId))throw new Error("Do not configure the other Robinhood network as an additional RPC. Set OAK_NETWORK and OAK_RPC_URL together.");await Promise.all([...new Set(h)].filter(t=>t!==e||s("OAK_RPC_URL")).map(async t=>{let c=a(t);if(t===e)await We(r,c);else if(await c.getChainId()!==t)throw new Error(`RPC chain does not match configured chain ${t}.`)}));let _=s("OAK_FINALITY");_&&G("OAK_FINALITY",_);let P=_===void 0?void 0:_==="safe"||_==="finalized"?_:Number(_),R=await Re(),M=t=>{if(!t)return;let c=JSON.parse(t),f=Ee(c,ye(c.chainId));return f.chainId===e?f:void 0},x=ce({base:D,signer:R,network:r,identity:E||A?void 0:M(n.identity),clearIdentity:()=>Y(l.configPath??U(),"identity"),loadIdentity:async()=>E||A?void 0:M((await H(l.configPath)).identity)}),W=oe({signer:R,clientFor:a,allowedChainIds:h,finality:P,preview:p,confirm:l.terminalConfirmation?_e(n.confirm==="auto"?"auto":"ask"):t=>v.confirmSignature(t)}),Te={withAction:t=>W.withAction(c=>t({...c,send:async f=>(f.length&&await p(JSON.stringify(await v.postTool("preview",{txs:f}))),c.send(f))}))},be,C=()=>be??=new ge({wallet:R.address,deployment:T(),client:a(e),sender:Te,issueNote:async t=>{try{let c=await fetch(new URL("/v1/price-note",D),{method:"POST",redirect:"error",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(3e4)}),f=await c.json();if(!c.ok&&!("reason"in f))throw new Error;return f}catch{throw new Error("Price note is unavailable. Retry when the server is reachable.")}},...n.grandfather?{grandfatherList:async()=>JSON.parse(n.grandfather)}:{}}),q=async()=>(await d(),he(C())),V=async t=>(await x.requireVerified(),await d(),C().subscribe(t)),De=async()=>(await d(),C().cancel()),v=we({oakTokenAddress:n.OAK_TOKEN_ADDRESS,confirmMode:n.confirm==="auto"?"auto":"ask",network:r,launchOnly:E,privateTestMode:A,identity:x,signOwner:l.signOwner,setup:t=>z(t),serverUrl:D.href,signer:R,sender:W,display:p,ensureSubscribed:q,startupInstructions:()=>le(R.address,r),subscribe:V,recipes:()=>J({directory:o}),recipeClient:a(e)}),z=pe({network:r,signer:{...R,signTypedData:t=>W.signTypedData(t)},identity:x,callTool:v.callTool,signOwner:l.signOwner,save:t=>Y(l.configPath??U(),"identity",JSON.stringify(t))});return{wallet:R.address,bridge:v,get lifecycle(){return C()},subscribe:V,cancel:De,renew:q,setup:z,profile:n.profile?O(JSON.parse(n.profile)):ue}}async function Ge(n,i={}){let o=i.output??(r=>{process.stdout.write(`${r}
4
+ `)}),l=i.error??i.output??(r=>{process.stderr.write(`${r}
5
+ `)}),p=r=>l($(r)),s=r=>o(JSON.stringify(r)),w=()=>{if(!(i.isTTY??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0)))throw new Error("run this in your own terminal, not through the agent")};try{let[r,...e]=n;if(r==="--version"||r==="-v")return o(Q),0;if(r==="--help"||r==="-h")return o(Be),0;if(r==="init"&&(!e.length||e[0]==="--recover"&&(e.length===1||e.length===2&&e[1]==="--replace"))){w();let a=i.initialize??Je;return s(await(e.length?a({recover:!0,replace:e[1]==="--replace"}):a())),0}if(r==="export"&&!e.length)return w(),await(i.exportWallet??je)(),0;if(r==="backup"&&!e.length)return o(fe),0;if(r==="address"&&!e.length){let a=await H(i.configPath),h=N(a.OAK_NETWORK);if(process.env.OAK_NETWORK!==void 0&&N(process.env.OAK_NETWORK)!==h)throw new Error("OAK_NETWORK disagrees with the local config; set the network in the config explicitly.");let _=I[h].chainId;if(a.OAK_CHAIN_ID!==void 0&&a.OAK_CHAIN_ID!==String(_)||process.env.OAK_CHAIN_ID!==void 0&&process.env.OAK_CHAIN_ID!==String(_))throw new Error(`Set OAK_CHAIN_ID to ${_} for the selected network.`);return s(de(await(i.address??(async()=>(await Re()).address))(),h)),0}if(r==="config"&&e.length===3&&e[0]==="set")return e[1]==="confirm"&&e[2]==="auto"&&w(),await Y(i.configPath??U(),e[1],e[2]),o(`Saved ${e[1]}.`),0;if(r==="recipes"){let a={directory:i.recipeDirectory};if(e[0]==="add"&&e.length===2)s({recipes:await ne(e[1],a),label:Ae});else if(e[0]==="remove"&&e.length===2)await ie(e[1],a),o("Recipe project removed.");else if(e[0]==="list"&&e.length<=2)s({recipes:(await J(a)).filter(h=>!e[1]||h.project===e[1]),label:Ae});else throw new Error(Se);return 0}let S=r==="identity"&&e[0]==="unlink"&&(e.length===1||e.length===3&&e[1]==="--owner"&&/^0x[0-9a-f]{64}$/.test(e[2])),g=r==="setup"&&(!e.length||e[0]==="register"&&(e.length===1||e.length===2&&e[1]==="--no-tag")||e[0]==="link"&&e.length===2),A=["status","renew","cancel","mcp"].includes(r??"")&&!e.length,E=r==="subscribe"&&e.length===2&&e[0]==="--plan"&&["holder","nohold"].includes(e[1]),T=r==="register"&&(!e.length||e.length===1&&e[0]==="--no-tag"),b=r==="call"&&e.length===2;if(!S&&!g&&!A&&!E&&!T&&!b)throw new Error(Se);let D=b?O(JSON.parse(e[1])):void 0,d=await(i.runtime??(async()=>Ye(await H(i.configPath),p,i.recipeDirectory,{configPath:i.configPath,terminalConfirmation:r!=="mcp",signOwner:i.signOwner??(["setup","identity","mcp","call"].includes(r??"")?Me(p):void 0)})))(),u;switch(r){case"identity":u=await d.bridge.callTool("oak_identity_unlink",e[1]==="--owner"?{actor:"owner",linkId:e[2]}:{actor:"agent"});break;case"setup":{if(!d.setup)throw new Error("Identity setup is unavailable in this runtime.");let a=e[0],h=e[1];if(!a){let P=(i.chooseSetup?await i.chooseSetup():"register").trim().split(/\s+/);a=P[0],h=P[1]}if(a==="link"&&h)u=await d.setup({mode:a,agentId:h});else if(a==="register"){if(!d.profile)throw new Error("Set a registration-v1 profile with oak config set profile <json>, then run oak setup register.");u=await d.setup({mode:a,profile:d.profile,tag:h!=="--no-tag"})}else throw new Error("Choose register or link <agentId> with oak setup.");break}case"status":u={wallet:d.wallet,...O(await d.bridge.postTool("account",{}))};break;case"subscribe":u=await(d.subscribe??(a=>d.lifecycle.subscribe(a)))(e[1]);break;case"renew":u=await d.renew();break;case"cancel":u=await(d.cancel??(()=>d.lifecycle.cancel()))();break;case"register":if(!d.profile)throw new Error("Set a registration-v1 profile with oak config set profile <json>, then run oak register.");u=await d.bridge.callTool("erc8004_register",{profile:d.profile,tag:e[0]!=="--no-tag"});break;case"call":u=await d.bridge.callTool(e[0],D);break;case"mcp":return await d.bridge.start(),0}return s(u),u&&typeof u=="object"&&"ok"in u&&u.ok===!1?1:0}catch(r){return p(r instanceof SyntaxError?"The JSON is not valid. Use a JSON object with double-quoted field names and strings, then retry.":Z(r,"Oak command failed. Run oak status and retry when the server is reachable.")),1}}function Me(n){return async i=>{if(!process.stdin.isTTY||!process.stderr.isTTY)throw new Error(ae);return n("In the current owner\u2019s wallet, sign this EIP-712 identity request (the audience identifies link or unlink). Paste only the signature below; input is hidden. Never paste a key or recovery words."),n(JSON.stringify(Ke(i),(o,l)=>typeof l=="bigint"?l.toString():l)),new Promise((o,l)=>{let p=process.stdin.isRaw,s="",w=S=>{process.stdin.off("data",e),process.stdin.off("end",r),process.stdin.setRawMode(p===!0),process.stdin.pause(),S?l(S):/^0x(?:[0-9a-fA-F]{2})+$/.test(s)?o(s):l(new Error(j))},r=()=>w(new Error(se)),e=S=>{for(let g of S.toString("utf8")){if(g===""||g===""){r();return}if(g==="\r"||g===`
6
+ `){w();return}if(g==="\x7F"?s=s.slice(0,-1):s+=g,s.length>131072){w(new Error(j));return}}};process.stdin.setRawMode(!0),process.stdin.on("data",e),process.stdin.once("end",r),process.stdin.resume()})}}process.argv[1]&&import.meta.url===Le(await ke(process.argv[1])).href&&(process.exitCode=await Ge(process.argv.slice(2)));export{Ye as createRuntime,H as readConfig,Ge as runCli,Me as terminalOwnerSign};
@@ -0,0 +1,120 @@
1
+ import { type Address, type Hex, type PublicClient } from 'viem';
2
+ import { type SwapQuote } from '@oakagentkit/core/swap';
3
+ import type { Recipe, ToolArgs, TypedDataRequest, UnsignedTx } from '@oakagentkit/core/types';
4
+ export declare const confirmationUnavailable = "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.";
5
+ export type ConfirmMode = 'ask' | 'auto';
6
+ export interface ConfirmationRequest {
7
+ hash: Hex;
8
+ summary: string;
9
+ }
10
+ export type Confirm = (request: ConfirmationRequest) => Promise<void>;
11
+ export interface Elicitor {
12
+ getClientCapabilities(): {
13
+ elicitation?: {
14
+ form?: unknown;
15
+ url?: unknown;
16
+ };
17
+ } | undefined;
18
+ elicitInput(params: {
19
+ mode: 'form';
20
+ message: string;
21
+ requestedSchema: {
22
+ type: 'object';
23
+ properties: {
24
+ confirm: {
25
+ type: 'boolean';
26
+ title: string;
27
+ default: false;
28
+ };
29
+ };
30
+ required: string[];
31
+ };
32
+ }, options: {
33
+ timeout: number;
34
+ }): Promise<{
35
+ action: string;
36
+ content?: Record<string, unknown>;
37
+ }>;
38
+ }
39
+ export declare const CONFIRMATION_SECONDS = 300;
40
+ export declare function createConfirmation(mode?: ConfirmMode, client?: () => Elicitor | undefined, timeout?: number): Confirm;
41
+ export type SigningTransaction = {
42
+ chainId: number;
43
+ to: Address;
44
+ data: Hex;
45
+ value: bigint;
46
+ gas: bigint;
47
+ nonce: number;
48
+ maxFeePerGas: bigint;
49
+ maxPriorityFeePerGas: bigint;
50
+ };
51
+ export declare function assertConfirmedBytes(rawTx: Hex, approved: SigningTransaction): void;
52
+ export declare function confirmTransaction(confirm: Confirm, tx: SigningTransaction, summary: string): Promise<SigningTransaction>;
53
+ export declare function snapshotTypedData(request: TypedDataRequest): TypedDataRequest;
54
+ export declare function confirmTypedData(confirm: Confirm, request: TypedDataRequest, action?: Pick<ActionRequest, 'name'>): Promise<TypedDataRequest>;
55
+ export declare function typedDataSummary(request: TypedDataRequest, action?: Pick<ActionRequest, 'name'>): string;
56
+ export interface ActionRequest {
57
+ name: string;
58
+ args: ToolArgs;
59
+ quote?: SwapQuote;
60
+ quoteArgs?: ToolArgs;
61
+ chainId?: number;
62
+ oakTokenAddress?: Address;
63
+ recipe?: Recipe;
64
+ destinations?: Address[];
65
+ }
66
+ export interface AssetInput {
67
+ token: Address;
68
+ amount: bigint;
69
+ id?: bigint;
70
+ }
71
+ export interface Transfer {
72
+ token: Address;
73
+ from: Address;
74
+ to: Address;
75
+ amount: bigint;
76
+ id?: bigint;
77
+ }
78
+ export declare function decodeTransfers(calls: readonly {
79
+ logs?: unknown;
80
+ }[], wallet: Address): Transfer[];
81
+ export interface ApprovalChange {
82
+ token: Address;
83
+ spender: Address;
84
+ amount: bigint;
85
+ expiration?: number;
86
+ permit2?: Address;
87
+ kind?: 'permit';
88
+ nft?: true;
89
+ }
90
+ export declare const MAX_PERMIT2_LIFETIME: number;
91
+ export declare function approvalDetails(tx: UnsignedTx, now?: number): ApprovalChange | undefined;
92
+ export declare function decodeApprovals(calls: readonly {
93
+ logs?: unknown;
94
+ }[], wallet: Address, now?: number): ApprovalChange[];
95
+ export declare const allowanceKey: (change: Pick<ApprovalChange, "token" | "spender">) => string;
96
+ type ApprovalCall = {
97
+ logs?: unknown;
98
+ status?: unknown;
99
+ returnData?: unknown;
100
+ data?: unknown;
101
+ };
102
+ export type AllowanceReader = (token: Address, spender: Address, blockNumber: bigint) => Promise<unknown>;
103
+ export type AllowancePair = Pick<ApprovalChange, 'token' | 'spender'>;
104
+ export type PostAllowanceSimulation = (index: number, pairs: readonly AllowancePair[]) => Promise<readonly ApprovalCall[]>;
105
+ export declare function allowanceCall(pair: AllowancePair, wallet: Address): {
106
+ account: `0x${string}`;
107
+ to: `0x${string}`;
108
+ data: `0x${string}`;
109
+ value: bigint;
110
+ gas: bigint;
111
+ };
112
+ export declare function assertApprovalChanges(calls: readonly ApprovalCall[], wallet: Address, txs: UnsignedTx[], now?: number, preState?: ReadonlyMap<string, bigint>, postStates?: readonly ReadonlyMap<string, bigint>[], pins?: readonly Address[]): ApprovalChange[];
113
+ export declare function verifyApprovalChanges(calls: readonly ApprovalCall[], wallet: Address, txs: UnsignedTx[], readAllowance: AllowanceReader, blockNumber: bigint, now?: number, simulatePostState?: PostAllowanceSimulation, pins?: readonly Address[]): Promise<ApprovalChange[]>;
114
+ export declare function assertOutflows(transfers: Transfer[], wallet: Address, inputs: AssetInput[], spent?: Map<string, bigint>, txs?: UnsignedTx[]): Map<string, bigint>;
115
+ export declare function assertModuleTransactions(txs: UnsignedTx[], action: ActionRequest): void;
116
+ export declare function assertActionTransactions(txs: UnsignedTx[], action: ActionRequest, wallet: Address, inputs: AssetInput[]): void;
117
+ export declare function summaryValue(value: string): string;
118
+ export declare function transactionSummary(name: string, tx: SigningTransaction, transfers: Transfer[], wallet: Address, txs: UnsignedTx[], approvals?: ApprovalChange[]): string;
119
+ export declare function actionInputs(action: ActionRequest, wallet: Address, client: Pick<PublicClient, 'readContract'>): Promise<AssetInput[]>;
120
+ export {};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v}from"./chunks/U3IXRJH7.js";import"./chunks/67E2KBUQ.js";export{b as CONFIRMATION_SECONDS,j as MAX_PERMIT2_LIFETIME,v as actionInputs,n as allowanceCall,m as allowanceKey,k as approvalDetails,s as assertActionTransactions,o as assertApprovalChanges,d as assertConfirmedBytes,r as assertModuleTransactions,q as assertOutflows,e as confirmTransaction,g as confirmTypedData,a as confirmationUnavailable,c as createConfirmation,l as decodeApprovals,i as decodeTransfers,f as snapshotTypedData,t as summaryValue,u as transactionSummary,h as typedDataSummary,p as verifyApprovalChanges};
@@ -0,0 +1,30 @@
1
+ import { type Address, type Hex } from 'viem';
2
+ export interface TraceCall {
3
+ account: Address;
4
+ to: Address;
5
+ data: Hex;
6
+ value: bigint;
7
+ blockNumber?: bigint;
8
+ gas?: bigint;
9
+ nonce?: number;
10
+ maxFeePerGas?: bigint;
11
+ maxPriorityFeePerGas?: bigint;
12
+ }
13
+ export declare function assertExecutionTrace(result: unknown, call: TraceCall, pins: readonly Address[]): void;
14
+ export declare function executionTraceRequest(call: TraceCall): {
15
+ method: string;
16
+ params: (string | {
17
+ maxPriorityFeePerGas?: `0x${string}` | undefined;
18
+ maxFeePerGas?: `0x${string}` | undefined;
19
+ nonce?: `0x${string}` | undefined;
20
+ gas?: `0x${string}` | undefined;
21
+ from: `0x${string}`;
22
+ to: `0x${string}`;
23
+ data: `0x${string}`;
24
+ value: `0x${string}`;
25
+ tracer?: undefined;
26
+ } | {
27
+ tracer: string;
28
+ })[];
29
+ };
30
+ export declare function createExecutionChecker(traceCall?: (call: TraceCall) => Promise<unknown>): (call: TraceCall, pins: readonly Address[], approvalToken?: Address) => Promise<"callTracer" | "simulation-only">;
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunks/2NJCYRBM.js";export{a as assertExecutionTrace,c as createExecutionChecker,b as executionTraceRequest};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i}from"./chunks/5HTX664S.js";import"./chunks/4B2GMIK7.js";export{d as challengeExpired,i as createIdentityClient,h as identityError,a as identityPaused,b as identityUnknown,c as ownerMismatch,f as signingCancelled,g as signingUnavailable,e as wrongNetwork};
1
+ import{a,b,c,d,e,f,g,h,i}from"./chunks/YR4WKA4P.js";import"./chunks/4B2GMIK7.js";export{d as challengeExpired,i as createIdentityClient,h as identityError,a as identityPaused,b as identityUnknown,c as ownerMismatch,f as signingCancelled,g as signingUnavailable,e as wrongNetwork};
@@ -0,0 +1,4 @@
1
+ import { type Address, type PublicClient } from 'viem';
2
+ import type { ActionRequest } from './confirm.js';
3
+ export declare function moduleDestinations(action: ActionRequest, chainId?: number): Address[];
4
+ export declare function resolveModuleDestinations(action: ActionRequest, client: Pick<PublicClient, 'readContract'>, chainId?: number): Promise<Address[]>;
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunks/67E2KBUQ.js";export{a as moduleDestinations,b as resolveModuleDestinations};
@@ -1 +1 @@
1
- import{a}from"./chunks/U4YOG57X.js";import"./chunks/HGFLLHB6.js";import"./chunks/HLAZAI2Q.js";import"./chunks/QIDB35RS.js";import"./chunks/YVAFJM4Y.js";export{a as ensureSubscribed};
1
+ import{a}from"./chunks/OB7JDPFV.js";import"./chunks/UTTRLIY5.js";import"./chunks/U5VW3XSD.js";import"./chunks/YVAFJM4Y.js";import"./chunks/IVR4JOHU.js";import"./chunks/U3IXRJH7.js";import"./chunks/2NJCYRBM.js";import"./chunks/QIDB35RS.js";import"./chunks/67E2KBUQ.js";export{a as ensureSubscribed};
@@ -1,3 +1,5 @@
1
+ import { type ActionRequest, type Confirm } from './confirm.js';
2
+ import { type TraceCall } from './execution-trace.js';
1
3
  import { erc20Abi, type Address, type Hex } from 'viem';
2
4
  import type { SenderResult, TypedDataRequest, UnsignedTx } from '@oakagentkit/core/types';
3
5
  import { type WalletSigner } from './wallet.js';
@@ -12,13 +14,28 @@ type Call = {
12
14
  to: Address;
13
15
  data: Hex;
14
16
  value: bigint;
17
+ gas?: bigint;
18
+ nonce?: number;
15
19
  };
20
+ type SimulationCall = Call & ({
21
+ gasPrice?: bigint;
22
+ maxFeePerGas?: never;
23
+ maxPriorityFeePerGas?: never;
24
+ } | {
25
+ gasPrice?: never;
26
+ maxFeePerGas: bigint;
27
+ maxPriorityFeePerGas: bigint;
28
+ });
16
29
  type SimulatedCall = {
30
+ data?: Hex;
31
+ returnData?: Hex;
32
+ logs?: unknown;
17
33
  status: 'success' | 'failure';
18
34
  gasUsed: bigint;
19
35
  maxUsedGas?: bigint;
20
36
  };
21
37
  export interface ChainClient {
38
+ traceCall?(call: TraceCall): Promise<unknown>;
22
39
  getChainId(): Promise<number>;
23
40
  getBalance(args: {
24
41
  address: Address;
@@ -28,10 +45,11 @@ export interface ChainClient {
28
45
  estimateGas(args: Call): Promise<bigint>;
29
46
  simulateBlocks(args: {
30
47
  blocks: [{
31
- calls: Call[];
48
+ calls: SimulationCall[];
32
49
  }];
33
50
  validation: false;
34
51
  traceTransfers: true;
52
+ blockNumber?: bigint;
35
53
  }): Promise<readonly {
36
54
  calls: readonly SimulatedCall[];
37
55
  }[]>;
@@ -40,6 +58,7 @@ export interface ChainClient {
40
58
  abi: typeof erc20Abi;
41
59
  functionName: 'allowance';
42
60
  args: readonly [Address, Address];
61
+ blockNumber?: bigint;
43
62
  }): Promise<unknown>;
44
63
  getTransactionCount(args: {
45
64
  address: Address;
@@ -61,6 +80,7 @@ export interface ChainClient {
61
80
  number: bigint | null;
62
81
  timestamp: bigint;
63
82
  baseFeePerGas?: bigint | null;
83
+ gasLimit?: bigint;
64
84
  }>;
65
85
  getTransactionReceipt(args: {
66
86
  hash: Hex;
@@ -80,12 +100,17 @@ export interface ChainClient {
80
100
  }): Promise<Receipt>;
81
101
  }
82
102
  export type Finality = number | 'safe' | 'finalized';
83
- export declare const NOT_AFTER_SECONDS = 12;
103
+ export declare const NOT_AFTER_SECONDS = 300;
84
104
  export type PreparedTx = UnsignedTx & {
85
105
  notAfter?: number;
86
106
  };
107
+ export type Reprepare = () => Promise<{
108
+ txs: PreparedTx[];
109
+ action?: ActionRequest;
110
+ }>;
87
111
  export interface SenderOptions {
88
112
  signer?: WalletSigner;
113
+ confirm?: Confirm;
89
114
  clientFor?: (chainId: number) => ChainClient;
90
115
  allowedChainIds?: readonly number[];
91
116
  directory?: string;
@@ -97,16 +122,16 @@ export interface SenderOptions {
97
122
  }
98
123
  export interface LockedSender {
99
124
  approvalStatus?(): Promise<string>;
100
- send(txs: PreparedTx[]): Promise<SenderResult>;
101
- signTypedData(request: TypedDataRequest): Promise<Hex>;
125
+ send(txs: PreparedTx[], action?: ActionRequest, reprepare?: Reprepare): Promise<SenderResult>;
126
+ signTypedData(request: TypedDataRequest, action?: Pick<ActionRequest, 'name'>): Promise<Hex>;
102
127
  assertCanPayGas(txs: PreparedTx[]): Promise<void>;
103
128
  }
104
129
  export declare class SenderError extends Error {
105
130
  }
106
131
  export declare function createSender(options?: SenderOptions): {
107
132
  withAction: <T>(action: (locked: LockedSender) => Promise<T>) => Promise<T>;
108
- send: (txs: UnsignedTx[]) => Promise<SenderResult>;
109
- signTypedData: (request: TypedDataRequest) => Promise<`0x${string}`>;
133
+ send: (txs: PreparedTx[], action?: ActionRequest, reprepare?: Reprepare) => Promise<SenderResult>;
134
+ signTypedData: (request: TypedDataRequest, action?: Pick<ActionRequest, "name">) => Promise<`0x${string}`>;
110
135
  assertCanPayGas: (txs: UnsignedTx[]) => Promise<void>;
111
136
  blockNumber: (chainId?: number) => Promise<bigint>;
112
137
  };
@@ -1 +1 @@
1
- import{a,b,c,d,e,f}from"./chunks/HLAZAI2Q.js";import"./chunks/QIDB35RS.js";import"./chunks/YVAFJM4Y.js";export{a as NOT_AFTER_SECONDS,b as SenderError,f as assertCanPayGas,c as createSender,d as send,e as signTypedData};
1
+ import{a,b,c,d,e,f}from"./chunks/U5VW3XSD.js";import"./chunks/YVAFJM4Y.js";import"./chunks/IVR4JOHU.js";import"./chunks/U3IXRJH7.js";import"./chunks/2NJCYRBM.js";import"./chunks/QIDB35RS.js";import"./chunks/67E2KBUQ.js";export{a as NOT_AFTER_SECONDS,b as SenderError,f as assertCanPayGas,c as createSender,d as send,e as signTypedData};
@@ -19,6 +19,8 @@ export declare function createSetup(options: {
19
19
  save(identity: SessionIdentity): Promise<void>;
20
20
  signOwner?: OwnerSign;
21
21
  }): (request: SetupRequest) => Promise<{
22
- identity: SessionIdentity;
23
22
  summary: string;
23
+ identity: SessionIdentity;
24
+ hashes: string[];
25
+ status: string;
24
26
  }>;
@@ -1 +1 @@
1
- import{a}from"./chunks/ILJVXWGD.js";import"./chunks/5HTX664S.js";import"./chunks/4B2GMIK7.js";import"./chunks/VZCMAMZL.js";import"./chunks/GONTF7K4.js";export{a as createSetup};
1
+ import{a}from"./chunks/44YOYZLT.js";import"./chunks/VZCMAMZL.js";import"./chunks/GONTF7K4.js";import"./chunks/YVAFJM4Y.js";import"./chunks/IVR4JOHU.js";import"./chunks/YR4WKA4P.js";import"./chunks/4B2GMIK7.js";export{a as createSetup};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f}from"./chunks/HGFLLHB6.js";import"./chunks/HLAZAI2Q.js";import"./chunks/QIDB35RS.js";import"./chunks/YVAFJM4Y.js";export{b as HOLDER_PRICE,c as RENEW_WINDOW,f as SubscriptionLifecycle,e as assertDeployment,a as subscriptionAbi,d as usdgDomain};
1
+ import{a,b,c,d,e,f}from"./chunks/UTTRLIY5.js";import"./chunks/U5VW3XSD.js";import"./chunks/YVAFJM4Y.js";import"./chunks/IVR4JOHU.js";import"./chunks/U3IXRJH7.js";import"./chunks/2NJCYRBM.js";import"./chunks/QIDB35RS.js";import"./chunks/67E2KBUQ.js";export{b as HOLDER_PRICE,c as RENEW_WINDOW,f as SubscriptionLifecycle,e as assertDeployment,a as subscriptionAbi,d as usdgDomain};
@@ -0,0 +1,7 @@
1
+ import { type Confirm, type ConfirmMode } from './confirm.js';
2
+ export interface TerminalConfirmationOptions {
3
+ isTTY?: () => boolean;
4
+ write?: (text: string) => void;
5
+ ask?: (prompt: string) => Promise<string>;
6
+ }
7
+ export declare function createTerminalConfirmation(mode?: ConfirmMode, options?: TerminalConfirmationOptions): Confirm;
@@ -0,0 +1 @@
1
+ import{a}from"./chunks/I5LKYO3W.js";import"./chunks/U3IXRJH7.js";import"./chunks/67E2KBUQ.js";export{a as createTerminalConfirmation};
@@ -1 +1 @@
1
- import{a}from"./chunks/4X7FLHGQ.js";export{a as version};
1
+ import{a}from"./chunks/RGOGWTRI.js";export{a as version};
@@ -1,4 +1,4 @@
1
- import{c as K}from"./chunks/QIDB35RS.js";import{a as Y,c as P,d as m}from"./chunks/GONTF7K4.js";import{createCipheriv as F,createDecipheriv as G,createHash as Q,randomBytes as x,randomInt as j,randomUUID as L,scrypt as V}from"node:crypto";import{constants as d}from"node:fs";import{lstat as C,rename as U,unlink as $}from"node:fs/promises";import{homedir as Z,platform as ee}from"node:os";import{join as W}from"node:path";import{stdin as T,stdout as A}from"node:process";import{createInterface as te}from"node:readline";import{english as J,generateMnemonic as re,generatePrivateKey as ie,mnemonicToAccount as ne,privateKeyToAccount as z}from"viem/accounts";var a=class extends Error{},ae="run this in your own terminal, not through the agent",_="Wallet could not be unlocked. Check the local keychain or passphrase.",oe="Oak wallet data key",se={N:131072,r:8,p:1,maxmem:256*1024*1024},q="0x0000000000000000000000000000000000000000";function R(){if(T.isTTY!==!0||A.isTTY!==!0)throw new a(ae)}function h(t){R(),A.write(t)}async function S(t,e=!1){R();let r=T.isRaw,i=te({input:T,...e?{output:A}:{},terminal:!0,historySize:0});try{return h(t),await new Promise((c,n)=>{i.once("SIGINT",()=>n(new a("Wallet input cancelled."))),i.once("close",()=>n(new a("Wallet input cancelled."))),i.once("error",()=>n(new a("Wallet input failed."))),i.question("",s=>{s.length>1024?n(new a("Wallet input is too long.")):c(s)})})}finally{i.close(),T.setRawMode(r===!0),h(`
1
+ import{a as Y,c as P,d as m}from"./chunks/GONTF7K4.js";import{c as K}from"./chunks/QIDB35RS.js";import{createCipheriv as F,createDecipheriv as G,createHash as Q,randomBytes as x,randomInt as j,randomUUID as L,scrypt as V}from"node:crypto";import{constants as d}from"node:fs";import{lstat as C,rename as U,unlink as $}from"node:fs/promises";import{homedir as Z,platform as ee}from"node:os";import{join as W}from"node:path";import{stdin as T,stdout as A}from"node:process";import{createInterface as te}from"node:readline";import{english as J,generateMnemonic as re,generatePrivateKey as ie,mnemonicToAccount as ne,privateKeyToAccount as z}from"viem/accounts";var a=class extends Error{},ae="run this in your own terminal, not through the agent",_="Wallet could not be unlocked. Check the local keychain or passphrase.",oe="Oak wallet data key",se={N:131072,r:8,p:1,maxmem:256*1024*1024},q="0x0000000000000000000000000000000000000000";function R(){if(T.isTTY!==!0||A.isTTY!==!0)throw new a(ae)}function h(t){R(),A.write(t)}async function S(t,e=!1){R();let r=T.isRaw,i=te({input:T,...e?{output:A}:{},terminal:!0,historySize:0});try{return h(t),await new Promise((c,n)=>{i.once("SIGINT",()=>n(new a("Wallet input cancelled."))),i.once("close",()=>n(new a("Wallet input cancelled."))),i.once("error",()=>n(new a("Wallet input failed."))),i.question("",s=>{s.length>1024?n(new a("Wallet input is too long.")):c(s)})})}finally{i.close(),T.setRawMode(r===!0),h(`
2
2
  `)}}function ce(t){let e=r=>r.replace(/^["'“”‘’`]+|["'“”‘’`]+$/g,"").trim();return e(e(t.normalize("NFKD").trim().toLowerCase()).replace(/^\d+[.)]\s*/,""))}function l(){let t=W(Z(),".oak");return{directory:t,file:W(t,"wallet.enc")}}async function B(t=!1){await Y(l().directory,t)}async function I(t){let e=ee();if(!["darwin","linux","win32"].includes(e))throw new Error("Unsupported keychain");let{Entry:r}=await import("@napi-rs/keyring");return new r(oe,t,e==="linux"?{linux:{store:"secret-service"}}:void 0)}function X(t,e){let r=Buffer.from(t,"utf8");return new Promise((i,c)=>{V(r,Buffer.from(e,"hex"),32,se,(n,s)=>{r.fill(0),n?c(new Error("Key derivation failed")):i(s)})})}function M(t){return Buffer.from(JSON.stringify({version:1,cipher:"aes-256-gcm",storage:t}))}function b(t,e){return typeof t=="string"&&t.length===e*2&&/^[0-9a-f]+$/.test(t)}function le(t){let e=JSON.parse(t);if(!e||e.version!==1||e.cipher!=="aes-256-gcm"||!b(e.iv,12)||!b(e.tag,16)||!b(e.ciphertext,32))throw new Error("Invalid wallet");let r=e.storage;if((r?.kind==="keychain"||r?.kind==="file")&&b(r.id,16))return{version:1,cipher:"aes-256-gcm",storage:{kind:r.kind,id:r.id},iv:e.iv,tag:e.tag,ciphertext:e.ciphertext};if(r?.kind==="scrypt"&&b(r.salt,32)&&r.N===131072&&r.r===8&&r.p===1)return{version:1,cipher:"aes-256-gcm",storage:{kind:"scrypt",salt:r.salt,N:131072,r:8,p:1},iv:e.iv,tag:e.tag,ciphertext:e.ciphertext};throw new Error("Invalid wallet storage")}async function H(){let t,e;try{await B();let r=await m(l().file,d.O_RDONLY,4096),i;try{i=le(await r.readFile("utf8"))}finally{await r.close()}if(i.storage.kind==="keychain"){let s=(await I(i.storage.id)).getSecret();if(!s||s.length!==32||s.some(f=>!Number.isInteger(f)||f<0||f>255))throw new Error("Missing data key");t=Buffer.from(s),s.fill(0)}else if(i.storage.kind==="file"){let s=await m(W(l().directory,`wallet-key-${i.storage.id}`),d.O_RDONLY,32);try{t=await s.readFile()}finally{await s.close()}if(t.length!==32)throw new Error("Invalid data key")}else{if(T.isTTY!==!0||A.isTTY!==!0)throw new a("Passphrase wallets cannot start stdio MCP. Use a persistent OS keychain for MCP, or run Oak CLI commands in your own terminal. Never pass a passphrase through MCP, argv or environment variables.");t=await X(await S("Wallet passphrase: "),i.storage.salt)}let c=G("aes-256-gcm",t,Buffer.from(i.iv,"hex"));if(c.setAAD(M(i.storage)),c.setAuthTag(Buffer.from(i.tag,"hex")),e=c.update(Buffer.from(i.ciphertext,"hex")),c.final(),e.length!==32)throw new Error("Invalid key");let n=e;return e=void 0,n}catch(r){throw r instanceof a?r:new a(_)}finally{t?.fill(0),e?.fill(0)}}function fe(t){if(t.length!==24)return!1;let e=t.map(n=>J.indexOf(n));if(e.some(n=>n<0))return!1;let r=e.map(n=>n.toString(2).padStart(11,"0")).join(""),i=Buffer.from(Array.from({length:32},(n,s)=>Number.parseInt(r.slice(s*8,s*8+8),2))),c=Q("sha256").update(i).digest();try{return c[0]===Number.parseInt(r.slice(256),2)}finally{i.fill(0),c.fill(0)}}async function Se(t={}){R();try{return await K(q,()=>de(t),{directory:l().directory})}catch(e){throw e instanceof a?e:new a("Wallet creation failed. Keep your confirmed backup; check local storage before retrying.")}}async function de(t){let e,r,i,c=!1,n={mnemonic:"",words:[]},s;try{if(t.replace&&!t.recover)throw new a("Use oak init --recover --replace to replace a wallet.");await B(!0);let f=await C(l().file).catch(o=>{if(o.code!=="ENOENT")throw o});if(f&&!t.replace)throw new a("Wallet already exists. Use oak address or oak export. Recovery replacement needs oak init --recover --replace.");if(f&&await(await m(l().file,d.O_RDONLY,4096)).close(),h(`setup is trusted because the owner runs it, not because a terminal exists
3
3
  `),t.recover){if(n.mnemonic=(await S("Enter your 24 recovery words or exported private key (hidden): ")).normalize("NFKD").trim().toLowerCase().replace(/\s+/g," "),n.words=n.mnemonic.split(" "),!/^0x[0-9a-f]{64}$/.test(n.mnemonic)&&!fe(n.words))throw new a("Recovery words are not valid. Check all 24 words and their order, or use the exported private key, then retry in your own terminal.")}else{h(`Write down these recovery words privately. They are shown once. Oak cannot recover a lost key.
4
4
  `),n.mnemonic=re(J,256),h(`${n.mnemonic}
package/package.json CHANGED
@@ -1,21 +1,11 @@
1
1
  {
2
2
  "name": "@oakagentkit/addon",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "engines": {
7
7
  "node": ">=22"
8
8
  },
9
- "scripts": {
10
- "lint": "eslint \"src/**/*.{js,mjs,cjs,ts,mts,cts,tsx}\" \"test/**/*.{js,mjs,cjs,ts,mts,cts,tsx}\" --no-error-on-unmatched-pattern --max-warnings 0",
11
- "typecheck": "pnpm --workspace-root run typecheck:package packages/addon/tsconfig.json",
12
- "test": "vitest run --passWithNoTests",
13
- "build": "node ../../scripts/release/build.mjs addon",
14
- "prepack": "node ../../scripts/release/prepare.mjs addon",
15
- "postpack": "node ../../scripts/release/prepare.mjs addon --postpack",
16
- "prepublishOnly": "node ../../scripts/release/prepare.mjs addon --verify",
17
- "postpublish": "node ../../scripts/release/prepare.mjs addon --restore"
18
- },
19
9
  "bin": {
20
10
  "oak": "build/dist/cli.js"
21
11
  },
@@ -26,7 +16,7 @@
26
16
  "LICENSE"
27
17
  ],
28
18
  "dependencies": {
29
- "@oakagentkit/core": "0.1.0",
19
+ "@oakagentkit/core": "0.1.1",
30
20
  "@modelcontextprotocol/sdk": "1.32.2",
31
21
  "@napi-rs/keyring": "2.1.2",
32
22
  "ajv": "8.20.0",
@@ -52,5 +42,11 @@
52
42
  "types": "./build/dist/*.d.ts",
53
43
  "default": "./build/dist/*.js"
54
44
  }
45
+ },
46
+ "scripts": {
47
+ "lint": "eslint \"src/**/*.{js,mjs,cjs,ts,mts,cts,tsx}\" \"test/**/*.{js,mjs,cjs,ts,mts,cts,tsx}\" --no-error-on-unmatched-pattern --max-warnings 0",
48
+ "typecheck": "pnpm --workspace-root run typecheck:package packages/addon/tsconfig.json",
49
+ "test": "vitest run --passWithNoTests",
50
+ "build": "node ../../scripts/release/build.mjs addon"
55
51
  }
56
- }
52
+ }
@@ -1 +0,0 @@
1
- var o="0.1.0";export{o as a};
@@ -1 +0,0 @@
1
- import{a as E,c as S}from"./4B2GMIK7.js";import{getAddress as R}from"viem";import{buildIdentityLinkTypedData as x,canonicalSessionIdentity as g}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.",f="Identity status is unavailable. Please try again. Reads remain available; actions are paused.",y=class extends Error{constructor(){super(w)}};function b(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.",O="Owner signing cancelled. Run the identity command again when ready.",v="Owner signing requires your terminal. Run oak setup link <agentId> or oak identity unlink --owner <linkId> there.";function k(e){if(e instanceof y)return e;let i=e instanceof Error?e.message:typeof e=="string"?e:"";return/cancelled|canceled/i.test(i)?new Error(O):[w,f,h,l,I,v].includes(i)?new Error(i):/identity changed|link revoked|reads remain available/i.test(i)?new Error(w):/challenge.*expir/i.test(i)?new Error(l):/network|registry|chain/i.test(i)?new Error(I):/owner|signature|proof/i.test(i)?new Error(h):new Error(w)}function N(e){let i=S({...e,refreshIdentity:async a=>{let t=await E({signer:e.signer,network:e.network,now:e.now});try{let r=await m(new URL("/v1/identity/status",e.base),{method:"POST",redirect:"error",headers:{"content-type":"application/json","X-Oak-Session":t},body:JSON.stringify({identity:a}),signal:AbortSignal.timeout(3e4)}),n=await r.json();if(r.ok&&n?.ok===!0&&n.data&&b(n.data)){await e.clearIdentity?.();return}}catch{}return a}}),m=e.fetch??fetch,c=e.now??(()=>Math.floor(Date.now()/1e3));async function u(a,t){try{let r=`/v1/identity/${a}`,n=JSON.stringify(t),d=await m(new URL(r,e.base),{method:"POST",redirect:"error",headers:{"content-type":"application/json",...await i.headers("POST",r,n)},body:n,signal:AbortSignal.timeout(3e4)}),o=await d.json();if(!d.ok||!o||o.ok!==!0||!o.data||typeof o.data!="object")throw a==="status"?new Error(f):k(o?.error);return o.data}catch(r){throw a==="status"?new Error(f):k(r)}}async function p(a){let t=await u("status",{identity:a});if(b(t))throw new y;if(t.verified!==!0)throw new Error(f);return t}return{sessions:i,async requireVerified(){if(e.loadIdentity){let t=await e.loadIdentity();JSON.stringify(t)!==JSON.stringify(i.identity)&&i.setIdentity(t)}let a=i.identity;if(!a)throw new Error("Run oak setup to register or link an ERC-8004 identity first. Reads remain available; actions are paused.");try{await p(a)}catch(t){throw t instanceof y&&(i.setIdentity(void 0),await e.clearIdentity?.()),t}},async unlink(a={actor:"agent"},t){let r=a.linkId??i.identity?.linkId;if(!r||!/^0x[0-9a-f]{64}$/.test(r))throw new Error("Provide the linkId to unlink, or link an identity first.");if(!["agent","owner"].includes(a.actor))throw new Error("Choose agent or owner to unlink.");let n;if(a.actor==="owner"){if(!t)throw new Error("Owner signing is unavailable. Run oak identity unlink --owner <linkId> in your terminal.");let o=await u("challenge",{linkId:r});try{if(x(o),g({chainId:o.chainId,registry:o.registry,agentId:o.agentId},e.network),o.audience!==JSON.stringify([e.base.origin,"unlink",r]))throw new Error(I);if(BigInt(o.issuedAt)>BigInt(c())||BigInt(o.expiresAt)<=BigInt(c()))throw new Error(l);let s=await t({...o});if(BigInt(o.expiresAt)<=BigInt(c()))throw new Error(l);if(!/^0x(?:[0-9a-fA-F]{2})+$/.test(s))throw new Error(h);n={link:o,signature:s}}catch(s){throw k(s)}}if((await u("unlink",{linkId:r,...n?{proof:n}:{}})).unlinked!==!0)throw new Error(w);return i.identity?.linkId===r&&(i.setIdentity(void 0),await e.clearIdentity?.()),{unlinked:!0,summary:"Identity link removed. Reads remain available; linked actions are paused."}},async accept(a){let t=g(a,e.network);return await p(t),i.setIdentity(t),t},async link(a,t){let r=g(a,e.network);if(r.linkId)throw new Error("Request a fresh identity link without an old linkId.");let n=await u("challenge",{identity:r});try{if(x(n),n.chainId!==r.chainId||n.registry!==r.registry||n.agentId!==r.agentId||R(n.agentWallet)!==e.signer.address||n.audience!==e.base.origin)throw new Error(I);if(BigInt(n.issuedAt)>BigInt(c())||BigInt(n.expiresAt)<=BigInt(c()))throw new Error(l);let d=await t({...n});if(BigInt(n.expiresAt)<=BigInt(c()))throw new Error(l);if(typeof d!="string"||!/^0x(?:[0-9a-fA-F]{2})+$/.test(d))throw new Error(h);let o=await u("link",{proof:{link:n,signature:d}}),s=g(o.identity,e.network);if(!s.linkId||s.agentId!==r.agentId)throw new Error(w);return await p(s),i.setIdentity(s),s}catch(d){throw k(d)}}}}export{w as a,f as b,h as c,l as d,I as e,O as f,v as g,k as h,N as i};
@@ -1,7 +0,0 @@
1
- import{c as ge}from"./HLAZAI2Q.js";import{a as pe}from"./4X7FLHGQ.js";import{i as be}from"./5HTX664S.js";import{a as ke,c as ve}from"./VZCMAMZL.js";import{b as we,c as he,e as ye}from"./4LWKW7PM.js";import{a as G,b as me,c as K}from"./YVAFJM4Y.js";import{isReadDiscovery as Q}from"@oakagentkit/core/tool-policy";import{LAUNCH_ACTION as Me,LAUNCH_TOOLS as xe}from"@oakagentkit/core/launch";import{rejectWalletSecrets as Ne}from"@oakagentkit/core/secret-fields";import{untrustedText as Te}from"@oakagentkit/core/untrusted";import{createModule as Ce}from"@oakagentkit/core/modules/kyberswap/index";import{createModule as $e}from"@oakagentkit/core/modules/velora/index";import{createModule as Ue}from"@oakagentkit/core/modules/steakhouse/index";import{createModule as Be}from"@oakagentkit/core/modules/spark/index";import{createModule as He}from"@oakagentkit/core/modules/netnet/index";import{createModule as Le}from"@oakagentkit/core/modules/longbow/index";import{createModule as De}from"@oakagentkit/core/modules/grove/index";import{createModule as Je}from"@oakagentkit/core/modules/beefy/index";import{createModule as Fe}from"@oakagentkit/core/modules/pons/index";import{createModule as Ve}from"@oakagentkit/core/modules/orbio/index";import{createModule as We}from"@oakagentkit/core/modules/hoodlock/index";import{createModule as ze}from"@oakagentkit/core/modules/merkl/index";import{createModule as Ge}from"@oakagentkit/core/modules/relay/index";import{createModule as Ke}from"@oakagentkit/core/modules/lighter/index";import{createModule as Ae}from"@oakagentkit/core/modules/erc8004/index";import{createModule as Qe}from"@oakagentkit/core/modules/hoodag/index";import{createModule as Xe}from"@oakagentkit/core/modules/heyresearch/index";import{createModule as Ye}from"@oakagentkit/core/modules/priors/index";import{createModule as Ze}from"@oakagentkit/core/modules/morpho/index";import{createModule as er}from"@oakagentkit/core/modules/uniswap/index";import{createModule as rr}from"@oakagentkit/core/modules/hookr/index";import{createModule as tr}from"@oakagentkit/core/modules/meridian/index";import{createModule as nr}from"@oakagentkit/core/modules/tickerspring/index";import{createModule as ir}from"@oakagentkit/core/modules/clanker/index";import{createModule as or}from"@oakagentkit/core/modules/poolstrade/index";import{isDeepStrictEqual as X}from"node:util";import{createPublicClient as ar,custom as cr,encodeAbiParameters as Y,keccak256 as Z,parseAbiParameters as ee,zeroAddress as _e}from"viem";import{Server as dr}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as ur}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as lr,ListToolsRequestSchema as fr}from"@modelcontextprotocol/sdk/types.js";import{ADDRESSES as pr,CHAIN_ID as ae,NETWORKS as mr,resolveNetwork as wr}from"@oakagentkit/core/addresses";import{createModuleContext as hr,createModuleRegistry as yr}from"@oakagentkit/core/module";import{unsignedTx as Pe}from"@oakagentkit/core/tx";var sr=[Ce,$e,Ue,Be,He,Le,De,Je,Fe,Ve,We,ze,Ge,Ke,Ae,Qe,Xe,Ye,Ze,er,rr,tr,nr,ir,or],re="as-is, not reviewed by Oak",te=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"]),ne="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.",H=()=>{throw new Error("Manifest construction must not execute a tool.")};function gr(e="mainnet"){let s=ar({transport:cr({request:H})}),f=hr({network:e,clientFor:()=>s,http:H,preview:H,quoteSwap:H,buildSwap:H}),m=(p,g={},I=[])=>({name:p,description:`Oak ${p}`,inputSchema:{type:"object",additionalProperties:!1,properties:g,required:I}}),a=[m("find_token",{query:{type:"string",minLength:1,description:"Token name, symbol or address on Robinhood Chain. Pons and pools.trade require an address."}},["query"]),m("balances"),m("price",{token:{type:"string"}},["token"]),m("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"]),m("swap",{quoteId:{type:"string"}},["quoteId"]),m("preview",{txs:{type:"array"}},["txs"]),m("history",{limit:{type:"integer",minimum:1}}),m("positions"),m("account")],h=yr(f,e==="testnet"?[Ae]:sr);if(h.errors.length)throw new Error("Oak module manifest could not be loaded.");return[...a,...h.tools.map(p=>({name:p.name,description:`Oak ${p.name}`,inputSchema:p.inputSchema}))]}function b(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function q(e,s){return typeof e=="string"&&typeof s=="string"&&e.toLowerCase()===s.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 V(e){if(!b(e))throw new Error("Provide a JSON object.");return Ne(e),e}function br(e){let s=new URL(e);if(s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(s.hostname))||s.username||s.password||s.search||s.hash)throw new Error("Use an HTTPS Oak server URL, or HTTP on loopback for local testing.");return s}var ie=pr[ae].meridian,kr=[{name:"predictionHash",type:"bytes32"},{name:"signer",type:"address"},{name:"collateral",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}],vr=[{name:"tradeHash",type:"bytes32"},{name:"signer",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}];function oe(e,s,f,m,a,h,p){let g=e==="meridian_buy";if(!g&&e!=="meridian_sell")throw new Error("Unexpected project continuation.");let I=(g?ie.PredictionMarketEscrow:ie.SecondaryMarketEscrow).address;if(a.chainId!==ae||!q(a.wallet,f)||!q(a.escrowContract,I)||typeof a.requestId!="string"||!a.requestId)throw new Error("Project chain, domain or wallet mismatch.");if(h&&a.requestId!==h.requestId)throw new Error("Project exchange changed during continuation.");let O=h?.stage;if(a.stage==="prerequisites"){if(O!==void 0&&O!=="prerequisites"||!m.length||m.some(S=>S.kind!=="tx"))throw new Error("Unexpected prerequisite step order.");return}if(m.length!==1||m[0]?.kind!=="typedData"||!b(a.request)||!X(a.request,m[0].request))throw new Error("Project must return exactly its current typed-data step.");if(g?a.stage!=="primary_accept"||O!==void 0&&O!=="prerequisites":a.stage==="secondary_start"?O!==void 0&&O!=="prerequisites":a.stage!=="secondary_accept"||O!=="secondary_start")throw new Error("Unexpected project step order.");let A=m[0].request,D=g?"MintApproval":"TradeApproval";if(!X(A.domain,{name:g?"PredictionMarketEscrow":"SecondaryMarketEscrow",version:"1",chainId:ae,verifyingContract:I})||A.primaryType!==D||!X(A.types,{[D]:g?kr:vr})||!q(A.message.signer,f))throw new Error("Project typed-data domain, type or wallet mismatch.");let j=[R(A.message.deadline)];if(R(A.message.nonce),a.stage!=="secondary_start"){if(!b(a.winningBid)||typeof a.auctionId!="string"||!a.auctionId||a.winningBid.auctionId!==a.auctionId)throw new Error("Project winning bid or auction mismatch.");j.push(R(a.acceptDeadline)),g?j.push(R(a.winningBid.counterpartyDeadline)):a.winningBid.buyerDeadline!==void 0&&j.push(R(a.winningBid.buyerDeadline))}if(j.some(S=>BigInt(p)>=S))throw new Error("Meridian exchange expired. Start a fresh auction.");let _=a.winningBid,P;if(g){let S=s.picks,C=Z(Y(ee("(address conditionResolver,bytes conditionId,uint8 predictedOutcome)[]"),[S]));if(P=Z(Y(ee("bytes32,uint256,uint256,address,address,address,bytes"),[C,R(s.stake),R(_?.counterpartyCollateral),f,_?.counterparty,_e,"0x"])),A.message.collateral!==s.stake)throw new Error("Project collateral differs from the requested stake.")}else if(P=Z(Y(ee("address,address,address,address,uint256,uint256"),[s.token,ie.CollateralToken_USDe.address,f,a.stage==="secondary_start"?_e:_?.buyer,R(s.amount),a.stage==="secondary_start"?0n:R(_?.price)])),h?.stage==="secondary_start"){let S=h.request;if(S.message.nonce!==A.message.nonce||S.message.deadline!==A.message.deadline)throw new Error("Project changed its signing nonce or deadline.")}if(A.message[g?"predictionHash":"tradeHash"]!==P)throw new Error("Project hash does not match the current winning terms.")}var xr=12;function T(e){return e>1e11?Math.floor(e/1e3):Math.floor(e)}function L(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return T(e);if(typeof e=="bigint"&&e>=0n)return T(Number(e));if(typeof e=="string"&&e.trim()){if(/^[0-9]+$/.test(e.trim()))return T(Number(e.trim()));let s=Date.parse(e);if(Number.isFinite(s)&&s>=0)return T(s)}}function W(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 N(e,s){for(let f of s?["sender","wallet","from","account"]:["sender","wallet","account"])if(typeof e[f]=="string")return e[f]}function se(e){if(!(!Array.isArray(e)||!e.length))try{return e.map(s=>{if(!b(s))throw new Error("Invalid preview transaction.");let f=typeof s.description=="string"&&s.description.trim()?s.description:"preview";return Pe({...s,description:f})})}catch{return}}function Se(e,s){return e.length===s.length&&e.every((f,m)=>{let a=s[m];return q(f.to,a.to)&&q(f.data,a.data)&&f.value===a.value&&f.chainId===a.chainId})}function ft(e){let s=br(e.serverUrl),f=wr(e.network),{chainId:m}=mr[f];if(f==="testnet"&&!e.sender)throw new Error("Configure a testnet sender before starting the bridge.");let a=e.fetch??fetch,h=e.identity??be({base:s,signer:e.signer,network:f,fetch:a,now:e.now}),p=e.now??(()=>Math.floor(Date.now()/1e3)),g=e.previewTtlSeconds??xr,I=e.sender??ge({signer:e.signer,preview:M,now:e.now,notAfterSeconds:g});if((e.launchOnly||e.privateTestMode)&&f!=="mainnet")throw new Error("Launch bootstrap requires mainnet chain 4663.");let O=gr(f).filter(r=>!e.launchOnly||xe.has(r.name)),A=new Set(O.map(r=>r.name)),D=e.recipes??(()=>ye()),j=async()=>e.launchOnly?[]:(await D()).filter(r=>r.chainId===m),_,P,S,C=!1,J;async function ce(r){try{if(typeof I.blockNumber=="function")return await I.blockNumber(r);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 U(r,o){if(r==="account"){if(V(o),Object.keys(o).length)throw new Error("Provide an empty JSON object.");let n=ve(e.signer.address,f);try{let{data:t}=await $(r,o);if(!b(t))throw new Error("Invalid account status.");return{...t,...n}}catch{return{...n,statusUnavailable:!0,summary:"Subscription status is unavailable. Retry account when the Oak service is reachable; do not assume action access."}}}return(await $(r,V(o))).data}async function $(r,o){if(!A.has(r))throw new Error("Unknown Oak tool.");let n=JSON.stringify(o);if(Buffer.byteLength(n)>(r==="pons_launch"?8388608:1048576))throw new Error("Tool arguments are too large.");!te.has(r)&&!Q(r,o)&&r!=="erc8004_register"&&await B(r);let t=r==="preview"||!te.has(r)&&!Q(r,o),y=r==="relay_bridge_in"&&typeof o.originChainId=="number"?o.originChainId:r==="preview"&&Array.isArray(o.txs)&&b(o.txs[0])&&typeof o.txs[0].chainId=="number"?o.txs[0].chainId:m,k=T(p()),x=t?await ce(y):void 0,w=`/v1/tools/${r}`,l=await h.sessions.headers("POST",w,n),d;try{d=await a(new URL(w,s),{method:"POST",redirect:"error",headers:{"content-type":"application/json",...l},body:n,signal:AbortSignal.timeout(18e4)})}catch{throw new Error("Oak server request failed. Check connectivity; any project exchange may need a fresh auction.")}let i;try{i=await d.json()}catch{throw new Error("Oak server returned invalid JSON.")}if(!b(i)||typeof i.ok!="boolean")throw new Error("Oak server returned an invalid tool envelope.");if(!i.ok)throw new Error(typeof i.error=="string"?G(i.error):"Oak tool failed.");if(!d.ok||!Object.hasOwn(i,"data"))throw new Error("Oak server returned an invalid tool response.");if(r==="preview"&&b(i.data)&&typeof i.data.summary=="string"&&(!("changes"in i.data)||Array.isArray(i.data.changes))){let c=se(o.txs),u=i.data.txs!==void 0?se(i.data.txs):c,v=Array.isArray(i.data.txs)?i.data.txs:Array.isArray(o.txs)?o.txs:[];c&&u&&Se(c,u)&&(J={preview:i.data,txs:u,rawTxs:v,sender:N(i.data,!0)??e.signer.address,at:L(i.data.timestamp??i.data.createdAt??i.data.simulatedAt)??k,blockNumber:W(i.data.blockNumber??i.data.block)??x})}return{data:i.data,meta:{at:k,blockNumber:x}}}async function M(r){r=G(r),await e.display(r),_?.getClientCapabilities()&&await _.sendLoggingMessage({level:"info",logger:"oak-preview",data:r}).catch(()=>{})}async function de(){try{return await Ie()}catch(r){throw K(r)}}async function Ie(){return e.launchOnly?O:[...O,...h.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 j()).map(r=>({name:`${r.project}.${r.name}`,description:`Third-party recipe; ${re}. Description: ${Te(r.description)}`,inputSchema:{type:"object",additionalProperties:!1,properties:Object.fromEntries(r.inputs.map(o=>[o.name,{description:`${o.type}; ${Te(o.description)}`}])),required:r.inputs.filter(o=>o.default===void 0).map(o=>o.name)}}))]}async function Oe(r,o,n,t,y){let k=J;J=void 0;let x=e.signer.address;if(t){let i=N(t,!1);if(i!==void 0&&!q(i,x))return}for(let i of r)if(b(i)){let c=N(i,!0);if(c!==void 0&&!q(c,x))return}let w=[];if(t&&b(t.preview)&&typeof t.preview.summary=="string"&&(!("changes"in t.preview)||Array.isArray(t.preview.changes))){let i=se(t.preview.txs);if(i){let c=W(t.preview.blockNumber??t.preview.block),u=W(t.blockNumber??t.block);(c===void 0||u===void 0||c===u)&&w.push({preview:t.preview,txs:i,rawTxs:t.preview.txs,sender:N(t.preview,!0)??N(t,!1)??x,at:L(t.preview.timestamp??t.preview.createdAt??t.preview.simulatedAt??t.timestamp??t.createdAt)??y?.at,blockNumber:c??u??y?.blockNumber})}}if(k&&(!t||t.preview===void 0)&&w.push(k),!w.length)return;let l=T(p()),d=t?W(t.blockNumber??t.block):void 0;for(let i of w){if(i.preview.stale===!0||t?.stale===!0||!q(i.sender,x)||i.preview.chainId!==void 0&&i.preview.chainId!==n||i.rawTxs.some(v=>b(v)&&N(v,!0)!==void 0&&!q(N(v,!0),x))||!Se(i.txs,o)||i.at===void 0||!Number.isFinite(i.at)||l<i.at||l-i.at>g)continue;let c=L(i.preview.expiresAt??t?.expiresAt);if(c!==void 0&&l>=c||i.blockNumber===void 0)continue;let u=d??await ce(n);if(!(u===void 0||i.blockNumber!==u))return i.preview}}async function F(r,o,n,t,y,k){let x=n.map(d=>b(d)?{...d}:d),w=n.map(d=>Pe(d)),l=r==="relay_bridge_in"?o.originChainId:m;if(w.some(d=>d.chainId!==l)||r==="relay_bridge_in"&&y?.originChainId!==void 0&&y.originChainId!==l)throw new Error("Transaction chain differs from the requested project or Relay origin chain.");if(w.length){let d=await Oe(x,w,l,y,k),i=d?k?.at??T(p()):T(p());d||(d=await U("preview",{txs:w}),i=T(p())),J=void 0;let c=(E,qe)=>{let fe=[L(E?.expiresAt),L(y?.expiresAt),qe].filter(je=>je!==void 0);return fe.length?Math.min(...fe):void 0},u=c(d),v=u!==void 0?Math.min(i+g,u):i+g;if(await M(`${t}
2
- ${JSON.stringify(d)}
3
- ${JSON.stringify(w)}`),r!=="erc8004_register"&&await B(r),T(p())>v||u!==void 0&&T(p())>=u){if(u!==void 0&&T(p())>=u)throw new Error("Prepared transaction expired before signing; request a fresh quote and preview.");if(d=await U("preview",{txs:w}),i=T(p()),u=c(d,u),v=u!==void 0?Math.min(i+g,u):i+g,await M(`${t}
4
- ${JSON.stringify(d)}
5
- ${JSON.stringify(w)}`),r!=="erc8004_register"&&await B(r),T(p())>v||u!==void 0&&T(p())>=u)throw new Error("Prepared transaction expired before signing; request a fresh quote and preview.")}for(let E of w)Object.defineProperty(E,"notAfter",{value:v,configurable:!0});return I.send(w)}return{hashes:[],summary:""}}async function ue(r,o){try{return await Ee(r,o)}catch(n){throw K(n)}}async function Ee(r,o){if(e.launchOnly&&!xe.has(r))throw new Error("Only Pons launch tools are available before deployment.");let n=V(JSON.parse(JSON.stringify(V(o))));if(n.continuation!==void 0||n.signature!==void 0)throw new Error("Start a fresh tool call; the local bridge owns project continuations.");if(r==="oak_identity_unlink"&&h.unlink){if(Object.keys(n).some(l=>!["actor","linkId"].includes(l))||n.actor!==void 0&&n.actor!=="agent"&&n.actor!=="owner"||n.linkId!==void 0&&typeof n.linkId!="string")throw new Error("Provide actor (agent or owner) and an optional linkId.");return h.unlink({actor:n.actor==="owner"?"owner":"agent",linkId:n.linkId},e.signOwner)}if(r==="oak_subscribe"&&e.subscribe){if(Object.keys(n).length!==1||n.plan!=="holder"&&n.plan!=="nohold")throw new Error("Choose plan holder or nohold.");return await h.requireVerified(),e.subscribe(n.plan)}if(r==="oak_renew"&&e.subscribe){if(Object.keys(n).length)throw new Error("Provide an empty JSON object.");return await h.requireVerified(),e.ensureSubscribed()}if(r==="oak_setup"&&e.setup){if(Object.keys(n).some(l=>!["mode","agentId","profile","tag"].includes(l)))throw new Error("Provide only documented setup arguments.");if(n.mode==="link"&&typeof n.agentId=="string"&&n.profile===void 0&&n.tag===void 0)return e.setup({mode:"link",agentId:n.agentId});if(n.mode==="register"&&(n.profile===void 0||b(n.profile))&&n.agentId===void 0&&(n.tag===void 0||typeof n.tag=="boolean"))return e.setup({mode:"register",profile:n.profile,tag:n.tag});throw new Error("Choose register (profile optional), or link with an agentId.")}if(r.includes(".")){let l=(await j()).find(c=>`${c.project}.${c.name}`===r);if(!l)throw new Error("Unknown or disabled recipe.");if(l.kind==="read")return we(l,n,{client:e.recipeClient});await B();let d=he(l,n,e.signer.address),i=await F(r,n,d,re);return{...i,summary:`${re}. ${i.summary}`}}if(r==="account")return U(r,n);let{data:t,meta:y}=await $(r,n);if(te.has(r)||Q(r,n))return t;let k=[],x,w;for(;;){if(!b(t)||!Array.isArray(t.txs)&&!Array.isArray(t.steps))return t;if(typeof t.summary!="string"||Array.isArray(t.txs)&&Array.isArray(t.steps))throw new Error("Invalid project action result.");if(Array.isArray(t.txs)){if(t.continuation!==void 0)throw new Error("Continuation requires project steps.");let c=await F(r,n,t.txs,t.summary,t,y);if(k.push(...c.hashes),r==="pons_launch"&&c.hashes.length){let v=c.hashes.at(-1);try{let E=await U(r,{transactionHash:v});if(!b(E)||E.txs!==void 0||E.steps!==void 0)throw new Error("Invalid Pons launch confirmation.");return{...E,hashes:k,summary:[t.summary,E.summary,c.summary].filter(Boolean).join(" ")}}catch{return{hashes:k,transactionHash:v,confirmationPending:!0,summary:`Pons launch transaction mined: ${v}. Token lookup is unavailable. Call pons_launch with only transactionHash to read it; do not launch again.`}}}if(r==="erc8004_register"&&c.hashes.length){if(c.hashes.length!==1)throw new Error("Unexpected ERC-8004 registration sequence.");if(!w)w=c.hashes[0],{data:t,meta:y}=await $(r,{...n,transactionHash:w});else if({data:t,meta:y}=await $(r,{...n,transactionHash:w,metadataTransactionHash:c.hashes[0]}),b(t)&&(Array.isArray(t.txs)||Array.isArray(t.steps)))throw new Error("Unexpected ERC-8004 confirmation response.");if(b(t)&&!Array.isArray(t.txs))return{...t,hashes:k};continue}return{...Object.fromEntries(Object.entries(t).filter(([v])=>v!=="txs")),hashes:k,summary:[t.summary,c.summary].filter(Boolean).join(" ")}}let l=t.steps;if(!b(t.continuation)){if(l.some(u=>u.kind!=="tx"))throw new Error("Typed signing requires a project continuation.");let c=await F(r,n,l.map(u=>u.tx),t.summary,t,y);return{hashes:[...k,...c.hashes],summary:`${t.summary} ${c.summary}`.trim()}}let d=t.continuation;oe(r,n,e.signer.address,l,d,x,p());let i;if(l[0]?.kind==="typedData")await M(`${t.summary}
6
- ${JSON.stringify(l[0].request)}
7
- Signature only; external settlement remains pending.`),await B(),oe(r,n,e.signer.address,l,d,x,p()),i=await I.signTypedData(l[0].request),oe(r,n,e.signer.address,l,d,x,p());else{let c=await F(r,n,l.map(u=>u.tx),t.summary,t,y);k.push(...c.hashes)}x=d,{data:t,meta:y}=await $(r,{...n,continuation:d,...i?{signature:i}:{}})}}function z(){let r="Wallet reconciliation failed. Wait for the pending transaction or check local wallet and RPC availability.";return S||(S=Promise.resolve().then(async()=>(typeof I.withAction=="function"&&await I.withAction(async()=>{}),r="Subscription check failed.",e.ensureSubscribed())).then(async o=>{let n=o.ok===!0&&o.access===!0;return await M(n?o.summary:`${o.summary} ${ne}`),n}).catch(async()=>(await M(`${r} ${ne}`).catch(()=>{}),!1)).finally(()=>{S=void 0})),S}async function B(r){if(e.privateTestMode||e.launchOnly&&r===Me){let o=e.privateTestMode?"/v1/private-access":"/v1/launch-access",n="{}",t=await a(new URL(o,s),{method:"POST",redirect:"error",headers:{"content-type":"application/json",...await h.sessions.headers("POST",o,n)},body:n,signal:AbortSignal.timeout(3e4)}),y=await t.json();if(!t.ok||y?.ok!==!0||y.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 h.requireVerified(),!await z())throw new Error(ne)}async function le(){C=!0,P&&globalThis.clearInterval(P),P=void 0,await _?.close(),await S,h.sessions.clear()}async function Re(r=new ur){if(_||C)throw new Error("MCP bridge has already started or closed.");!e.launchOnly&&!e.privateTestMode&&await h.requireVerified().then(()=>z()).catch(async()=>{await M("Run oak setup to register or link your identity first. Reads remain available.")}),_=new dr({name:"oak",version:pe},{capabilities:{tools:{},logging:{}},instructions:e.startupInstructions?await e.startupInstructions():ke(e.signer.address,f)}),_.setRequestHandler(fr,async()=>({tools:await de()})),_.setRequestHandler(lr,async o=>{try{return{content:[{type:"text",text:JSON.stringify(await ue(o.params.name,o.params.arguments??{}))}]}}catch(n){return{isError:!0,content:[{type:"text",text:me(n,"Oak tool failed.")}]}}}),_.onclose=()=>{C=!0,P&&globalThis.clearInterval(P),P=void 0};try{await _.connect(r)}catch(o){throw await le(),o}!C&&!e.launchOnly&&!e.privateTestMode&&(P=globalThis.setInterval(()=>{h.requireVerified().then(()=>z()).catch(()=>{})},36e5),P.unref())}return{listTools:de,postTool:U,callTool:ue,start:Re,stop:le}}export{sr as a,te as b,gr as c,V as d,br as e,xr as f,ft as g};
@@ -1 +0,0 @@
1
- import{b as P}from"./HLAZAI2Q.js";import{randomBytes as D}from"node:crypto";import{encodeFunctionData as f,erc20Abi as O,getAddress as C,parseAbi as v,parseSignature as I,zeroAddress as y,zeroHash as L}from"viem";import{ADDRESSES as $,ETH_USDG_POOL as G,NETWORKS as H,assertNetworkUsdg as z}from"@oakagentkit/core/addresses";import{approval as A,unsignedTx as B}from"@oakagentkit/core/tx";import{verifyNoteOffchain as _}from"@oakagentkit/core/pricenote";import{grandfatherProofFor as W,verifyGrandfatherProof as q}from"@oakagentkit/core/grandfather";var u=v(["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=v(["function phase() view returns (uint8)","function priceSigner() view returns (address)","function spotOakPerEthE18() view returns (uint256)"]),S=v(["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)"]),K={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"}]},j=new Set(Object.values($[4663]).flatMap(s=>Object.values(s).map(e=>e.address.toLowerCase()))),F={wallet:y,oakPerEthE18:0n,timestamp:0n,nonce:L},b=9000000n,ne=3n*86400n,R=s=>(s*101n+99n)/100n,m=(s,e)=>s.toLowerCase()===e.toLowerCase(),i=class extends Error{constructor(n,t=!1){super(n);this.retryNote=t}retryNote};function E(s){if(s.network!=="mainnet"&&s.network!=="testnet")throw new i("Set the subscription deployment network to mainnet or testnet.");let e=H[s.network];if(s.chainId!==e.chainId)throw new i("Network does not match the subscription deployment chain.");return z(s.network,s.usdg),{...e.usdgDomain}}function M(s){E(s);for(let e of["subscription","usdg","oak","oracle","ethUsdgPool"]){let n=C(s[e]);if(n===y)throw new i(`Configure a non-zero ${e} in the deployment config.`);if(s.network==="testnet"&&j.has(n.toLowerCase()))throw new i(`${e} cannot use a mainnet pin in the testnet deployment config.`)}if(s.network==="mainnet"&&!m(s.ethUsdgPool,G))throw new i("ETH/USDG pool must match the pinned mainnet pool.")}function J(s){let e=s;for(let n=0;e&&typeof e=="object"&&n<12;n++){let t=e;if(t.data?.errorName)return t.data.errorName;e=t.cause}}var l=(s,e=!1,n=!1,t=[])=>({ok:e,access:n,summary:s,hashes:t}),x=class{constructor(e){this.options=e;M(e.deployment),C(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,n=this.deployment.subscription;for(let t=0;n!==y&&t<256;t++){if(e.has(n.toLowerCase()))throw new i("Invalid subscription lineage.");e.add(n.toLowerCase());let o=r=>this.options.client.readContract({address:n,abi:u,functionName:r,args:[this.wallet]});if(await o("hasRecord")){let[r,a,c,d]=await Promise.all([o("plan"),o("paidUntil"),o("signupOakCount"),this.options.client.readContract({address:n,abi:u,functionName:"retired"})]);return{contract:n,plan:Number(r),paidUntil:BigInt(a),count:BigInt(c),retired:d}}n=await this.options.client.readContract({address:n,abi:u,functionName:"previous"})}if(n!==y)throw new i("Subscription lineage is too deep.");return null}async proof(e){let n=await this.options.grandfatherList?.();if(!n)return null;let t=W(n,this.wallet);if(!t||!m(t.source,e.contract)||BigInt(t.count)!==e.count)return null;let o=await this.options.client.readContract({address:this.deployment.subscription,abi:u,functionName:"grandfatherRoot"});if(!q(o,t.entry,t.proof))throw new i("Grandfather proof does not match the successor root.");return t}async balance(e){return this.options.client.readContract({address:e,abi:O,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 P)return new i(e.message);let n=J(e);return n==="OracleUnreadable"?new i(`Price unavailable: check the ETH/USDG pool ${this.deployment.ethUsdgPool}; try again when the oracle recovers.`):n?.startsWith("Note")?new i(`Price note rejected (${n}); 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,n=!1){for(let t=0;t<(n?2:1);t++){let o;try{let r=await this.options.sender.withAction(async a=>{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(a)}catch(c){o=this.plain(c);let d=await a.approvalStatus?.();return l(`${o.message}${d?` ${d}`:""}`)}});if(o?.retryNote&&t===0&&n)continue;return r}catch(r){return r instanceof P?l(r.message):l("Payment failed or remains pending; tools are paused. Run oak renew to reconcile the wallet journal before another payment.")}}return l("Price note unavailable; retry with a fresh note.")}tx(e,n,t){return B({to:e,data:n,value:"0",chainId:this.deployment.chainId,description:t})}async funds(e,n=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(n>0n&&await this.balance(this.deployment.oak)<n)throw new i(`Needs ${n} OAK base units (token ${this.deployment.oak}, decimals 18). Buy back OAK and retry.`)}async authorization(e,n){let t=`0x${D(32).toString("hex")}`;if(await this.options.client.readContract({address:this.deployment.usdg,abi:S,functionName:"authorizationState",args:[this.wallet,t]}))throw new i("USDG authorization nonce is used or cancelled; retry with a new nonce.");let o=await this.now()+300n,r={domain:E(this.deployment),types:K,primaryType:"ReceiveWithAuthorization",message:{from:this.wallet,to:n,value:b.toString(),validAfter:"0",validBefore:o.toString(),nonce:t}},a=I(await e.signTypedData(r));return f({abi:S,functionName:"receiveWithAuthorization",args:[this.wallet,n,b,0n,o,t,Number(a.v??BigInt(a.yParity??0)+27n),a.r,a.s]})}async note(e){for(let n=0;n<2;n++){let t=await this.options.issueNote({for:"subscription",wallet:this.wallet});if("reason"in t)throw t.reason==="eth_usd_unreadable"&&/price source is stale|freshness is unavailable/.test(t.error)?new i(`Price unavailable: ETH/USDG pool ${this.deployment.ethUsdgPool} needs a readable observation within 30 minutes. Retry after the pool updates.`):t.reason==="history_too_thin"&&/OAK price source is stale/.test(t.error)?new i("Price unavailable: refresh the stale OAK 30-minute trade history before retrying."):t.reason==="eth_usd_unreadable"?new i(`Price unavailable: ETH/USDG pool ${this.deployment.ethUsdgPool} is unreadable.`):t.reason==="history_too_thin"?new i("Price warmup: wait until the pool has 30 minutes of history, then retry."):new i(`Price unavailable (${t.reason}); retry in a minute.`);if(!m(t.consumer,e)||!m(t.note.wallet,this.wallet))throw new i("Price note consumer or wallet does not match this subscription.");let o=await this.now();if(BigInt(t.note.timestamp)+300n-o<60n)continue;let[r,a]=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 _({note:t.note,signature:t.signature,consumer:e,wallet:this.wallet,signer:r,spotOakPerEthE18:a,now:o,expiresAt:t.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 t}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,n,t,o=!1){let r=await this.options.client.readContract({address:this.deployment.oracle,abi:k,functionName:"phase"});if(r!==0&&r!==1)throw new i("Unknown subscription phase; nothing was signed.");if(r===0&&t==="holder")throw new i("Holder plan is closed during the curve; use oak subscribe --plan nohold.");let a=r===1?await this.note(n):null,c=a?{...a.note,timestamp:BigInt(a.note.timestamp),oakPerEthE18:BigInt(a.note.oakPerEthE18)}:F,d=a?.signature??"0x",h=[];if(t==="holder"){let[w,p]=await this.options.client.readContract({address:n,abi:u,functionName:"quoteHolder",args:[c,d],account:this.wallet}),g=R(w);await this.funds(b,w),await this.fresh(a);let U=await this.authorization(e,n);h.push(A(this.deployment.oak,n,p.toString(),this.deployment.chainId)),h.push(this.tx(n,f({abi:u,functionName:"subscribeWithAuthorization",args:[g,c,d,U]}),`Subscribe holder: 9000000 USDG base units (decimals 6); exact OAK burn ${p} (decimals 18).`))}else{let w=r===0?12333333n:await this.options.client.readContract({address:n,abi:u,functionName:"quoteNoHold",args:[c,d],account:this.wallet}),p=r===0?w:R(w);await this.funds(w),h.push(A(this.deployment.usdg,n,p.toString(),this.deployment.chainId));let g=o?f({abi:u,functionName:"renewNoHold",args:[p,c,d]}):f({abi:u,functionName:"subscribe",args:[2,0n,p,c,d]});h.push(this.tx(n,g,`${o?"Renew":"Subscribe"} nohold: at most ${p} USDG base units (token ${this.deployment.usdg}, decimals 6).`))}await this.fresh(a),await e.assertCanPayGas(h);let T=await e.send(h.slice(0,-1));await this.fresh(a),a&&(t==="holder"?await this.options.client.readContract({address:n,abi:u,functionName:"quoteHolder",args:[c,d],account:this.wallet}):await this.options.client.readContract({address:n,abi:u,functionName:"quoteNoHold",args:[c,d],account:this.wallet}));let N=await e.send(h.slice(-1));return l(N.summary,!0,await this.access(await this.authoritative()),[...T.hashes,...N.hashes])}async holderPayment(e,n,t){let o=t?this.deployment.subscription:n.contract;if(t&&await this.options.client.readContract({address:o,abi:u,functionName:"grandfatherDeadline"})<await this.now())return l("Grandfather deadline has passed; once the old paid days expire, use oak subscribe for a fresh subscription.",!1,await this.access(n));await this.funds(b,t?n.count:0n);let r=await this.authorization(e,o),a=t?f({abi:u,functionName:"subscribeGrandfatheredWithAuthorization",args:[BigInt(t.count),t.proof,r]}):f({abi:u,functionName:"renewWithAuthorization",args:[r]}),c=await e.send([this.tx(o,a,`Renew holder: 9000000 USDG base units (token ${this.deployment.usdg}, decimals 6); no OAK burn.`)]);return l(c.summary,!0,await this.access(await this.authoritative()),c.hashes)}subscribe(e){return this.action(async n=>{if(e!=="holder"&&e!=="nohold")throw new i("Choose oak subscribe --plan holder or --plan nohold.");let t=await this.authoritative();if(t?.plan===1&&!m(t.contract,this.deployment.subscription)&&t.paidUntil>=await this.now()&&await this.proof(t))throw new i("your paid days carry over with `oak renew` when it is due");if(t&&m(t.contract,this.deployment.subscription)&&t.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(n,this.deployment.subscription,e)},!0)}cancel(){return this.action(async e=>{let n=await this.authoritative();if(!n||n.plan===0)return l("No active subscription to cancel.",!0);let t=await e.send([this.tx(n.contract,f({abi:u,functionName:"cancel"}),"Cancel subscription; all remaining paid days are forfeited immediately.")]);return l("Subscription cancelled; remaining paid days forfeited.",!0,!1,t.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,ne as c,E as d,M as e,x as f};
@@ -1,4 +0,0 @@
1
- import{b as J,c as te,d as ne}from"./QIDB35RS.js";import{a as ae}from"./YVAFJM4Y.js";import{createPublicClient as fe,decodeFunctionData as me,encodeFunctionData as pe,erc20Abi as O,getAddress as re,http as ge,keccak256 as be,parseTransaction as R,recoverTypedDataAddress as ye,TransactionNotFoundError as xe,TransactionReceiptNotFoundError as Pe}from"viem";import{CHAIN_ID as M,OAK_FINALITY as Te}from"@oakagentkit/core/addresses";import{hasErrorCode as ke}from"@oakagentkit/core/errors";import{unsignedTx as ve}from"@oakagentkit/core/tx";import{loadSigner as Ce}from"#oak-wallet";var Ie=12,w=class extends Error{},f=()=>new w("Wallet journal is unresolved; wait for the pending transaction before a new action."),C=()=>new w("Local signing failed."),ie=()=>new w("Transaction reverted; the remaining sequence was stopped."),G=(s,h)=>new w(`needs ETH for network fees: send ETH to ${s} on chain ${h}.`),se=(s,h,m)=>new w(`Transaction ${s+1} of ${h} cannot be estimated on chain ${m}; it was not signed.`),W=()=>new w("Prepared transaction expired before signing; preview and retry with a fresh quote."),q=s=>s instanceof w?s:new w("Wallet action failed; check local custody and RPC availability. Any pending journal remains unresolved."),z=s=>s+s/4n,U=s=>s+s/10n+1n,I=(s,h)=>s>h?s:h;function Se(){let s=process.env.OAK_FINALITY??Te;if(s==="safe"||s==="finalized")return s;if(/^[1-9]\d*$/.test(s)&&Number.isSafeInteger(Number(s)))return Number(s);throw new w("Invalid OAK_FINALITY setting.")}function Fe(s){if(s!==M)throw new w("Configure an RPC for the transaction chain.");let h=process.env.OAK_RPC_URL;if(!h)throw new w("Set OAK_RPC_URL before sending a transaction.");return fe({transport:ge(h),cacheTime:0})}function Ne(s,h){let m=`${s} transaction${s===1?"":"s"}`;return h===s?`${m} mined and final.`:h===0?`${m} mined, awaiting finality.`:`${m} mined; ${h} final, ${s-h} awaiting finality.`}function K(s={}){let h=new Set(s.allowedChainIds??[M]),m=s.finality??Se();if(typeof m=="number"&&(!Number.isSafeInteger(m)||m<1))throw new w("Invalid finality block count.");let N=s.notAfterSeconds??Ie;if(!Number.isSafeInteger(N)||N<1)throw new w("Invalid transaction not-after window.");let k=()=>{let t=(s.now??(()=>Math.floor(Date.now()/1e3)))(),e=t>1e11?Math.floor(t/1e3):Math.floor(t);if(!Number.isSafeInteger(e)||e<0)throw new w("Invalid local timestamp; check the system clock.");return e},$=s.preview?t=>s.preview(ae(t)):void 0;async function S(t){if(!Number.isSafeInteger(t)||!h.has(t))throw new w("Unsupported transaction chain.");let e=(s.clientFor??Fe)(t);if(await e.getChainId()!==t)throw new w("RPC chain does not match the requested chain; nothing was signed.");return e}async function v(t,e){let a=await t.getBlock(e);if(a.number===null)throw new w("RPC returned a block without a height; retry when the node is synchronized.");return{...a,number:a.number}}async function H(t){let[e,a]=await Promise.all([v(t,{blockTag:"latest"}),t.estimateMaxPriorityFeePerGas()]),n=e.baseFeePerGas;if(typeof n!="bigint"||n<0n||a<0n||n*2n+a<=0n)throw new w("Network fee data is unavailable; nothing was signed.");return{baseFee:n,maxFeePerGas:n*2n+a,maxPriorityFeePerGas:a,blockNumber:e.number}}async function oe(t,e,a,n){let r=a.map(i=>({account:e,to:i.to,data:i.data,value:BigInt(i.value)})),d;try{d=(await t.simulateBlocks({blocks:[{calls:r}],validation:!1,traceTransfers:!0}))[0]?.calls??[]}catch(i){if(!ke(i,-32601,-32004))throw i;return Promise.all(r.map((o,u)=>t.estimateGas(o).catch(()=>{throw se(u,r.length,n)})))}if(d.length!==r.length)throw new w(`Simulation on chain ${n} returned an unexpected result; nothing was signed.`);return d.map((i,o)=>{if(i.status!=="success")throw new w(`Transaction ${o+1} of ${r.length} would revert on chain ${n}; nothing was signed.`);let u=I(i.gasUsed,i.maxUsedGas??0n);if(u<=0n)throw new w("Gas estimate is unavailable.");return u})}async function Y(t,e){let a=k(),n=t.map(i=>{let o=ve(i),u=i.notAfter;if(u!==void 0&&(typeof u!="number"||!Number.isSafeInteger(u)||u<0))throw new w("Invalid transaction not-after timestamp.");let l=u??a+N;if(a>l)throw W();return{tx:o,notAfter:l}}),r=new Map;for(let{tx:i}of n){let o=r.get(i.chainId)??{client:await S(i.chainId),txs:[]};o.txs.push(i),r.set(i.chainId,o)}let d=new Map;for(let[i,o]of r){let[u,l]=await Promise.all([o.client.getBalance({address:e.address,blockTag:"pending"}),H(o.client)]),c=o.txs.reduce((g,b)=>g+BigInt(b.value),0n);if(u<c)throw G(e.address,i);let p=await oe(o.client,e.address,o.txs,i);if(o.txs.forEach((g,b)=>{d.set(g,p[b]),c+=z(p[b])*l.maxFeePerGas}),u<c)throw G(e.address,i)}return n.map(({tx:i,notAfter:o})=>({tx:i,notAfter:o,client:r.get(i.chainId).client,value:BigInt(i.value),simulated:d.get(i)}))}async function X(t,e){let{blockNumber:a}=e;try{return e.blockHash&&(await v(t,{blockNumber:a})).hash!==e.blockHash?!1:typeof m=="number"?(await v(t,{blockTag:"latest"})).number-a+1n>=BigInt(m):(await v(t,{blockTag:m})).number>=a}catch{return!1}}async function L(t,e,a,n=t.hash){let r=await e.waitForTransactionReceipt({hash:n,confirmations:1,timeout:s.receiptTimeoutMs??12e4});if(!J(t).some(i=>i.toLowerCase()===r.transactionHash.toLowerCase()))throw f();let d=await X(e,r);if(d&&await a.clear(t.hash),r.status!=="success")throw ie();return d}async function ce(t,e){for(let a of e)try{let n=await t.getTransactionReceipt({hash:a});if(n.transactionHash.toLowerCase()!==a.toLowerCase())throw f();return n}catch(n){if(!(n instanceof Pe))throw n}}async function Q(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 xe))throw n}}async function de(t,e,a,n){let r=R(t.rawTx),d=r.maxFeePerGas??r.gasPrice??0n,i=await H(e),o=t;if(d<i.baseFee){if(!r.to||r.gas===void 0)throw f();let l=r.value??0n,c=I(i.maxPriorityFeePerGas,U(r.maxPriorityFeePerGas??0n)),p=I(i.baseFee*2n+c,U(d));if(await e.getBalance({address:a.address,blockTag:"pending"})<l+r.gas*p)throw G(a.address,t.chainId);let g;try{g=await a.signTransaction({chainId:t.chainId,nonce:t.nonce,to:r.to,data:r.data??"0x",value:l,gas:r.gas,maxFeePerGas:p,maxPriorityFeePerGas:c})}catch{throw C()}o=await n.replace(t.hash,g,i.blockNumber.toString(),k())}if((await e.sendRawTransaction({serializedTransaction:o.rawTx})).toLowerCase()!==o.hash.toLowerCase())throw f();return o}async function le(t,e,a,n){let r=R(t.rawTx),d=r.maxFeePerGas??r.gasPrice??0n,i=await H(e),o=await e.estimateGas({account:a.address,to:a.address,data:"0x",value:0n}),u=I(21000n,o),l=I(i.maxPriorityFeePerGas,U(r.maxPriorityFeePerGas??r.gasPrice??0n)),c=I(i.baseFee*2n+l,U(d));if(await e.getBalance({address:a.address,blockTag:"pending"})<u*c){let y=await Q(e,J(t));if(!y)throw G(a.address,t.chainId);if(!await L(t,e,n,y))throw f();return}let g=c,b=l,T;try{T=await a.signTransaction({chainId:t.chainId,nonce:t.nonce,to:a.address,data:"0x",value:0n,gas:u,maxFeePerGas:g,maxPriorityFeePerGas:b});let y=R(T);if(!y.to||y.to.toLowerCase()!==a.address.toLowerCase()||(y.data??"0x")!=="0x"||(y.value??0n)!==0n||y.chainId!==t.chainId||y.nonce!==t.nonce||y.gas!==u)throw C()}catch{throw C()}let x=k(),A=await n.burn(t.hash,T,i.blockNumber.toString(),x,x+N);if((await e.sendRawTransaction({serializedTransaction:A.rawTx})).toLowerCase()!==A.hash.toLowerCase())throw f();return A}async function ue(t,e){for(let a of await e.read()){let n=E(a);n&&n.amount>0n&&await e.retainApproval(a);let r=await S(a.chainId),d=J(a),[i,o]=await Promise.all([r.getTransactionCount({address:t.address,blockTag:"latest"}),r.getTransactionCount({address:t.address,blockTag:"pending"})]),u=await ce(r,d);if(u){if(!await X(r,u))throw f();if(await e.clear(a.hash),u.status!=="success")throw ie();continue}let l=a.notAfter??a.sentAt+N,c=await v(r,{blockTag:"latest"});if(c.timestamp<0n||c.timestamp>BigInt(Number.MAX_SAFE_INTEGER))throw new w("Invalid block timestamp; check RPC availability.");let p=k()>l||c.timestamp>BigInt(l);if(!p||a.kind==="burn"){let x=await Q(r,d);if(x){if(!await L(a,r,e,x))throw f();continue}}let g=typeof m=="number"?c:await v(r,{blockTag:m}),b=BigInt(a.blockNumber)+BigInt(typeof m=="number"?m:1);if(!p&&g.number<b)throw f();if(i>a.nonce){if(g.number<b)throw f();let x=typeof m=="number"?c.number-BigInt(m)+1n:g.number;if(x<0n||await r.getTransactionCount({address:t.address,blockNumber:x})<=a.nonce)throw f();await e.clear(a.hash,"nonce_consumed");continue}if(i!==a.nonce||o<a.nonce||!p&&o!==a.nonce)throw f();let T=p&&a.kind!=="burn"?await le(a,r,t,e):await de(a,r,t,e);if(T&&!await L(T,r,e))throw f()}}function E(t){let e=R(t.rawTx);if(!(!e.to||(e.value??0n)!==0n))try{let a=me({abi:O,data:e.data??"0x"});return a.functionName!=="approve"?void 0:{token:re(e.to),spender:re(a.args[0]),amount:a.args[1]}}catch{return}}async function _(t){let e=[];for(let a of await t.approvals()){let n=E(a);if(!n)throw f();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 V(t,e,a){let n=await Y(t,e),r=[],d=0;for(let[i,{tx:o,notAfter:u,client:l,value:c,simulated:p}]of n.entries()){if(k()>u)throw W();await S(o.chainId);let[g,b,T]=await Promise.all([l.estimateGas({account:e.address,to:o.to,data:o.data,value:c}).catch(()=>{throw se(i,n.length,o.chainId)}),H(l),l.getTransactionCount({address:e.address,blockTag:"pending"})]);if(k()>u)throw W();let x=z(I(g,p)),A=n.slice(i+1).filter(P=>P.tx.chainId===o.chainId).reduce((P,ee)=>P+ee.value+z(ee.simulated)*b.maxFeePerGas,0n);if(await l.getBalance({address:e.address,blockTag:"pending"})<c+x*b.maxFeePerGas+A)throw G(e.address,o.chainId);let F;try{F=await e.signTransaction({chainId:o.chainId,to:o.to,data:o.data,value:c,gas:x,nonce:T,maxFeePerGas:b.maxFeePerGas,maxPriorityFeePerGas:b.maxPriorityFeePerGas});let P=R(F);if(!P.to||P.to.toLowerCase()!==o.to.toLowerCase()||(P.data??"0x").toLowerCase()!==o.data.toLowerCase()||(P.value??0n)!==c||P.chainId!==o.chainId||P.nonce!==T||P.gas!==x)throw C()}catch{throw C()}let y=be(F),Z=k(),he=Z<=u?Z:u,D={nonce:T,hash:y,rawTx:F,kind:o.data.startsWith("0x095ea7b3")?"approval":"main",sentAt:he,notAfter:u,chainId:o.chainId,blockNumber:b.blockNumber.toString()},j=E(D);if(j&&j.amount>0n&&await a.retainApproval(D),await a.append(D),(await l.sendRawTransaction({serializedTransaction:F})).toLowerCase()!==y.toLowerCase())throw f();await L(D,l,a)&&d++,r.push(y)}return{hashes:r,summary:Ne(r.length,d)}}async function we(t,e){for(let a of await e.approvals()){let n=E(a);if(!n)throw f();let r=await S(a.chainId),d=await r.readContract({address:n.token,abi:O,functionName:"allowance",args:[t.address,n.spender]});if(typeof d!="bigint"||d<0n)throw f();if(d>0n){let i={to:n.token,data:pe({abi:O,functionName:"approve",args:[n.spender,0n]}),value:"0",chainId:a.chainId,description:`Revoke remaining ${d} base-unit approval to ${n.spender}`};if(!$)throw new w("Approval cleanup requires a preview display. Clear the recorded approval in your wallet before retrying.");let o=await r.simulateBlocks({blocks:[{calls:[{account:t.address,to:i.to,data:i.data,value:0n}]}],validation:!1,traceTransfers:!0});if(await $(`Remaining approval: token ${n.token}, spender ${n.spender}, amount ${d} base units, chain ${a.chainId}. Revoke to zero. Simulation: ${JSON.stringify(o,(l,c)=>typeof c=="bigint"?c.toString():c)}`),await V([i],t,e),(await e.read()).length||await r.readContract({address:n.token,abi:O,functionName:"allowance",args:[t.address,n.spender]})!==0n)throw f()}await e.forgetApproval(a.hash)}}async function B(t){try{let e=s.signer??await Ce();return await te(e.address,async()=>{let a=new ne(e.address,s.directory);try{await ue(e,a),await we(e,a)}catch(l){let c=await _(a);throw new w(`${q(l).message}${c?` ${c}`:""}`)}let n=!0,r=!1,d,i;function o(l){if(!n||r||d)return Promise.reject(new w("Wallet action must be awaited inside its lock."));r=!0;let c=l().catch(async p=>{d=q(p);let g=await _(a);throw g&&(d=new w(`${d.message} ${g}`)),d}).finally(()=>{r=!1});return i=c.then(()=>{},()=>{}),c}let u={approvalStatus:()=>_(a),assertCanPayGas:l=>o(async()=>{await Y(l,e)}),send:l=>o(()=>V(l,e,a)),signTypedData:l=>o(async()=>{if(!$)throw new w("No preview display is configured; nothing was signed.");let c=JSON.parse(JSON.stringify(l));await S(c.domain.chainId??0),await $(`Project: ${c.domain.name??c.primaryType}
2
- Domain, deadline and exact typed request:
3
- ${JSON.stringify(c,null,2)}
4
- Signature only; external settlement remains pending.`);try{let p=await e.signTypedData(c);if((await ye({...c,signature:p})).toLowerCase()!==e.address.toLowerCase())throw C();return p}catch{throw C()}})};try{let l=await t(u);if(n=!1,await i,d)throw d;return l}finally{n=!1,await i}},{directory:s.directory})}catch(e){throw q(e)}}return{withAction:B,send:t=>B(e=>e.send(t)),signTypedData:t=>B(e=>e.signTypedData(t)),assertCanPayGas:t=>B(e=>e.assertCanPayGas(t)),blockNumber:async(t=M)=>(await v(await S(t),{blockTag:"latest"})).number}}var De=(s,h)=>K(h).send(s),Je=(s,h)=>K(h).signTypedData(s),Oe=(s,h)=>K(h).assertCanPayGas(s);export{Ie as a,w as b,K as c,De as d,Je as e,Oe as f};
@@ -1 +0,0 @@
1
- import{c as o,e as a}from"./5HTX664S.js";import{e as s}from"./VZCMAMZL.js";import{getAddress as d}from"viem";import{buildIdentityLinkTypedData as w,buildIdentityTuple as g,canonicalSessionIdentity as c}from"@oakagentkit/core/identity-link";function k(e){return async n=>{let r;if(n.mode==="register"){let t=await e.callTool("erc8004_register",{profile:n.profile??s,tag:n.tag??!0});if(!t||typeof t.agentId!="string"||!Array.isArray(t.hashes)||!t.hashes.length)throw new Error("Registration is not confirmed. Wait for the mined receipt before running oak setup again.");if(r=g(t.agentId,e.network),t.chainId!==r.chainId||t.registry!==r.registry)throw new Error(a);if(typeof t.owner!="string"||d(t.owner)!==e.signer.address)throw new Error(o);await e.identity.accept(r)}else{let t=g(n.agentId,e.network),i=await e.callTool("erc8004_identity",{agentId:n.agentId});if(i.chainId!==t.chainId||i.registry!==t.registry)throw new Error(a);let l=typeof i.owner=="string"&&d(i.owner)===e.signer.address?y=>e.signer.signTypedData(w(y)):e.signOwner??(async()=>{throw new Error(o)});r=await e.identity.link(t,l)}r=c(r,e.network);try{await e.save(r)}catch{throw e.identity.sessions.setIdentity(),new Error("Could not save identity. Run oak setup again after fixing local configuration.")}return{identity:r,summary:`Agent ${r.agentId} verified on chain ${r.chainId}. Identity setup is complete; run oak subscribe --plan holder or oak subscribe --plan nohold next.`}}}export{k as a};