@fangorn-network/sdk 2026.3.11 → 2026.3.27

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 (87) hide show
  1. package/README.md +311 -198
  2. package/lib/builders/a2aCardBuilder.js +1 -0
  3. package/lib/cli/cli.js +406 -379
  4. package/lib/cli/index.d.ts +170 -170
  5. package/lib/cli/index.js +1 -4
  6. package/lib/config.d.ts +543 -163
  7. package/lib/config.js +11 -8
  8. package/lib/fangorn.d.ts +28 -45
  9. package/lib/fangorn.js +98 -119
  10. package/lib/index.d.ts +8 -5
  11. package/lib/index.js +8 -7
  12. package/lib/modules/encryption/index.d.ts +4 -3
  13. package/lib/modules/encryption/lit.d.ts +3 -18
  14. package/lib/modules/encryption/lit.js +20 -49
  15. package/lib/modules/encryption/rand.js +2 -2
  16. package/lib/modules/encryption/types.d.ts +23 -8
  17. package/lib/modules/gadgets/settledGadget.d.ts +26 -0
  18. package/lib/modules/gadgets/settledGadget.js +63 -0
  19. package/lib/modules/gadgets/types.d.ts +16 -4
  20. package/lib/providers/storage/index.d.ts +15 -4
  21. package/lib/providers/storage/pinata/index.d.ts +5 -4
  22. package/lib/providers/storage/pinata/index.js +17 -2
  23. package/lib/providers/storage/storacha/index.d.ts +13 -0
  24. package/lib/providers/storage/storacha/index.js +49 -0
  25. package/lib/providers/storage/storacha/readOnly.d.ts +8 -0
  26. package/lib/providers/storage/storacha/readOnly.js +16 -0
  27. package/lib/{interface → registries}/datasource-registry/abi.d.ts +29 -43
  28. package/lib/registries/datasource-registry/abi.js +16 -0
  29. package/lib/{interface/datasource-registry/dataSourceRegistry.d.ts → registries/datasource-registry/index.d.ts} +9 -9
  30. package/lib/{interface/datasource-registry/dataSourceRegistry.js → registries/datasource-registry/index.js} +35 -34
  31. package/lib/registries/index.d.ts +3 -0
  32. package/lib/registries/index.js +4 -0
  33. package/lib/registries/schema-registry/abi.d.ts +127 -0
  34. package/lib/registries/schema-registry/abi.js +19 -0
  35. package/lib/registries/schema-registry/index.d.ts +29 -0
  36. package/lib/registries/schema-registry/index.js +114 -0
  37. package/lib/registries/settlement-registry/abi.d.ts +228 -0
  38. package/lib/registries/settlement-registry/abi.js +29 -0
  39. package/lib/registries/settlement-registry/index.d.ts +72 -0
  40. package/lib/registries/settlement-registry/index.js +316 -0
  41. package/lib/registries/settlement-registry/types.d.ts +51 -0
  42. package/lib/roles/consumer/index.d.ts +64 -0
  43. package/lib/roles/consumer/index.js +114 -0
  44. package/lib/roles/consumer/types.d.ts +66 -0
  45. package/lib/roles/index.js +1 -0
  46. package/lib/roles/publisher/index.d.ts +70 -0
  47. package/lib/roles/publisher/index.js +203 -0
  48. package/lib/roles/publisher/types.d.ts +93 -0
  49. package/lib/roles/publisher/types.js +1 -0
  50. package/lib/roles/schema/index.d.ts +44 -0
  51. package/lib/roles/schema/index.js +137 -0
  52. package/lib/roles/schema/types.d.ts +67 -0
  53. package/lib/roles/schema/types.js +1 -0
  54. package/lib/test/index.d.ts +5 -2
  55. package/lib/test/index.js +5 -3
  56. package/lib/test/testbed.d.ts +54 -32
  57. package/lib/test/testbed.js +149 -135
  58. package/lib/types/index.d.ts +65 -21
  59. package/lib/types/index.js +1 -12
  60. package/lib/utils/index.d.ts +2 -3
  61. package/lib/utils/index.js +4 -18
  62. package/package.json +9 -18
  63. package/lib/cli/registry.d.ts +0 -29
  64. package/lib/cli/registry.js +0 -53
  65. package/lib/deployContract.d.ts +0 -23
  66. package/lib/deployContract.js +0 -78
  67. package/lib/interface/datasource-registry/abi.js +0 -110
  68. package/lib/interface/index.d.ts +0 -3
  69. package/lib/interface/index.js +0 -4
  70. package/lib/interface/manifest.d.ts +0 -7
  71. package/lib/interface/manifest.js +0 -10
  72. package/lib/interface/settlement-tracker/abi.d.ts +0 -26
  73. package/lib/interface/settlement-tracker/abi.js +0 -88
  74. package/lib/interface/settlement-tracker/settlementTracker.d.ts +0 -32
  75. package/lib/interface/settlement-tracker/settlementTracker.js +0 -64
  76. package/lib/modules/gadgets/acc/gadgets.d.ts +0 -7
  77. package/lib/modules/gadgets/acc/gadgets.js +0 -10
  78. package/lib/modules/gadgets/acc.d.ts +0 -15
  79. package/lib/modules/gadgets/acc.js +0 -24
  80. package/lib/modules/gadgets/builder.d.ts +0 -1
  81. package/lib/modules/gadgets/payment.d.ts +0 -23
  82. package/lib/modules/gadgets/payment.js +0 -88
  83. package/lib/test/test-gadget.d.ts +0 -7
  84. package/lib/test/test-gadget.js +0 -10
  85. /package/lib/{modules/gadgets/builder.js → registries/settlement-registry/types.js} +0 -0
  86. /package/lib/{providers/storage/s3/index.js → roles/consumer/types.js} +0 -0
  87. /package/lib/{providers/storage/s3 → roles}/index.d.ts +0 -0
package/lib/config.js CHANGED
@@ -24,23 +24,26 @@ function getNetwork(name) {
24
24
  else if (name === SupportedNetworks.BaseSepolia.name) return baseSepolia;
25
25
  throw new Error(`Chain ${name} is not supported`);
26
26
  }
27
- let FangornConfig;
28
- (function(_FangornConfig) {
29
- _FangornConfig.ArbitrumSepolia = {
30
- dataSourceRegistryContractAddress: "0x602aedafe1096004d4db591b6537bc39d7ac71a6",
27
+ const FangornConfig = {
28
+ ArbitrumSepolia: {
29
+ dataSourceRegistryContractAddress: "0xddd338e6a200012642a103c6631ea92eea94cabe",
30
+ schemaRegistryContractAddress: "0xef6754c29cfd0c8937a080695899f2a9a23c7c70",
31
+ settlementRegistryContractAddress: "0x5e918ba3fe33b0bdc68cd46eb6a77db754edef57",
31
32
  chainName: "arbitrumSepolia",
32
33
  chain: arbitrumSepolia,
33
34
  rpcUrl: "https://sepolia-rollup.arbitrum.io/rpc",
34
35
  caip2: 421614
35
- };
36
- _FangornConfig.BaseSepolia = {
36
+ },
37
+ BaseSepolia: {
37
38
  dataSourceRegistryContractAddress: "0x6fd0e50073dbd8169bcaf066bb4a4991bfa48eeb",
39
+ schemaRegistryContractAddress: "0x0",
40
+ settlementRegistryContractAddress: "0x0",
38
41
  chainName: "baseSepolia",
39
42
  chain: baseSepolia,
40
43
  rpcUrl: "https://sepolia.base.org",
41
44
  caip2: 84532
42
- };
43
- })(FangornConfig || (FangornConfig = {}));
45
+ }
46
+ };
44
47
 
45
48
  //#endregion
46
49
  export { FangornConfig, SupportedNetworks, getNetwork as default };
package/lib/fangorn.d.ts CHANGED
@@ -1,59 +1,42 @@
1
- import { Gadget } from "./modules/gadgets/types.js";
2
1
  import { AppConfig } from "./config.js";
3
- import { Filedata, VaultEntry, VaultManifest } from "./types/index.js";
4
- import { DataSourceRegistry, Vault } from "./interface/datasource-registry/dataSourceRegistry.js";
5
- import StorageProvider from "./providers/storage/index.js";
6
- import { EncryptionService } from "./modules/encryption/index.js";
7
- import { Address, Hex, WalletClient } from "viem";
2
+ import { SchemaRegistry } from "./registries/schema-registry/index.js";
3
+ import { SchemaRole } from "./roles/schema/index.js";
4
+ import { DataSourceRegistry } from "./registries/datasource-registry/index.js";
5
+ import { SettlementRegistry } from "./registries/settlement-registry/index.js";
6
+ import { FangornCreateOptions } from "./types/index.js";
7
+ import { PublisherRole } from "./roles/publisher/index.js";
8
+ import { ConsumerRole } from "./roles/consumer/index.js";
9
+ import { Hex, WalletClient } from "viem";
8
10
 
9
11
  //#region src/fangorn.d.ts
10
-
11
- /**
12
- *
13
- */
14
12
  declare class Fangorn {
15
- private dataSourceRegistry;
16
- private walletClient;
17
- private storage;
18
- private encryptionService;
19
- private domain;
20
- private pendingEntries;
21
- constructor(dataSourceRegistry: DataSourceRegistry, walletClient: WalletClient, storage: StorageProvider<any>, encryptionService: EncryptionService, domain: string);
22
- static init(walletClient: WalletClient, storage: StorageProvider<any>, encryptionService: EncryptionService, domain: string, config?: AppConfig): Promise<Fangorn>;
23
- /**
24
- * Register a new named data source owned by the current wallet.
25
- */
26
- registerDataSource(name: string, agentId?: string): Promise<Hex>;
27
- /**
28
- * Upload files to a vault with the given gadget for access control.
29
- */
30
- upload(name: string, filedata: Filedata[], gadgetFactory: (file: Filedata) => Gadget | Promise<Gadget>, overwrite?: boolean): Promise<string>;
31
- /**
32
- * Encrypt and stage a single file.
33
- * Call commitVault() after adding all files.
34
- */
35
- addFile(file: Filedata, gadget: Gadget): Promise<{
36
- cid: string;
37
- }>;
13
+ private readonly ctx;
14
+ private _schema;
15
+ private _publisher;
16
+ private _consumer;
17
+ private constructor();
38
18
  /**
39
- * Remove a staged file before committing.
19
+ * Schema owner: register agents, register schemas, validate definitions.
20
+ * Requires writable storage.
40
21
  */
41
- removeFile(tag: string): boolean;
22
+ get schema(): SchemaRole;
42
23
  /**
43
- * Commit all staged files to the vault.
24
+ * Publisher: encrypt, stage, and commit data under a schema.
25
+ * Requires writable storage.
44
26
  */
45
- commit(name: string): Promise<string>;
27
+ get publisher(): PublisherRole;
46
28
  /**
47
- * Decrypt a file from a vault.
29
+ * Consumer: purchase, claim, and decrypt data.
30
+ * Works with both readable and writable storage.
48
31
  */
49
- decryptFile(owner: Address, name: string, tag: string, authContext?: any): Promise<Uint8Array>;
50
- getDataSource(owner: Address, name: string): Promise<Vault>;
51
- registry(): DataSourceRegistry;
52
- getManifest(owner: Address, name: string): Promise<VaultManifest | undefined>;
53
- getDataSourceData(owner: Address, name: string, tag: string): Promise<VaultEntry>;
32
+ get consumer(): ConsumerRole;
33
+ static create(options: FangornCreateOptions): Promise<Fangorn>;
34
+ getConfig(): AppConfig;
35
+ getSchemaRegistry(): SchemaRegistry;
36
+ getDatasourceRegistry(): DataSourceRegistry;
37
+ getSettlementRegistry(): SettlementRegistry;
38
+ getWalletClient(): WalletClient;
54
39
  getAddress(): Hex;
55
- fetchManifest(cid: string): Promise<VaultManifest>;
56
- private loadManifest;
57
40
  }
58
41
  //#endregion
59
42
  export { Fangorn };
package/lib/fangorn.js CHANGED
@@ -1,143 +1,122 @@
1
1
  import { FangornConfig } from "./config.js";
2
- import { DataSourceRegistry } from "./interface/datasource-registry/dataSourceRegistry.js";
3
- import { createPublicClient, http } from "viem";
2
+ import { LitEncryptionService } from "./modules/encryption/lit.js";
3
+ import "./modules/encryption/index.js";
4
+ import { SchemaRole } from "./roles/schema/index.js";
5
+ import { SettlementRegistry } from "./registries/settlement-registry/index.js";
6
+ import { PublisherRole } from "./roles/publisher/index.js";
7
+ import { ConsumerRole } from "./roles/consumer/index.js";
8
+ import { SchemaRegistry } from "./registries/schema-registry/index.js";
9
+ import { DataSourceRegistry } from "./registries/datasource-registry/index.js";
10
+ import { PinataStorage } from "./providers/storage/pinata/index.js";
11
+ import "./providers/storage/index.js";
12
+ import { StorachaStorage } from "./providers/storage/storacha/index.js";
13
+ import { ReadOnlyStorachaStorage } from "./providers/storage/storacha/readOnly.js";
14
+ import { createPublicClient, createWalletClient, http } from "viem";
15
+ import { privateKeyToAccount } from "viem/accounts";
4
16
 
5
17
  //#region src/fangorn.ts
6
- /**
7
- *
8
- */
18
+ function isEncryptionService(e) {
19
+ return typeof e.encrypt === "function";
20
+ }
21
+ function isPinataConfig(s) {
22
+ return "pinata" in s;
23
+ }
24
+ function isStorachaReadOnly(s) {
25
+ return "storacha" in s && "readOnly" in s.storacha;
26
+ }
27
+ function isStorachaConfig(s) {
28
+ return "storacha" in s && "email" in s.storacha;
29
+ }
30
+ function isWritable(s) {
31
+ return "store" in s && "delete" in s;
32
+ }
33
+ async function resolveStorage(storage) {
34
+ if (isPinataConfig(storage)) return new PinataStorage(storage.pinata.jwt, storage.pinata.gateway);
35
+ if (isStorachaReadOnly(storage)) return new ReadOnlyStorachaStorage();
36
+ if (isStorachaConfig(storage)) return StorachaStorage.create(storage.storacha.email);
37
+ throw new Error("Invalid storage config: must be a StorageProvider instance, a { pinata } object, or a { storacha } object.");
38
+ }
9
39
  var Fangorn = class Fangorn {
10
- pendingEntries = /* @__PURE__ */ new Map();
11
- constructor(dataSourceRegistry, walletClient, storage, encryptionService, domain) {
12
- this.dataSourceRegistry = dataSourceRegistry;
13
- this.walletClient = walletClient;
14
- this.storage = storage;
15
- this.encryptionService = encryptionService;
16
- this.domain = domain;
17
- }
18
- static async init(walletClient, storage, encryptionService, domain, config) {
19
- const resolvedConfig = config || FangornConfig.ArbitrumSepolia;
20
- const publicClient = createPublicClient({ transport: http(resolvedConfig.rpcUrl) });
21
- return new Fangorn(new DataSourceRegistry(resolvedConfig.dataSourceRegistryContractAddress, publicClient, walletClient), walletClient, storage, encryptionService, domain);
22
- }
23
- /**
24
- * Register a new named data source owned by the current wallet.
25
- */
26
- async registerDataSource(name, agentId) {
27
- return await this.dataSourceRegistry.registerDataSource(name, agentId || "");
40
+ ctx;
41
+ _schema = null;
42
+ _publisher = null;
43
+ _consumer = null;
44
+ constructor(ctx) {
45
+ this.ctx = ctx;
28
46
  }
29
47
  /**
30
- * Upload files to a vault with the given gadget for access control.
48
+ * Schema owner: register agents, register schemas, validate definitions.
49
+ * Requires writable storage.
31
50
  */
32
- async upload(name, filedata, gadgetFactory, overwrite) {
33
- const who = this.walletClient.account.address;
34
- const datasource = await this.dataSourceRegistry.getDataSource(who, name);
35
- if (datasource.manifestCid && !overwrite) {
36
- const oldManifest = await this.fetchManifest(datasource.manifestCid);
37
- this.loadManifest(oldManifest);
38
- try {
39
- await this.storage.delete(datasource.manifestCid);
40
- } catch (e) {
41
- console.warn("Failed to unpin old manifest:", e);
42
- }
43
- }
44
- for (const file of filedata) {
45
- const gadget = await gadgetFactory(file);
46
- await this.addFile(file, gadget);
47
- }
48
- return await this.commit(name);
51
+ get schema() {
52
+ if (!isWritable(this.ctx.storage)) throw new Error("fangorn.schema requires writable storage. Use { storacha: { email } } or { pinata: { ... } }");
53
+ return this._schema ??= new SchemaRole(this.ctx.schemaRegistry, this.ctx.storage, this.ctx.walletClient, this.ctx.schemaRoleConfig);
49
54
  }
50
55
  /**
51
- * Encrypt and stage a single file.
52
- * Call commitVault() after adding all files.
56
+ * Publisher: encrypt, stage, and commit data under a schema.
57
+ * Requires writable storage.
53
58
  */
54
- async addFile(file, gadget) {
55
- if (!this.walletClient.account?.address) throw new Error("Wallet not connected");
56
- const encrypted = await this.encryptionService.encrypt(file, gadget);
57
- const cid = await this.storage.store(encrypted, { metadata: { name: file.tag } });
58
- this.pendingEntries.set(file.tag, {
59
- tag: file.tag,
60
- cid,
61
- extension: file.extension,
62
- fileType: file.fileType,
63
- gadgetDescriptor: gadget.toDescriptor()
64
- });
65
- return { cid };
59
+ get publisher() {
60
+ if (!isWritable(this.ctx.storage)) throw new Error("fangorn.publisher requires writable storage. Use { storacha: { email } } or { pinata: { ... } }");
61
+ return this._publisher ??= new PublisherRole(this.ctx.dataSourceRegistry, this.ctx.settlementRegistry, this.ctx.storage, this.ctx.encryption, this.ctx.walletClient);
66
62
  }
67
63
  /**
68
- * Remove a staged file before committing.
64
+ * Consumer: purchase, claim, and decrypt data.
65
+ * Works with both readable and writable storage.
69
66
  */
70
- removeFile(tag) {
71
- return this.pendingEntries.delete(tag);
67
+ get consumer() {
68
+ return this._consumer ??= new ConsumerRole(this.ctx.dataSourceRegistry, this.ctx.settlementRegistry, this.ctx.storage, this.ctx.encryption, this.ctx.domain);
72
69
  }
73
- /**
74
- * Commit all staged files to the vault.
75
- */
76
- async commit(name) {
77
- if (this.pendingEntries.size === 0) throw new Error("No files to commit");
78
- const manifest = {
79
- version: 1,
80
- entries: Array.from(this.pendingEntries.values()).map((e, i) => ({
81
- tag: e.tag,
82
- cid: e.cid,
83
- index: i,
84
- extension: e.extension,
85
- fileType: e.fileType,
86
- gadgetDescriptor: e.gadgetDescriptor
87
- })),
88
- tree: []
89
- };
90
- const manifestCid = await this.storage.store(manifest, { metadata: { name: `manifest-${name}` } });
91
- const hash = await this.dataSourceRegistry.updateDataSource(name, manifestCid);
92
- await this.dataSourceRegistry.waitForTransaction(hash);
93
- this.pendingEntries.clear();
94
- return manifestCid;
70
+ static async create(options) {
71
+ if (!options.privateKey && !options.walletClient) throw new Error("Either privateKey or walletClient must be provided");
72
+ const resolvedConfig = options.config ?? FangornConfig.ArbitrumSepolia;
73
+ const walletClient = options.walletClient ?? createWalletClient({
74
+ account: privateKeyToAccount(options.privateKey ?? "0x0"),
75
+ chain: resolvedConfig.chain,
76
+ transport: http(resolvedConfig.rpcUrl)
77
+ });
78
+ const storage = await resolveStorage(options.storage);
79
+ const encryption = isEncryptionService(options.encryption) ? options.encryption : await LitEncryptionService.init(resolvedConfig.chainName);
80
+ const domain = options.domain ?? new URL(resolvedConfig.rpcUrl).hostname;
81
+ const publicClient = createPublicClient({ transport: http(resolvedConfig.rpcUrl) });
82
+ return new Fangorn({
83
+ walletClient,
84
+ storage,
85
+ encryption,
86
+ domain,
87
+ schemaRegistry: new SchemaRegistry(resolvedConfig.schemaRegistryContractAddress, publicClient, walletClient),
88
+ dataSourceRegistry: new DataSourceRegistry(resolvedConfig.dataSourceRegistryContractAddress, publicClient, walletClient),
89
+ settlementRegistry: new SettlementRegistry(resolvedConfig.settlementRegistryContractAddress, publicClient, walletClient),
90
+ schemaRoleConfig: options.agentConfig ? {
91
+ chainId: resolvedConfig.chain.id,
92
+ rpcUrl: resolvedConfig.rpcUrl,
93
+ privateKey: options.agentConfig.privateKey,
94
+ pinataJwt: options.agentConfig.pinataJwt,
95
+ registryOverrides: options.agentConfig.registryOverrides,
96
+ subgraphOverrides: options.agentConfig.subgraphOverrides
97
+ } : void 0,
98
+ config: resolvedConfig
99
+ });
95
100
  }
96
- /**
97
- * Decrypt a file from a vault.
98
- */
99
- async decryptFile(owner, name, tag, authContext) {
100
- const vault = await this.dataSourceRegistry.getDataSource(owner, name);
101
- const entry = (await this.storage.retrieve(vault.manifestCid)).entries.find((e) => e.tag === tag);
102
- if (!entry) throw new Error(`Entry not found: ${tag}`);
103
- const encrypted = await this.storage.retrieve(entry.cid);
104
- const resolvedAuthContext = authContext ?? await this.encryptionService.createAuthContext(this.walletClient, this.domain);
105
- return (await this.encryptionService.decrypt(encrypted, resolvedAuthContext)).data;
101
+ getConfig() {
102
+ return this.ctx.config;
106
103
  }
107
- async getDataSource(owner, name) {
108
- return await this.dataSourceRegistry.getDataSource(owner, name);
104
+ getSchemaRegistry() {
105
+ return this.ctx.schemaRegistry;
109
106
  }
110
- registry() {
111
- return this.dataSourceRegistry;
107
+ getDatasourceRegistry() {
108
+ return this.ctx.dataSourceRegistry;
112
109
  }
113
- async getManifest(owner, name) {
114
- const vault = await this.getDataSource(owner, name);
115
- if (!vault.manifestCid || vault.manifestCid === "") return;
116
- return await this.fetchManifest(vault.manifestCid);
110
+ getSettlementRegistry() {
111
+ return this.ctx.settlementRegistry;
117
112
  }
118
- async getDataSourceData(owner, name, tag) {
119
- const manifest = await this.getManifest(owner, name);
120
- if (!manifest) throw new Error("Vault has no manifest");
121
- const entry = manifest.entries.find((e) => e.tag === tag);
122
- if (!entry) throw new Error(`Entry not found: ${tag}`);
123
- return entry;
113
+ getWalletClient() {
114
+ return this.ctx.walletClient;
124
115
  }
125
116
  getAddress() {
126
- const account = this.walletClient.account;
127
- if (!account?.address) throw new Error("Wallet not connected");
128
- return account.address;
129
- }
130
- async fetchManifest(cid) {
131
- return await this.storage.retrieve(cid);
132
- }
133
- loadManifest(oldManifest) {
134
- for (const entry of oldManifest.entries) this.pendingEntries.set(entry.tag, {
135
- tag: entry.tag,
136
- cid: entry.cid,
137
- extension: entry.extension,
138
- fileType: entry.fileType,
139
- gadgetDescriptor: entry.gadgetDescriptor
140
- });
117
+ const address = this.ctx.walletClient.account?.address;
118
+ if (!address) throw new Error("No account connected to wallet client");
119
+ return address;
141
120
  }
142
121
  };
143
122
 
package/lib/index.d.ts CHANGED
@@ -1,9 +1,12 @@
1
1
  import { AppConfig, FangornConfig, SupportedNetworks } from "./config.js";
2
2
  import { PinataStorage } from "./providers/storage/pinata/index.js";
3
- import { LitEncryptionService, LitEncryptionServiceConfig } from "./modules/encryption/lit.js";
3
+ import { ReadableStorage, WritableStorage } from "./providers/storage/index.js";
4
+ import { Gadget } from "./modules/gadgets/types.js";
5
+ import "./modules/gadgets/index.js";
6
+ import { LitEncryptionService } from "./modules/encryption/lit.js";
4
7
  import { AuthContext, AuthSig, EncryptionService } from "./modules/encryption/index.js";
5
8
  import { Fangorn } from "./fangorn.js";
6
- import { SETTLEMENT_TRACKER_ABI } from "./interface/settlement-tracker/abi.js";
7
- import { DS_REGISTRY_ABI } from "./interface/datasource-registry/abi.js";
8
- import { addressToBytes32Array, computeTagCommitment, deriveDatasourceId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array } from "./utils/index.js";
9
- export { AppConfig, AuthContext, AuthSig, DS_REGISTRY_ABI, EncryptionService, Fangorn, FangornConfig, LitEncryptionService, LitEncryptionServiceConfig, PinataStorage, SETTLEMENT_TRACKER_ABI, SupportedNetworks, addressToBytes32Array, computeTagCommitment, deriveDatasourceId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array };
9
+ import { SETTLEMENT_REGISTRY_ABI } from "./registries/settlement-registry/abi.js";
10
+ import { DS_REGISTRY_ABI } from "./registries/datasource-registry/abi.js";
11
+ import { addressToBytes32Array, computeSchemaId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array } from "./utils/index.js";
12
+ export { AppConfig, AuthContext, AuthSig, DS_REGISTRY_ABI, EncryptionService, Fangorn, FangornConfig, Gadget, LitEncryptionService, PinataStorage, ReadableStorage, SETTLEMENT_REGISTRY_ABI, SupportedNetworks, WritableStorage, addressToBytes32Array, computeSchemaId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array };
package/lib/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { FangornConfig, SupportedNetworks } from "./config.js";
2
- import { DS_REGISTRY_ABI } from "./interface/datasource-registry/abi.js";
3
- import { Fangorn } from "./fangorn.js";
4
- import { PinataStorage } from "./providers/storage/pinata/index.js";
5
- import "./providers/storage/index.js";
6
- import { SETTLEMENT_TRACKER_ABI } from "./interface/settlement-tracker/abi.js";
7
- import { addressToBytes32Array, computeTagCommitment, deriveDatasourceId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array } from "./utils/index.js";
8
2
  import { LitEncryptionService } from "./modules/encryption/lit.js";
9
3
  import "./modules/encryption/index.js";
4
+ import { SETTLEMENT_REGISTRY_ABI } from "./registries/settlement-registry/abi.js";
5
+ import { DS_REGISTRY_ABI } from "./registries/datasource-registry/abi.js";
6
+ import { PinataStorage } from "./providers/storage/pinata/index.js";
7
+ import "./providers/storage/index.js";
8
+ import { Fangorn } from "./fangorn.js";
9
+ import "./registries/index.js";
10
+ import { addressToBytes32Array, computeSchemaId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array } from "./utils/index.js";
10
11
 
11
- export { DS_REGISTRY_ABI, Fangorn, FangornConfig, LitEncryptionService, PinataStorage, SETTLEMENT_TRACKER_ABI, SupportedNetworks, addressToBytes32Array, computeTagCommitment, deriveDatasourceId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array };
12
+ export { DS_REGISTRY_ABI, Fangorn, FangornConfig, LitEncryptionService, PinataStorage, SETTLEMENT_REGISTRY_ABI, SupportedNetworks, addressToBytes32Array, computeSchemaId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array };
@@ -1,14 +1,15 @@
1
1
  import { Gadget } from "../gadgets/types.js";
2
2
  import { Filedata } from "../../types/index.js";
3
+ import "../gadgets/index.js";
3
4
  import { DecryptedPayload, EncryptedPayload } from "./types.js";
4
- import { LitEncryptionService, LitEncryptionServiceConfig } from "./lit.js";
5
+ import { LitEncryptionService } from "./lit.js";
5
6
  import { WalletClient } from "viem";
6
7
 
7
8
  //#region src/modules/encryption/index.d.ts
8
9
  interface EncryptionService {
9
10
  encrypt(file: Filedata, gadget: Gadget): Promise<EncryptedPayload>;
10
11
  decrypt(payload: EncryptedPayload, authContext: AuthContext): Promise<DecryptedPayload>;
11
- createAuthContext(walletClient: WalletClient, domain: string): Promise<AuthContext>;
12
+ createAuthContext(walletClient: WalletClient, domain: string, nullifierHash: bigint): Promise<AuthContext>;
12
13
  }
13
14
  /**
14
15
  * Auth context needed for Lit decryption
@@ -24,4 +25,4 @@ interface AuthSig {
24
25
  address: string;
25
26
  }
26
27
  //#endregion
27
- export { AuthContext, AuthSig, EncryptionService, LitEncryptionService, LitEncryptionServiceConfig };
28
+ export { AuthContext, AuthSig, EncryptionService, LitEncryptionService };
@@ -6,31 +6,16 @@ import { WalletClient } from "viem";
6
6
  import { LitClient } from "@lit-protocol/lit-client";
7
7
 
8
8
  //#region src/modules/encryption/lit.d.ts
9
- interface LitEncryptionServiceConfig {
10
- chainName: string;
11
- }
12
9
  declare class LitEncryptionService implements EncryptionService {
13
- private litClient;
14
- private chainName;
10
+ private readonly litClient;
11
+ private readonly chainName;
15
12
  constructor(litClient: LitClient, chainName: string);
16
13
  static init(chain: string): Promise<LitEncryptionService>;
17
- /**
18
- * Encrypt filedata under the given gadget
19
- * @param file The filedata to encrypt
20
- * @param gadget The gadget to use
21
- * @returns The ciphertext bundle
22
- */
23
14
  encrypt(file: Filedata, gadget: Gadget): Promise<EncryptedPayload>;
24
- /**
25
- * Attempt to decrypt some encrypted data
26
- * @param payload The encrytped bundle to recover
27
- * @param authContext The authorization context
28
- * @returns The decrytped output (on success), else empty
29
- */
30
15
  decrypt(payload: EncryptedPayload, authContext: AuthContextWrapper): Promise<DecryptedPayload>;
31
16
  createAuthContext(walletClient: WalletClient, domain: string): Promise<AuthContextWrapper>;
32
17
  private createAuthSig;
33
18
  private parseKeyResponse;
34
19
  }
35
20
  //#endregion
36
- export { LitEncryptionService, LitEncryptionServiceConfig };
21
+ export { LitEncryptionService };
@@ -5,26 +5,6 @@ import { createAuthManager, storagePlugins } from "@lit-protocol/auth";
5
5
  import { nagaDev } from "@lit-protocol/networks";
6
6
 
7
7
  //#region src/modules/encryption/lit.ts
8
- const createDecryptLitActionCode = (chainName) => `(async () => {
9
- try {
10
- const decryptedContent = await Lit.Actions.decryptAndCombine({
11
- accessControlConditions: jsParams.accessControlConditions,
12
- ciphertext: jsParams.ciphertext,
13
- dataToEncryptHash: jsParams.dataToEncryptHash,
14
- authSig: jsParams.authSig,
15
- chain: "${chainName}",
16
- });
17
- Lit.Actions.setResponse({
18
- response: decryptedContent,
19
- success: true,
20
- });
21
- } catch (error) {
22
- Lit.Actions.setResponse({
23
- response: error.message,
24
- success: false,
25
- });
26
- }
27
- })();`;
28
8
  var LitEncryptionService = class LitEncryptionService {
29
9
  constructor(litClient, chainName) {
30
10
  this.litClient = litClient;
@@ -33,18 +13,12 @@ var LitEncryptionService = class LitEncryptionService {
33
13
  static async init(chain) {
34
14
  return new LitEncryptionService(await createLitClient({ network: nagaDev }), chain);
35
15
  }
36
- /**
37
- * Encrypt filedata under the given gadget
38
- * @param file The filedata to encrypt
39
- * @param gadget The gadget to use
40
- * @returns The ciphertext bundle
41
- */
42
16
  async encrypt(file, gadget) {
43
17
  const { encryptedData, keyMaterial } = await encryptData(file.data);
44
- const acc = await gadget.toAccessCondition();
18
+ const rawAcc = gadget.toAccessCondition()[0];
45
19
  const litEncryptedKey = await this.litClient.encrypt({
46
20
  dataToEncrypt: keyMaterial.toString(),
47
- unifiedAccessControlConditions: acc,
21
+ evmContractConditions: [rawAcc],
48
22
  chain: this.chainName
49
23
  });
50
24
  return {
@@ -53,34 +27,30 @@ var LitEncryptionService = class LitEncryptionService {
53
27
  ciphertext: litEncryptedKey.ciphertext,
54
28
  dataToEncryptHash: litEncryptedKey.dataToEncryptHash
55
29
  },
56
- acc,
57
- litAction: gadget.toLitAction()
30
+ acc: [rawAcc]
58
31
  };
59
32
  }
60
- /**
61
- * Attempt to decrypt some encrypted data
62
- * @param payload The encrytped bundle to recover
63
- * @param authContext The authorization context
64
- * @returns The decrytped output (on success), else empty
65
- */
66
33
  async decrypt(payload, authContext) {
67
- const result = await this.litClient.executeJs({
68
- code: createDecryptLitActionCode(authContext.chainName),
69
- authContext: authContext.sessionContext,
70
- jsParams: {
71
- accessControlConditions: payload.acc,
34
+ console.log("authSig address:", authContext.authSig.address);
35
+ const result = await this.litClient.decrypt({
36
+ data: {
72
37
  ciphertext: payload.key.ciphertext,
73
- dataToEncryptHash: payload.key.dataToEncryptHash,
74
- authSig: authContext.authSig
75
- }
38
+ dataToEncryptHash: payload.key.dataToEncryptHash
39
+ },
40
+ unifiedAccessControlConditions: payload.acc,
41
+ authContext: authContext.sessionContext,
42
+ chain: this.chainName
76
43
  });
77
- const key = this.parseKeyResponse(result.response);
44
+ const decryptedString = new TextDecoder().decode(result.decryptedData);
45
+ const key = new Uint8Array(decryptedString.split(",").map((n) => parseInt(n.trim(), 10)));
78
46
  return { data: await decryptData(payload.data, key) };
79
47
  }
80
48
  async createAuthContext(walletClient, domain) {
81
- const isWindowUndefined = typeof window === "undefined";
82
- const account = isWindowUndefined ? walletClient.account : walletClient;
83
- const sessionContext = await (isWindowUndefined ? createAuthManager({ storage: storagePlugins.localStorageNode({
49
+ const isNode = typeof window === "undefined";
50
+ const account = isNode ? walletClient.account : walletClient;
51
+ if (!account) throw new Error("No account found in wallet client");
52
+ if (!walletClient.chain) throw new Error("No chain found in wallet client");
53
+ const sessionContext = await (isNode ? createAuthManager({ storage: storagePlugins.localStorageNode({
84
54
  appName: "fangorn",
85
55
  networkName: "naga-dev",
86
56
  storagePath: "./lit-auth-storage"
@@ -109,6 +79,7 @@ var LitEncryptionService = class LitEncryptionService {
109
79
  }
110
80
  async createAuthSig(walletClient, domain) {
111
81
  const account = walletClient.account;
82
+ if (!account) throw new Error("No account found in wallet client");
112
83
  const resources = [
113
84
  {
114
85
  resource: new LitAccessControlConditionResource("*"),
@@ -126,7 +97,7 @@ var LitEncryptionService = class LitEncryptionService {
126
97
  const siweMessage = await createSiweMessage({
127
98
  walletAddress: account.address,
128
99
  domain,
129
- statement: "Decrypt data",
100
+ statement: "Decrypt data.",
130
101
  uri: `https://${domain}`,
131
102
  version: "1",
132
103
  chainId: 1,
@@ -4,11 +4,11 @@ function getCrypto() {
4
4
  throw new Error("No crypto available - are you in Node < 19?");
5
5
  }
6
6
  function getSubtleCrypto() {
7
- if (typeof window !== "undefined" && window.crypto) return window.crypto.subtle;
7
+ if (typeof window !== "undefined") return window.crypto.subtle;
8
8
  else return getCrypto().subtle;
9
9
  }
10
10
  function getRandomValues(array) {
11
- if (typeof window !== "undefined" && window.crypto) return window.crypto.getRandomValues(array);
11
+ if (typeof window !== "undefined") return window.crypto.getRandomValues(array);
12
12
  else return getCrypto().getRandomValues(array);
13
13
  }
14
14
 
@@ -1,4 +1,8 @@
1
+ import { createAuthManager } from "@lit-protocol/auth";
2
+ import { UnifiedAccessControlCondition } from "@lit-protocol/access-control-conditions";
3
+
1
4
  //#region src/modules/encryption/types.d.ts
5
+ type EoaAuthContext = Awaited<ReturnType<ReturnType<typeof createAuthManager>["createEoaAuthContext"]>>;
2
6
  interface AesEncryptedData {
3
7
  ciphertext: Uint8Array<ArrayBuffer>;
4
8
  iv: Uint8Array<ArrayBuffer>;
@@ -9,14 +13,24 @@ interface LitEncryptedData {
9
13
  ciphertext: string;
10
14
  dataToEncryptHash: string;
11
15
  }
12
- /**
13
- * Complete encrypted payload - stored to IPFS
14
- */
15
16
  interface EncryptedPayload {
17
+ /** Locally AES-encrypted file bytes */
16
18
  data: AesEncryptedData;
17
- key: LitEncryptedData;
18
- acc: AccessControlCondition;
19
- litAction: string;
19
+ /** Lit-threshold-encrypted AES key */
20
+ key: {
21
+ ciphertext: string;
22
+ dataToEncryptHash: string;
23
+ };
24
+ /**
25
+ * The ACC used to encrypt the key — stored here so decrypt() can
26
+ * reconstruct the exact conditions without re-deriving them from
27
+ * the gadget. The gadget is a publisher-time concept; the consumer
28
+ * only has the payload.
29
+ */
30
+ acc: UnifiedAccessControlCondition[];
31
+ }
32
+ interface DecryptedPayload {
33
+ data: Uint8Array;
20
34
  }
21
35
  /**
22
36
  * Lit's access control condition structure
@@ -37,8 +51,9 @@ interface AuthSig {
37
51
  */
38
52
  interface AuthContextWrapper {
39
53
  authSig: AuthSig;
40
- sessionContext: any;
54
+ sessionContext: EoaAuthContext;
41
55
  chainName: string;
56
+ nullifierHash?: string;
42
57
  }
43
58
  /**
44
59
  * Result of successful decryption
@@ -52,4 +67,4 @@ interface DecryptedPayload {
52
67
  };
53
68
  }
54
69
  //#endregion
55
- export { AccessControlCondition, AesEncryptedData, AuthContextWrapper, AuthSig, DecryptedPayload, EncryptedPayload, LitEncryptedData };
70
+ export { AccessControlCondition, AesEncryptedData, AuthContextWrapper, AuthSig, DecryptedPayload, EncryptedPayload, EoaAuthContext, LitEncryptedData };