@blindmarket/sdk 0.1.4

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 (244) hide show
  1. package/README.md +72 -0
  2. package/biome.json +19 -0
  3. package/dist/BlindEscrowClient-CyPuKMge.d.cts +54 -0
  4. package/dist/BlindEscrowClient-R7iGpE-n.d.ts +54 -0
  5. package/dist/KeyStore-Be_SSpCt.d.cts +21 -0
  6. package/dist/KeyStore-k1JgYPJY.d.ts +21 -0
  7. package/dist/Signer-BnqH_qew.d.cts +38 -0
  8. package/dist/Signer-LColE0Uo.d.ts +38 -0
  9. package/dist/Storage-4QOrh7rm.d.ts +17 -0
  10. package/dist/Storage-Cf4IJRMk.d.cts +17 -0
  11. package/dist/TaskRegistryClient-Ch6lYqM_.d.ts +24 -0
  12. package/dist/TaskRegistryClient-CrQjddDc.d.cts +24 -0
  13. package/dist/aes-J-7HrHze.d.cts +17 -0
  14. package/dist/aes-J-7HrHze.d.ts +17 -0
  15. package/dist/agent/Agent.d.ts +59 -0
  16. package/dist/agent/Agent.js +73 -0
  17. package/dist/agent/index.cjs +425 -0
  18. package/dist/agent/index.cjs.map +1 -0
  19. package/dist/agent/index.d.cts +63 -0
  20. package/dist/agent/index.d.ts +1 -0
  21. package/dist/agent/index.js +1 -0
  22. package/dist/agent/index.js.map +1 -0
  23. package/dist/api/index.cjs +4 -0
  24. package/dist/api/index.cjs.map +1 -0
  25. package/dist/api/index.d.cts +2 -0
  26. package/dist/api/index.d.ts +1 -0
  27. package/dist/api/index.js +1 -0
  28. package/dist/api/index.js.map +1 -0
  29. package/dist/chain/BlindEscrowClient.d.ts +51 -0
  30. package/dist/chain/BlindEscrowClient.js +142 -0
  31. package/dist/chain/BlindReputationClient.d.ts +16 -0
  32. package/dist/chain/BlindReputationClient.js +45 -0
  33. package/dist/chain/ChainClient.d.ts +26 -0
  34. package/dist/chain/ChainClient.js +46 -0
  35. package/dist/chain/TaskRegistryClient.d.ts +21 -0
  36. package/dist/chain/TaskRegistryClient.js +70 -0
  37. package/dist/chain/abi/BlindEscrow.json +1113 -0
  38. package/dist/chain/abi/BlindReputation.json +447 -0
  39. package/dist/chain/abi/TaskRegistry.json +586 -0
  40. package/dist/chain/abi/index.d.ts +4 -0
  41. package/dist/chain/abi/index.js +4 -0
  42. package/dist/chain/errors.d.ts +8 -0
  43. package/dist/chain/errors.js +32 -0
  44. package/dist/chain/index.cjs +2484 -0
  45. package/dist/chain/index.cjs.map +1 -0
  46. package/dist/chain/index.d.cts +2305 -0
  47. package/dist/chain/index.d.ts +6 -0
  48. package/dist/chain/index.js +6 -0
  49. package/dist/chain/index.js.map +1 -0
  50. package/dist/compute/index.cjs +4 -0
  51. package/dist/compute/index.cjs.map +1 -0
  52. package/dist/compute/index.d.cts +2 -0
  53. package/dist/compute/index.d.ts +1 -0
  54. package/dist/compute/index.js +1 -0
  55. package/dist/compute/index.js.map +1 -0
  56. package/dist/crypto/aes.d.ts +15 -0
  57. package/dist/crypto/aes.js +81 -0
  58. package/dist/crypto/constants.d.ts +7 -0
  59. package/dist/crypto/constants.js +7 -0
  60. package/dist/crypto/ecies.d.ts +8 -0
  61. package/dist/crypto/ecies.js +51 -0
  62. package/dist/crypto/envelope.d.ts +35 -0
  63. package/dist/crypto/envelope.js +103 -0
  64. package/dist/crypto/hkdf.d.ts +5 -0
  65. package/dist/crypto/hkdf.js +34 -0
  66. package/dist/crypto/index.cjs +424 -0
  67. package/dist/crypto/index.cjs.map +1 -0
  68. package/dist/crypto/index.d.cts +74 -0
  69. package/dist/crypto/index.d.ts +6 -0
  70. package/dist/crypto/index.js +6 -0
  71. package/dist/crypto/index.js.map +1 -0
  72. package/dist/crypto/keys.d.ts +12 -0
  73. package/dist/crypto/keys.js +42 -0
  74. package/dist/errors/BlindBountyError.d.ts +14 -0
  75. package/dist/errors/BlindBountyError.js +30 -0
  76. package/dist/errors/codes.d.ts +19 -0
  77. package/dist/errors/codes.js +48 -0
  78. package/dist/errors/index.cjs +136 -0
  79. package/dist/errors/index.cjs.map +1 -0
  80. package/dist/errors/index.d.cts +60 -0
  81. package/dist/errors/index.d.ts +3 -0
  82. package/dist/errors/index.js +3 -0
  83. package/dist/errors/index.js.map +1 -0
  84. package/dist/errors/subclasses.d.ts +26 -0
  85. package/dist/errors/subclasses.js +41 -0
  86. package/dist/events/EventBus.d.ts +13 -0
  87. package/dist/events/EventBus.js +41 -0
  88. package/dist/events/index.cjs +41 -0
  89. package/dist/events/index.cjs.map +1 -0
  90. package/dist/events/index.d.cts +61 -0
  91. package/dist/events/index.d.ts +2 -0
  92. package/dist/events/index.js +2 -0
  93. package/dist/events/index.js.map +1 -0
  94. package/dist/events/types.d.ts +45 -0
  95. package/dist/events/types.js +1 -0
  96. package/dist/index.cjs +4 -0
  97. package/dist/index.cjs.map +1 -0
  98. package/dist/index.d.cts +2 -0
  99. package/dist/index.d.ts +129 -0
  100. package/dist/index.js +154 -0
  101. package/dist/index.js.map +1 -0
  102. package/dist/keystore/InMemoryKeyStore.d.ts +21 -0
  103. package/dist/keystore/InMemoryKeyStore.js +111 -0
  104. package/dist/keystore/KeyStore.d.ts +18 -0
  105. package/dist/keystore/KeyStore.js +1 -0
  106. package/dist/keystore/index.cjs +335 -0
  107. package/dist/keystore/index.cjs.map +1 -0
  108. package/dist/keystore/index.d.cts +23 -0
  109. package/dist/keystore/index.d.ts +2 -0
  110. package/dist/keystore/index.js +2 -0
  111. package/dist/keystore/index.js.map +1 -0
  112. package/dist/network/index.cjs +74 -0
  113. package/dist/network/index.cjs.map +1 -0
  114. package/dist/network/index.d.cts +36 -0
  115. package/dist/network/index.d.ts +3 -0
  116. package/dist/network/index.js +3 -0
  117. package/dist/network/index.js.map +1 -0
  118. package/dist/network/presets.d.ts +24 -0
  119. package/dist/network/presets.js +23 -0
  120. package/dist/network/resolve.d.ts +7 -0
  121. package/dist/network/resolve.js +17 -0
  122. package/dist/network/types.d.ts +16 -0
  123. package/dist/network/types.js +1 -0
  124. package/dist/signer/EthersSigner.d.ts +24 -0
  125. package/dist/signer/EthersSigner.js +68 -0
  126. package/dist/signer/PrivateKeySigner.d.ts +14 -0
  127. package/dist/signer/PrivateKeySigner.js +18 -0
  128. package/dist/signer/Signer.d.ts +35 -0
  129. package/dist/signer/Signer.js +1 -0
  130. package/dist/signer/index.cjs +121 -0
  131. package/dist/signer/index.cjs.map +1 -0
  132. package/dist/signer/index.d.cts +40 -0
  133. package/dist/signer/index.d.ts +3 -0
  134. package/dist/signer/index.js +3 -0
  135. package/dist/signer/index.js.map +1 -0
  136. package/dist/storage/MemoryStorage.d.ts +18 -0
  137. package/dist/storage/MemoryStorage.js +40 -0
  138. package/dist/storage/Storage.d.ts +14 -0
  139. package/dist/storage/Storage.js +1 -0
  140. package/dist/storage/ZgStorage.d.ts +24 -0
  141. package/dist/storage/ZgStorage.js +102 -0
  142. package/dist/storage/index.cjs +221 -0
  143. package/dist/storage/index.cjs.map +1 -0
  144. package/dist/storage/index.d.cts +44 -0
  145. package/dist/storage/index.d.ts +3 -0
  146. package/dist/storage/index.js +3 -0
  147. package/dist/storage/index.js.map +1 -0
  148. package/dist/testing/index.cjs +4 -0
  149. package/dist/testing/index.cjs.map +1 -0
  150. package/dist/testing/index.d.cts +2 -0
  151. package/dist/testing/index.d.ts +1 -0
  152. package/dist/testing/index.js +1 -0
  153. package/dist/testing/index.js.map +1 -0
  154. package/dist/types-BOG5Ub1z.d.cts +31 -0
  155. package/dist/types-BOG5Ub1z.d.ts +31 -0
  156. package/dist/types-V7_ZmUb-.d.cts +19 -0
  157. package/dist/types-hAsITUQ7.d.ts +19 -0
  158. package/dist/types.d.ts +58 -0
  159. package/dist/types.js +1 -0
  160. package/dist/verifier/index.cjs +4 -0
  161. package/dist/verifier/index.cjs.map +1 -0
  162. package/dist/verifier/index.d.cts +2 -0
  163. package/dist/verifier/index.d.ts +1 -0
  164. package/dist/verifier/index.js +1 -0
  165. package/dist/verifier/index.js.map +1 -0
  166. package/dist/worker/Worker.d.ts +53 -0
  167. package/dist/worker/Worker.js +53 -0
  168. package/dist/worker/index.cjs +382 -0
  169. package/dist/worker/index.cjs.map +1 -0
  170. package/dist/worker/index.d.cts +58 -0
  171. package/dist/worker/index.d.ts +1 -0
  172. package/dist/worker/index.js +1 -0
  173. package/dist/worker/index.js.map +1 -0
  174. package/examples/agent-demo.ts +121 -0
  175. package/package.json +46 -0
  176. package/scripts/gen-crypto-fixtures.mjs +72 -0
  177. package/src/agent/Agent.ts +122 -0
  178. package/src/agent/index.ts +1 -0
  179. package/src/api/index.ts +1 -0
  180. package/src/chain/BlindEscrowClient.ts +182 -0
  181. package/src/chain/BlindReputationClient.ts +55 -0
  182. package/src/chain/ChainClient.ts +59 -0
  183. package/src/chain/TaskRegistryClient.ts +82 -0
  184. package/src/chain/abi/BlindEscrow.json +1113 -0
  185. package/src/chain/abi/BlindReputation.json +447 -0
  186. package/src/chain/abi/TaskRegistry.json +586 -0
  187. package/src/chain/abi/index.ts +5 -0
  188. package/src/chain/errors.ts +43 -0
  189. package/src/chain/index.ts +6 -0
  190. package/src/compute/index.ts +1 -0
  191. package/src/crypto/aes.ts +104 -0
  192. package/src/crypto/constants.ts +7 -0
  193. package/src/crypto/ecies.ts +60 -0
  194. package/src/crypto/envelope.ts +131 -0
  195. package/src/crypto/hkdf.ts +45 -0
  196. package/src/crypto/index.ts +6 -0
  197. package/src/crypto/keys.ts +56 -0
  198. package/src/errors/BlindMarketError.ts +38 -0
  199. package/src/errors/codes.ts +67 -0
  200. package/src/errors/index.ts +3 -0
  201. package/src/errors/subclasses.ts +59 -0
  202. package/src/events/EventBus.ts +45 -0
  203. package/src/events/index.ts +2 -0
  204. package/src/events/types.ts +13 -0
  205. package/src/index.ts +222 -0
  206. package/src/keystore/InMemoryKeyStore.ts +146 -0
  207. package/src/keystore/KeyStore.ts +19 -0
  208. package/src/keystore/index.ts +2 -0
  209. package/src/network/index.ts +3 -0
  210. package/src/network/presets.ts +27 -0
  211. package/src/network/resolve.ts +19 -0
  212. package/src/network/types.ts +18 -0
  213. package/src/signer/EthersSigner.ts +82 -0
  214. package/src/signer/PrivateKeySigner.ts +19 -0
  215. package/src/signer/Signer.ts +40 -0
  216. package/src/signer/index.ts +3 -0
  217. package/src/storage/MemoryStorage.ts +49 -0
  218. package/src/storage/Storage.ts +15 -0
  219. package/src/storage/ZgStorage.ts +124 -0
  220. package/src/storage/index.ts +3 -0
  221. package/src/testing/index.ts +1 -0
  222. package/src/types.ts +76 -0
  223. package/src/verifier/index.ts +1 -0
  224. package/src/worker/Worker.ts +98 -0
  225. package/src/worker/index.ts +1 -0
  226. package/test/agent.test.ts +193 -0
  227. package/test/chain.test.ts +145 -0
  228. package/test/crypto.aes.test.ts +81 -0
  229. package/test/crypto.compat.test.ts +33 -0
  230. package/test/crypto.ecies.test.ts +64 -0
  231. package/test/envelope.test.ts +82 -0
  232. package/test/errors.test.ts +64 -0
  233. package/test/events.test.ts +59 -0
  234. package/test/fixtures/crypto.json +16 -0
  235. package/test/keystore.test.ts +103 -0
  236. package/test/network.test.ts +53 -0
  237. package/test/signer.test.ts +66 -0
  238. package/test/smoke.test.ts +7 -0
  239. package/test/storage.test.ts +55 -0
  240. package/test/worker.test.ts +181 -0
  241. package/tsconfig.build.json +1 -0
  242. package/tsconfig.json +13 -0
  243. package/tsup.config.ts +32 -0
  244. package/vitest.config.ts +17 -0
package/src/index.ts ADDED
@@ -0,0 +1,222 @@
1
+ import { Wallet, ethers } from 'ethers';
2
+ import { createCipheriv, randomBytes, createHash } from 'crypto';
3
+
4
+ export interface BlindMarketConfig {
5
+ apiBase?: string;
6
+ apiKey: string;
7
+ rpcUrl?: string;
8
+ }
9
+
10
+ export interface DeployAgentParams {
11
+ name: string;
12
+ instructions: string;
13
+ provider: 'openai' | 'anthropic' | 'groq' | 'gemini';
14
+ model: string;
15
+ apiKey: string;
16
+ ownerAddress: string;
17
+ ownerPublicKey: string;
18
+ capabilities?: string[];
19
+ tools?: object[];
20
+ }
21
+
22
+ export interface PostTaskParams {
23
+ instructions: string;
24
+ category: string;
25
+ amount: string; // wei as string
26
+ token: string; // ERC-20 address
27
+ locationZone?: string;
28
+ duration?: string; // seconds
29
+ }
30
+
31
+ export interface DeployedAgent {
32
+ id: string;
33
+ name: string;
34
+ walletAddress: string;
35
+ publicKey: string;
36
+ inftTokenId?: number;
37
+ status: string;
38
+ }
39
+
40
+ export interface PostedTask {
41
+ unsignedTx: object;
42
+ taskHash: string;
43
+ storageRoot: string;
44
+ }
45
+
46
+ export class BlindMarket {
47
+ private apiBase: string;
48
+ private apiKey: string;
49
+
50
+ constructor(config: BlindMarketConfig) {
51
+ this.apiBase = config.apiBase ?? 'http://localhost:3001';
52
+ this.apiKey = config.apiKey;
53
+ }
54
+
55
+ private async req<T>(method: string, path: string, body?: unknown): Promise<T> {
56
+ const res = await fetch(`${this.apiBase}${path}`, {
57
+ method,
58
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.apiKey}` },
59
+ body: body ? JSON.stringify(body) : undefined,
60
+ });
61
+ const json = await res.json() as { success: boolean; data?: T; error?: { message: string } };
62
+ if (!json.success) throw new Error(json.error?.message ?? `HTTP ${res.status}`);
63
+ return json.data as T;
64
+ }
65
+
66
+ // ── Agent deployment ──────────────────────────────────────────────────────
67
+
68
+ /**
69
+ * Deploy a new agent. Generates a wallet, mints an INFT, returns the agent.
70
+ *
71
+ * @example
72
+ * const agent = await bb.deployAgent({
73
+ * name: 'research-agent',
74
+ * instructions: 'You research topics and post tasks for humans to verify.',
75
+ * provider: 'anthropic',
76
+ * model: 'claude-sonnet-4-5',
77
+ * apiKey: process.env.ANTHROPIC_API_KEY!,
78
+ * ownerAddress: wallet.address,
79
+ * ownerPublicKey: wallet.publicKey,
80
+ * });
81
+ */
82
+ async deployAgent(params: DeployAgentParams): Promise<DeployedAgent> {
83
+ return this.req<DeployedAgent>('POST', '/api/v1/agents/deploy', params);
84
+ }
85
+
86
+ /**
87
+ * List all agents owned by an address.
88
+ */
89
+ async listAgents(ownerAddress: string): Promise<DeployedAgent[]> {
90
+ return this.req<DeployedAgent[]>('GET', `/api/v1/agents?owner=${ownerAddress}`);
91
+ }
92
+
93
+ // ── Task lifecycle ────────────────────────────────────────────────────────
94
+
95
+ /**
96
+ * Encrypt instructions and post a task. Returns an unsigned tx to sign + broadcast.
97
+ *
98
+ * @example
99
+ * const { unsignedTx, taskHash } = await bb.postTask({
100
+ * instructions: 'Photograph the exterior of 42 Oak Street, NYC.',
101
+ * category: 'photography',
102
+ * amount: ethers.parseEther('30').toString(),
103
+ * token: '0x317227efcA18D004E12CA8046AEf7E1597458F25',
104
+ * locationZone: 'US-NY',
105
+ * });
106
+ * const receipt = await wallet.sendTransaction(unsignedTx);
107
+ */
108
+ async postTask(params: PostTaskParams): Promise<PostedTask> {
109
+ // Encrypt instructions
110
+ const key = randomBytes(32);
111
+ const iv = randomBytes(12);
112
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
113
+ const encrypted = Buffer.concat([cipher.update(params.instructions, 'utf8'), cipher.final()]);
114
+ const tag = (cipher as any).getAuthTag() as Buffer;
115
+ const blob = Buffer.concat([iv, tag, encrypted]).toString('base64');
116
+
117
+ // Upload to storage
118
+ const { rootHash } = await this.req<{ rootHash: string }>('POST', '/api/v1/storage/upload', { data: blob });
119
+
120
+ // taskHash = SHA-256 of ciphertext
121
+ const taskHash = '0x' + createHash('sha256').update(Buffer.concat([iv, tag, encrypted])).digest('hex');
122
+
123
+ // Build unsigned tx
124
+ const { unsignedTx } = await this.req<{ unsignedTx: object }>('POST', '/api/v1/tasks', {
125
+ taskHash,
126
+ token: params.token,
127
+ amount: params.amount,
128
+ category: params.category,
129
+ locationZone: params.locationZone ?? 'global',
130
+ duration: params.duration ?? '86400',
131
+ });
132
+
133
+ return { unsignedTx, taskHash, storageRoot: rootHash };
134
+ }
135
+
136
+ /**
137
+ * Assign a worker to a task. Returns an unsigned tx.
138
+ */
139
+ async assignWorker(taskId: string, worker: string): Promise<{ unsignedTx: object }> {
140
+ return this.req('POST', `/api/v1/tasks/${taskId}/assign`, { worker });
141
+ }
142
+
143
+ /**
144
+ * Trigger TEE verification for a task.
145
+ */
146
+ async verify(params: {
147
+ taskId: number;
148
+ requirements: string;
149
+ evidenceSummary: string;
150
+ category?: string;
151
+ }): Promise<{ passed: boolean; confidence: number; reasoning: string }> {
152
+ return this.req('POST', '/api/v1/verification/trigger', {
153
+ taskId: params.taskId,
154
+ taskCategory: params.category ?? 'general',
155
+ taskRequirements: params.requirements,
156
+ evidenceSummary: params.evidenceSummary,
157
+ });
158
+ }
159
+
160
+ /**
161
+ * Submit evidence for an assigned task.
162
+ */
163
+ async submitEvidence(params: { taskId: number; evidence: string }): Promise<{ unsignedTx: object }> {
164
+ const key = randomBytes(32);
165
+ const iv = randomBytes(12);
166
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
167
+ const encrypted = Buffer.concat([cipher.update(params.evidence, 'utf8'), cipher.final()]);
168
+ const tag = (cipher as any).getAuthTag() as Buffer;
169
+ const blob = Buffer.concat([iv, tag, encrypted]).toString('base64');
170
+
171
+ await this.req('POST', '/api/v1/storage/upload', { data: blob });
172
+ const evidenceHash = '0x' + createHash('sha256').update(Buffer.concat([iv, tag, encrypted])).digest('hex');
173
+
174
+ return this.req('POST', '/api/v1/submissions/submit', { taskId: params.taskId, evidenceHash });
175
+ }
176
+
177
+ /**
178
+ * Get task status.
179
+ */
180
+ async getTask(taskId: string): Promise<{ status: number; agent: string; worker: string; amount: string }> {
181
+ return this.req('GET', `/api/v1/tasks/${taskId}`);
182
+ }
183
+
184
+ /**
185
+ * List open tasks.
186
+ */
187
+ async listTasks(limit = 20): Promise<object[]> {
188
+ const { tasks } = await this.req<{ tasks: object[] }>('GET', `/api/v1/tasks?limit=${limit}`);
189
+ return tasks;
190
+ }
191
+
192
+ // ── Auth helper ───────────────────────────────────────────────────────────
193
+
194
+ /**
195
+ * Authenticate with a wallet and return a JWT.
196
+ * Use this to get the apiKey for the constructor.
197
+ *
198
+ * @example
199
+ * const wallet = new ethers.Wallet(privateKey);
200
+ * const apiKey = await BlindMarket.authenticate(wallet, 'http://localhost:3001');
201
+ * const bb = new BlindMarket({ apiKey });
202
+ */
203
+ static async authenticate(wallet: Wallet, apiBase = 'http://localhost:3001'): Promise<string> {
204
+ const nonceRes = await fetch(`${apiBase}/api/v1/auth/nonce`, {
205
+ method: 'POST',
206
+ headers: { 'Content-Type': 'application/json' },
207
+ body: JSON.stringify({ address: wallet.address }),
208
+ });
209
+ const { data: { nonce } } = await nonceRes.json() as { data: { nonce: string } };
210
+ const message = `Sign this message to authenticate with BlindMarket.\n\nNonce: ${nonce}`;
211
+ const signature = await wallet.signMessage(message);
212
+ const verifyRes = await fetch(`${apiBase}/api/v1/auth/verify`, {
213
+ method: 'POST',
214
+ headers: { 'Content-Type': 'application/json' },
215
+ body: JSON.stringify({ address: wallet.address, signature }),
216
+ });
217
+ const { data: { token } } = await verifyRes.json() as { data: { token: string } };
218
+ return token;
219
+ }
220
+ }
221
+
222
+ export { ethers };
@@ -0,0 +1,146 @@
1
+ import { aesDecrypt, aesEncrypt, generateAesKey, hkdfSha256 } from '../crypto/index.js';
2
+ import { CryptoError } from '../errors/index.js';
3
+ import type { Address, Hex, TaskId, TaskKey, TaskKeyRef } from '../types.js';
4
+ import type { KeyStore } from './KeyStore.js';
5
+
6
+ const EXPORT_FORMAT = 'blindmarket.keystore.v1';
7
+ const EXPORT_INFO = new TextEncoder().encode('BlindMarket-Keystore-Export-v1');
8
+
9
+ interface Entry {
10
+ aesKey: Uint8Array;
11
+ createdAt: number;
12
+ }
13
+
14
+ interface ExportShape {
15
+ format: typeof EXPORT_FORMAT;
16
+ salt: string;
17
+ blob: string;
18
+ }
19
+
20
+ interface PlainExport {
21
+ keys: Array<{ taskId: string; aesKey: string; createdAt: number }>;
22
+ peers: Array<{ addr: Address; pubkey: Hex }>;
23
+ }
24
+
25
+ /**
26
+ * Default KeyStore. Non-persistent — keys live only for the process lifetime.
27
+ * Export/import is encrypted with a passphrase via HKDF-derived AES-256-GCM,
28
+ * so exported blobs are safe to move between processes.
29
+ */
30
+ export class InMemoryKeyStore implements KeyStore {
31
+ private readonly keys = new Map<string, Entry>();
32
+ private readonly peers = new Map<Address, Hex>();
33
+
34
+ async putTaskKey(taskId: TaskId, key: TaskKey): Promise<void> {
35
+ this.keys.set(taskId.toString(), {
36
+ aesKey: copy(key.aesKey),
37
+ createdAt: key.createdAt.getTime(),
38
+ });
39
+ }
40
+
41
+ async getTaskKey(taskId: TaskId): Promise<TaskKey | null> {
42
+ const e = this.keys.get(taskId.toString());
43
+ if (!e) return null;
44
+ return { aesKey: copy(e.aesKey), createdAt: new Date(e.createdAt) };
45
+ }
46
+
47
+ async putPeerPubKey(addr: Address, pubkey: Hex): Promise<void> {
48
+ this.peers.set(addr, pubkey);
49
+ }
50
+
51
+ async getPeerPubKey(addr: Address): Promise<Hex | null> {
52
+ return this.peers.get(addr) ?? null;
53
+ }
54
+
55
+ async list(): Promise<TaskKeyRef[]> {
56
+ return Array.from(this.keys.entries()).map(([id, e]) => ({
57
+ taskId: BigInt(id),
58
+ createdAt: new Date(e.createdAt),
59
+ }));
60
+ }
61
+
62
+ async delete(taskId: TaskId): Promise<void> {
63
+ this.keys.delete(taskId.toString());
64
+ }
65
+
66
+ async export(passphrase: string): Promise<string> {
67
+ if (!passphrase || passphrase.length < 8) {
68
+ throw new CryptoError('CRYPTO/INVALID_KEY', 'passphrase must be ≥8 characters');
69
+ }
70
+ const salt = randomBytes(16);
71
+ const wrapKey = await deriveWrapKey(passphrase, salt);
72
+ const plain: PlainExport = {
73
+ keys: Array.from(this.keys.entries()).map(([taskId, e]) => ({
74
+ taskId,
75
+ aesKey: bytesToHex(e.aesKey),
76
+ createdAt: e.createdAt,
77
+ })),
78
+ peers: Array.from(this.peers.entries()).map(([addr, pubkey]) => ({ addr, pubkey })),
79
+ };
80
+ const blob = await aesEncrypt(new TextEncoder().encode(JSON.stringify(plain)), wrapKey);
81
+ const out: ExportShape = { format: EXPORT_FORMAT, salt: bytesToHex(salt), blob: bytesToHex(blob) };
82
+ return JSON.stringify(out);
83
+ }
84
+
85
+ async import(data: string, passphrase: string): Promise<void> {
86
+ let parsed: ExportShape;
87
+ try {
88
+ parsed = JSON.parse(data) as ExportShape;
89
+ } catch (cause) {
90
+ throw new CryptoError('CRYPTO/INTEGRITY_CHECK', 'keystore export is not valid JSON', { cause });
91
+ }
92
+ if (parsed.format !== EXPORT_FORMAT) {
93
+ throw new CryptoError(
94
+ 'CRYPTO/UNSUPPORTED_CIPHER',
95
+ `unknown keystore export format: ${parsed.format ?? '(missing)'}`,
96
+ );
97
+ }
98
+ const salt = hexToBytes(parsed.salt);
99
+ const wrapKey = await deriveWrapKey(passphrase, salt);
100
+ const blob = hexToBytes(parsed.blob);
101
+ const plainBytes = await aesDecrypt(blob, wrapKey);
102
+ const plain = JSON.parse(new TextDecoder().decode(plainBytes)) as PlainExport;
103
+ this.keys.clear();
104
+ this.peers.clear();
105
+ for (const k of plain.keys) {
106
+ this.keys.set(k.taskId, { aesKey: hexToBytes(k.aesKey), createdAt: k.createdAt });
107
+ }
108
+ for (const p of plain.peers) {
109
+ this.peers.set(p.addr, p.pubkey);
110
+ }
111
+ }
112
+ }
113
+
114
+ function copy(u: Uint8Array): Uint8Array {
115
+ const c = new Uint8Array(u.byteLength);
116
+ c.set(u);
117
+ return c;
118
+ }
119
+
120
+ function randomBytes(n: number): Uint8Array {
121
+ const c = (globalThis as { crypto: Crypto }).crypto;
122
+ const out = new Uint8Array(n);
123
+ c.getRandomValues(out);
124
+ return out;
125
+ }
126
+
127
+ async function deriveWrapKey(passphrase: string, salt: Uint8Array): Promise<Uint8Array> {
128
+ const ikm = new TextEncoder().encode(passphrase);
129
+ return hkdfSha256(ikm, 32, EXPORT_INFO, salt);
130
+ }
131
+
132
+ function bytesToHex(u: Uint8Array): string {
133
+ return Array.from(u, (b) => b.toString(16).padStart(2, '0')).join('');
134
+ }
135
+
136
+ function hexToBytes(hex: string): Uint8Array {
137
+ const out = new Uint8Array(hex.length / 2);
138
+ for (let i = 0; i < out.length; i++) {
139
+ out[i] = Number.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
140
+ }
141
+ return out;
142
+ }
143
+
144
+ // Tree-shakable helper kept here so we don't accidentally ship generateAesKey
145
+ // from this module — it's re-exported from crypto only.
146
+ export { generateAesKey };
@@ -0,0 +1,19 @@
1
+ import type { Address, Hex, TaskId, TaskKey, TaskKeyRef } from '../types.js';
2
+
3
+ /**
4
+ * Per-session storage for task AES keys and cached peer public keys. The SDK
5
+ * never logs or serializes anything from here — this is the one place at-rest
6
+ * secrets live. Implementations MUST treat passphrase-protected exports as the
7
+ * only portable format.
8
+ */
9
+ export interface KeyStore {
10
+ putTaskKey(taskId: TaskId, key: TaskKey): Promise<void>;
11
+ getTaskKey(taskId: TaskId): Promise<TaskKey | null>;
12
+ putPeerPubKey(addr: Address, pubkey: Hex): Promise<void>;
13
+ getPeerPubKey(addr: Address): Promise<Hex | null>;
14
+ list(): Promise<TaskKeyRef[]>;
15
+ delete(taskId: TaskId): Promise<void>;
16
+ /** Portable, encrypted-at-rest JSON export for backup/migration. */
17
+ export(passphrase: string): Promise<string>;
18
+ import(data: string, passphrase: string): Promise<void>;
19
+ }
@@ -0,0 +1,2 @@
1
+ export * from './KeyStore.js';
2
+ export * from './InMemoryKeyStore.js';
@@ -0,0 +1,3 @@
1
+ export * from './types.js';
2
+ export * from './presets.js';
3
+ export * from './resolve.js';
@@ -0,0 +1,27 @@
1
+ import type { Network } from './types.js';
2
+
3
+ /**
4
+ * Known-good network presets. Addresses pinned per SDK version so upgrading
5
+ * the SDK cannot silently move contracts under a consumer.
6
+ *
7
+ * testnet = 0G Galileo (chainId 16602) — addresses from
8
+ * contracts/deployments/0g-testnet.json (deployed 2026-04-15).
9
+ */
10
+ export const networks = {
11
+ testnet: {
12
+ name: '0g-galileo-testnet',
13
+ chainId: 16602n,
14
+ rpc: ['https://evmrpc-testnet.0g.ai'],
15
+ contracts: {
16
+ escrow: '0xFd4F93F5A7BE144c405D1D8fbEC63Fb776207681',
17
+ registry: '0xeE52d780A47F77E8a4a1cEb236e3C65A48FbD828',
18
+ reputation: '0x4A6374Fae37E19E69ba43E7cf6994AC15F63256e',
19
+ usdc: '0x317227efcA18D004E12CA8046AEf7E1597458F25',
20
+ },
21
+ indexer: 'https://indexer-storage-testnet-turbo.0g.ai',
22
+ broker: 'https://broker.testnet.0g.ai',
23
+ explorer: 'https://chainscan-galileo.0g.ai',
24
+ },
25
+ } as const satisfies Record<string, Network>;
26
+
27
+ export type NetworkName = keyof typeof networks;
@@ -0,0 +1,19 @@
1
+ import { ConfigError } from '../errors/index.js';
2
+ import { networks, type NetworkName } from './presets.js';
3
+ import type { Network } from './types.js';
4
+
5
+ /**
6
+ * Resolve a preset name or a literal Network object into the canonical
7
+ * Network used throughout the SDK. Throws ConfigError for unknown names.
8
+ */
9
+ export function resolveNetwork(arg: NetworkName | Network): Network {
10
+ if (typeof arg === 'string') {
11
+ const preset = (networks as Record<string, Network | undefined>)[arg];
12
+ if (!preset) {
13
+ const known = Object.keys(networks).join(', ');
14
+ throw new ConfigError('CONFIG/INVALID_NETWORK', `unknown network '${arg}' (known: ${known})`);
15
+ }
16
+ return preset;
17
+ }
18
+ return arg;
19
+ }
@@ -0,0 +1,18 @@
1
+ import type { Address } from '../types.js';
2
+
3
+ export interface NetworkContracts {
4
+ escrow: Address;
5
+ registry: Address;
6
+ reputation: Address;
7
+ usdc: Address;
8
+ }
9
+
10
+ export interface Network {
11
+ name: string;
12
+ chainId: bigint;
13
+ rpc: string[];
14
+ contracts: NetworkContracts;
15
+ indexer: string;
16
+ broker: string;
17
+ explorer?: string;
18
+ }
@@ -0,0 +1,82 @@
1
+ import { ethers } from 'ethers';
2
+ import { ChainError, ConfigError } from '../errors/index.js';
3
+ import type { Address, Hex } from '../types.js';
4
+ import type { Signer, TxRequest, TypedDataDomain, TypedDataField } from './Signer.js';
5
+
6
+ /**
7
+ * Wraps any ethers v6 Signer. The most common path — accepts ethers.Wallet,
8
+ * ethers.BrowserProvider signer, JsonRpcSigner, etc. Caches the recovered
9
+ * public key after the first successful getPublicKey() call.
10
+ */
11
+ export class EthersSigner implements Signer {
12
+ private publicKeyCache: Hex | undefined;
13
+
14
+ constructor(private readonly inner: ethers.Signer) {}
15
+
16
+ async getAddress(): Promise<Address> {
17
+ return (await this.inner.getAddress()) as Address;
18
+ }
19
+
20
+ async chainId(): Promise<bigint> {
21
+ const provider = this.inner.provider;
22
+ if (!provider) {
23
+ throw new ConfigError('CONFIG/BAD_CONFIG', 'signer has no attached provider; cannot read chainId');
24
+ }
25
+ const net = await provider.getNetwork();
26
+ return net.chainId;
27
+ }
28
+
29
+ async signMessage(msg: string | Uint8Array): Promise<Hex> {
30
+ return (await this.inner.signMessage(msg)) as Hex;
31
+ }
32
+
33
+ async signTypedData(
34
+ domain: TypedDataDomain,
35
+ types: Record<string, TypedDataField[]>,
36
+ value: Record<string, unknown>,
37
+ ): Promise<Hex> {
38
+ return (await this.inner.signTypedData(domain, types, value)) as Hex;
39
+ }
40
+
41
+ async signTransaction(tx: TxRequest): Promise<Hex> {
42
+ try {
43
+ return (await this.inner.signTransaction({
44
+ to: tx.to,
45
+ ...(tx.from !== undefined ? { from: tx.from } : {}),
46
+ ...(tx.data !== undefined ? { data: tx.data } : {}),
47
+ ...(tx.value !== undefined ? { value: tx.value } : {}),
48
+ ...(tx.gasLimit !== undefined ? { gasLimit: tx.gasLimit } : {}),
49
+ ...(tx.nonce !== undefined ? { nonce: tx.nonce } : {}),
50
+ ...(tx.chainId !== undefined ? { chainId: tx.chainId } : {}),
51
+ })) as Hex;
52
+ } catch (cause) {
53
+ throw new ChainError('CHAIN/TX_REVERTED', 'signTransaction failed', { cause });
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Recovers the uncompressed secp256k1 public key from the signer. For Wallet
59
+ * signers we can read it directly; for generic Signers we sign a canonical
60
+ * probe message once and recover from the signature.
61
+ */
62
+ async getPublicKey(): Promise<Hex> {
63
+ if (this.publicKeyCache) return this.publicKeyCache;
64
+
65
+ // Fast path: ethers.Wallet exposes signingKey.publicKey directly.
66
+ const maybeWallet = this.inner as unknown as { signingKey?: { publicKey: string } };
67
+ if (maybeWallet.signingKey?.publicKey) {
68
+ this.publicKeyCache = maybeWallet.signingKey.publicKey as Hex;
69
+ return this.publicKeyCache;
70
+ }
71
+
72
+ // Slow path: sign a probe message and recover the public key.
73
+ const probe = 'BlindMarket-PublicKey-Recovery-v1';
74
+ const sig = await this.inner.signMessage(probe);
75
+ const recovered = ethers.SigningKey.recoverPublicKey(
76
+ ethers.hashMessage(probe),
77
+ sig,
78
+ );
79
+ this.publicKeyCache = recovered as Hex;
80
+ return this.publicKeyCache;
81
+ }
82
+ }
@@ -0,0 +1,19 @@
1
+ import { ethers } from 'ethers';
2
+ import { EthersSigner } from './EthersSigner.js';
3
+
4
+ /**
5
+ * Convenience factory for Node / headless agents: builds an EthersSigner
6
+ * backed by a fresh ethers.Wallet from a raw private key (hex, with or
7
+ * without 0x prefix). Optionally attaches an RPC provider so chainId()
8
+ * and on-chain reads work.
9
+ *
10
+ * NEVER pass a private key you don't control — prefer KMS, browser wallet,
11
+ * or hardware signer for production.
12
+ */
13
+ export class PrivateKeySigner extends EthersSigner {
14
+ constructor(privateKey: string, provider?: ethers.Provider) {
15
+ const pk = privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`;
16
+ const wallet = provider ? new ethers.Wallet(pk, provider) : new ethers.Wallet(pk);
17
+ super(wallet);
18
+ }
19
+ }
@@ -0,0 +1,40 @@
1
+ import type { Address, Hex } from '../types.js';
2
+
3
+ export interface TxRequest {
4
+ to: Address;
5
+ from?: Address;
6
+ data?: Hex;
7
+ value?: bigint;
8
+ gasLimit?: bigint;
9
+ nonce?: number;
10
+ chainId?: bigint;
11
+ }
12
+
13
+ export interface TypedDataDomain {
14
+ name?: string;
15
+ version?: string;
16
+ chainId?: bigint | number;
17
+ verifyingContract?: Address;
18
+ salt?: Hex;
19
+ }
20
+
21
+ export type TypedDataField = { name: string; type: string };
22
+
23
+ /**
24
+ * Uniform signing interface used across the SDK. Adapters wrap ethers Signer,
25
+ * raw private keys, EIP-1193 providers, or KMS. Implementations MUST return
26
+ * hex-encoded signatures (0x-prefixed) and addresses (0x-prefixed, 20 bytes).
27
+ */
28
+ export interface Signer {
29
+ getAddress(): Promise<Address>;
30
+ chainId(): Promise<bigint>;
31
+ signMessage(msg: string | Uint8Array): Promise<Hex>;
32
+ signTypedData(
33
+ domain: TypedDataDomain,
34
+ types: Record<string, TypedDataField[]>,
35
+ value: Record<string, unknown>,
36
+ ): Promise<Hex>;
37
+ signTransaction(tx: TxRequest): Promise<Hex>;
38
+ /** Uncompressed secp256k1 public key, 0x04-prefixed (hex). */
39
+ getPublicKey(): Promise<Hex>;
40
+ }
@@ -0,0 +1,3 @@
1
+ export * from './Signer.js';
2
+ export * from './EthersSigner.js';
3
+ export * from './PrivateKeySigner.js';
@@ -0,0 +1,49 @@
1
+ import { sha256 } from '../crypto/index.js';
2
+ import { StorageError } from '../errors/index.js';
3
+ import type { RootHash, UploadResult } from '../types.js';
4
+ import type { Storage } from './Storage.js';
5
+
6
+ /**
7
+ * In-process Storage for tests and local development. Deterministic: rootHash
8
+ * is the SHA-256 of the content (not a merkle root), so the same bytes always
9
+ * produce the same hash. Not for production — no replication, no integrity
10
+ * proofs beyond SHA-256.
11
+ */
12
+ export class MemoryStorage implements Storage {
13
+ private readonly blobs = new Map<string, Uint8Array>();
14
+
15
+ async upload(bytes: Uint8Array): Promise<UploadResult> {
16
+ const rootHash = await this.hash(bytes);
17
+ this.blobs.set(rootHash, copy(bytes));
18
+ return { rootHash, size: bytes.byteLength };
19
+ }
20
+
21
+ async download(rootHash: RootHash): Promise<Uint8Array> {
22
+ const data = this.blobs.get(rootHash);
23
+ if (!data) {
24
+ throw new StorageError('STORAGE/NOT_FOUND', `no blob at ${rootHash}`);
25
+ }
26
+ return copy(data);
27
+ }
28
+
29
+ async hash(bytes: Uint8Array): Promise<RootHash> {
30
+ const digest = await sha256(bytes);
31
+ return ('0x' + Array.from(digest, (b) => b.toString(16).padStart(2, '0')).join('')) as RootHash;
32
+ }
33
+
34
+ /** Test helper: wipe all stored blobs. */
35
+ clear(): void {
36
+ this.blobs.clear();
37
+ }
38
+
39
+ /** Test helper: count of stored blobs. */
40
+ size(): number {
41
+ return this.blobs.size;
42
+ }
43
+ }
44
+
45
+ function copy(u: Uint8Array): Uint8Array {
46
+ const c = new Uint8Array(u.byteLength);
47
+ c.set(u);
48
+ return c;
49
+ }
@@ -0,0 +1,15 @@
1
+ import type { RootHash, UploadResult } from '../types.js';
2
+
3
+ /**
4
+ * Abstraction over blob storage. Default implementation (ZgStorage) uses
5
+ * 0G Storage; MemoryStorage is for tests and local fallback. Consumers can
6
+ * provide their own adapter for IPFS, S3, etc.
7
+ */
8
+ export interface Storage {
9
+ /** Upload bytes, return root hash + optional tx hash + size. */
10
+ upload(bytes: Uint8Array): Promise<UploadResult>;
11
+ /** Download bytes by root hash. Throws StorageError('STORAGE/NOT_FOUND') if absent. */
12
+ download(rootHash: RootHash): Promise<Uint8Array>;
13
+ /** Compute the canonical root hash without uploading. */
14
+ hash(bytes: Uint8Array): Promise<RootHash>;
15
+ }