@0gfoundation/0g-agentdna 0.0.0-stage → 0.2.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 (206) hide show
  1. package/GUIDE.md +975 -0
  2. package/LICENSE +21 -0
  3. package/MIGRATION.md +84 -0
  4. package/MIGRATION.zh.md +70 -0
  5. package/PROVIDERS.md +273 -0
  6. package/PROVIDERS.zh.md +234 -0
  7. package/README.md +334 -2
  8. package/dist/AgentClient.d.ts +312 -0
  9. package/dist/AgentClient.d.ts.map +1 -0
  10. package/dist/AgentClient.js +715 -0
  11. package/dist/AgentClient.js.map +1 -0
  12. package/dist/AgenticID.d.ts +823 -0
  13. package/dist/AgenticID.d.ts.map +1 -0
  14. package/dist/AgenticID.js +1188 -0
  15. package/dist/AgenticID.js.map +1 -0
  16. package/dist/AgenticIDClient.d.ts +68 -0
  17. package/dist/AgenticIDClient.d.ts.map +1 -0
  18. package/dist/AgenticIDClient.js +198 -0
  19. package/dist/AgenticIDClient.js.map +1 -0
  20. package/dist/AttestorClient.d.ts +465 -0
  21. package/dist/AttestorClient.d.ts.map +1 -0
  22. package/dist/AttestorClient.js +1030 -0
  23. package/dist/AttestorClient.js.map +1 -0
  24. package/dist/Providers.d.ts +72 -0
  25. package/dist/Providers.d.ts.map +1 -0
  26. package/dist/Providers.js +182 -0
  27. package/dist/Providers.js.map +1 -0
  28. package/dist/ReputationClient.d.ts +213 -0
  29. package/dist/ReputationClient.d.ts.map +1 -0
  30. package/dist/ReputationClient.js +708 -0
  31. package/dist/ReputationClient.js.map +1 -0
  32. package/dist/SandboxClient.d.ts +107 -0
  33. package/dist/SandboxClient.d.ts.map +1 -0
  34. package/dist/SandboxClient.js +200 -0
  35. package/dist/SandboxClient.js.map +1 -0
  36. package/dist/ServeProof.d.ts +161 -0
  37. package/dist/ServeProof.d.ts.map +1 -0
  38. package/dist/ServeProof.js +230 -0
  39. package/dist/ServeProof.js.map +1 -0
  40. package/dist/ServeSession.d.ts +180 -0
  41. package/dist/ServeSession.d.ts.map +1 -0
  42. package/dist/ServeSession.js +336 -0
  43. package/dist/ServeSession.js.map +1 -0
  44. package/dist/Settings.d.ts +179 -0
  45. package/dist/Settings.d.ts.map +1 -0
  46. package/dist/Settings.js +247 -0
  47. package/dist/Settings.js.map +1 -0
  48. package/dist/abi.d.ts +2216 -0
  49. package/dist/abi.d.ts.map +1 -0
  50. package/dist/abi.js +1248 -0
  51. package/dist/abi.js.map +1 -0
  52. package/dist/cli/commands/cells.d.ts +34 -0
  53. package/dist/cli/commands/cells.d.ts.map +1 -0
  54. package/dist/cli/commands/cells.js +66 -0
  55. package/dist/cli/commands/cells.js.map +1 -0
  56. package/dist/cli/commands/doctor.d.ts +15 -0
  57. package/dist/cli/commands/doctor.d.ts.map +1 -0
  58. package/dist/cli/commands/doctor.js +236 -0
  59. package/dist/cli/commands/doctor.js.map +1 -0
  60. package/dist/cli/commands/interactive.d.ts +107 -0
  61. package/dist/cli/commands/interactive.d.ts.map +1 -0
  62. package/dist/cli/commands/interactive.js +3034 -0
  63. package/dist/cli/commands/interactive.js.map +1 -0
  64. package/dist/cli/commands/list.d.ts +31 -0
  65. package/dist/cli/commands/list.d.ts.map +1 -0
  66. package/dist/cli/commands/list.js +115 -0
  67. package/dist/cli/commands/list.js.map +1 -0
  68. package/dist/cli/commands/providers.d.ts +3 -0
  69. package/dist/cli/commands/providers.d.ts.map +1 -0
  70. package/dist/cli/commands/providers.js +21 -0
  71. package/dist/cli/commands/providers.js.map +1 -0
  72. package/dist/cli/commands/settings.d.ts +22 -0
  73. package/dist/cli/commands/settings.d.ts.map +1 -0
  74. package/dist/cli/commands/settings.js +188 -0
  75. package/dist/cli/commands/settings.js.map +1 -0
  76. package/dist/cli/commands/status.d.ts +16 -0
  77. package/dist/cli/commands/status.d.ts.map +1 -0
  78. package/dist/cli/commands/status.js +148 -0
  79. package/dist/cli/commands/status.js.map +1 -0
  80. package/dist/cli/commands/update.d.ts +21 -0
  81. package/dist/cli/commands/update.d.ts.map +1 -0
  82. package/dist/cli/commands/update.js +95 -0
  83. package/dist/cli/commands/update.js.map +1 -0
  84. package/dist/cli/config.d.ts +73 -0
  85. package/dist/cli/config.d.ts.map +1 -0
  86. package/dist/cli/config.js +239 -0
  87. package/dist/cli/config.js.map +1 -0
  88. package/dist/cli/env.d.ts +36 -0
  89. package/dist/cli/env.d.ts.map +1 -0
  90. package/dist/cli/env.js +74 -0
  91. package/dist/cli/env.js.map +1 -0
  92. package/dist/cli/envelope.d.ts +33 -0
  93. package/dist/cli/envelope.d.ts.map +1 -0
  94. package/dist/cli/envelope.js +62 -0
  95. package/dist/cli/envelope.js.map +1 -0
  96. package/dist/cli/errors.d.ts +48 -0
  97. package/dist/cli/errors.d.ts.map +1 -0
  98. package/dist/cli/errors.js +81 -0
  99. package/dist/cli/errors.js.map +1 -0
  100. package/dist/cli/inference.d.ts +21 -0
  101. package/dist/cli/inference.d.ts.map +1 -0
  102. package/dist/cli/inference.js +60 -0
  103. package/dist/cli/inference.js.map +1 -0
  104. package/dist/cli/logo.d.ts +21 -0
  105. package/dist/cli/logo.d.ts.map +1 -0
  106. package/dist/cli/logo.js +131 -0
  107. package/dist/cli/logo.js.map +1 -0
  108. package/dist/cli/main.d.ts +14 -0
  109. package/dist/cli/main.d.ts.map +1 -0
  110. package/dist/cli/main.js +223 -0
  111. package/dist/cli/main.js.map +1 -0
  112. package/dist/cli/proofs.d.ts +67 -0
  113. package/dist/cli/proofs.d.ts.map +1 -0
  114. package/dist/cli/proofs.js +133 -0
  115. package/dist/cli/proofs.js.map +1 -0
  116. package/dist/cli/ref.d.ts +39 -0
  117. package/dist/cli/ref.d.ts.map +1 -0
  118. package/dist/cli/ref.js +48 -0
  119. package/dist/cli/ref.js.map +1 -0
  120. package/dist/cli/sdk.d.ts +24 -0
  121. package/dist/cli/sdk.d.ts.map +1 -0
  122. package/dist/cli/sdk.js +65 -0
  123. package/dist/cli/sdk.js.map +1 -0
  124. package/dist/cli/settings.d.ts +66 -0
  125. package/dist/cli/settings.d.ts.map +1 -0
  126. package/dist/cli/settings.js +137 -0
  127. package/dist/cli/settings.js.map +1 -0
  128. package/dist/cli/tokenize.d.ts +61 -0
  129. package/dist/cli/tokenize.d.ts.map +1 -0
  130. package/dist/cli/tokenize.js +157 -0
  131. package/dist/cli/tokenize.js.map +1 -0
  132. package/dist/cli/types.d.ts +25 -0
  133. package/dist/cli/types.d.ts.map +1 -0
  134. package/dist/cli/types.js +8 -0
  135. package/dist/cli/types.js.map +1 -0
  136. package/dist/constants.d.ts +107 -0
  137. package/dist/constants.d.ts.map +1 -0
  138. package/dist/constants.js +74 -0
  139. package/dist/constants.js.map +1 -0
  140. package/dist/context.d.ts +108 -0
  141. package/dist/context.d.ts.map +1 -0
  142. package/dist/context.js +64 -0
  143. package/dist/context.js.map +1 -0
  144. package/dist/index.d.ts +45 -0
  145. package/dist/index.d.ts.map +1 -0
  146. package/dist/index.js +118 -0
  147. package/dist/index.js.map +1 -0
  148. package/dist/provider-catalog.json +23 -0
  149. package/dist/seal.d.ts +47 -0
  150. package/dist/seal.d.ts.map +1 -0
  151. package/dist/seal.js +145 -0
  152. package/dist/seal.js.map +1 -0
  153. package/dist/secretEnv.d.ts +119 -0
  154. package/dist/secretEnv.d.ts.map +1 -0
  155. package/dist/secretEnv.js +199 -0
  156. package/dist/secretEnv.js.map +1 -0
  157. package/dist/taskHash.d.ts +39 -0
  158. package/dist/taskHash.d.ts.map +1 -0
  159. package/dist/taskHash.js +119 -0
  160. package/dist/taskHash.js.map +1 -0
  161. package/dist/types.d.ts +336 -0
  162. package/dist/types.d.ts.map +1 -0
  163. package/dist/types.js +19 -0
  164. package/dist/types.js.map +1 -0
  165. package/package.json +75 -4
  166. package/scripts/sync-providers.cjs +8 -0
  167. package/src/AgentClient.ts +897 -0
  168. package/src/AgenticID.ts +1382 -0
  169. package/src/AgenticIDClient.ts +238 -0
  170. package/src/AttestorClient.ts +1306 -0
  171. package/src/Providers.ts +176 -0
  172. package/src/ReputationClient.ts +821 -0
  173. package/src/SandboxClient.ts +227 -0
  174. package/src/ServeProof.ts +290 -0
  175. package/src/ServeSession.ts +421 -0
  176. package/src/Settings.ts +296 -0
  177. package/src/abi.ts +1282 -0
  178. package/src/cli/commands/cells.ts +61 -0
  179. package/src/cli/commands/doctor.ts +235 -0
  180. package/src/cli/commands/interactive.ts +2715 -0
  181. package/src/cli/commands/list.ts +117 -0
  182. package/src/cli/commands/providers.ts +16 -0
  183. package/src/cli/commands/settings.ts +197 -0
  184. package/src/cli/commands/status.ts +170 -0
  185. package/src/cli/commands/update.ts +86 -0
  186. package/src/cli/config.ts +225 -0
  187. package/src/cli/env.ts +90 -0
  188. package/src/cli/envelope.ts +57 -0
  189. package/src/cli/errors.ts +114 -0
  190. package/src/cli/inference.ts +57 -0
  191. package/src/cli/logo.ts +125 -0
  192. package/src/cli/main.ts +235 -0
  193. package/src/cli/proofs.ts +160 -0
  194. package/src/cli/ref.ts +58 -0
  195. package/src/cli/sdk.ts +65 -0
  196. package/src/cli/settings.ts +153 -0
  197. package/src/cli/tokenize.ts +131 -0
  198. package/src/cli/types.ts +27 -0
  199. package/src/constants.ts +106 -0
  200. package/src/context.ts +161 -0
  201. package/src/index.ts +129 -0
  202. package/src/provider-catalog.json +23 -0
  203. package/src/seal.ts +163 -0
  204. package/src/secretEnv.ts +250 -0
  205. package/src/taskHash.ts +100 -0
  206. package/src/types.ts +357 -0
@@ -0,0 +1,227 @@
1
+ /**
2
+ * @file SandboxClient.ts
3
+ * @description Internal client for trust-root ack (TappRegistry) + prepaid
4
+ * sandbox balance (SandboxServing). Surfaced on the `AgenticID` facade as
5
+ * top-level ops (`ack`/`ackStatus`/`deposit`/`getBalance`) — none is scoped to a
6
+ * single agent. (Agent-seal gas top-up lives on the `agent` namespace.)
7
+ *
8
+ * - ack: acknowledge the TEE component set (attestor/kms/sandbox) in one
9
+ * batched call over whatever isn't already acknowledged.
10
+ * - deposit: prepaid sandbox balance (charged for create/CPU/mem before deploy).
11
+ *
12
+ * NOTE: acknowledgeApps is a TappRegistry (tapp-layer) primitive wrapped here
13
+ * until a dedicated tapp SDK exists.
14
+ */
15
+
16
+ import {
17
+ type Address,
18
+ type WriteContractReturnType,
19
+ } from 'viem';
20
+ import { tappRegistryAbi, sandboxServingAbi } from './abi';
21
+ import { requireWallet, type Ctx } from './context';
22
+
23
+ export class SandboxClient {
24
+ constructor(private readonly ctx: Ctx) {}
25
+
26
+ private get tappRegistry(): Address { return this.ctx.addresses.tappRegistry; }
27
+ private get sandboxServing(): Address { return this.ctx.addresses.sandboxServing; }
28
+
29
+ /**
30
+ * Component appIds to ack: explicit config wins, else the attestor's
31
+ * GET /config (each environment names its own apps — the built-in
32
+ * defaults are prod names and made ack() revert "app not found" on
33
+ * -dev), else the built-in defaults.
34
+ */
35
+ async resolveAppIds(): Promise<string[]> {
36
+ if (this.ctx.componentAppIdsExplicit) return this.ctx.componentAppIds;
37
+ const cfg = await this.ctx.attestorConfig();
38
+ if (cfg) {
39
+ const ids = [cfg.attestor_app_id, cfg.kms_app_id, cfg.sandbox_app_id]
40
+ .filter((s): s is string => !!s && s.length > 0);
41
+ if (ids.length > 0) return ids;
42
+ }
43
+ return this.ctx.componentAppIds;
44
+ }
45
+
46
+ /** Sandbox provider address: explicit arg wins, else attestor /config. */
47
+ async resolveProvider(provider?: Address): Promise<Address> {
48
+ if (provider) return provider;
49
+ const cfg = await this.ctx.attestorConfig();
50
+ if (cfg?.sandbox_provider_addr) return cfg.sandbox_provider_addr;
51
+ throw new Error(
52
+ 'sandbox provider address unknown — pass `provider` explicitly or set attestorUrl (it is read from GET /config)',
53
+ );
54
+ }
55
+
56
+ // ── ack ──────────────────────────────────────────────────────────────────
57
+
58
+ /** Which of the configured component appIds `user` still needs to acknowledge. */
59
+ async ackStatus(user?: Address): Promise<{ allAcked: boolean; missing: string[] }> {
60
+ const addr = user ?? this.ctx.account?.address;
61
+ if (!addr) throw new Error('no user address (pass one or set account)');
62
+ const appIds = await this.resolveAppIds();
63
+ const flags = await Promise.all(
64
+ appIds.map((appId) =>
65
+ this.ctx.publicClient.readContract({
66
+ address: this.tappRegistry,
67
+ abi: tappRegistryAbi,
68
+ functionName: 'isAcknowledged',
69
+ args: [addr, appId],
70
+ }) as Promise<boolean>,
71
+ ),
72
+ );
73
+ const missing = appIds.filter((_, i) => !flags[i]);
74
+ return { allAcked: missing.length === 0, missing };
75
+ }
76
+
77
+ /**
78
+ * Acknowledge the whole component set in one tx. Returns null (no tx) when
79
+ * everything is already acknowledged.
80
+ */
81
+ async ack(): Promise<WriteContractReturnType | null> {
82
+ const { walletClient, account } = requireWallet(this.ctx);
83
+ const { missing } = await this.ackStatus(account.address);
84
+ if (missing.length === 0) return null;
85
+ return walletClient.writeContract({
86
+ address: this.tappRegistry,
87
+ abi: tappRegistryAbi,
88
+ functionName: 'acknowledgeApps',
89
+ args: [missing],
90
+ account,
91
+ chain: this.ctx.chain,
92
+ });
93
+ }
94
+
95
+ /**
96
+ * Full TappRegistry picture of every trust-root component this
97
+ * environment depends on — the "what am I actually acknowledging"
98
+ * data (code hashes, current ackVersion, registered nodes) that
99
+ * ack() asks the user to sign off on. One entry per component appId.
100
+ */
101
+ async components(user?: Address): Promise<Array<{
102
+ appId: string;
103
+ acked: boolean | null;
104
+ ackVersion: bigint;
105
+ owner: Address;
106
+ registeredAt: bigint;
107
+ composeHash: `0x${string}`;
108
+ imageHashes: `0x${string}`[];
109
+ nodes: Address[];
110
+ }>> {
111
+ const addr = user ?? this.ctx.account?.address ?? null;
112
+ const appIds = await this.resolveAppIds();
113
+ return Promise.all(appIds.map(async (appId) => {
114
+ const read = (functionName: string, args: unknown[]) =>
115
+ this.ctx.publicClient.readContract({
116
+ address: this.tappRegistry, abi: tappRegistryAbi,
117
+ functionName: functionName as never, args: args as never,
118
+ });
119
+ const [info, ackVersion, nodes, acked] = await Promise.all([
120
+ read('getAppInfo', [appId]) as Promise<{ composeHash: `0x${string}`; volumesHash: `0x${string}`; imageHashes: `0x${string}`[]; owner: Address; registeredAt: bigint }>,
121
+ read('getAckVersion', [appId]) as Promise<bigint>,
122
+ read('getNodeList', [appId]) as Promise<Address[]>,
123
+ addr ? (read('isAcknowledged', [addr, appId]) as Promise<boolean>) : Promise.resolve(null),
124
+ ]);
125
+ return {
126
+ appId, acked, ackVersion,
127
+ owner: info.owner, registeredAt: info.registeredAt,
128
+ composeHash: info.composeHash, imageHashes: info.imageHashes,
129
+ nodes,
130
+ };
131
+ }));
132
+ }
133
+
134
+ // ── deposit ──────────────────────────────────────────────────────────────
135
+
136
+ /**
137
+ * Read a user's *spendable* prepaid sandbox balance against a provider (wei).
138
+ * Both args optional: `user` defaults to the configured account,
139
+ * `provider` to the attestor /config's provider.
140
+ * Funds mid-refund are excluded — see {@link getBalanceDetail}.
141
+ */
142
+ async getBalance(user?: Address, provider?: Address): Promise<bigint> {
143
+ return (await this.getBalanceDetail(user, provider)).balance;
144
+ }
145
+
146
+ /**
147
+ * Full prepaid-account view: spendable `balance`, `pendingRefund` (moved out
148
+ * by requestRefund, locked), and `refundUnlockAt` (unix seconds when the
149
+ * pending refund becomes withdrawable; 0 if none). All wei/bigint.
150
+ */
151
+ async getBalanceDetail(user?: Address, provider?: Address): Promise<{ balance: bigint; pendingRefund: bigint; refundUnlockAt: bigint }> {
152
+ const addr = user ?? this.ctx.account?.address;
153
+ if (!addr) throw new Error('no user address (pass one or set account)');
154
+ const [balance, pendingRefund, refundUnlockAt] = (await this.ctx.publicClient.readContract({
155
+ address: this.sandboxServing,
156
+ abi: sandboxServingAbi,
157
+ functionName: 'getBalance',
158
+ args: [addr, await this.resolveProvider(provider)],
159
+ })) as [bigint, bigint, bigint];
160
+ return { balance, pendingRefund, refundUnlockAt };
161
+ }
162
+
163
+ /** Provider's registered service entry (endpoint + price schedule). Provider defaults from /config. */
164
+ async services(provider?: Address): Promise<{ url: string; appId: string; pricePerCPUPerMin: bigint; pricePerMemGBPerMin: bigint; createFee: bigint }> {
165
+ const p = await this.resolveProvider(provider);
166
+ const [url, appId, pricePerCPUPerMin, pricePerMemGBPerMin, createFee] =
167
+ (await this.ctx.publicClient.readContract({
168
+ address: this.sandboxServing, abi: sandboxServingAbi, functionName: 'services', args: [p],
169
+ })) as [string, string, bigint, bigint, bigint];
170
+ return { url, appId, pricePerCPUPerMin, pricePerMemGBPerMin, createFee };
171
+ }
172
+
173
+ /**
174
+ * Fund a prepaid sandbox balance (SandboxServing.deposit, payable).
175
+ * Recipient defaults to the caller; provider to the attestor /config's.
176
+ */
177
+ async deposit(params: {
178
+ amountWei: bigint;
179
+ provider?: Address;
180
+ recipient?: Address;
181
+ }): Promise<WriteContractReturnType> {
182
+ const { walletClient, account } = requireWallet(this.ctx);
183
+ return walletClient.writeContract({
184
+ address: this.sandboxServing,
185
+ abi: sandboxServingAbi,
186
+ functionName: 'deposit',
187
+ args: [params.recipient ?? account.address, await this.resolveProvider(params.provider)],
188
+ value: params.amountWei,
189
+ account,
190
+ chain: this.ctx.chain,
191
+ });
192
+ }
193
+
194
+ /**
195
+ * Start withdrawing prepaid funds: moves `amountWei` into `pendingRefund`,
196
+ * locked until `refundUnlockAt` (contract-set delay). NB the contract
197
+ * REPLACES any existing pending refund (re-absorbing it into the spendable
198
+ * balance first) and restarts the lock — `amountWei` is the new total, and
199
+ * may go up to `balance + pendingRefund`. Claim with {@link withdrawRefund}
200
+ * once unlocked; track via {@link getBalanceDetail}. Provider defaults to
201
+ * the attestor /config's.
202
+ */
203
+ async requestRefund(params: { amountWei: bigint; provider?: Address }): Promise<WriteContractReturnType> {
204
+ const { walletClient, account } = requireWallet(this.ctx);
205
+ return walletClient.writeContract({
206
+ address: this.sandboxServing,
207
+ abi: sandboxServingAbi,
208
+ functionName: 'requestRefund',
209
+ args: [await this.resolveProvider(params.provider), params.amountWei],
210
+ account,
211
+ chain: this.ctx.chain,
212
+ });
213
+ }
214
+
215
+ /** Claim the pending refund (reverts before `refundUnlockAt`); pays out to the caller's wallet. */
216
+ async withdrawRefund(provider?: Address): Promise<WriteContractReturnType> {
217
+ const { walletClient, account } = requireWallet(this.ctx);
218
+ return walletClient.writeContract({
219
+ address: this.sandboxServing,
220
+ abi: sandboxServingAbi,
221
+ functionName: 'withdrawRefund',
222
+ args: [await this.resolveProvider(provider)],
223
+ account,
224
+ chain: this.ctx.chain,
225
+ });
226
+ }
227
+ }
@@ -0,0 +1,290 @@
1
+ /**
2
+ * @file ServeProof.ts
3
+ * @description ServeProof construction and signing utilities for the 0G AgenticID protocol.
4
+ *
5
+ * A ServeProof attests that an agent (identified by agentSeal) served a task at a
6
+ * specific time. The agentSeal private key signs the proof. Two hashes:
7
+ *
8
+ * proofHash = keccak256(abi.encode(<proof fields>)) (buildServeProofMessageHash)
9
+ * digest = keccak256(0x19 ‖ 0x00 ‖ validator ‖ proofHash) (buildServeProofSigningHash)
10
+ *
11
+ * The signed digest is EIP-191 version 0x00 ("data with intended validator",
12
+ * OZ `MessageHashUtils.toDataWithIntendedValidatorHash`), where `validator` is
13
+ * the VerifiedFeedbackRegistry proxy that redeems the proof. It is NOT
14
+ * personal_sign: the sealed sign socket offers personal_sign (0x19 0x45),
15
+ * EIP-712 typed data (0x19 0x01) and transactions — never raw hashes or
16
+ * 0x19 0x00 — so an in-container agent cannot forge ServeProof contents
17
+ * through it. A personal_sign over proofHash is rejected on purpose.
18
+ *
19
+ * Attribution is msg.sender at giveFeedback submission (feedback is stored
20
+ * under the submitting address); the proof additionally names a `submitter`,
21
+ * the only address the registry lets redeem it (single-use via the signature).
22
+ */
23
+
24
+ import {
25
+ keccak256,
26
+ toHex,
27
+ pad,
28
+ concat,
29
+ isAddress,
30
+ recoverAddress,
31
+ type Address,
32
+ type Hex,
33
+ type Hash,
34
+ } from 'viem';
35
+ import type { ServeProof as ServeProofType } from './types';
36
+
37
+ const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
38
+
39
+ /**
40
+ * Parameters for building a ServeProof message hash (the inner `proofHash`).
41
+ */
42
+ export interface BuildServeProofHashParams {
43
+ /** Chain id the proof is bound to (domain separation) */
44
+ chainId: bigint;
45
+ /** The AgenticID (identity registry) address the reputation contract is
46
+ * anchored to — the verifying-contract domain */
47
+ verifyingContract: Address;
48
+ /** The only address allowed to redeem this proof */
49
+ submitter: Address;
50
+ /** The agent ID */
51
+ agentId: bigint;
52
+ /** Timestamp of service (unix seconds) */
53
+ timestamp: bigint;
54
+ /** Deadline for the proof's validity (unix seconds) */
55
+ deadline: bigint;
56
+ /** Hash of the task performed */
57
+ taskHash: Hash;
58
+ /** Hashes of the data involved in the service */
59
+ dataHashes: Hash[];
60
+ /** Hash of the agent framework version */
61
+ frameworkHash: Hash;
62
+ }
63
+
64
+ /**
65
+ * Parameters for building the signed ServeProof digest: the proof fields plus
66
+ * the intended validator.
67
+ */
68
+ export interface BuildServeProofSigningHashParams extends BuildServeProofHashParams {
69
+ /** The VerifiedFeedbackRegistry PROXY address that redeems the proof — the
70
+ * EIP-191 version 0x00 intended validator. Must be a non-zero address. */
71
+ validator: Address;
72
+ }
73
+
74
+ /**
75
+ * Compute the ServeProof message hash exactly as the Solidity contract does.
76
+ *
77
+ * Solidity:
78
+ * ```solidity
79
+ * bytes32 messageHash = keccak256(abi.encode(
80
+ * block.chainid,
81
+ * identityRegistry, // verifyingContract
82
+ * submitter,
83
+ * agentId,
84
+ * timestamp,
85
+ * deadline,
86
+ * taskHash,
87
+ * keccak256(abi.encodePacked(dataHashes)),
88
+ * frameworkHash
89
+ * ));
90
+ * ```
91
+ *
92
+ * chainId + verifyingContract give cross-chain / cross-deployment separation;
93
+ * submitter binds the proof to the single address allowed to redeem it.
94
+ * This is the inner hash only — what gets signed is
95
+ * {@link buildServeProofSigningHash}.
96
+ *
97
+ * @param params - The ServeProof hash parameters
98
+ * @returns The keccak256 hash of the abi.encode payload
99
+ */
100
+ export function buildServeProofMessageHash(params: BuildServeProofHashParams): Hash {
101
+ const { chainId, verifyingContract, submitter, agentId, timestamp, deadline, taskHash, dataHashes, frameworkHash } = params;
102
+
103
+ // Step 1: keccak256(abi.encodePacked(dataHashes)) — concatenate bytes32 values
104
+ const packedDataHashes: Hex = dataHashes.length > 0
105
+ ? concat(dataHashes as readonly Hex[])
106
+ : '0x';
107
+ const dataHashesHash = keccak256(packedDataHashes);
108
+
109
+ // Step 2: abi.encode(chainId, verifyingContract, submitter, agentId, timestamp,
110
+ // deadline, taskHash, dataHashesHash, frameworkHash). Each field is a static
111
+ // 32-byte word: uint256 = 32, address = 32 (left-padded), bytes32 = 32.
112
+ const encoded = concat([
113
+ pad(toHex(chainId), { size: 32 }),
114
+ pad(verifyingContract as Hex, { size: 32 }),
115
+ pad(submitter as Hex, { size: 32 }),
116
+ pad(toHex(agentId), { size: 32 }),
117
+ pad(toHex(timestamp), { size: 32 }),
118
+ pad(toHex(deadline), { size: 32 }),
119
+ pad(taskHash as Hex, { size: 32 }),
120
+ pad(dataHashesHash as Hex, { size: 32 }),
121
+ pad(frameworkHash as Hex, { size: 32 }),
122
+ ]);
123
+
124
+ // Step 3: keccak256(encoded)
125
+ return keccak256(encoded);
126
+ }
127
+
128
+ /** True for a well-formed (any case), non-zero 20-byte address. viem's
129
+ * `concat` does not validate lengths, so a short or padded validator would
130
+ * silently yield a digest nobody can redeem. */
131
+ function isUsableValidator(validator: unknown): validator is Address {
132
+ return (
133
+ typeof validator === 'string' &&
134
+ isAddress(validator, { strict: false }) &&
135
+ validator.toLowerCase() !== ZERO_ADDRESS
136
+ );
137
+ }
138
+
139
+ /**
140
+ * Compute the digest a ServeProof signature covers.
141
+ *
142
+ * EIP-191 version 0x00 (data with intended validator):
143
+ * `keccak256(0x19 ‖ 0x00 ‖ validator (20 bytes) ‖ proofHash (32 bytes))` —
144
+ * Solidity: `MessageHashUtils.toDataWithIntendedValidatorHash(address(this),
145
+ * abi.encodePacked(proofHash))` in the VerifiedFeedbackRegistry.
146
+ *
147
+ * @param params - The ServeProof hash parameters plus the validator
148
+ * @returns The final digest — sign it raw, never re-wrap it
149
+ * @throws if `validator` is missing, malformed, or the zero address
150
+ */
151
+ export function buildServeProofSigningHash(params: BuildServeProofSigningHashParams): Hash {
152
+ if (!isUsableValidator(params.validator)) {
153
+ throw new Error(
154
+ `buildServeProofSigningHash: validator must be the non-zero VerifiedFeedbackRegistry address (got ${String(params.validator)})`,
155
+ );
156
+ }
157
+ const messageHash = buildServeProofMessageHash(params);
158
+ return keccak256(concat(['0x1900', params.validator, messageHash]));
159
+ }
160
+
161
+ /**
162
+ * Build a complete ServeProof object from components (without signature).
163
+ *
164
+ * Use this to construct the proof, then sign it with the agentSeal private key
165
+ * using `signServeProof`.
166
+ *
167
+ * @param params - The ServeProof parameters (without signature)
168
+ * @returns ServeProof object with empty signature
169
+ */
170
+ export function buildServeProof(
171
+ params: Omit<ServeProofType, 'signature'>,
172
+ ): ServeProofType {
173
+ return {
174
+ ...params,
175
+ signature: '0x',
176
+ };
177
+ }
178
+
179
+ /**
180
+ * Sign a ServeProof using a viem account or wallet client.
181
+ *
182
+ * The hash handed to `sign` is already the final EIP-191 version 0x00 digest
183
+ * (`buildServeProofSigningHash`), so the callback must sign it raw —
184
+ * `account.sign({ hash })`. Do NOT use `signMessage({ message: { raw } })`:
185
+ * that produces the personal_sign (0x19 0x45) form, which the registry
186
+ * rejects on purpose, and the proof fails `verifyServeProofSignature`.
187
+ *
188
+ * @param params - The ServeProof parameters plus the validator (VerifiedFeedbackRegistry)
189
+ * @param sign - A function that raw-signs the final digest (e.g. `account.sign`)
190
+ * @returns The complete ServeProof with signature (and `validator`, informational)
191
+ *
192
+ * @example
193
+ * ```typescript
194
+ * import { signServeProof } from '@0gfoundation/0g-agentdna';
195
+ *
196
+ * const proof = await signServeProof(
197
+ * { chainId: 16602n, verifyingContract: '0x...', submitter: '0x...',
198
+ * agentId: 1n, timestamp: 1700000000n, deadline: 1700003600n,
199
+ * taskHash: '0x...', dataHashes: ['0x...'], frameworkHash: '0x...',
200
+ * validator: '0x...' }, // the VerifiedFeedbackRegistry proxy
201
+ * async (hash) => account.sign({ hash }),
202
+ * );
203
+ * ```
204
+ */
205
+ export async function signServeProof(
206
+ params: BuildServeProofSigningHashParams,
207
+ sign: (signingHash: Hash) => Promise<`0x${string}`>,
208
+ ): Promise<ServeProofType> {
209
+ const signingHash = buildServeProofSigningHash(params);
210
+ const signature = await sign(signingHash);
211
+ return {
212
+ agentId: params.agentId,
213
+ submitter: params.submitter,
214
+ timestamp: params.timestamp,
215
+ deadline: params.deadline,
216
+ taskHash: params.taskHash,
217
+ dataHashes: params.dataHashes,
218
+ frameworkHash: params.frameworkHash,
219
+ signature,
220
+ validator: params.validator,
221
+ };
222
+ }
223
+
224
+ /**
225
+ * Verify that a ServeProof signature matches the expected agentSeal address.
226
+ *
227
+ * The digest is domain-bound, so the caller supplies the chain id, the
228
+ * identity-registry (verifyingContract) the proof was issued against, and the
229
+ * VerifiedFeedbackRegistry (validator) it is meant for; the submitter comes
230
+ * from the proof itself. The proof's own `validator` field is NOT consulted —
231
+ * it is unsigned diagnostics; pass the registry you trust.
232
+ *
233
+ * Exactly as strict as the registry (OZ 5.0.2 `ECDSA.recover`): the signature
234
+ * must be 65 bytes with `v` ∈ {27, 28} and a low `s` (≤ secp256k1n / 2).
235
+ * A high-`s` or `v` ∈ {0, 1} encoding of an otherwise genuine signature
236
+ * recovers the same signer off chain but reverts on chain, so it is `false`
237
+ * here too — never an `ok` that the registry then refuses.
238
+ *
239
+ * @param proof - The complete ServeProof with signature
240
+ * @param expectedSigner - The agentSeal address that should have signed
241
+ * @param domain - The chainId + verifyingContract + validator the proof is bound to
242
+ * @returns True if the signature is valid for the expected signer; false for a
243
+ * missing / malformed / zero validator or a non-canonical signature encoding
244
+ */
245
+ export async function verifyServeProofSignature(
246
+ proof: ServeProofType,
247
+ expectedSigner: Address,
248
+ domain: { chainId: bigint; verifyingContract: Address; validator: Address },
249
+ ): Promise<boolean> {
250
+ // No usable validator → nothing to verify against. Never fall back to the
251
+ // legacy personal_sign digest.
252
+ if (!isUsableValidator(domain?.validator)) return false;
253
+ if (!isRegistryCanonicalSignature(proof.signature)) return false;
254
+ const signingHash = buildServeProofSigningHash({
255
+ chainId: domain.chainId,
256
+ verifyingContract: domain.verifyingContract,
257
+ validator: domain.validator,
258
+ submitter: proof.submitter,
259
+ agentId: proof.agentId,
260
+ timestamp: proof.timestamp,
261
+ deadline: proof.deadline,
262
+ taskHash: proof.taskHash,
263
+ dataHashes: proof.dataHashes,
264
+ frameworkHash: proof.frameworkHash,
265
+ });
266
+ // A malformed signature (bad length / invalid v) is just a failed verification,
267
+ // not an exception — a buyer verifying a hostile proof should get `false`.
268
+ let recovered: Address;
269
+ try {
270
+ recovered = await recoverAddress({ hash: signingHash, signature: proof.signature });
271
+ } catch {
272
+ return false;
273
+ }
274
+ return recovered.toLowerCase() === expectedSigner.toLowerCase();
275
+ }
276
+
277
+ /** secp256k1n / 2 — OZ ECDSA rejects any `s` above it (signature malleability). */
278
+ const SECP256K1N_HALF = BigInt('0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0');
279
+
280
+ /**
281
+ * Whether `sig` is an encoding the VerifiedFeedbackRegistry accepts: 65 bytes
282
+ * (`r ‖ s ‖ v`), `v` ∈ {27, 28} (ecrecover yields no signer for anything else)
283
+ * and `s` ≤ secp256k1n / 2 (OZ `ECDSA.tryRecover` → `ECDSAInvalidSignatureS`).
284
+ */
285
+ function isRegistryCanonicalSignature(sig: unknown): boolean {
286
+ if (typeof sig !== 'string' || !/^0x[0-9a-fA-F]{130}$/.test(sig)) return false;
287
+ const s = BigInt(`0x${sig.slice(66, 130)}`);
288
+ const v = parseInt(sig.slice(130, 132), 16);
289
+ return (v === 27 || v === 28) && s <= SECP256K1N_HALF;
290
+ }