@oobe-protocol-labs/synapse-sap-sdk 0.1.0

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 (315) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +882 -0
  3. package/dist/cjs/constants/index.js +43 -0
  4. package/dist/cjs/constants/index.js.map +1 -0
  5. package/dist/cjs/constants/limits.js +161 -0
  6. package/dist/cjs/constants/limits.js.map +1 -0
  7. package/dist/cjs/constants/programs.js +78 -0
  8. package/dist/cjs/constants/programs.js.map +1 -0
  9. package/dist/cjs/constants/seeds.js +57 -0
  10. package/dist/cjs/constants/seeds.js.map +1 -0
  11. package/dist/cjs/core/client.js +391 -0
  12. package/dist/cjs/core/client.js.map +1 -0
  13. package/dist/cjs/core/connection.js +319 -0
  14. package/dist/cjs/core/connection.js.map +1 -0
  15. package/dist/cjs/core/index.js +24 -0
  16. package/dist/cjs/core/index.js.map +1 -0
  17. package/dist/cjs/errors/index.js +334 -0
  18. package/dist/cjs/errors/index.js.map +1 -0
  19. package/dist/cjs/events/index.js +136 -0
  20. package/dist/cjs/events/index.js.map +1 -0
  21. package/dist/cjs/idl/index.js +63 -0
  22. package/dist/cjs/idl/index.js.map +1 -0
  23. package/dist/cjs/idl/synapse_agent_sap.json +9710 -0
  24. package/dist/cjs/index.js +147 -0
  25. package/dist/cjs/index.js.map +1 -0
  26. package/dist/cjs/modules/agent.js +272 -0
  27. package/dist/cjs/modules/agent.js.map +1 -0
  28. package/dist/cjs/modules/attestation.js +147 -0
  29. package/dist/cjs/modules/attestation.js.map +1 -0
  30. package/dist/cjs/modules/base.js +128 -0
  31. package/dist/cjs/modules/base.js.map +1 -0
  32. package/dist/cjs/modules/escrow.js +246 -0
  33. package/dist/cjs/modules/escrow.js.map +1 -0
  34. package/dist/cjs/modules/feedback.js +166 -0
  35. package/dist/cjs/modules/feedback.js.map +1 -0
  36. package/dist/cjs/modules/index.js +35 -0
  37. package/dist/cjs/modules/index.js.map +1 -0
  38. package/dist/cjs/modules/indexing.js +375 -0
  39. package/dist/cjs/modules/indexing.js.map +1 -0
  40. package/dist/cjs/modules/ledger.js +234 -0
  41. package/dist/cjs/modules/ledger.js.map +1 -0
  42. package/dist/cjs/modules/tools.js +319 -0
  43. package/dist/cjs/modules/tools.js.map +1 -0
  44. package/dist/cjs/modules/vault.js +410 -0
  45. package/dist/cjs/modules/vault.js.map +1 -0
  46. package/dist/cjs/pda/index.js +377 -0
  47. package/dist/cjs/pda/index.js.map +1 -0
  48. package/dist/cjs/plugin/index.js +934 -0
  49. package/dist/cjs/plugin/index.js.map +1 -0
  50. package/dist/cjs/plugin/protocols.js +282 -0
  51. package/dist/cjs/plugin/protocols.js.map +1 -0
  52. package/dist/cjs/plugin/schemas.js +831 -0
  53. package/dist/cjs/plugin/schemas.js.map +1 -0
  54. package/dist/cjs/postgres/adapter.js +715 -0
  55. package/dist/cjs/postgres/adapter.js.map +1 -0
  56. package/dist/cjs/postgres/index.js +50 -0
  57. package/dist/cjs/postgres/index.js.map +1 -0
  58. package/dist/cjs/postgres/serializers.js +381 -0
  59. package/dist/cjs/postgres/serializers.js.map +1 -0
  60. package/dist/cjs/postgres/sync.js +221 -0
  61. package/dist/cjs/postgres/sync.js.map +1 -0
  62. package/dist/cjs/postgres/types.js +44 -0
  63. package/dist/cjs/postgres/types.js.map +1 -0
  64. package/dist/cjs/registries/builder.js +414 -0
  65. package/dist/cjs/registries/builder.js.map +1 -0
  66. package/dist/cjs/registries/discovery.js +362 -0
  67. package/dist/cjs/registries/discovery.js.map +1 -0
  68. package/dist/cjs/registries/index.js +51 -0
  69. package/dist/cjs/registries/index.js.map +1 -0
  70. package/dist/cjs/registries/session.js +433 -0
  71. package/dist/cjs/registries/session.js.map +1 -0
  72. package/dist/cjs/registries/x402.js +577 -0
  73. package/dist/cjs/registries/x402.js.map +1 -0
  74. package/dist/cjs/types/accounts.js +13 -0
  75. package/dist/cjs/types/accounts.js.map +1 -0
  76. package/dist/cjs/types/common.js +13 -0
  77. package/dist/cjs/types/common.js.map +1 -0
  78. package/dist/cjs/types/enums.js +174 -0
  79. package/dist/cjs/types/enums.js.map +1 -0
  80. package/dist/cjs/types/index.js +36 -0
  81. package/dist/cjs/types/index.js.map +1 -0
  82. package/dist/cjs/types/instructions.js +92 -0
  83. package/dist/cjs/types/instructions.js.map +1 -0
  84. package/dist/cjs/utils/hash.js +58 -0
  85. package/dist/cjs/utils/hash.js.map +1 -0
  86. package/dist/cjs/utils/index.js +27 -0
  87. package/dist/cjs/utils/index.js.map +1 -0
  88. package/dist/cjs/utils/serialization.js +105 -0
  89. package/dist/cjs/utils/serialization.js.map +1 -0
  90. package/dist/cjs/utils/validation.js +36 -0
  91. package/dist/cjs/utils/validation.js.map +1 -0
  92. package/dist/esm/constants/index.js +29 -0
  93. package/dist/esm/constants/index.js.map +1 -0
  94. package/dist/esm/constants/limits.js +158 -0
  95. package/dist/esm/constants/limits.js.map +1 -0
  96. package/dist/esm/constants/programs.js +75 -0
  97. package/dist/esm/constants/programs.js.map +1 -0
  98. package/dist/esm/constants/seeds.js +54 -0
  99. package/dist/esm/constants/seeds.js.map +1 -0
  100. package/dist/esm/core/client.js +384 -0
  101. package/dist/esm/core/client.js.map +1 -0
  102. package/dist/esm/core/connection.js +315 -0
  103. package/dist/esm/core/connection.js.map +1 -0
  104. package/dist/esm/core/index.js +19 -0
  105. package/dist/esm/core/index.js.map +1 -0
  106. package/dist/esm/errors/index.js +325 -0
  107. package/dist/esm/errors/index.js.map +1 -0
  108. package/dist/esm/events/index.js +132 -0
  109. package/dist/esm/events/index.js.map +1 -0
  110. package/dist/esm/idl/index.js +57 -0
  111. package/dist/esm/idl/index.js.map +1 -0
  112. package/dist/esm/idl/synapse_agent_sap.json +9710 -0
  113. package/dist/esm/index.js +70 -0
  114. package/dist/esm/index.js.map +1 -0
  115. package/dist/esm/modules/agent.js +268 -0
  116. package/dist/esm/modules/agent.js.map +1 -0
  117. package/dist/esm/modules/attestation.js +143 -0
  118. package/dist/esm/modules/attestation.js.map +1 -0
  119. package/dist/esm/modules/base.js +124 -0
  120. package/dist/esm/modules/base.js.map +1 -0
  121. package/dist/esm/modules/escrow.js +242 -0
  122. package/dist/esm/modules/escrow.js.map +1 -0
  123. package/dist/esm/modules/feedback.js +162 -0
  124. package/dist/esm/modules/feedback.js.map +1 -0
  125. package/dist/esm/modules/index.js +23 -0
  126. package/dist/esm/modules/index.js.map +1 -0
  127. package/dist/esm/modules/indexing.js +371 -0
  128. package/dist/esm/modules/indexing.js.map +1 -0
  129. package/dist/esm/modules/ledger.js +230 -0
  130. package/dist/esm/modules/ledger.js.map +1 -0
  131. package/dist/esm/modules/tools.js +315 -0
  132. package/dist/esm/modules/tools.js.map +1 -0
  133. package/dist/esm/modules/vault.js +406 -0
  134. package/dist/esm/modules/vault.js.map +1 -0
  135. package/dist/esm/pda/index.js +357 -0
  136. package/dist/esm/pda/index.js.map +1 -0
  137. package/dist/esm/plugin/index.js +927 -0
  138. package/dist/esm/plugin/index.js.map +1 -0
  139. package/dist/esm/plugin/protocols.js +279 -0
  140. package/dist/esm/plugin/protocols.js.map +1 -0
  141. package/dist/esm/plugin/schemas.js +828 -0
  142. package/dist/esm/plugin/schemas.js.map +1 -0
  143. package/dist/esm/postgres/adapter.js +678 -0
  144. package/dist/esm/postgres/adapter.js.map +1 -0
  145. package/dist/esm/postgres/index.js +27 -0
  146. package/dist/esm/postgres/index.js.map +1 -0
  147. package/dist/esm/postgres/serializers.js +362 -0
  148. package/dist/esm/postgres/serializers.js.map +1 -0
  149. package/dist/esm/postgres/sync.js +217 -0
  150. package/dist/esm/postgres/sync.js.map +1 -0
  151. package/dist/esm/postgres/types.js +41 -0
  152. package/dist/esm/postgres/types.js.map +1 -0
  153. package/dist/esm/registries/builder.js +410 -0
  154. package/dist/esm/registries/builder.js.map +1 -0
  155. package/dist/esm/registries/discovery.js +358 -0
  156. package/dist/esm/registries/discovery.js.map +1 -0
  157. package/dist/esm/registries/index.js +44 -0
  158. package/dist/esm/registries/index.js.map +1 -0
  159. package/dist/esm/registries/session.js +429 -0
  160. package/dist/esm/registries/session.js.map +1 -0
  161. package/dist/esm/registries/x402.js +573 -0
  162. package/dist/esm/registries/x402.js.map +1 -0
  163. package/dist/esm/types/accounts.js +12 -0
  164. package/dist/esm/types/accounts.js.map +1 -0
  165. package/dist/esm/types/common.js +12 -0
  166. package/dist/esm/types/common.js.map +1 -0
  167. package/dist/esm/types/enums.js +171 -0
  168. package/dist/esm/types/enums.js.map +1 -0
  169. package/dist/esm/types/index.js +25 -0
  170. package/dist/esm/types/index.js.map +1 -0
  171. package/dist/esm/types/instructions.js +89 -0
  172. package/dist/esm/types/instructions.js.map +1 -0
  173. package/dist/esm/utils/hash.js +53 -0
  174. package/dist/esm/utils/hash.js.map +1 -0
  175. package/dist/esm/utils/index.js +19 -0
  176. package/dist/esm/utils/index.js.map +1 -0
  177. package/dist/esm/utils/serialization.js +98 -0
  178. package/dist/esm/utils/serialization.js.map +1 -0
  179. package/dist/esm/utils/validation.js +33 -0
  180. package/dist/esm/utils/validation.js.map +1 -0
  181. package/dist/types/constants/index.d.ts +27 -0
  182. package/dist/types/constants/index.d.ts.map +1 -0
  183. package/dist/types/constants/limits.d.ts +149 -0
  184. package/dist/types/constants/limits.d.ts.map +1 -0
  185. package/dist/types/constants/programs.d.ts +69 -0
  186. package/dist/types/constants/programs.d.ts.map +1 -0
  187. package/dist/types/constants/seeds.d.ts +61 -0
  188. package/dist/types/constants/seeds.d.ts.map +1 -0
  189. package/dist/types/core/client.d.ts +323 -0
  190. package/dist/types/core/client.d.ts.map +1 -0
  191. package/dist/types/core/connection.d.ts +279 -0
  192. package/dist/types/core/connection.d.ts.map +1 -0
  193. package/dist/types/core/index.d.ts +20 -0
  194. package/dist/types/core/index.d.ts.map +1 -0
  195. package/dist/types/errors/index.d.ts +276 -0
  196. package/dist/types/errors/index.d.ts.map +1 -0
  197. package/dist/types/events/index.d.ts +248 -0
  198. package/dist/types/events/index.d.ts.map +1 -0
  199. package/dist/types/idl/index.d.ts +70 -0
  200. package/dist/types/idl/index.d.ts.map +1 -0
  201. package/dist/types/index.d.ts +68 -0
  202. package/dist/types/index.d.ts.map +1 -0
  203. package/dist/types/modules/agent.d.ts +166 -0
  204. package/dist/types/modules/agent.d.ts.map +1 -0
  205. package/dist/types/modules/attestation.d.ts +96 -0
  206. package/dist/types/modules/attestation.d.ts.map +1 -0
  207. package/dist/types/modules/base.d.ts +126 -0
  208. package/dist/types/modules/base.d.ts.map +1 -0
  209. package/dist/types/modules/escrow.d.ts +151 -0
  210. package/dist/types/modules/escrow.d.ts.map +1 -0
  211. package/dist/types/modules/feedback.d.ts +105 -0
  212. package/dist/types/modules/feedback.d.ts.map +1 -0
  213. package/dist/types/modules/index.d.ts +24 -0
  214. package/dist/types/modules/index.d.ts.map +1 -0
  215. package/dist/types/modules/indexing.d.ts +200 -0
  216. package/dist/types/modules/indexing.d.ts.map +1 -0
  217. package/dist/types/modules/ledger.d.ts +150 -0
  218. package/dist/types/modules/ledger.d.ts.map +1 -0
  219. package/dist/types/modules/tools.d.ts +182 -0
  220. package/dist/types/modules/tools.d.ts.map +1 -0
  221. package/dist/types/modules/vault.d.ts +240 -0
  222. package/dist/types/modules/vault.d.ts.map +1 -0
  223. package/dist/types/pda/index.d.ts +296 -0
  224. package/dist/types/pda/index.d.ts.map +1 -0
  225. package/dist/types/plugin/index.d.ts +171 -0
  226. package/dist/types/plugin/index.d.ts.map +1 -0
  227. package/dist/types/plugin/protocols.d.ts +152 -0
  228. package/dist/types/plugin/protocols.d.ts.map +1 -0
  229. package/dist/types/plugin/schemas.d.ts +823 -0
  230. package/dist/types/plugin/schemas.d.ts.map +1 -0
  231. package/dist/types/postgres/adapter.d.ts +355 -0
  232. package/dist/types/postgres/adapter.d.ts.map +1 -0
  233. package/dist/types/postgres/index.d.ts +24 -0
  234. package/dist/types/postgres/index.d.ts.map +1 -0
  235. package/dist/types/postgres/serializers.d.ts +30 -0
  236. package/dist/types/postgres/serializers.d.ts.map +1 -0
  237. package/dist/types/postgres/sync.d.ts +132 -0
  238. package/dist/types/postgres/sync.d.ts.map +1 -0
  239. package/dist/types/postgres/types.d.ts +167 -0
  240. package/dist/types/postgres/types.d.ts.map +1 -0
  241. package/dist/types/registries/builder.d.ts +340 -0
  242. package/dist/types/registries/builder.d.ts.map +1 -0
  243. package/dist/types/registries/discovery.d.ts +333 -0
  244. package/dist/types/registries/discovery.d.ts.map +1 -0
  245. package/dist/types/registries/index.d.ts +48 -0
  246. package/dist/types/registries/index.d.ts.map +1 -0
  247. package/dist/types/registries/session.d.ts +323 -0
  248. package/dist/types/registries/session.d.ts.map +1 -0
  249. package/dist/types/registries/x402.d.ts +463 -0
  250. package/dist/types/registries/x402.d.ts.map +1 -0
  251. package/dist/types/types/accounts.d.ts +565 -0
  252. package/dist/types/types/accounts.d.ts.map +1 -0
  253. package/dist/types/types/common.d.ts +166 -0
  254. package/dist/types/types/common.d.ts.map +1 -0
  255. package/dist/types/types/enums.d.ts +238 -0
  256. package/dist/types/types/enums.d.ts.map +1 -0
  257. package/dist/types/types/index.d.ts +28 -0
  258. package/dist/types/types/index.d.ts.map +1 -0
  259. package/dist/types/types/instructions.d.ts +366 -0
  260. package/dist/types/types/instructions.d.ts.map +1 -0
  261. package/dist/types/utils/hash.d.ts +48 -0
  262. package/dist/types/utils/hash.d.ts.map +1 -0
  263. package/dist/types/utils/index.d.ts +19 -0
  264. package/dist/types/utils/index.d.ts.map +1 -0
  265. package/dist/types/utils/serialization.d.ts +69 -0
  266. package/dist/types/utils/serialization.d.ts.map +1 -0
  267. package/dist/types/utils/validation.d.ts +29 -0
  268. package/dist/types/utils/validation.d.ts.map +1 -0
  269. package/package.json +178 -0
  270. package/src/constants/index.ts +44 -0
  271. package/src/constants/limits.ts +165 -0
  272. package/src/constants/programs.ts +83 -0
  273. package/src/constants/seeds.ts +66 -0
  274. package/src/core/client.ts +416 -0
  275. package/src/core/connection.ts +409 -0
  276. package/src/core/index.ts +20 -0
  277. package/src/errors/index.ts +346 -0
  278. package/src/events/index.ts +335 -0
  279. package/src/idl/index.ts +76 -0
  280. package/src/idl/synapse_agent_sap.json +9710 -0
  281. package/src/index.ts +253 -0
  282. package/src/modules/agent.ts +319 -0
  283. package/src/modules/attestation.ts +168 -0
  284. package/src/modules/base.ts +158 -0
  285. package/src/modules/escrow.ts +308 -0
  286. package/src/modules/feedback.ts +186 -0
  287. package/src/modules/index.ts +24 -0
  288. package/src/modules/indexing.ts +444 -0
  289. package/src/modules/ledger.ts +262 -0
  290. package/src/modules/tools.ts +411 -0
  291. package/src/modules/vault.ts +533 -0
  292. package/src/pda/index.ts +512 -0
  293. package/src/plugin/index.ts +1202 -0
  294. package/src/plugin/protocols.ts +404 -0
  295. package/src/plugin/schemas.ts +909 -0
  296. package/src/postgres/adapter.ts +904 -0
  297. package/src/postgres/index.ts +59 -0
  298. package/src/postgres/schema.sql +683 -0
  299. package/src/postgres/serializers.ts +485 -0
  300. package/src/postgres/sync.ts +254 -0
  301. package/src/postgres/types.ts +245 -0
  302. package/src/registries/builder.ts +607 -0
  303. package/src/registries/discovery.ts +572 -0
  304. package/src/registries/index.ts +77 -0
  305. package/src/registries/session.ts +613 -0
  306. package/src/registries/x402.ts +906 -0
  307. package/src/types/accounts.ts +618 -0
  308. package/src/types/common.ts +187 -0
  309. package/src/types/enums.ts +214 -0
  310. package/src/types/index.ts +92 -0
  311. package/src/types/instructions.ts +413 -0
  312. package/src/utils/hash.ts +57 -0
  313. package/src/utils/index.ts +19 -0
  314. package/src/utils/serialization.ts +98 -0
  315. package/src/utils/validation.ts +36 -0
@@ -0,0 +1,927 @@
1
+ /**
2
+ * @module plugin
3
+ * @description SynapsePlugin adapter for SAP v2.
4
+ *
5
+ * Exposes 52 tools across 8 on-chain protocol domains as a drop-in
6
+ * `SynapsePlugin` for `SynapseAgentKit`:
7
+ *
8
+ * ```ts
9
+ * import { SynapseAgentKit } from '@oobe-protocol-labs/synapse-client-sdk/ai/plugins';
10
+ * import { createSAPPlugin } from '@synapse-sap/sdk/plugin';
11
+ *
12
+ * const sapPlugin = createSAPPlugin({ provider });
13
+ * const kit = new SynapseAgentKit({ rpcUrl })
14
+ * .use(sapPlugin);
15
+ *
16
+ * const tools = kit.getTools(); // → StructuredTool[] (LangChain)
17
+ * ```
18
+ *
19
+ * Architecture:
20
+ * 1. Schemas (Zod) → runtime validation + LLM-friendly descriptions
21
+ * 2. Protocols → 8 domain method registries (agent, feedback, …)
22
+ * 3. Executor → dispatches tool calls to SapClient module methods
23
+ * 4. Serialization → PublicKey↔string, BN↔string bridging
24
+ *
25
+ * @category Plugin
26
+ * @since v0.1.0
27
+ */
28
+ import { PublicKey } from "@solana/web3.js";
29
+ import BN from "bn.js";
30
+ import { SapClient } from "../core/client";
31
+ import { SAP_PROTOCOLS, } from "./protocols";
32
+ import { deriveAgent, deriveVault, deriveSession, deriveLedger } from "../pda";
33
+ import { hashToArray, sha256 } from "../utils";
34
+ // ═══════════════════════════════════════════════════════════════════
35
+ // Version
36
+ // ═══════════════════════════════════════════════════════════════════
37
+ /**
38
+ * Current SAP plugin version string.
39
+ *
40
+ * @name SAP_PLUGIN_VERSION
41
+ * @description Semver version embedded in the plugin’s {@link PluginMeta}.
42
+ * @internal
43
+ * @since v0.1.0
44
+ */
45
+ const SAP_PLUGIN_VERSION = "0.1.0";
46
+ // ═══════════════════════════════════════════════════════════════════
47
+ // Serialization Helpers
48
+ // ═══════════════════════════════════════════════════════════════════
49
+ /**
50
+ * Convert a base58 string to PublicKey.
51
+ *
52
+ * @name toPubkey
53
+ * @description Returns `undefined` for nullish input, otherwise wraps
54
+ * the base58 string in a Solana `PublicKey`.
55
+ * @param value - Base58-encoded public key or nullish
56
+ * @returns A `PublicKey` instance, or `undefined`
57
+ * @internal
58
+ * @since v0.1.0
59
+ */
60
+ function toPubkey(value) {
61
+ return value ? new PublicKey(value) : undefined;
62
+ }
63
+ /**
64
+ * Convert a string amount to BN.
65
+ *
66
+ * @name toBN
67
+ * @description Returns `undefined` for nullish input, otherwise parses
68
+ * the string as a `BN` (big number) instance.
69
+ * @param value - Numeric string or nullish
70
+ * @returns A `BN` instance, or `undefined`
71
+ * @internal
72
+ * @since v0.1.0
73
+ */
74
+ function toBN(value) {
75
+ return value ? new BN(value) : undefined;
76
+ }
77
+ /**
78
+ * Convert a hex string to a Node.js Buffer.
79
+ *
80
+ * @name hexToBuffer
81
+ * @description Used for encrypted data payloads before sending to
82
+ * on-chain instructions.
83
+ * @param hex - Hex-encoded string
84
+ * @returns Buffer of decoded bytes
85
+ * @internal
86
+ * @since v0.1.0
87
+ */
88
+ function hexToBuffer(hex) {
89
+ return Buffer.from(hex, "hex");
90
+ }
91
+ /**
92
+ * Convert a hex string to Uint8Array for PDA seed derivation.
93
+ *
94
+ * @name hexToBytes
95
+ * @description Wraps `Buffer.from(hex, 'hex')` into a `Uint8Array`
96
+ * suitable for Solana PDA seed arrays.
97
+ * @param hex - Hex-encoded string
98
+ * @returns Uint8Array of decoded bytes
99
+ * @internal
100
+ * @since v0.1.0
101
+ */
102
+ function hexToBytes(hex) {
103
+ return new Uint8Array(Buffer.from(hex, "hex"));
104
+ }
105
+ /**
106
+ * Map token type strings to Anchor enum variant objects.
107
+ *
108
+ * @name toTokenType
109
+ * @description Converts `"sol"`, `"usdc"`, or `"spl"` to the
110
+ * corresponding Anchor enum variant. Defaults to `{ sol: {} }`.
111
+ * @param s - Token type string
112
+ * @returns Anchor-compatible enum variant object
113
+ * @internal
114
+ * @since v0.1.0
115
+ */
116
+ function toTokenType(s) {
117
+ const map = {
118
+ sol: { sol: {} },
119
+ usdc: { usdc: {} },
120
+ spl: { spl: {} },
121
+ };
122
+ return map[s] ?? { sol: {} };
123
+ }
124
+ /**
125
+ * Map settlement mode strings to Anchor enum variant objects.
126
+ *
127
+ * @name toSettlementMode
128
+ * @description Converts `"instant"`, `"escrow"`, `"batched"`, or `"x402"`
129
+ * to the corresponding Anchor enum variant. Returns `null` for nullish input.
130
+ * @param s - Settlement mode string or nullish
131
+ * @returns Anchor-compatible enum variant object, or `null`
132
+ * @internal
133
+ * @since v0.1.0
134
+ */
135
+ function toSettlementMode(s) {
136
+ if (!s)
137
+ return null;
138
+ const map = {
139
+ instant: { instant: {} },
140
+ escrow: { escrow: {} },
141
+ batched: { batched: {} },
142
+ x402: { x402: {} },
143
+ };
144
+ return map[s] ?? null;
145
+ }
146
+ /**
147
+ * Map HTTP method strings to numeric enum values.
148
+ *
149
+ * @name toHttpMethodNum
150
+ * @description Converts lowercase method names (`"get"`, `"post"`, etc.)
151
+ * to their on-chain numeric representation. Defaults to `0` (GET).
152
+ * @param s - HTTP method string
153
+ * @returns Numeric enum value
154
+ * @internal
155
+ * @since v0.1.0
156
+ */
157
+ function toHttpMethodNum(s) {
158
+ const map = {
159
+ get: 0,
160
+ post: 1,
161
+ put: 2,
162
+ delete: 3,
163
+ compound: 4,
164
+ };
165
+ return map[s] ?? 0;
166
+ }
167
+ /**
168
+ * Map category strings to numeric enum values.
169
+ *
170
+ * @name toCategoryNum
171
+ * @description Converts category names (`"swap"`, `"lend"`, etc.)
172
+ * to their on-chain numeric representation. Defaults to `9` (custom).
173
+ * @param s - Category string
174
+ * @returns Numeric enum value
175
+ * @internal
176
+ * @since v0.1.0
177
+ */
178
+ function toCategoryNum(s) {
179
+ const map = {
180
+ swap: 0,
181
+ lend: 1,
182
+ stake: 2,
183
+ nft: 3,
184
+ payment: 4,
185
+ data: 5,
186
+ governance: 6,
187
+ bridge: 7,
188
+ analytics: 8,
189
+ custom: 9,
190
+ };
191
+ return map[s] ?? 9;
192
+ }
193
+ /**
194
+ * Map schema type strings to numeric enum values.
195
+ *
196
+ * @name toSchemaTypeNum
197
+ * @description Converts `"input"`, `"output"`, or `"description"`
198
+ * to their on-chain numeric representation. Defaults to `0` (input).
199
+ * @param s - Schema type string
200
+ * @returns Numeric enum value
201
+ * @internal
202
+ * @since v0.1.0
203
+ */
204
+ function toSchemaTypeNum(s) {
205
+ const map = { input: 0, output: 1, description: 2 };
206
+ return map[s] ?? 0;
207
+ }
208
+ /**
209
+ * Map compression type strings to numeric enum values.
210
+ *
211
+ * @name toCompressionNum
212
+ * @description Converts `"none"`, `"deflate"`, `"gzip"`, or `"brotli"`
213
+ * to their on-chain numeric representation. Defaults to `0` (none).
214
+ * @param s - Compression type string
215
+ * @returns Numeric enum value
216
+ * @internal
217
+ * @since v0.1.0
218
+ */
219
+ function toCompressionNum(s) {
220
+ const map = {
221
+ none: 0,
222
+ deflate: 1,
223
+ gzip: 2,
224
+ brotli: 3,
225
+ };
226
+ return map[s] ?? 0;
227
+ }
228
+ /**
229
+ * Convert a JSON-serialized pricing tier from plugin input
230
+ * into the SDK’s PricingTier shape with BN/PublicKey/enum conversions.
231
+ *
232
+ * @name toPricingTier
233
+ * @description Transforms raw JSON input (string amounts, string enums)
234
+ * into the native Anchor-compatible shape with `BN`, `PublicKey`,
235
+ * and enum variant objects.
236
+ * @param raw - Raw pricing tier object from Zod-validated plugin input
237
+ * @returns Anchor-compatible PricingTier object
238
+ * @internal
239
+ * @since v0.1.0
240
+ */
241
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
242
+ function toPricingTier(raw) {
243
+ return {
244
+ tierId: raw.tierId,
245
+ pricePerCall: new BN(raw.pricePerCall),
246
+ minPricePerCall: toBN(raw.minPricePerCall) ?? null,
247
+ maxPricePerCall: toBN(raw.maxPricePerCall) ?? null,
248
+ rateLimit: raw.rateLimit,
249
+ maxCallsPerSession: raw.maxCallsPerSession,
250
+ burstLimit: raw.burstLimit ?? null,
251
+ tokenType: toTokenType(raw.tokenType),
252
+ tokenMint: toPubkey(raw.tokenMint) ?? null,
253
+ tokenDecimals: raw.tokenDecimals ?? null,
254
+ settlementMode: toSettlementMode(raw.settlementMode),
255
+ minEscrowDeposit: toBN(raw.minEscrowDeposit) ?? null,
256
+ batchIntervalSec: raw.batchIntervalSec ?? null,
257
+ volumeCurve: raw.volumeCurve
258
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
259
+ ? raw.volumeCurve.map((v) => ({
260
+ afterCalls: v.afterCalls,
261
+ pricePerCall: new BN(v.pricePerCall),
262
+ }))
263
+ : null,
264
+ };
265
+ }
266
+ /**
267
+ * Serialize an on-chain account object to a JSON-safe shape.
268
+ *
269
+ * @name serializeAccount
270
+ * @description Recursively converts `PublicKey` → base58 string,
271
+ * `BN` → decimal string, and nested objects/arrays. Used to
272
+ * return tool output that is JSON-serializable for LLMs.
273
+ * @param obj - Raw account data record from Anchor deserialization
274
+ * @returns JSON-safe record with all Solana types converted to strings
275
+ * @internal
276
+ * @since v0.1.0
277
+ */
278
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
279
+ function serializeAccount(obj) {
280
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
281
+ const result = {};
282
+ for (const [key, value] of Object.entries(obj)) {
283
+ if (value === null || value === undefined) {
284
+ result[key] = null;
285
+ }
286
+ else if (value instanceof PublicKey) {
287
+ result[key] = value.toBase58();
288
+ }
289
+ else if (BN.isBN(value)) {
290
+ result[key] = value.toString();
291
+ }
292
+ else if (Array.isArray(value)) {
293
+ result[key] = value.map((item) => {
294
+ if (item instanceof PublicKey)
295
+ return item.toBase58();
296
+ if (BN.isBN(item))
297
+ return item.toString();
298
+ if (typeof item === "object" && item !== null)
299
+ return serializeAccount(item);
300
+ return item;
301
+ });
302
+ }
303
+ else if (typeof value === "object") {
304
+ result[key] = serializeAccount(value);
305
+ }
306
+ else {
307
+ result[key] = value;
308
+ }
309
+ }
310
+ return result;
311
+ }
312
+ // ═══════════════════════════════════════════════════════════════════
313
+ // Executor Builder
314
+ // ═══════════════════════════════════════════════════════════════════
315
+ /**
316
+ * Build the executor function that dispatches incoming tool calls
317
+ * to the appropriate SapClient module method.
318
+ *
319
+ * @name buildExecutor
320
+ * @description Creates a closure over a `SapClient` instance that routes
321
+ * each incoming `ProtocolMethod` to the correct per-protocol dispatcher
322
+ * based on `method.protocol`.
323
+ * @param client - Initialized SapClient for the configured provider
324
+ * @returns Async executor function `(method, input) => Promise<unknown>`
325
+ * @internal
326
+ * @since v0.1.0
327
+ */
328
+ function buildExecutor(client) {
329
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
330
+ return async (method, raw) => {
331
+ switch (method.protocol) {
332
+ // ────────────────────── Agent ──────────────────────
333
+ case "sap-agent":
334
+ return executeAgent(client, method.name, raw);
335
+ // ────────────────────── Feedback ───────────────────
336
+ case "sap-feedback":
337
+ return executeFeedback(client, method.name, raw);
338
+ // ────────────────────── Attestation ────────────────
339
+ case "sap-attestation":
340
+ return executeAttestation(client, method.name, raw);
341
+ // ────────────────────── Escrow ─────────────────────
342
+ case "sap-escrow":
343
+ return executeEscrow(client, method.name, raw);
344
+ // ────────────────────── Tools ──────────────────────
345
+ case "sap-tools":
346
+ return executeTools(client, method.name, raw);
347
+ // ────────────────────── Vault ──────────────────────
348
+ case "sap-vault":
349
+ return executeVault(client, method.name, raw);
350
+ // ────────────────────── Indexing ───────────────────
351
+ case "sap-indexing":
352
+ return executeIndexing(client, method.name, raw);
353
+ // ────────────────────── Ledger ─────────────────────
354
+ case "sap-ledger":
355
+ return executeLedger(client, method.name, raw);
356
+ default:
357
+ throw new Error(`Unknown SAP protocol: ${method.protocol}`);
358
+ }
359
+ };
360
+ }
361
+ // ═══════════════════════════════════════════════════════════════════
362
+ // Per-Protocol Dispatchers
363
+ // ═══════════════════════════════════════════════════════════════════
364
+ /**
365
+ * Dispatch tool calls for the **sap-agent** protocol.
366
+ *
367
+ * @name executeAgent
368
+ * @description Routes agent-domain method names to `client.agent.*` calls,
369
+ * handling argument conversion and account serialization.
370
+ * @param client - SapClient instance
371
+ * @param name - Method name (e.g. `"registerAgent"`)
372
+ * @param input - Zod-validated input from the LLM tool call
373
+ * @returns Transaction signature or serialized account data
374
+ * @internal
375
+ * @since v0.1.0
376
+ */
377
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
378
+ async function executeAgent(client, name, input) {
379
+ switch (name) {
380
+ case "registerAgent": {
381
+ const args = {
382
+ name: input.name,
383
+ description: input.description,
384
+ capabilities: input.capabilities,
385
+ pricing: (input.pricing ?? []).map(toPricingTier),
386
+ protocols: input.protocols ?? [],
387
+ agentId: input.agentId ?? null,
388
+ agentUri: input.agentUri ?? null,
389
+ x402Endpoint: input.x402Endpoint ?? null,
390
+ };
391
+ const tx = await client.agent.register(args);
392
+ return { txSignature: tx };
393
+ }
394
+ case "updateAgent": {
395
+ const args = {
396
+ name: input.name ?? null,
397
+ description: input.description ?? null,
398
+ capabilities: input.capabilities ?? null,
399
+ pricing: input.pricing ? input.pricing.map(toPricingTier) : null,
400
+ protocols: input.protocols ?? null,
401
+ agentId: input.agentId ?? null,
402
+ agentUri: input.agentUri ?? null,
403
+ x402Endpoint: input.x402Endpoint ?? null,
404
+ };
405
+ const tx = await client.agent.update(args);
406
+ return { txSignature: tx };
407
+ }
408
+ case "deactivateAgent": {
409
+ const tx = await client.agent.deactivate();
410
+ return { txSignature: tx };
411
+ }
412
+ case "reactivateAgent": {
413
+ const tx = await client.agent.reactivate();
414
+ return { txSignature: tx };
415
+ }
416
+ case "reportCalls": {
417
+ const tx = await client.agent.reportCalls(input.callsServed);
418
+ return { txSignature: tx };
419
+ }
420
+ case "updateReputation": {
421
+ const tx = await client.agent.updateReputation(input.avgLatencyMs, input.uptimePercent);
422
+ return { txSignature: tx };
423
+ }
424
+ case "fetchAgent": {
425
+ const wallet = toPubkey(input.wallet);
426
+ const data = await client.agent.fetch(wallet);
427
+ return serializeAccount(data);
428
+ }
429
+ case "fetchGlobalRegistry": {
430
+ const data = await client.agent.fetchGlobalRegistry();
431
+ return serializeAccount(data);
432
+ }
433
+ default:
434
+ throw new Error(`Unknown sap-agent method: ${name}`);
435
+ }
436
+ }
437
+ /**
438
+ * Dispatch tool calls for the **sap-feedback** protocol.
439
+ *
440
+ * @name executeFeedback
441
+ * @description Routes feedback-domain method names to `client.feedback.*` calls.
442
+ * @param client - SapClient instance
443
+ * @param name - Method name (e.g. `"giveFeedback"`)
444
+ * @param input - Zod-validated input from the LLM tool call
445
+ * @returns Transaction signature or serialized account data
446
+ * @internal
447
+ * @since v0.1.0
448
+ */
449
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
450
+ async function executeFeedback(client, name, input) {
451
+ switch (name) {
452
+ case "giveFeedback": {
453
+ const agentWallet = new PublicKey(input.agentWallet);
454
+ const args = {
455
+ score: input.score,
456
+ tag: input.tag,
457
+ commentHash: input.commentHash ?? null,
458
+ };
459
+ const tx = await client.feedback.give(agentWallet, args);
460
+ return { txSignature: tx };
461
+ }
462
+ case "updateFeedback": {
463
+ const agentWallet = new PublicKey(input.agentWallet);
464
+ const args = {
465
+ newScore: input.newScore,
466
+ newTag: input.newTag ?? null,
467
+ commentHash: input.commentHash ?? null,
468
+ };
469
+ const tx = await client.feedback.update(agentWallet, args);
470
+ return { txSignature: tx };
471
+ }
472
+ case "revokeFeedback": {
473
+ const tx = await client.feedback.revoke(new PublicKey(input.agentWallet));
474
+ return { txSignature: tx };
475
+ }
476
+ case "fetchFeedback": {
477
+ const [agentPda] = deriveAgent(new PublicKey(input.agentWallet));
478
+ const reviewer = toPubkey(input.reviewer);
479
+ const data = await client.feedback.fetch(agentPda, reviewer);
480
+ return serializeAccount(data);
481
+ }
482
+ default:
483
+ throw new Error(`Unknown sap-feedback method: ${name}`);
484
+ }
485
+ }
486
+ /**
487
+ * Dispatch tool calls for the **sap-attestation** protocol.
488
+ *
489
+ * @name executeAttestation
490
+ * @description Routes attestation-domain method names to `client.attestation.*` calls.
491
+ * @param client - SapClient instance
492
+ * @param name - Method name (e.g. `"createAttestation"`)
493
+ * @param input - Zod-validated input from the LLM tool call
494
+ * @returns Transaction signature or serialized account data
495
+ * @internal
496
+ * @since v0.1.0
497
+ */
498
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
499
+ async function executeAttestation(client, name, input) {
500
+ switch (name) {
501
+ case "createAttestation": {
502
+ const args = {
503
+ attestationType: input.attestationType,
504
+ metadataHash: input.metadataHash,
505
+ expiresAt: new BN(input.expiresAt),
506
+ };
507
+ const tx = await client.attestation.create(new PublicKey(input.agentWallet), args);
508
+ return { txSignature: tx };
509
+ }
510
+ case "revokeAttestation": {
511
+ const tx = await client.attestation.revoke(new PublicKey(input.agentWallet));
512
+ return { txSignature: tx };
513
+ }
514
+ case "fetchAttestation": {
515
+ const [agentPda] = deriveAgent(new PublicKey(input.agentWallet));
516
+ const attester = toPubkey(input.attester);
517
+ const data = await client.attestation.fetch(agentPda, attester);
518
+ return serializeAccount(data);
519
+ }
520
+ default:
521
+ throw new Error(`Unknown sap-attestation method: ${name}`);
522
+ }
523
+ }
524
+ /**
525
+ * Dispatch tool calls for the **sap-escrow** protocol.
526
+ *
527
+ * @name executeEscrow
528
+ * @description Routes escrow-domain method names to `client.escrow.*` calls,
529
+ * including BN conversion for amounts and volume curves.
530
+ * @param client - SapClient instance
531
+ * @param name - Method name (e.g. `"createEscrow"`)
532
+ * @param input - Zod-validated input from the LLM tool call
533
+ * @returns Transaction signature or serialized account data
534
+ * @internal
535
+ * @since v0.1.0
536
+ */
537
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
538
+ async function executeEscrow(client, name, input) {
539
+ switch (name) {
540
+ case "createEscrow": {
541
+ const args = {
542
+ pricePerCall: new BN(input.pricePerCall),
543
+ maxCalls: new BN(input.maxCalls),
544
+ initialDeposit: new BN(input.initialDeposit),
545
+ expiresAt: new BN(input.expiresAt),
546
+ volumeCurve: (input.volumeCurve ?? []).map(
547
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
548
+ (v) => ({
549
+ afterCalls: v.afterCalls,
550
+ pricePerCall: new BN(v.pricePerCall),
551
+ })),
552
+ tokenMint: toPubkey(input.tokenMint) ?? null,
553
+ tokenDecimals: input.tokenDecimals ?? 9,
554
+ };
555
+ const tx = await client.escrow.create(new PublicKey(input.agentWallet), args);
556
+ return { txSignature: tx };
557
+ }
558
+ case "depositEscrow": {
559
+ const tx = await client.escrow.deposit(new PublicKey(input.agentWallet), new BN(input.amount));
560
+ return { txSignature: tx };
561
+ }
562
+ case "settleEscrow": {
563
+ const tx = await client.escrow.settle(new PublicKey(input.depositorWallet), new BN(input.callsToSettle), input.serviceHash);
564
+ return { txSignature: tx };
565
+ }
566
+ case "withdrawEscrow": {
567
+ const tx = await client.escrow.withdraw(new PublicKey(input.agentWallet), new BN(input.amount));
568
+ return { txSignature: tx };
569
+ }
570
+ case "batchSettle": {
571
+ const settlements = input.settlements.map(
572
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
573
+ (s) => ({
574
+ callsToSettle: new BN(s.callsToSettle),
575
+ serviceHash: s.serviceHash,
576
+ }));
577
+ const tx = await client.escrow.settleBatch(new PublicKey(input.depositorWallet), settlements);
578
+ return { txSignature: tx };
579
+ }
580
+ case "fetchEscrow": {
581
+ const [agentPda] = deriveAgent(new PublicKey(input.agentWallet));
582
+ const depositor = toPubkey(input.depositor);
583
+ const data = await client.escrow.fetch(agentPda, depositor);
584
+ return serializeAccount(data);
585
+ }
586
+ default:
587
+ throw new Error(`Unknown sap-escrow method: ${name}`);
588
+ }
589
+ }
590
+ /**
591
+ * Dispatch tool calls for the **sap-tools** protocol.
592
+ *
593
+ * @name executeTools
594
+ * @description Routes tools-domain method names to `client.tools.*` calls,
595
+ * handling schema hashing and enum conversions.
596
+ * @param client - SapClient instance
597
+ * @param name - Method name (e.g. `"publishToolByName"`)
598
+ * @param input - Zod-validated input from the LLM tool call
599
+ * @returns Transaction signature or serialized account data
600
+ * @internal
601
+ * @since v0.1.0
602
+ */
603
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
604
+ async function executeTools(client, name, input) {
605
+ switch (name) {
606
+ case "publishToolByName": {
607
+ const tx = await client.tools.publishByName(input.toolName, input.protocolId, input.description, input.inputSchema, input.outputSchema, toHttpMethodNum(input.httpMethod), toCategoryNum(input.category), input.paramsCount, input.requiredParams, input.isCompound ?? false);
608
+ return { txSignature: tx };
609
+ }
610
+ case "inscribeToolSchema": {
611
+ const args = {
612
+ schemaType: toSchemaTypeNum(input.schemaType),
613
+ schemaData: Buffer.from(input.schemaData, "utf-8"),
614
+ schemaHash: hashToArray(sha256(input.schemaData)),
615
+ compression: toCompressionNum(input.compression ?? "none"),
616
+ };
617
+ const tx = await client.tools.inscribeSchema(input.toolName, args);
618
+ return { txSignature: tx };
619
+ }
620
+ case "updateTool": {
621
+ const args = {
622
+ descriptionHash: null,
623
+ inputSchemaHash: null,
624
+ outputSchemaHash: null,
625
+ httpMethod: input.httpMethod != null ? toHttpMethodNum(input.httpMethod) : null,
626
+ category: input.category != null ? toCategoryNum(input.category) : null,
627
+ paramsCount: input.paramsCount ?? null,
628
+ requiredParams: input.requiredParams ?? null,
629
+ };
630
+ const tx = await client.tools.update(input.toolName, args);
631
+ return { txSignature: tx };
632
+ }
633
+ case "deactivateTool": {
634
+ const tx = await client.tools.deactivate(input.toolName);
635
+ return { txSignature: tx };
636
+ }
637
+ case "reactivateTool": {
638
+ const tx = await client.tools.reactivate(input.toolName);
639
+ return { txSignature: tx };
640
+ }
641
+ case "reportInvocations": {
642
+ const tx = await client.tools.reportInvocations(input.toolName, input.invocations);
643
+ return { txSignature: tx };
644
+ }
645
+ case "fetchTool": {
646
+ const [agentPda] = deriveAgent(new PublicKey(input.agentWallet));
647
+ const data = await client.tools.fetch(agentPda, input.toolName);
648
+ return serializeAccount(data);
649
+ }
650
+ default:
651
+ throw new Error(`Unknown sap-tools method: ${name}`);
652
+ }
653
+ }
654
+ /**
655
+ * Dispatch tool calls for the **sap-vault** protocol.
656
+ *
657
+ * @name executeVault
658
+ * @description Routes vault-domain method names to `client.vault.*` calls,
659
+ * handling hex-to-bytes conversion and PDA derivation for sessions.
660
+ * @param client - SapClient instance
661
+ * @param name - Method name (e.g. `"initVault"`)
662
+ * @param input - Zod-validated input from the LLM tool call
663
+ * @returns Transaction signature or serialized account data
664
+ * @internal
665
+ * @since v0.1.0
666
+ */
667
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
668
+ async function executeVault(client, name, input) {
669
+ switch (name) {
670
+ case "initVault": {
671
+ const tx = await client.vault.initVault(input.vaultNonce);
672
+ return { txSignature: tx };
673
+ }
674
+ case "openSession": {
675
+ const tx = await client.vault.openSession(input.sessionHash);
676
+ return { txSignature: tx };
677
+ }
678
+ case "inscribeMemory": {
679
+ const args = {
680
+ sequence: input.sequence,
681
+ encryptedData: hexToBuffer(input.encryptedData),
682
+ nonce: input.nonce,
683
+ contentHash: input.contentHash,
684
+ totalFragments: input.totalFragments ?? 1,
685
+ fragmentIndex: input.fragmentIndex ?? 0,
686
+ compression: input.compression ?? 0,
687
+ epochIndex: input.epochIndex ?? 0,
688
+ };
689
+ const tx = await client.vault.inscribe(args);
690
+ return { txSignature: tx };
691
+ }
692
+ case "closeSession": {
693
+ const [agentPda] = deriveAgent(client.walletPubkey);
694
+ const [vaultPda] = deriveVault(agentPda);
695
+ const sessionHashBytes = hexToBytes(input.sessionHash);
696
+ const [sessionPda] = deriveSession(vaultPda, sessionHashBytes);
697
+ const tx = await client.vault.closeSession(vaultPda, sessionPda);
698
+ return { txSignature: tx };
699
+ }
700
+ case "closeVault": {
701
+ const tx = await client.vault.closeVault();
702
+ return { txSignature: tx };
703
+ }
704
+ case "rotateNonce": {
705
+ const tx = await client.vault.rotateNonce(input.newNonce);
706
+ return { txSignature: tx };
707
+ }
708
+ case "addDelegate": {
709
+ const tx = await client.vault.addDelegate(new PublicKey(input.delegatePubkey), input.permissions, BigInt(input.expiresAt));
710
+ return { txSignature: tx };
711
+ }
712
+ case "revokeDelegate": {
713
+ const tx = await client.vault.revokeDelegate(new PublicKey(input.delegatePubkey));
714
+ return { txSignature: tx };
715
+ }
716
+ case "fetchVault": {
717
+ const wallet = toPubkey(input.agentWallet) ?? client.walletPubkey;
718
+ const [agentPda] = deriveAgent(wallet);
719
+ const data = await client.vault.fetchVault(agentPda);
720
+ return serializeAccount(data);
721
+ }
722
+ case "fetchSession": {
723
+ const wallet = new PublicKey(input.agentWallet);
724
+ const [agentPda] = deriveAgent(wallet);
725
+ const [vaultPda] = deriveVault(agentPda);
726
+ const sessionHashBytes = hexToBytes(input.sessionHash);
727
+ const data = await client.vault.fetchSession(vaultPda, sessionHashBytes);
728
+ return serializeAccount(data);
729
+ }
730
+ default:
731
+ throw new Error(`Unknown sap-vault method: ${name}`);
732
+ }
733
+ }
734
+ /**
735
+ * Dispatch tool calls for the **sap-indexing** protocol.
736
+ *
737
+ * @name executeIndexing
738
+ * @description Routes indexing-domain method names to `client.indexing.*` calls
739
+ * for capability and protocol index management.
740
+ * @param client - SapClient instance
741
+ * @param name - Method name (e.g. `"initCapabilityIndex"`)
742
+ * @param input - Zod-validated input from the LLM tool call
743
+ * @returns Transaction signature or serialized account data
744
+ * @internal
745
+ * @since v0.1.0
746
+ */
747
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
748
+ async function executeIndexing(client, name, input) {
749
+ switch (name) {
750
+ case "initCapabilityIndex": {
751
+ const tx = await client.indexing.initCapabilityIndex(input.capabilityId);
752
+ return { txSignature: tx };
753
+ }
754
+ case "addToCapabilityIndex": {
755
+ const tx = await client.indexing.addToCapabilityIndex(input.capabilityId);
756
+ return { txSignature: tx };
757
+ }
758
+ case "removeFromCapabilityIndex": {
759
+ const tx = await client.indexing.removeFromCapabilityIndex(input.capabilityId);
760
+ return { txSignature: tx };
761
+ }
762
+ case "initProtocolIndex": {
763
+ const tx = await client.indexing.initProtocolIndex(input.protocolId);
764
+ return { txSignature: tx };
765
+ }
766
+ case "addToProtocolIndex": {
767
+ const tx = await client.indexing.addToProtocolIndex(input.protocolId);
768
+ return { txSignature: tx };
769
+ }
770
+ case "removeFromProtocolIndex": {
771
+ const tx = await client.indexing.removeFromProtocolIndex(input.protocolId);
772
+ return { txSignature: tx };
773
+ }
774
+ case "fetchCapabilityIndex": {
775
+ const data = await client.indexing.fetchCapabilityIndex(input.capabilityId);
776
+ return serializeAccount(data);
777
+ }
778
+ case "fetchProtocolIndex": {
779
+ const data = await client.indexing.fetchProtocolIndex(input.protocolId);
780
+ return serializeAccount(data);
781
+ }
782
+ default:
783
+ throw new Error(`Unknown sap-indexing method: ${name}`);
784
+ }
785
+ }
786
+ /**
787
+ * Dispatch tool calls for the **sap-ledger** protocol.
788
+ *
789
+ * @name executeLedger
790
+ * @description Routes ledger-domain method names to `client.ledger.*` calls,
791
+ * deriving session PDAs from hex-encoded session hashes.
792
+ * @param client - SapClient instance
793
+ * @param name - Method name (e.g. `"initLedger"`)
794
+ * @param input - Zod-validated input from the LLM tool call
795
+ * @returns Transaction signature or serialized account data
796
+ * @internal
797
+ * @since v0.1.0
798
+ */
799
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
800
+ async function executeLedger(client, name, input) {
801
+ const resolveSessionPda = (sessionHash, agentWallet) => {
802
+ const wallet = toPubkey(agentWallet) ?? client.walletPubkey;
803
+ const [agentPda] = deriveAgent(wallet);
804
+ const [vaultPda] = deriveVault(agentPda);
805
+ const sessionHashBytes = hexToBytes(sessionHash);
806
+ const [sessionPda] = deriveSession(vaultPda, sessionHashBytes);
807
+ return sessionPda;
808
+ };
809
+ switch (name) {
810
+ case "initLedger": {
811
+ const sessionPda = resolveSessionPda(input.sessionHash, input.agentWallet);
812
+ const tx = await client.ledger.init(sessionPda);
813
+ return { txSignature: tx };
814
+ }
815
+ case "writeLedger": {
816
+ const sessionPda = resolveSessionPda(input.sessionHash, input.agentWallet);
817
+ const data = hexToBuffer(input.data);
818
+ const tx = await client.ledger.write(sessionPda, data, input.contentHash);
819
+ return { txSignature: tx };
820
+ }
821
+ case "sealLedger": {
822
+ const sessionPda = resolveSessionPda(input.sessionHash, input.agentWallet);
823
+ const tx = await client.ledger.seal(sessionPda);
824
+ return { txSignature: tx };
825
+ }
826
+ case "closeLedger": {
827
+ const sessionPda = resolveSessionPda(input.sessionHash, input.agentWallet);
828
+ const tx = await client.ledger.close(sessionPda);
829
+ return { txSignature: tx };
830
+ }
831
+ case "fetchLedger": {
832
+ const sessionPda = resolveSessionPda(input.sessionHash, input.agentWallet);
833
+ const data = await client.ledger.fetchLedger(sessionPda);
834
+ return serializeAccount(data);
835
+ }
836
+ case "fetchLedgerPage": {
837
+ const sessionPda = resolveSessionPda(input.sessionHash, input.agentWallet);
838
+ const [ledgerPda] = deriveLedger(sessionPda);
839
+ const data = await client.ledger.fetchPage(ledgerPda, input.pageIndex);
840
+ return serializeAccount(data);
841
+ }
842
+ default:
843
+ throw new Error(`Unknown sap-ledger method: ${name}`);
844
+ }
845
+ }
846
+ // ═══════════════════════════════════════════════════════════════════
847
+ // Plugin Factory
848
+ // ═══════════════════════════════════════════════════════════════════
849
+ /**
850
+ * Create a SynapsePlugin for SAP v2.
851
+ *
852
+ * @name createSAPPlugin
853
+ * @description Factory function that returns a fully configured
854
+ * {@link SynapsePlugin} exposing 52 tools across 8 on-chain
855
+ * protocol domains. The plugin can be installed into a
856
+ * `SynapseAgentKit` instance or used standalone.
857
+ * @param config - Plugin configuration with Anchor provider and optional program ID
858
+ * @returns A configured {@link SynapsePlugin} instance
859
+ * @category Plugin
860
+ * @since v0.1.0
861
+ *
862
+ * @example
863
+ * ```ts
864
+ * import { createSAPPlugin } from '@synapse-sap/sdk/plugin';
865
+ *
866
+ * const sapPlugin = createSAPPlugin({ provider });
867
+ *
868
+ * // Use with SynapseAgentKit:
869
+ * kit.use(sapPlugin);
870
+ *
871
+ * // Or standalone:
872
+ * const executor = sapPlugin.install({ client, config: {} }).executor;
873
+ * await executor(someMethod, someInput);
874
+ * ```
875
+ */
876
+ export function createSAPPlugin(config) {
877
+ return {
878
+ meta: {
879
+ id: "sap",
880
+ name: "SAP v2 — Solana Agent Protocol",
881
+ version: SAP_PLUGIN_VERSION,
882
+ description: "On-chain agent identity, reputation, tool registry, encrypted memory vault, x402 escrow, attestation, discovery indexes, and unified memory ledger on Solana",
883
+ tags: [
884
+ "solana",
885
+ "agent",
886
+ "identity",
887
+ "reputation",
888
+ "x402",
889
+ "escrow",
890
+ "vault",
891
+ "memory",
892
+ "tools",
893
+ "attestation",
894
+ "erc-8004",
895
+ ],
896
+ },
897
+ protocols: SAP_PROTOCOLS,
898
+ install(_context) {
899
+ const client = SapClient.from(config.provider, config.programId);
900
+ const executor = buildExecutor(client);
901
+ return { executor };
902
+ },
903
+ };
904
+ }
905
+ /**
906
+ * Pre-built plugin object for static use patterns.
907
+ *
908
+ * @name SAPPlugin
909
+ * @description Convenience namespace exposing a `configure` method
910
+ * that delegates to {@link createSAPPlugin}. Useful for concise
911
+ * one-liner instantiation.
912
+ * @category Plugin
913
+ * @since v0.1.0
914
+ *
915
+ * @example
916
+ * ```ts
917
+ * import { SAPPlugin } from '@synapse-sap/sdk/plugin';
918
+ *
919
+ * const plugin = SAPPlugin.configure({ provider });
920
+ * kit.use(plugin);
921
+ * ```
922
+ */
923
+ export const SAPPlugin = {
924
+ /** Create a configured SynapsePlugin from an AnchorProvider. */
925
+ configure: createSAPPlugin,
926
+ };
927
+ //# sourceMappingURL=index.js.map