@fangorn-network/sdk 0.1.0-dev

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 (102) hide show
  1. package/LICENSE.md +20 -0
  2. package/README.md +80 -0
  3. package/lib/cli/cli.d.ts +2 -0
  4. package/lib/cli/cli.js +571 -0
  5. package/lib/cli/index.d.ts +10 -0
  6. package/lib/cli/index.js +18 -0
  7. package/lib/cli/sell.d.ts +28 -0
  8. package/lib/cli/sell.js +95 -0
  9. package/lib/cli/stage.d.ts +19 -0
  10. package/lib/cli/stage.js +94 -0
  11. package/lib/config.d.ts +697 -0
  12. package/lib/config.js +45 -0
  13. package/lib/contracts/data-registry/abi.d.ts +442 -0
  14. package/lib/contracts/data-registry/abi.js +508 -0
  15. package/lib/contracts/data-registry/index.d.ts +131 -0
  16. package/lib/contracts/data-registry/index.js +183 -0
  17. package/lib/contracts/index.d.ts +6 -0
  18. package/lib/contracts/index.js +6 -0
  19. package/lib/contracts/logs.d.ts +17 -0
  20. package/lib/contracts/logs.js +28 -0
  21. package/lib/contracts/settlement-registry/abi.d.ts +810 -0
  22. package/lib/contracts/settlement-registry/abi.js +962 -0
  23. package/lib/contracts/settlement-registry/index.d.ts +143 -0
  24. package/lib/contracts/settlement-registry/index.js +213 -0
  25. package/lib/contracts/write.d.ts +59 -0
  26. package/lib/contracts/write.js +102 -0
  27. package/lib/crypto/aes.d.ts +19 -0
  28. package/lib/crypto/aes.js +26 -0
  29. package/lib/crypto/encryption.d.ts +38 -0
  30. package/lib/crypto/encryption.js +68 -0
  31. package/lib/crypto/paid.d.ts +104 -0
  32. package/lib/crypto/paid.js +147 -0
  33. package/lib/crypto/rand.d.ts +5 -0
  34. package/lib/crypto/rand.js +16 -0
  35. package/lib/crypto/types.d.ts +23 -0
  36. package/lib/crypto/types.js +1 -0
  37. package/lib/engine/car.d.ts +14 -0
  38. package/lib/engine/car.js +42 -0
  39. package/lib/engine/index.d.ts +206 -0
  40. package/lib/engine/index.js +377 -0
  41. package/lib/engine/records.d.ts +121 -0
  42. package/lib/engine/records.js +239 -0
  43. package/lib/engine/test-helpers.d.ts +38 -0
  44. package/lib/engine/test-helpers.js +63 -0
  45. package/lib/erc8004.d.ts +56 -0
  46. package/lib/erc8004.js +140 -0
  47. package/lib/fangorn.d.ts +342 -0
  48. package/lib/fangorn.js +642 -0
  49. package/lib/feed.d.ts +34 -0
  50. package/lib/feed.js +67 -0
  51. package/lib/index.d.ts +17 -0
  52. package/lib/index.js +16 -0
  53. package/lib/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.js +77 -0
  54. package/lib/node_modules/@vitest/expect/dist/index.js +1414 -0
  55. package/lib/node_modules/@vitest/pretty-format/dist/index.js +858 -0
  56. package/lib/node_modules/@vitest/runner/dist/chunk-tasks.js +51 -0
  57. package/lib/node_modules/@vitest/runner/dist/index.js +1199 -0
  58. package/lib/node_modules/@vitest/runner/dist/utils.js +3 -0
  59. package/lib/node_modules/@vitest/snapshot/dist/index.js +1075 -0
  60. package/lib/node_modules/@vitest/spy/dist/index.js +353 -0
  61. package/lib/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +7 -0
  62. package/lib/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +81 -0
  63. package/lib/node_modules/@vitest/utils/dist/diff.js +1345 -0
  64. package/lib/node_modules/@vitest/utils/dist/display.js +534 -0
  65. package/lib/node_modules/@vitest/utils/dist/error.js +30 -0
  66. package/lib/node_modules/@vitest/utils/dist/helpers.js +118 -0
  67. package/lib/node_modules/@vitest/utils/dist/serialize.js +76 -0
  68. package/lib/node_modules/@vitest/utils/dist/source-map.js +93 -0
  69. package/lib/node_modules/@vitest/utils/dist/timers.js +36 -0
  70. package/lib/node_modules/chai/index.js +2874 -0
  71. package/lib/node_modules/magic-string/dist/magic-string.es.js +939 -0
  72. package/lib/node_modules/pathe/dist/shared/pathe.M-eThtNZ.js +81 -0
  73. package/lib/node_modules/tinyrainbow/dist/index.js +85 -0
  74. package/lib/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js +5 -0
  75. package/lib/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.js +50 -0
  76. package/lib/node_modules/vitest/dist/chunks/utils.DvEY5TfP.js +44 -0
  77. package/lib/node_modules/vitest/dist/chunks/vi.2VT5v0um.js +2578 -0
  78. package/lib/providers/storage/car.d.ts +36 -0
  79. package/lib/providers/storage/car.js +81 -0
  80. package/lib/providers/storage/index.d.ts +5 -0
  81. package/lib/providers/storage/index.js +5 -0
  82. package/lib/providers/storage/pinata.d.ts +53 -0
  83. package/lib/providers/storage/pinata.js +178 -0
  84. package/lib/providers/storage/signed-url.d.ts +54 -0
  85. package/lib/providers/storage/signed-url.js +122 -0
  86. package/lib/providers/storage/types.d.ts +62 -0
  87. package/lib/providers/storage/types.js +1 -0
  88. package/lib/providers/storage/utils.d.ts +30 -0
  89. package/lib/providers/storage/utils.js +107 -0
  90. package/lib/repo/index.d.ts +56 -0
  91. package/lib/repo/index.js +73 -0
  92. package/lib/test/key-server.d.ts +12 -0
  93. package/lib/test/key-server.js +30 -0
  94. package/lib/test/mem-registry.d.ts +46 -0
  95. package/lib/test/mem-registry.js +114 -0
  96. package/lib/test/sdk-suite.d.ts +10 -0
  97. package/lib/test/sdk-suite.js +155 -0
  98. package/lib/test/testbed.d.ts +16786 -0
  99. package/lib/test/testbed.js +175 -0
  100. package/lib/types/index.d.ts +37 -0
  101. package/lib/types/index.js +1 -0
  102. package/package.json +87 -0
@@ -0,0 +1,239 @@
1
+ import { CID } from "multiformats/cid";
2
+ import * as dagCbor from "@ipld/dag-cbor";
3
+ import { sha256 } from "@noble/hashes/sha2.js";
4
+ import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
5
+ import { sha256 as sha256$1 } from "multiformats/hashes/sha2";
6
+
7
+ //#region src/engine/records.ts
8
+ /** Encode any value as canonical dag-cbor and derive its CIDv1 (sha256). */
9
+ async function encodeBlock(obj) {
10
+ const bytes = dagCbor.encode(obj);
11
+ const hash = await sha256$1.digest(bytes);
12
+ return {
13
+ cid: CID.createV1(dagCbor.code, hash),
14
+ bytes
15
+ };
16
+ }
17
+ /**
18
+ * Decode a dag-cbor block. The decoder is strict (minimal encodings, sorted
19
+ * map keys), so a block has one accepted byte form (FOUNDATIONS P1).
20
+ */
21
+ function decodeBlock(bytes) {
22
+ return dagCbor.decode(bytes);
23
+ }
24
+ /** Throw unless `bytes` hash to `cid`. Hosts are untrusted; every fetched block goes through this. */
25
+ function assertBlockMatches(cid, bytes) {
26
+ if (bytesToHex(cid.multihash.digest) !== bytesToHex(sha256(bytes))) throw new Error(`block ${cid.toString()} does not match its content hash`);
27
+ }
28
+ /** Upper bound on a record id's length. */
29
+ const MAX_RECORD_ID_LENGTH = 256;
30
+ /**
31
+ * Record ids are printable ASCII, so JS string order is byte order and every
32
+ * implementation sorts MST keys the same way. Ids of sealed data should be
33
+ * random (FOUNDATIONS P7): a guessable id lets an observer test what exists.
34
+ */
35
+ function assertValidRecordId(id) {
36
+ if (typeof id !== "string" || id.length === 0 || id.length > MAX_RECORD_ID_LENGTH || !/^[\x21-\x7e]+$/.test(id)) throw new Error(`invalid record id ${JSON.stringify(id)}: must be 1-${MAX_RECORD_ID_LENGTH.toString()} printable ASCII characters, no spaces`);
37
+ }
38
+ /** b: expected fanout 2^b = 16. */
39
+ const MST_BITS = 4;
40
+ /** Levels come from a 256-bit hash, so no honest tree is deeper (FOUNDATIONS P22). */
41
+ const MAX_DEPTH = 256 / MST_BITS + 1;
42
+ /** level(k) = ⌊leading zero bits of sha256(k) / b⌋ */
43
+ function keyLevel(key) {
44
+ const digest = sha256(utf8ToBytes(key));
45
+ let zeros = 0;
46
+ for (const byte of digest) {
47
+ if (byte !== 0) {
48
+ zeros += Math.clz32(byte) - 24;
49
+ break;
50
+ }
51
+ zeros += 8;
52
+ }
53
+ return Math.floor(zeros / MST_BITS);
54
+ }
55
+ /**
56
+ * Build the MST for a state. Returns the root and every node block; callers
57
+ * diff node CIDs against the parent's to find what to upload.
58
+ * ponytail: rebuilds the whole tree per commit (O(n) hashing, same as the
59
+ * page model it replaced); update only the changed paths if large repos
60
+ * make commits CPU-bound.
61
+ */
62
+ async function buildMst(state) {
63
+ const items = [...state].map(([key, value]) => ({
64
+ key,
65
+ value,
66
+ level: keyLevel(key)
67
+ })).sort((a, b) => a.key < b.key ? -1 : 1);
68
+ const nodes = [];
69
+ const build = async (slice, level) => {
70
+ if (slice.length === 0) return null;
71
+ const node = {
72
+ level,
73
+ left: null,
74
+ entries: []
75
+ };
76
+ let gap = [];
77
+ const closeGap = async () => {
78
+ const child = level === 0 ? null : await build(gap, level - 1);
79
+ const last = node.entries.at(-1);
80
+ if (last) last.right = child;
81
+ else node.left = child;
82
+ gap = [];
83
+ };
84
+ for (const item of slice) {
85
+ if (item.level !== level) {
86
+ gap.push(item);
87
+ continue;
88
+ }
89
+ await closeGap();
90
+ node.entries.push({
91
+ key: item.key,
92
+ value: item.value,
93
+ right: null
94
+ });
95
+ }
96
+ await closeGap();
97
+ const block = await encodeBlock(node);
98
+ nodes.push(block);
99
+ return block.cid;
100
+ };
101
+ let root = await build(items, items.reduce((max, i) => Math.max(max, i.level), 0));
102
+ if (!root) {
103
+ const empty = await encodeBlock({
104
+ level: 0,
105
+ left: null,
106
+ entries: []
107
+ });
108
+ nodes.push(empty);
109
+ root = empty.cid;
110
+ }
111
+ return {
112
+ root,
113
+ nodes
114
+ };
115
+ }
116
+ /**
117
+ * Read a whole MST back into its state, rejecting any tree that isn't exactly
118
+ * what `buildMst` makes of that state (MSTCheck, FOUNDATIONS P2): rebuilding
119
+ * and comparing roots catches duplicate, misordered, misplaced and wrong-level
120
+ * keys in one check.
121
+ */
122
+ async function readMst(root, getBlock) {
123
+ const state = /* @__PURE__ */ new Map();
124
+ const nodeCids = /* @__PURE__ */ new Set();
125
+ const walk = async (cid, depth) => {
126
+ if (depth > MAX_DEPTH) throw new Error(`MST at ${root.toString()} is deeper than ${MAX_DEPTH.toString()}`);
127
+ nodeCids.add(cid.toString());
128
+ const node = decodeBlock(await getBlock(cid));
129
+ if (!Array.isArray(node.entries)) throw new Error(`${cid.toString()} is not a record tree node — graph-era data (vertices/edges) is no longer readable. Reset the on-chain head (\`fangorn reset\`) and re-publish.`);
130
+ if (node.left) await walk(node.left, depth + 1);
131
+ for (const e of node.entries) {
132
+ state.set(e.key, e.value);
133
+ if (e.right) await walk(e.right, depth + 1);
134
+ }
135
+ };
136
+ await walk(root, 0);
137
+ if ((await buildMst(state)).root.toString() !== root.toString()) throw new Error(`MST at ${root.toString()} is not canonical`);
138
+ return {
139
+ state,
140
+ nodeCids
141
+ };
142
+ }
143
+ /**
144
+ * What changed from one tree to another: `puts` (new keys, and keys with a new value) and `deletes`
145
+ * (keys gone), each with its old value in `before`. Both trees are read as in-order streams of entries
146
+ * and unopened subtrees; a subtree with the same CID at the head of both streams holds the same keys
147
+ * and values, so it is dropped unread. Only nodes on changed paths are fetched: ~changes × depth,
148
+ * not the size of either tree.
149
+ * ponytail: unlike readMst, does not prove either tree canonical (that needs every key). Blocks are
150
+ * still hash-checked by `getBlock`; a publisher's malformed tree can only misreport its own records.
151
+ */
152
+ async function diffMst(oldRoot, newRoot, getOld, getNew) {
153
+ const a = oldRoot ? [{
154
+ sub: oldRoot,
155
+ level: Infinity
156
+ }] : [];
157
+ const b = newRoot ? [{
158
+ sub: newRoot,
159
+ level: Infinity
160
+ }] : [];
161
+ const open = async (s, get) => {
162
+ const { sub } = s.pop();
163
+ const node = decodeBlock(await get(sub));
164
+ const items = node.left ? [{
165
+ sub: node.left,
166
+ level: node.level - 1
167
+ }] : [];
168
+ for (const e of node.entries) {
169
+ items.push({
170
+ key: e.key,
171
+ value: e.value
172
+ });
173
+ if (e.right) items.push({
174
+ sub: e.right,
175
+ level: node.level - 1
176
+ });
177
+ }
178
+ s.push(...items.reverse());
179
+ };
180
+ const puts = /* @__PURE__ */ new Map(), before = /* @__PURE__ */ new Map(), deletes = [];
181
+ for (let steps = 0; a.length || b.length; steps++) {
182
+ if (steps > 1e8) throw new Error("MST diff did not terminate");
183
+ const x = a.at(-1), y = b.at(-1);
184
+ if (x && y && "sub" in x && "sub" in y) if (x.sub.equals(y.sub)) {
185
+ a.pop();
186
+ b.pop();
187
+ } else if (x.level > y.level) await open(a, getOld);
188
+ else if (y.level > x.level) await open(b, getNew);
189
+ else {
190
+ await open(a, getOld);
191
+ await open(b, getNew);
192
+ }
193
+ else if (x && "sub" in x) await open(a, getOld);
194
+ else if (y && "sub" in y) await open(b, getNew);
195
+ else if (x && (!y || x.key < y.key)) {
196
+ a.pop();
197
+ deletes.push(x.key);
198
+ before.set(x.key, x.value);
199
+ } else if (y && (!x || y.key < x.key)) {
200
+ b.pop();
201
+ puts.set(y.key, y.value);
202
+ } else if (x && y) {
203
+ a.pop();
204
+ b.pop();
205
+ if (!x.value.equals(y.value)) {
206
+ puts.set(y.key, y.value);
207
+ before.set(x.key, x.value);
208
+ }
209
+ }
210
+ }
211
+ return {
212
+ puts,
213
+ deletes,
214
+ before
215
+ };
216
+ }
217
+ /**
218
+ * The record CID stored under `key`, or null if absent — one node per level.
219
+ * ponytail: trusts node ordering on the path, so a malformed tree can hide a
220
+ * record (never forge one: the caller checks the record's id). Run `readMst`
221
+ * first where absence must be proven.
222
+ */
223
+ async function lookupMst(root, key, getBlock) {
224
+ let cursor = root;
225
+ for (let depth = 0; cursor && depth <= MAX_DEPTH; depth++) {
226
+ const node = decodeBlock(await getBlock(cursor));
227
+ let next = node.left;
228
+ for (const e of node.entries) {
229
+ if (e.key === key) return e.value;
230
+ if (e.key > key) break;
231
+ next = e.right;
232
+ }
233
+ cursor = next;
234
+ }
235
+ return null;
236
+ }
237
+
238
+ //#endregion
239
+ export { MAX_RECORD_ID_LENGTH, MST_BITS, assertBlockMatches, assertValidRecordId, buildMst, decodeBlock, diffMst, encodeBlock, keyLevel, lookupMst, readMst };
@@ -0,0 +1,38 @@
1
+ import { MetadataStorage, RawBlock, StorageMeta } from "../providers/storage/types.js";
2
+ import { MemRegistry } from "../test/mem-registry.js";
3
+ import { Hex } from "viem";
4
+ import { CID } from "multiformats/cid";
5
+
6
+ //#region src/engine/test-helpers.d.ts
7
+ declare const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
8
+ /** The raw 32-byte root hex a commit CID settles to on-chain (bare sha256 digest). */
9
+ declare const rootHex: (commitCid: CID) => `0x${string}`;
10
+ /**
11
+ * In-memory MetadataStorage: individually-pinned blocks + opaque files, with
12
+ * write/read counters — remote writes are the publish cost driver, so tests
13
+ * assert on them directly.
14
+ */
15
+ declare class MemStorage implements MetadataStorage {
16
+ blocks: Map<string, Uint8Array<ArrayBufferLike>>;
17
+ files: Map<string, Uint8Array<ArrayBufferLike>>;
18
+ /** Remote uploads performed (putBlock + putFile). */
19
+ writes: number;
20
+ /** Remote fetches performed (getRawBlock + getFile). */
21
+ reads: number;
22
+ putBlock(block: RawBlock): Promise<void>;
23
+ putFile(bytes: Uint8Array): Promise<string>;
24
+ getFile(uri: string): Promise<Uint8Array>;
25
+ getRawBlock(uri: string): Promise<Uint8Array>;
26
+ put(_data: unknown, _meta?: StorageMeta): Promise<string>;
27
+ putMany(_items: {
28
+ data: unknown;
29
+ name: string;
30
+ }[]): Promise<Record<string, string>>;
31
+ get<T>(_uri: string): Promise<T>;
32
+ delete(_uri: string): Promise<void>;
33
+ }
34
+ /** The paper's registry in memory, signing as PUBLISHER. */
35
+ declare const PUBLISHER: Hex;
36
+ declare const newRegistry: () => MemRegistry;
37
+ //#endregion
38
+ export { MemStorage, PUBLISHER, ZERO_BYTES32, newRegistry, rootHex };
@@ -0,0 +1,63 @@
1
+ import { MemRegistry } from "../test/mem-registry.js";
2
+ import { CID } from "multiformats/cid";
3
+ import { sha256 } from "multiformats/hashes/sha2";
4
+ import * as raw from "multiformats/codecs/raw";
5
+
6
+ //#region src/engine/test-helpers.ts
7
+ const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
8
+ /** The raw 32-byte root hex a commit CID settles to on-chain (bare sha256 digest). */
9
+ const rootHex = (commitCid) => `0x${Buffer.from(commitCid.multihash.digest).toString("hex")}`;
10
+ /**
11
+ * In-memory MetadataStorage: individually-pinned blocks + opaque files, with
12
+ * write/read counters — remote writes are the publish cost driver, so tests
13
+ * assert on them directly.
14
+ */
15
+ var MemStorage = class {
16
+ blocks = /* @__PURE__ */ new Map();
17
+ files = /* @__PURE__ */ new Map();
18
+ /** Remote uploads performed (putBlock + putFile). */
19
+ writes = 0;
20
+ /** Remote fetches performed (getRawBlock + getFile). */
21
+ reads = 0;
22
+ putBlock(block) {
23
+ this.writes++;
24
+ this.blocks.set(block.cid.toString(), block.bytes);
25
+ return Promise.resolve();
26
+ }
27
+ async putFile(bytes) {
28
+ this.writes++;
29
+ const uri = CID.createV1(raw.code, await sha256.digest(bytes)).toString();
30
+ this.files.set(uri, bytes);
31
+ return uri;
32
+ }
33
+ getFile(uri) {
34
+ const bytes = this.files.get(uri);
35
+ if (!bytes) return Promise.reject(/* @__PURE__ */ new Error(`no such file: ${uri}`));
36
+ this.reads++;
37
+ return Promise.resolve(bytes);
38
+ }
39
+ getRawBlock(uri) {
40
+ const bytes = this.blocks.get(uri);
41
+ if (!bytes) return Promise.reject(/* @__PURE__ */ new Error(`no such block: ${uri}`));
42
+ this.reads++;
43
+ return Promise.resolve(bytes);
44
+ }
45
+ put(_data, _meta) {
46
+ return Promise.reject(/* @__PURE__ */ new Error("MemStorage.put not implemented"));
47
+ }
48
+ putMany(_items) {
49
+ return Promise.reject(/* @__PURE__ */ new Error("MemStorage.putMany not implemented"));
50
+ }
51
+ get(_uri) {
52
+ return Promise.reject(/* @__PURE__ */ new Error("MemStorage.get not implemented"));
53
+ }
54
+ delete(_uri) {
55
+ return Promise.resolve();
56
+ }
57
+ };
58
+ /** The paper's registry in memory, signing as PUBLISHER. */
59
+ const PUBLISHER = "0x0000000000000000000000000000000000000001";
60
+ const newRegistry = () => new MemRegistry(PUBLISHER);
61
+
62
+ //#endregion
63
+ export { MemStorage, PUBLISHER, ZERO_BYTES32, newRegistry, rootHex };
@@ -0,0 +1,56 @@
1
+ import { MetadataStorage } from "./providers/storage/types.js";
2
+ import { Address, Chain, Hex, PublicClient, WalletClient } from "viem";
3
+
4
+ //#region src/erc8004.d.ts
5
+ /** The ERC-8004 identity registry by chain id */
6
+ declare const IDENTITY_REGISTRY: Record<number, Address>;
7
+ interface AgentCard {
8
+ name: string;
9
+ description: string;
10
+ skills?: {
11
+ tags?: unknown;
12
+ }[];
13
+ }
14
+ /**
15
+ * Get the agent card URL based on the access worker if defined, else return the carUrl
16
+ * Both params are optional, but at least one must be defined.
17
+ *
18
+ * Agent cards must live at accessWorker/.well-known/agent-card.json
19
+ *
20
+ * @param cardUrl The cardUrl (passthrough when defined)
21
+ * @param accessWorker The (optional) access worker url
22
+ * @returns
23
+ */
24
+ declare function agentCardUrl(cardUrl?: string, accessWorker?: string): string;
25
+ declare function mcpTools(endpoint: string): Promise<string[] | undefined>;
26
+ /**
27
+ * Build a registration file
28
+ * Since it desfines its own agent id,
29
+ * first registration mints without an agent URI and must be set retroactively.
30
+ */
31
+ declare function registrationFile(opts: {
32
+ cardUrl: string;
33
+ card: AgentCard;
34
+ chainId: number;
35
+ agentId: bigint;
36
+ mcp?: {
37
+ endpoint: string;
38
+ tools?: string[];
39
+ };
40
+ now?: number;
41
+ }): Record<string, unknown>;
42
+ /** `84532:10323` or `10323` → the token id, refusing an agent on another chain. */
43
+ declare function parseAgentId(id: string, chainId: number): bigint;
44
+ interface Erc8004Clients {
45
+ chain: Chain;
46
+ publicClient: PublicClient;
47
+ walletClient: WalletClient;
48
+ storage: Pick<MetadataStorage, "put">;
49
+ }
50
+ declare function retryNonce<T>(f: () => Promise<T>, tries?: number): Promise<T>;
51
+ /** Pin `file` and point agent `agentId` at it. */
52
+ declare function setAgentFile(c: Erc8004Clients, agentId: bigint, file: unknown): Promise<Hex>;
53
+ /** Mint an agent with no URI yet, and return its id. */
54
+ declare function mintAgent(c: Erc8004Clients): Promise<bigint>;
55
+ //#endregion
56
+ export { AgentCard, Erc8004Clients, IDENTITY_REGISTRY, agentCardUrl, mcpTools, mintAgent, parseAgentId, registrationFile, retryNonce, setAgentFile };
package/lib/erc8004.js ADDED
@@ -0,0 +1,140 @@
1
+ import { parseAbi, parseEventLogs } from "viem";
2
+
3
+ //#region src/erc8004.ts
4
+ /** The ERC-8004 identity registry by chain id */
5
+ const IDENTITY_REGISTRY = { 84532: "0x8004A818BFB912233c491871b3d84c89A494BD9e" };
6
+ const ABI = parseAbi([
7
+ "function register(string agentURI, (string metadataKey, bytes metadataValue)[] metadata) returns (uint256 agentId)",
8
+ "function setAgentURI(uint256 agentId, string newURI)",
9
+ "event Registered(uint256 indexed agentId, string agentURI, address indexed owner)"
10
+ ]);
11
+ /**
12
+ * Get the agent card URL based on the access worker if defined, else return the carUrl
13
+ * Both params are optional, but at least one must be defined.
14
+ *
15
+ * Agent cards must live at accessWorker/.well-known/agent-card.json
16
+ *
17
+ * @param cardUrl The cardUrl (passthrough when defined)
18
+ * @param accessWorker The (optional) access worker url
19
+ * @returns
20
+ */
21
+ function agentCardUrl(cardUrl, accessWorker) {
22
+ if (cardUrl) return cardUrl;
23
+ if (!accessWorker) throw new Error("No card URL. Pass one, or pass --access-worker <url>.");
24
+ return `${accessWorker.replace(/\/$/, "")}/.well-known/agent-card.json`;
25
+ }
26
+ async function mcpTools(endpoint) {
27
+ try {
28
+ const res = await fetch(endpoint, {
29
+ method: "POST",
30
+ headers: {
31
+ "Content-Type": "application/json",
32
+ Accept: "application/json, text/event-stream"
33
+ },
34
+ body: JSON.stringify({
35
+ jsonrpc: "2.0",
36
+ id: 1,
37
+ method: "tools/list"
38
+ }),
39
+ signal: AbortSignal.timeout(1e4)
40
+ });
41
+ if (!res.ok) return void 0;
42
+ const text = await res.text();
43
+ const body = text.split("\n").find((l) => l.startsWith("data: "))?.slice(6) ?? text;
44
+ const names = (JSON.parse(body).result?.tools ?? []).map((t) => t.name).filter((n) => typeof n === "string");
45
+ return names.length ? names : void 0;
46
+ } catch {
47
+ return;
48
+ }
49
+ }
50
+ /**
51
+ * Build a registration file
52
+ * Since it desfines its own agent id,
53
+ * first registration mints without an agent URI and must be set retroactively.
54
+ */
55
+ function registrationFile(opts) {
56
+ const { cardUrl, card, chainId, agentId, mcp } = opts;
57
+ const tags = [...new Set((card.skills ?? []).flatMap((s) => Array.isArray(s.tags) ? s.tags : []).filter((t) => typeof t === "string"))];
58
+ const services = [{
59
+ name: "A2A",
60
+ endpoint: cardUrl,
61
+ version: "0.30",
62
+ ...tags.length && { a2aSkills: tags }
63
+ }];
64
+ if (mcp) services.push({
65
+ name: "MCP",
66
+ endpoint: mcp.endpoint,
67
+ version: "2025-06-18",
68
+ ...mcp.tools && { mcpTools: mcp.tools }
69
+ });
70
+ return {
71
+ type: "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",
72
+ name: card.name,
73
+ description: card.description,
74
+ services,
75
+ registrations: [{
76
+ agentId: Number(agentId),
77
+ agentRegistry: `eip155:${String(chainId)}:${IDENTITY_REGISTRY[chainId]}`
78
+ }],
79
+ supportedTrust: ["reputation"],
80
+ active: true,
81
+ x402Support: card.skills?.some((s) => Array.isArray(s.tags) && s.tags.includes("x402")) ?? false,
82
+ updatedAt: opts.now ?? Math.floor(Date.now() / 1e3)
83
+ };
84
+ }
85
+ /** `84532:10323` or `10323` → the token id, refusing an agent on another chain. */
86
+ function parseAgentId(id, chainId) {
87
+ const m = /^(?:(\d+):)?(\d+)$/.exec(id.trim());
88
+ if (!m) throw new Error(`not an agent id: ${JSON.stringify(id)} (expected <chainId>:<tokenId>, e.g. 84532:10323)`);
89
+ if (m[1] && Number(m[1]) !== chainId) throw new Error(`agent ${id} is on chain ${m[1]}, but the CLI is configured for ${String(chainId)}`);
90
+ return BigInt(m[2]);
91
+ }
92
+ async function retryNonce(f, tries = 4) {
93
+ for (let i = 0;; i++) try {
94
+ return await f();
95
+ } catch (e) {
96
+ if (i >= tries - 1 || !/underpriced|nonce too low|nonce has already been used|already known/i.test(e.message)) throw e;
97
+ await new Promise((ok) => setTimeout(ok, 3e3 * (i + 1)));
98
+ }
99
+ }
100
+ function registry(chain) {
101
+ const address = IDENTITY_REGISTRY[chain.id];
102
+ if (!address) throw new Error(`no ERC-8004 identity registry known for chain ${String(chain.id)}`);
103
+ return address;
104
+ }
105
+ /** Pin `file` and point agent `agentId` at it. */
106
+ async function setAgentFile(c, agentId, file) {
107
+ const cid = await c.storage.put(file, { name: "agent-registration.json" });
108
+ const hash = await c.walletClient.writeContract({
109
+ address: registry(c.chain),
110
+ abi: ABI,
111
+ functionName: "setAgentURI",
112
+ args: [agentId, `ipfs://${cid}`],
113
+ chain: c.chain,
114
+ account: c.walletClient.account ?? null
115
+ });
116
+ await c.publicClient.waitForTransactionReceipt({ hash });
117
+ return hash;
118
+ }
119
+ /** Mint an agent with no URI yet, and return its id. */
120
+ async function mintAgent(c) {
121
+ const address = registry(c.chain);
122
+ const hash = await c.walletClient.writeContract({
123
+ address,
124
+ abi: ABI,
125
+ functionName: "register",
126
+ args: ["", []],
127
+ chain: c.chain,
128
+ account: c.walletClient.account ?? null
129
+ });
130
+ const minted = parseEventLogs({
131
+ abi: ABI,
132
+ eventName: "Registered",
133
+ logs: (await c.publicClient.waitForTransactionReceipt({ hash })).logs
134
+ }).find((l) => l.address.toLowerCase() === address.toLowerCase());
135
+ if (!minted) throw new Error(`register ${hash} confirmed with no Registered event`);
136
+ return minted.args.agentId;
137
+ }
138
+
139
+ //#endregion
140
+ export { IDENTITY_REGISTRY, agentCardUrl, mcpTools, mintAgent, parseAgentId, registrationFile, retryNonce, setAgentFile };