@dignetwork/dig-sdk 0.0.1-alpha.110 → 0.0.1-alpha.112

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.
@@ -17,6 +17,7 @@ declare class DataIntegrityTree {
17
17
  files: Map<string, {
18
18
  hash: string;
19
19
  sha256: string;
20
+ bytes: string;
20
21
  }>;
21
22
  private tree;
22
23
  constructor(storeId: string, options?: DataIntegrityTreeOptions);
@@ -1 +1 @@
1
- {"version":3,"file":"DataIntegrityTree.d.ts","sourceRoot":"","sources":["../../src/DataIntegrityTree/DataIntegrityTree.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAuClC,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAClC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAGlB,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;GAEG;AACH,cAAM,iBAAiB;IACrB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,OAAO,CAAS;IACjB,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC5D,OAAO,CAAC,IAAI,CAAa;gBAEb,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,wBAA6B;WAgDrD,IAAI,CAChB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,wBAAwB,GAChC,iBAAiB;IAOpB;;;OAGG;IACH,OAAO,CAAC,aAAa;IAQrB;;;OAGG;IACH,OAAO,CAAC,eAAe;IAevB;;;;OAIG;IACH,OAA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CnC,OAAO,CAAC,MAAM,CAAC,wBAAwB;IAkCvC,OAAO,CAAC,MAAM,CAAC,eAAe;CAgB/B;AAED,OAAO,EAAE,iBAAiB,EAAE,CAAC"}
@@ -191,11 +191,16 @@ class DataIntegrityTree {
191
191
  fs.mkdirSync(tempDir, { recursive: true });
192
192
  }
193
193
  const tempFilePath = path.join(tempDir, `${crypto.randomUUID()}.gz`);
194
+ let totalBytes = 0;
194
195
  return new Promise((resolve, reject) => {
195
196
  const tempWriteStream = fs.createWriteStream(tempFilePath);
196
197
  readStream.on("data", (chunk) => {
197
198
  uncompressedHash.update(chunk);
198
199
  });
200
+ // Now listen to the gzip stream for compressed data size
201
+ gzip.on("data", (chunk) => {
202
+ totalBytes += chunk.length; // This counts compressed bytes
203
+ });
199
204
  readStream.pipe(gzip).pipe(tempWriteStream);
200
205
  tempWriteStream.on("finish", async () => {
201
206
  sha256 = uncompressedHash.digest("hex");
@@ -224,6 +229,7 @@ class DataIntegrityTree {
224
229
  this.files.set(key, {
225
230
  hash: combinedHash,
226
231
  sha256: sha256,
232
+ bytes: totalBytes.toString(),
227
233
  });
228
234
  await new Promise((resolve) => setTimeout(resolve, 100));
229
235
  this._rebuildTree();
@@ -8,6 +8,7 @@ export declare class ContentServer {
8
8
  private static readonly port;
9
9
  constructor(ipAddress: string, storeId: string);
10
10
  getKey(key: string, rootHash: string, challengeHex?: string): Promise<string>;
11
+ getKeyChunk(key: string, rootHash: string): Promise<Buffer>;
11
12
  getPaymentAddress(): Promise<string | null>;
12
13
  getWellKnown(): Promise<any>;
13
14
  getKnownStores(): Promise<any>;
@@ -29,5 +30,6 @@ export declare class ContentServer {
29
30
  private fetchJson;
30
31
  private fetchWithRetries;
31
32
  private fetch;
33
+ private fetchFirstChunk;
32
34
  }
33
35
  //# sourceMappingURL=ContentServer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ContentServer.d.ts","sourceRoot":"","sources":["../../src/DigNetwork/ContentServer.ts"],"names":[],"mappings":"AAC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AAE;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QACjE,OAAO,EAAE,OAAO,CAAC;QACjB,OAAO,CAAC,EAAE,IAAI,CAAC,mBAAmB,CAAC;KACpC,CAAC;IAUW,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAUrD,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;YAgDrD,IAAI;YA0EJ,SAAS;YAMT,gBAAgB;YAiChB,KAAK;YA+GL,eAAe;CA2G9B"}
@@ -29,6 +29,12 @@ class ContentServer {
29
29
  }
30
30
  return this.fetchWithRetries(url);
31
31
  }
32
+ // New method to get only the first chunk of the content
33
+ async getKeyChunk(key, rootHash) {
34
+ // Construct the base URL
35
+ let url = `https://${(0, network_1.formatHost)(this.ipAddress)}:${ContentServer.port}/chia.${this.storeId}.${rootHash}/${key}`;
36
+ return this.fetchFirstChunk(url);
37
+ }
32
38
  // Method to get the payment address from the peer
33
39
  async getPaymentAddress() {
34
40
  console.log(`Fetching payment address from peer ${this.ipAddress}...`);
@@ -304,6 +310,82 @@ class ContentServer {
304
310
  request.end();
305
311
  });
306
312
  }
313
+ // New core method to fetch only the first chunk without retries
314
+ async fetchFirstChunk(url) {
315
+ return new Promise((resolve, reject) => {
316
+ const urlObj = new url_1.URL(url);
317
+ const timeoutDuration = 5000; // 5 seconds
318
+ let timeout = null;
319
+ const requestOptions = {
320
+ hostname: urlObj.hostname,
321
+ port: urlObj.port || ContentServer.port,
322
+ path: urlObj.pathname + urlObj.search, // Include query params
323
+ method: "GET",
324
+ key: fs_1.default.readFileSync(ContentServer.keyPath),
325
+ cert: fs_1.default.readFileSync(ContentServer.certPath),
326
+ rejectUnauthorized: false,
327
+ };
328
+ const request = http_1.default.request(requestOptions, (response) => {
329
+ // Set timeout for inactivity
330
+ timeout = setTimeout(() => {
331
+ console.error(`Request timeout: No data received for ${timeoutDuration / 1000} seconds.`);
332
+ request.destroy(); // Use destroy instead of abort
333
+ reject(new Error(`Request timed out after ${timeoutDuration / 1000} seconds of inactivity`));
334
+ }, timeoutDuration);
335
+ const resetTimeout = () => {
336
+ if (timeout) {
337
+ clearTimeout(timeout);
338
+ }
339
+ timeout = setTimeout(() => {
340
+ console.error(`Request timeout: No data received for ${timeoutDuration / 1000} seconds.`);
341
+ request.destroy(); // Use destroy instead of abort
342
+ reject(new Error(`Request timed out after ${timeoutDuration / 1000} seconds of inactivity`));
343
+ }, timeoutDuration);
344
+ };
345
+ if (response.statusCode === 200) {
346
+ response.once("data", (chunk) => {
347
+ if (timeout) {
348
+ clearTimeout(timeout);
349
+ }
350
+ response.destroy(); // Close the connection after receiving the first chunk
351
+ resolve(chunk);
352
+ });
353
+ response.on("end", () => {
354
+ if (timeout) {
355
+ clearTimeout(timeout);
356
+ }
357
+ // In case the response ends before any data is received
358
+ reject(new Error("No data received"));
359
+ });
360
+ }
361
+ else if ((response.statusCode === 301 || response.statusCode === 302) &&
362
+ response.headers.location) {
363
+ // Handle redirects
364
+ const redirectUrl = new url_1.URL(response.headers.location, url).toString(); // Resolve relative URLs
365
+ if (timeout) {
366
+ clearTimeout(timeout);
367
+ }
368
+ this.fetchFirstChunk(redirectUrl)
369
+ .then(resolve)
370
+ .catch(reject);
371
+ }
372
+ else {
373
+ if (timeout) {
374
+ clearTimeout(timeout);
375
+ }
376
+ reject(new Error(`Failed to retrieve data from ${url}. Status code: ${response.statusCode}`));
377
+ }
378
+ });
379
+ request.on("error", (error) => {
380
+ if (timeout) {
381
+ clearTimeout(timeout);
382
+ }
383
+ console.error(`GET ${url}:`, error.message);
384
+ reject(error);
385
+ });
386
+ request.end();
387
+ });
388
+ }
307
389
  }
308
390
  exports.ContentServer = ContentServer;
309
391
  ContentServer.port = 4161;
@@ -1 +1 @@
1
- {"version":3,"file":"DigPeer.d.ts","sourceRoot":"","sources":["../../src/DigNetwork/DigPeer.ts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BAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAOhE"}
@@ -12,7 +12,6 @@ const blockchain_1 = require("../blockchain");
12
12
  const datalayer_driver_1 = require("@dignetwork/datalayer-driver");
13
13
  const blockchain_2 = require("../blockchain");
14
14
  const blockchain_3 = require("../blockchain");
15
- const coins_1 = require("../blockchain/coins");
16
15
  class DigPeer {
17
16
  constructor(ipAddress, storeId) {
18
17
  this.ipAddress = ipAddress;
@@ -59,7 +58,7 @@ class DigPeer {
59
58
  const publicSyntheticKey = await wallet.getPublicSyntheticKey();
60
59
  const peer = await blockchain_2.FullNodePeer.connect();
61
60
  const totalAmount = outputs.reduce((acc, output) => acc + output.amount, BigInt(0));
62
- const coins = await (0, coins_1.selectUnspentCoins)(peer, totalAmount, totalFee, [], walletName);
61
+ const coins = await wallet.selectUnspentCoins(peer, totalAmount, totalFee, []);
63
62
  const coinSpends = await (0, datalayer_driver_1.sendXch)(publicSyntheticKey, coins, outputs, totalFee);
64
63
  const sig = (0, datalayer_driver_1.signCoinSpends)(coinSpends, [await wallet.getPrivateSyntheticKey()], false);
65
64
  const err = await peer.broadcastSpend(coinSpends, [sig]);
@@ -1 +1 @@
1
- {"version":3,"file":"DataStore.d.ts","sourceRoot":"","sources":["../../src/blockchain/DataStore.ts"],"names":[],"mappings":"AAEA,OAAO,EAOL,SAAS,IAAI,eAAe,EAE5B,iBAAiB,EAIlB,MAAM,8BAA8B,CAAC;AAWtC,OAAO,EAAE,eAAe,EAAW,MAAM,UAAU,CAAC;AAGpD,OAAO,EACL,iBAAiB,EACjB,wBAAwB,EACzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AAcjD,qBAAa,SAAS;IACpB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,IAAI,CAAoB;gBAEpB,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,wBAAwB;IAiB/D,IA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IA4FzB;;;OAGG;IACU,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC;IAK5C;;;OAGG;WACiB,iBAAiB,IAAI,OAAO,CAAC,MAAM,CAAC;IAIxD;;;;OAIG;mBACkB,mBAAmB;WAqB1B,YAAY,IAAI,SAAS,EAAE;IAW5B,aAAa,IAAI,OAAO,CAAC;QACpC,WAAW,EAAE,eAAe,CAAC;QAC7B,YAAY,EAAE,MAAM,CAAC;QACrB,UAAU,EAAE,MAAM,CAAC;KACpB,CAAC;IAsEW,wBAAwB,IAAI,OAAO,CAAC;QAC/C,eAAe,EAAE,MAAM,CAAC;QACxB,aAAa,EAAE,MAAM,CAAC;KACvB,CAAC;IAiBW,iBAAiB,IAAI,OAAO,CAAC;QACxC,eAAe,EAAE,MAAM,CAAC;QACxB,aAAa,EAAE,MAAM,CAAC;KACvB,CAAC;YA0BY,iBAAiB;IAYlB,cAAc,CAAC,SAAS,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;IA4C/D,oBAAoB,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAexD,WAAW,IAAI,OAAO,CAAC,iBAAiB,CAAC;IAKzC,QAAQ,IAAI,OAAO,CAAC,OAAO,CAAC;IAM5B,uBAAuB,CAClC,kBAAkB,CAAC,EAAE,MAAM,GAC1B,OAAO,CAAC,OAAO,CAAC;IAkBN,cAAc,CACzB,QAAQ,EAAE,iBAAiB,GAC1B,OAAO,CAAC,eAAe,CAAC;IAgD3B;;;;;OAKG;IACU,qBAAqB,CAChC,QAAQ,EAAE,MAAM,EAChB,kBAAkB,GAAE,OAAe,GAClC,OAAO,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CA6C7C"}
@@ -21,6 +21,7 @@ const DataStoreSerializer_1 = require("./DataStoreSerializer");
21
21
  const node_cache_1 = __importDefault(require("node-cache"));
22
22
  const config_2 = require("../utils/config");
23
23
  const StoreInfoCacheUpdater_1 = require("./StoreInfoCacheUpdater");
24
+ const utils_1 = require("../utils");
24
25
  // Initialize the cache with a TTL of 180 seconds (3 minutes)
25
26
  const rootHistoryCache = new node_cache_1.default({ stdTTL: 180 });
26
27
  const stat = (0, util_1.promisify)(fs_1.default.stat);
@@ -115,7 +116,7 @@ class DataStore {
115
116
  const wallet = await Wallet_1.Wallet.load("default");
116
117
  const publicSyntheticKey = await wallet.getPublicSyntheticKey();
117
118
  const ownerSyntheicPuzzleHash = (0, datalayer_driver_1.syntheticKeyToPuzzleHash)(publicSyntheticKey);
118
- const storeCreationCoins = await (0, coins_1.selectUnspentCoins)(peer, BigInt(1), BigInt(0));
119
+ const storeCreationCoins = await wallet.selectUnspentCoins(peer, BigInt(1), BigInt(0));
119
120
  const delegationLayers = [];
120
121
  if (adminPublicSyntheticKey) {
121
122
  delegationLayers.push((0, datalayer_driver_1.adminDelegatedPuzzleFromKey)(Buffer.from(adminPublicSyntheticKey, "hex")));
@@ -203,24 +204,26 @@ class DataStore {
203
204
  }
204
205
  async fetchCoinInfo() {
205
206
  try {
206
- // Kick off the updater instance in the backgounf if not already running
207
- StoreInfoCacheUpdater_1.StoreInfoCacheUpdater.initInstance();
208
207
  // Initialize the cache for the current storeId's coin info
209
- const storeCoinCache = new FileCache_1.FileCache(`stores`);
210
- // Try to get cached store info
211
- const cachedInfo = storeCoinCache.get(this.storeId);
212
- if (cachedInfo) {
213
- // If we have cached info, return it directly
214
- const { latestStore, latestHeight } = DataStoreSerializer_1.DataStoreSerializer.deserialize({
215
- latestStore: cachedInfo.latestStore,
216
- latestHeight: cachedInfo.latestHeight.toString(),
217
- latestHash: cachedInfo.latestHash,
218
- });
219
- return {
220
- latestStore,
221
- latestHeight: cachedInfo.latestHeight,
222
- latestHash: Buffer.from(cachedInfo.latestHash, "hex"),
223
- };
208
+ const storeCoinCache = new FileCache_1.FileCache(`stores`, config_1.USER_DIR_PATH);
209
+ if (!utils_1.Environment.CLI_MODE) {
210
+ // Kick off the updater instance in the backgounf if not already running
211
+ StoreInfoCacheUpdater_1.StoreInfoCacheUpdater.initInstance();
212
+ // Try to get cached store info
213
+ const cachedInfo = storeCoinCache.get(this.storeId);
214
+ if (cachedInfo) {
215
+ // If we have cached info, return it directly
216
+ const { latestStore } = DataStoreSerializer_1.DataStoreSerializer.deserialize({
217
+ latestStore: cachedInfo.latestStore,
218
+ latestHeight: cachedInfo.latestHeight.toString(),
219
+ latestHash: cachedInfo.latestHash,
220
+ });
221
+ return {
222
+ latestStore,
223
+ latestHeight: cachedInfo.latestHeight,
224
+ latestHash: Buffer.from(cachedInfo.latestHash, "hex"),
225
+ };
226
+ }
224
227
  }
225
228
  // If no cached info, proceed to fetch and cache it
226
229
  // Use getCreationHeight to retrieve height and hash information
@@ -345,7 +348,7 @@ class DataStore {
345
348
  const { latestStore } = await this.fetchCoinInfo();
346
349
  const updateStoreResponse = (0, datalayer_driver_1.updateStoreMetadata)(latestStore, metadata.rootHash, metadata.label, metadata.description, metadata.bytes, publicSyntheticKey, null, null);
347
350
  const fee = await (0, coins_1.calculateFeeForCoinSpends)(peer, null);
348
- const unspentCoins = await (0, coins_1.selectUnspentCoins)(peer, BigInt(0), fee);
351
+ const unspentCoins = await wallet.selectUnspentCoins(peer, BigInt(0), fee);
349
352
  const feeCoinSpends = await (0, datalayer_driver_1.addFee)(publicSyntheticKey, unspentCoins, updateStoreResponse.coinSpends.map((coinSpend) => (0, datalayer_driver_1.getCoinId)(coinSpend.coin)), fee);
350
353
  const combinedCoinSpends = [
351
354
  ...updateStoreResponse.coinSpends,
@@ -1 +1 @@
1
- {"version":3,"file":"ServerCoin.d.ts","sourceRoot":"","sources":["../../src/blockchain/ServerCoin.ts"],"names":[],"mappings":"AACA,OAAO,EAML,UAAU,IAAI,gBAAgB,EAE/B,MAAM,8BAA8B,CAAC;AAItC,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAYrD,qBAAa,UAAU;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AAE,MAAM,CAAA;KAAE;IAKpD,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiFrD,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;WA+B1C,uBAAuB;YAkE7B,sBAAsB;IAWvB,uBAAuB,CAClC,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,OAAO,CAAC;WAuBL,sBAAsB,CAAC,mBAAmB,EAAE,IAAI,GAAG;QAC/D,KAAK,EAAE,MAAM,CAAC;QACd,KAAK,EAAE,MAAM,CAAC;KACf;CA2BF"}
@@ -7,7 +7,6 @@ exports.ServerCoin = void 0;
7
7
  const lodash_1 = __importDefault(require("lodash"));
8
8
  const datalayer_driver_1 = require("@dignetwork/datalayer-driver");
9
9
  const FullNodePeer_1 = require("./FullNodePeer");
10
- const coins_1 = require("./coins");
11
10
  const Wallet_1 = require("./Wallet");
12
11
  const NconfManager_1 = require("../utils/NconfManager");
13
12
  const DataStore_1 = require("./DataStore");
@@ -27,7 +26,7 @@ class ServerCoin {
27
26
  const peer = await FullNodePeer_1.FullNodePeer.connect();
28
27
  const wallet = await Wallet_1.Wallet.load("default");
29
28
  const publicSyntheticKey = await wallet.getPublicSyntheticKey();
30
- const serverCoinCreationCoins = await (0, coins_1.selectUnspentCoins)(peer, BigInt(serverCoinCollateral), BigInt(1000000));
29
+ const serverCoinCreationCoins = await wallet.selectUnspentCoins(peer, BigInt(serverCoinCollateral), BigInt(1000000));
31
30
  const { epoch: currentEpoch } = ServerCoin.getCurrentEpoch();
32
31
  const epochBasedHint = (0, datalayer_driver_1.morphLauncherId)(Buffer.from(this.storeId, "hex"), BigInt(currentEpoch));
33
32
  const newServerCoin = (0, datalayer_driver_1.createServerCoin)(publicSyntheticKey, serverCoinCreationCoins, epochBasedHint, [peerIp, publicSyntheticKey.toString("hex")], BigInt(serverCoinCollateral), BigInt(1000000));
@@ -76,7 +75,7 @@ class ServerCoin {
76
75
  if (!serverCoin) {
77
76
  throw new Error(`No server coin found for epoch ${epoch} in store ${this.storeId}.`);
78
77
  }
79
- const feeCoins = await (0, coins_1.selectUnspentCoins)(peer, BigInt(0), BigInt(1000000));
78
+ const feeCoins = await wallet.selectUnspentCoins(peer, BigInt(0), BigInt(1000000));
80
79
  const coin = {
81
80
  amount: BigInt(serverCoin.coin.amount),
82
81
  puzzleHash: Buffer.from(serverCoin.coin.puzzleHash, "hex"),
@@ -1,14 +1,14 @@
1
1
  export declare class StoreInfoCacheUpdater {
2
2
  private static instance;
3
3
  private storeCoinCache;
4
- private updateInterval;
4
+ private monitors;
5
5
  private lockFilePath;
6
6
  private releaseLock;
7
+ private isMonitoring;
7
8
  private constructor();
8
9
  static initInstance(): StoreInfoCacheUpdater;
9
- private scheduleNextUpdate;
10
- private checkAndUpdateCache;
11
- private updateCache;
12
- private setupExitHandlers;
10
+ private startMonitors;
11
+ private monitorStore;
12
+ private isUnrecoverableError;
13
13
  }
14
14
  //# sourceMappingURL=StoreInfoCacheUpdater.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"StoreInfoCacheUpdater.d.ts","sourceRoot":"","sources":["../../src/blockchain/StoreInfoCacheUpdater.ts"],"names":[],"mappings":"AAQA,qBAAa,qBAAqB;IAChC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAwB;IAC/C,OAAO,CAAC,cAAc,CAInB;IACH,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,WAAW,CAAsC;IAEzD,OAAO;WAcO,YAAY,IAAI,qBAAqB;IAOnD,OAAO,CAAC,kBAAkB;YAIZ,mBAAmB;YAkBnB,WAAW;IA4FzB,OAAO,CAAC,iBAAiB;CAsB1B"}
1
+ {"version":3,"file":"StoreInfoCacheUpdater.d.ts","sourceRoot":"","sources":["../../src/blockchain/StoreInfoCacheUpdater.ts"],"names":[],"mappings":"AAYA,qBAAa,qBAAqB;IAChC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAwB;IAC/C,OAAO,CAAC,cAAc,CAInB;IACH,OAAO,CAAC,QAAQ,CAAyC;IACzD,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,WAAW,CAAsC;IACzD,OAAO,CAAC,YAAY,CAAiB;IAErC,OAAO;WAUO,YAAY,IAAI,qBAAqB;YAQrC,aAAa;YAsDb,YAAY;IAoH1B,OAAO,CAAC,oBAAoB;CAM7B"}
@@ -30,128 +30,147 @@ const DataStoreSerializer_1 = require("./DataStoreSerializer");
30
30
  const utils_2 = require("../utils");
31
31
  const lockfile = __importStar(require("proper-lockfile"));
32
32
  const path = __importStar(require("path"));
33
- const utils_3 = require("../utils");
33
+ const datalayer_driver_1 = require("@dignetwork/datalayer-driver");
34
34
  class StoreInfoCacheUpdater {
35
- constructor(updateIntervalInMinutes = 5) {
36
- this.releaseLock = null; // Holds the release function for cleanup
37
- this.storeCoinCache = new utils_1.FileCache(`stores`);
38
- this.updateInterval = updateIntervalInMinutes * 60 * 1000; // Convert minutes to milliseconds
35
+ constructor() {
36
+ this.monitors = new Map();
37
+ this.releaseLock = null;
38
+ this.isMonitoring = true;
39
+ this.storeCoinCache = new utils_1.FileCache(`stores`, utils_1.USER_DIR_PATH);
39
40
  // Construct lock file path using the path module
40
- this.lockFilePath = path.join(utils_3.DIG_FOLDER_PATH, 'store-info-cache.lock');
41
- // Start the cache updater using setTimeout
42
- this.scheduleNextUpdate();
43
- // Set up process exit handlers for cleanup
44
- this.setupExitHandlers();
41
+ this.lockFilePath = path.join(utils_1.DIG_FOLDER_PATH, "store-info-cache.lock");
42
+ // Start monitors for existing storeIds
43
+ this.startMonitors();
45
44
  }
46
45
  static initInstance() {
47
46
  if (!StoreInfoCacheUpdater.instance) {
47
+ console.log("Initializing DataStore Monitor");
48
48
  StoreInfoCacheUpdater.instance = new StoreInfoCacheUpdater();
49
49
  }
50
50
  return StoreInfoCacheUpdater.instance;
51
51
  }
52
- scheduleNextUpdate() {
53
- setTimeout(() => this.checkAndUpdateCache(), this.updateInterval);
54
- }
55
- async checkAndUpdateCache() {
52
+ async startMonitors() {
56
53
  try {
54
+ // Check if the lockfile is already held
57
55
  const isLocked = await lockfile.check(this.lockFilePath, {
58
- stale: this.updateInterval,
56
+ realpath: false,
59
57
  });
60
- if (!isLocked) {
61
- await this.updateCache();
58
+ if (isLocked) {
59
+ // Another process is already running the monitors; skip starting monitors
60
+ console.log("Another process is already running the StoreInfoCacheUpdater.");
61
+ return;
62
62
  }
63
- // Else, lock is held; skip update without logging
64
- }
65
- catch (error) {
66
- console.error("Error checking lockfile:", error);
67
- }
68
- finally {
69
- // Schedule the next update regardless of whether we updated or not
70
- this.scheduleNextUpdate();
71
- }
72
- }
73
- async updateCache() {
74
- try {
75
63
  // Attempt to acquire the lock
76
- const release = await lockfile.lock(this.lockFilePath, {
64
+ this.releaseLock = await lockfile.lock(this.lockFilePath, {
77
65
  retries: {
78
- retries: 0, // No retries since we already checked the lock
66
+ retries: 0, // No retries since we only need one lock
79
67
  },
80
- stale: this.updateInterval, // Lock expires after the update interval
68
+ stale: 60000, // Lock expires after 1 minute (adjust as needed)
69
+ realpath: false, // Ensure lockfile uses the exact path
81
70
  });
82
- // Store the release function for cleanup during process exit
83
- this.releaseLock = release;
84
- try {
85
- const storeIds = this.storeCoinCache.getCachedKeys();
86
- for (const storeId of storeIds) {
87
- try {
88
- const cachedInfo = this.storeCoinCache.get(storeId);
89
- if (!cachedInfo) {
90
- continue;
91
- }
92
- // Deserialize the cached store info
93
- const { latestStore: serializedStore, latestHeight, latestHash } = cachedInfo;
94
- const { latestStore: previousInfo } = DataStoreSerializer_1.DataStoreSerializer.deserialize({
95
- latestStore: serializedStore,
96
- latestHeight: latestHeight.toString(),
97
- latestHash: latestHash,
98
- });
99
- // Wrap the connection with a timeout
100
- const peer = await (0, utils_2.withTimeout)(FullNodePeer_1.FullNodePeer.connect(), 60000, "Timeout connecting to FullNodePeer");
101
- // Wrap the syncStore call with a timeout
102
- const { latestStore, latestHeight: newHeight } = await (0, utils_2.withTimeout)(peer.syncStore(previousInfo, latestHeight, Buffer.from(latestHash, "hex"), false), 60000, `Timeout syncing store for storeId ${storeId}`);
103
- // Wrap the getHeaderHash call with a timeout
104
- const latestHashBuffer = await (0, utils_2.withTimeout)(peer.getHeaderHash(newHeight), 60000, `Timeout getting header hash for height ${newHeight}`);
105
- // Serialize the updated store data for caching
106
- const serializedLatestStore = new DataStoreSerializer_1.DataStoreSerializer(latestStore, newHeight, latestHashBuffer).serialize();
107
- // Recache the updated store info
108
- this.storeCoinCache.set(storeId, {
109
- latestStore: serializedLatestStore,
110
- latestHeight: newHeight,
111
- latestHash: latestHashBuffer.toString("hex"),
112
- });
113
- }
114
- catch (error) {
115
- console.error(`Failed to update cache for storeId ${storeId}:`, error);
116
- // Continue with the next storeId
117
- }
71
+ const storeIds = this.storeCoinCache.getCachedKeys();
72
+ for (const storeId of storeIds) {
73
+ // Check if a monitor is already running for this storeId
74
+ if (!this.monitors.has(storeId)) {
75
+ // Start monitoring in the background
76
+ const monitorPromise = this.monitorStore(storeId);
77
+ this.monitors.set(storeId, monitorPromise);
118
78
  }
119
79
  }
120
- finally {
121
- // Always release the lock after finishing the update
122
- await this.releaseLock?.();
123
- this.releaseLock = null;
124
- }
80
+ // Wait for all monitors to settle
81
+ const monitorPromises = Array.from(this.monitors.values());
82
+ await Promise.all(monitorPromises);
125
83
  }
126
84
  catch (error) {
127
- if (error.code === 'ELOCKED') {
128
- // Another process acquired the lock; skip without logging
129
- }
130
- else {
131
- }
85
+ console.error("Monitor system encountered an error:", error);
132
86
  }
133
- }
134
- setupExitHandlers() {
135
- const cleanup = async () => {
87
+ finally {
88
+ // Release the lock
136
89
  if (this.releaseLock) {
137
90
  try {
138
91
  await this.releaseLock();
139
- console.log("Lock released successfully on process exit.");
92
+ console.log("Lock released successfully.");
140
93
  }
141
- catch (error) {
142
- console.error("Failed to release lock on exit:", error);
94
+ catch (releaseError) {
95
+ console.error("Error releasing the lock:", releaseError);
143
96
  }
144
97
  }
145
- };
146
- // Listen for process exit events and call cleanup
147
- process.on('SIGINT', cleanup); // Catch CTRL+C
148
- process.on('SIGTERM', cleanup); // Catch termination signals
149
- process.on('exit', cleanup); // On normal exit
150
- process.on('uncaughtException', async (error) => {
151
- console.error("Uncaught exception, cleaning up:", error);
152
- await cleanup();
153
- process.exit(1); // Ensure process exits after handling exception
154
- });
98
+ }
99
+ }
100
+ // Monitor a single store's coin
101
+ async monitorStore(storeId) {
102
+ while (this.isMonitoring) {
103
+ let peer = null;
104
+ try {
105
+ // Connect to a peer
106
+ peer = await (0, utils_2.withTimeout)(FullNodePeer_1.FullNodePeer.connect(), 60000, "Timeout connecting to FullNodePeer");
107
+ // Get the latest store info (from cache if available)
108
+ const cachedInfo = this.storeCoinCache.get(storeId);
109
+ if (!cachedInfo) {
110
+ // If no cached info, skip and wait before retrying
111
+ console.error(`No cached info for storeId ${storeId}`);
112
+ await new Promise((resolve) => setTimeout(resolve, 5000));
113
+ continue;
114
+ }
115
+ const { latestStore: serializedStore, latestHeight, latestHash, } = cachedInfo;
116
+ const { latestStore } = DataStoreSerializer_1.DataStoreSerializer.deserialize({
117
+ latestStore: serializedStore,
118
+ latestHeight: latestHeight.toString(),
119
+ latestHash: latestHash,
120
+ });
121
+ // Get the coinId associated with the store
122
+ const coinId = (0, datalayer_driver_1.getCoinId)(latestStore.coin);
123
+ // Wait for the coin to be spent
124
+ await peer.waitForCoinToBeSpent(coinId, latestHeight, Buffer.from(latestHash, "hex"));
125
+ let updatedStore, newHeight;
126
+ try {
127
+ // When resolved, sync the store
128
+ //const { latestStore: updatedStore, latestHeight: newHeight } = await withTimeout(
129
+ const storeInfo = await (0, utils_2.withTimeout)(peer.syncStore(latestStore, latestHeight, Buffer.from(latestHash, "hex"), false // withHistory
130
+ ), 60000, `Timeout syncing store for storeId ${storeId}`);
131
+ updatedStore = storeInfo.latestStore;
132
+ newHeight = storeInfo.latestHeight;
133
+ }
134
+ catch {
135
+ const genesisChallenge = await (0, datalayer_driver_1.getMainnetGenesisChallenge)();
136
+ const storeInfo = await (0, utils_2.withTimeout)(peer.syncStore(latestStore, null, genesisChallenge, false), 60000, `Timeout syncing store for storeId ${storeId}`);
137
+ updatedStore = storeInfo.latestStore;
138
+ newHeight = storeInfo.latestHeight;
139
+ }
140
+ // Get the latest header hash
141
+ const latestHashBuffer = await (0, utils_2.withTimeout)(peer.getHeaderHash(newHeight), 60000, `Timeout getting header hash for height ${newHeight}`);
142
+ // Serialize the updated store data for caching
143
+ const serializedLatestStore = new DataStoreSerializer_1.DataStoreSerializer(updatedStore, newHeight, latestHashBuffer).serialize();
144
+ // Update the cache
145
+ this.storeCoinCache.set(storeId, {
146
+ latestStore: serializedLatestStore,
147
+ latestHeight: newHeight,
148
+ latestHash: latestHashBuffer.toString("hex"),
149
+ });
150
+ peer = null;
151
+ // Continue monitoring
152
+ }
153
+ catch (error) {
154
+ console.error(`Error monitoring store ${storeId}:`, error);
155
+ // Close the peer connection if it's open
156
+ if (peer) {
157
+ peer = null;
158
+ }
159
+ // Determine if the error is unrecoverable
160
+ if (this.isUnrecoverableError(error)) {
161
+ this.isMonitoring = false; // Signal other monitors to stop
162
+ throw error; // Propagate error up to stop monitoring
163
+ }
164
+ // Wait before retrying
165
+ await new Promise((resolve) => setTimeout(resolve, 5000));
166
+ }
167
+ }
168
+ }
169
+ isUnrecoverableError(error) {
170
+ // Determine whether the error is unrecoverable
171
+ // For this example, we'll treat any unexpected error as unrecoverable
172
+ // You can customize this logic based on your application's needs
173
+ return true;
155
174
  }
156
175
  }
157
176
  exports.StoreInfoCacheUpdater = StoreInfoCacheUpdater;
@@ -1 +1 @@
1
- {"version":3,"file":"Wallet.d.ts","sourceRoot":"","sources":["../../src/blockchain/Wallet.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EASL,IAAI,EACJ,IAAI,EAEJ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AC,MAAM,EAAE,CAAC;mBAU/B,oBAAoB;mBAcpB,mBAAmB;IAS3B,2BAA2B,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;WAUpD,2BAA2B,CAC7C,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,OAAO,CAAC;IASN,kBAAkB,CAC7B,IAAI,EAAE,IAAI,EACV,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,SAAS,GAAE,IAAI,EAAO,GACrB,OAAO,CAAC,IAAI,EAAE,CAAC;WAiFE,yBAAyB,CAC3C,IAAI,EAAE,IAAI,EACV,UAAU,EAAE,SAAS,EAAE,GAAG,IAAI,GAC7B,OAAO,CAAC,MAAM,CAAC;WAIE,eAAe,CACjC,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,OAAO,CAAC;CAWpB"}
@@ -42,7 +42,6 @@ const datalayer_driver_1 = require("@dignetwork/datalayer-driver");
42
42
  const config_1 = require("../utils/config");
43
43
  const FileCache_1 = require("../utils/FileCache");
44
44
  const config_2 = require("../utils/config");
45
- const path_1 = __importDefault(require("path"));
46
45
  const KEYRING_FILE = "keyring.json";
47
46
  const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
48
47
  exports.DEFAULT_FEE_COIN_COST = 64000000;
@@ -181,7 +180,7 @@ class Wallet {
181
180
  return (0, datalayer_driver_1.verifySignedMessage)(buffer_1.Buffer.from(signature, "hex"), buffer_1.Buffer.from(publicKey, "hex"), buffer_1.Buffer.from(message, "utf-8"));
182
181
  }
183
182
  async selectUnspentCoins(peer, coinAmount, feeBigInt, omitCoins = []) {
184
- const cache = new FileCache_1.FileCache(path_1.default.join(config_2.USER_DIR_PATH, "reserved_coins"));
183
+ const cache = new FileCache_1.FileCache("reserved_coins", config_2.USER_DIR_PATH);
185
184
  const ownerPuzzleHash = await this.getOwnerPuzzleHash();
186
185
  // Define a function to attempt selecting unspent coins
187
186
  const trySelectCoins = async () => {
@@ -1,6 +1,5 @@
1
- import { Peer, Coin, CoinSpend } from "@dignetwork/datalayer-driver";
1
+ import { Peer, CoinSpend } from "@dignetwork/datalayer-driver";
2
2
  export declare const DEFAULT_FEE_COIN_COST = 64000000;
3
3
  export declare const calculateFeeForCoinSpends: (peer: Peer, coinSpends: CoinSpend[] | null) => Promise<bigint>;
4
- export declare const selectUnspentCoins: (peer: Peer, coinAmount: bigint, feeBigInt: bigint, omitCoins?: Coin[], walletName?: string) => Promise<Coin[]>;
5
4
  export declare const isCoinSpendable: (peer: Peer, coinId: Buffer) => Promise<boolean>;
6
5
  //# sourceMappingURL=coins.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"coins.d.ts","sourceRoot":"","sources":["../../src/blockchain/coins.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,IAAI,EACJ,IAAI,EAEJ,SAAS,EAEV,MAAM,8BAA8B,CAAC;AAMtC,eAAO,MAAM,qBAAqB,WAAa,CAAC;AAWhD,eAAO,MAAM,yBAAyB,SAC9B,IAAI,cACE,SAAS,EAAE,GAAG,IAAI,KAC7B,OAAO,CAAC,MAAM,CA4BhB,CAAC;AAEF,eAAO,MAAM,kBAAkB,SACvB,IAAI,cACE,MAAM,aACP,MAAM,cACN,IAAI,EAAE,eACL,MAAM,KACjB,OAAO,CAAC,IAAI,EAAE,CAoEhB,CAAC;AAGF,eAAO,MAAM,eAAe,SACpB,IAAI,UACF,MAAM,KACb,OAAO,CAAC,OAAO,CAWjB,CAAC"}
1
+ {"version":3,"file":"coins.d.ts","sourceRoot":"","sources":["../../src/blockchain/coins.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,IAAI,EAGJ,SAAS,EAEV,MAAM,8BAA8B,CAAC;AAMtC,eAAO,MAAM,qBAAqB,WAAa,CAAC;AAWhD,eAAO,MAAM,yBAAyB,SAC9B,IAAI,cACE,SAAS,EAAE,GAAG,IAAI,KAC7B,OAAO,CAAC,MAAM,CA4BhB,CAAC;AAEF,eAAO,MAAM,eAAe,SACpB,IAAI,UACF,MAAM,KACb,OAAO,CAAC,OAAO,CAWjB,CAAC"}
@@ -1,11 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isCoinSpendable = exports.selectUnspentCoins = exports.calculateFeeForCoinSpends = exports.DEFAULT_FEE_COIN_COST = void 0;
4
- const datalayer_driver_1 = require("@dignetwork/datalayer-driver");
5
- const Wallet_1 = require("./Wallet");
3
+ exports.isCoinSpendable = exports.calculateFeeForCoinSpends = exports.DEFAULT_FEE_COIN_COST = void 0;
6
4
  const config_1 = require("../utils/config");
7
- const FileCache_1 = require("../utils/FileCache");
8
- const Environment_1 = require("../utils/Environment");
9
5
  exports.DEFAULT_FEE_COIN_COST = 64000000;
10
6
  // Set cache expiration time (5 minutes)
11
7
  const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes in milliseconds
@@ -39,57 +35,6 @@ const calculateFeeForCoinSpends = async (peer, coinSpends) => {
39
35
  */
40
36
  };
41
37
  exports.calculateFeeForCoinSpends = calculateFeeForCoinSpends;
42
- const selectUnspentCoins = async (peer, coinAmount, feeBigInt, omitCoins = [], walletName = "default") => {
43
- // Initialize the cache for reserved coins
44
- const cache = new FileCache_1.FileCache("reserved_coins");
45
- // Get all cached reserved coins
46
- const cachedReservedCoins = cache.getCachedKeys();
47
- // Filter expired reserved coins and omit valid reservations
48
- const now = Date.now();
49
- const omitCoinIds = omitCoins.map((coin) => (0, datalayer_driver_1.getCoinId)(coin).toString("hex"));
50
- const validReservedCoins = cachedReservedCoins.filter((coinId) => {
51
- const reservation = cache.get(coinId);
52
- if (reservation && reservation.expiry > now) {
53
- // Valid reservation, add to omit list
54
- omitCoinIds.push(coinId);
55
- return true;
56
- }
57
- else {
58
- // Reservation expired, remove it
59
- cache.delete(coinId);
60
- return false;
61
- }
62
- });
63
- // Fetch all unspent coins from the peer
64
- const wallet = await Wallet_1.Wallet.load(walletName);
65
- const ownerPuzzleHash = await wallet.getOwnerPuzzleHash();
66
- const coinsResp = await peer.getAllUnspentCoins(ownerPuzzleHash, config_1.MIN_HEIGHT, Buffer.from(config_1.MIN_HEIGHT_HEADER_HASH, "hex"));
67
- if (Environment_1.Environment.DEBUG) {
68
- console.log("Unspent Coins:", coinsResp); // Debugging
69
- }
70
- const unspentCoins = coinsResp.coins;
71
- // Filter out the omitted coins
72
- const filteredUnspentCoins = unspentCoins.filter((coin) => !omitCoinIds.includes((0, datalayer_driver_1.getCoinId)(coin).toString("hex")));
73
- if (Environment_1.Environment.DEBUG) {
74
- console.log("Unspent Coins after filtering:", filteredUnspentCoins); // Debugging
75
- }
76
- // Select coins needed for the transaction
77
- const selectedCoins = (0, datalayer_driver_1.selectCoins)(filteredUnspentCoins, feeBigInt + coinAmount);
78
- if (Environment_1.Environment.DEBUG) {
79
- console.log("Selected Coins:", selectedCoins); // Debugging
80
- }
81
- // If no coins are selected, throw an error
82
- if (selectedCoins.length === 0) {
83
- throw new Error("No unspent coins available.");
84
- }
85
- // Cache the selected coins as reserved for the next 5 minutes
86
- selectedCoins.forEach((coin) => {
87
- const coinId = (0, datalayer_driver_1.getCoinId)(coin).toString("hex");
88
- cache.set(coinId, { coinId, expiry: Date.now() + CACHE_DURATION });
89
- });
90
- return selectedCoins;
91
- };
92
- exports.selectUnspentCoins = selectUnspentCoins;
93
38
  const isCoinSpendable = async (peer, coinId) => {
94
39
  try {
95
40
  const spent = await peer.isCoinSpent(coinId, config_1.MIN_HEIGHT, Buffer.from(config_1.MIN_HEIGHT_HEADER_HASH, "hex"));
@@ -1,4 +1,5 @@
1
1
  export declare class Environment {
2
+ private static cliMode;
2
3
  private static isValidIp;
3
4
  private static isValidHostnameOrIp;
4
5
  private static isValidPort;
@@ -14,5 +15,7 @@ export declare class Environment {
14
15
  static get DEBUG(): boolean | undefined;
15
16
  static get DIG_FOLDER_PATH(): string | undefined;
16
17
  static get REMOTE_NODE(): boolean | undefined;
18
+ static set CLI_MODE(mode: boolean);
19
+ static get CLI_MODE(): boolean | undefined;
17
20
  }
18
21
  //# sourceMappingURL=Environment.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Environment.d.ts","sourceRoot":"","sources":["../../src/utils/Environment.ts"],"names":[],"mappings":"AAGA,qBAAa,WAAW;IAEtB,OAAO,CAAC,MAAM,CAAC,SAAS;IAOxB,OAAO,CAAC,MAAM,CAAC,mBAAmB;IAQlC,OAAO,CAAC,MAAM,CAAC,WAAW;IAK1B,OAAO,CAAC,MAAM,CAAC,eAAe;IAK9B,OAAO,CAAC,MAAM,CAAC,eAAe;IAO9B,MAAM,KAAK,YAAY,IAAI,MAAM,GAAG,SAAS,CAG5C;IAGD,MAAM,KAAK,YAAY,IAAI,MAAM,GAAG,SAAS,CAG5C;IAGD,MAAM,KAAK,gBAAgB,IAAI,MAAM,GAAG,SAAS,CAGhD;IAGD,MAAM,KAAK,qBAAqB,IAAI,MAAM,GAAG,SAAS,CAGrD;IAGD,MAAM,KAAK,SAAS,IAAI,MAAM,GAAG,SAAS,CAGzC;IAGD,MAAM,KAAK,sBAAsB,IAAI,MAAM,GAAG,SAAS,CAEtD;IAGD,MAAM,KAAK,cAAc,IAAI,OAAO,GAAG,SAAS,CAG/C;IAGD,MAAM,KAAK,KAAK,IAAI,OAAO,GAAG,SAAS,CAGtC;IAGD,MAAM,KAAK,eAAe,IAAI,MAAM,GAAG,SAAS,CAG/C;IAGD,MAAM,KAAK,WAAW,IAAI,OAAO,GAAG,SAAS,CAG5C;CACF"}
1
+ {"version":3,"file":"Environment.d.ts","sourceRoot":"","sources":["../../src/utils/Environment.ts"],"names":[],"mappings":"AAGA,qBAAa,WAAW;IACtB,OAAO,CAAC,MAAM,CAAC,OAAO,CAAkB;IAGxC,OAAO,CAAC,MAAM,CAAC,SAAS;IAOxB,OAAO,CAAC,MAAM,CAAC,mBAAmB;IAQlC,OAAO,CAAC,MAAM,CAAC,WAAW;IAK1B,OAAO,CAAC,MAAM,CAAC,eAAe;IAK9B,OAAO,CAAC,MAAM,CAAC,eAAe;IAO9B,MAAM,KAAK,YAAY,IAAI,MAAM,GAAG,SAAS,CAG5C;IAGD,MAAM,KAAK,YAAY,IAAI,MAAM,GAAG,SAAS,CAG5C;IAGD,MAAM,KAAK,gBAAgB,IAAI,MAAM,GAAG,SAAS,CAGhD;IAGD,MAAM,KAAK,qBAAqB,IAAI,MAAM,GAAG,SAAS,CAGrD;IAGD,MAAM,KAAK,SAAS,IAAI,MAAM,GAAG,SAAS,CAGzC;IAGD,MAAM,KAAK,sBAAsB,IAAI,MAAM,GAAG,SAAS,CAEtD;IAGD,MAAM,KAAK,cAAc,IAAI,OAAO,GAAG,SAAS,CAG/C;IAGD,MAAM,KAAK,KAAK,IAAI,OAAO,GAAG,SAAS,CAGtC;IAGD,MAAM,KAAK,eAAe,IAAI,MAAM,GAAG,SAAS,CAG/C;IAGD,MAAM,KAAK,WAAW,IAAI,OAAO,GAAG,SAAS,CAG5C;IAED,MAAM,KAAK,QAAQ,CAAC,IAAI,EAAE,OAAO,EAEhC;IAED,MAAM,KAAK,QAAQ,IAAI,OAAO,GAAG,SAAS,CAEzC;CACF"}
@@ -81,5 +81,12 @@ class Environment {
81
81
  const value = process.env["REMOTE_NODE"];
82
82
  return value === "1" ? true : value === "0" ? false : undefined;
83
83
  }
84
+ static set CLI_MODE(mode) {
85
+ this.cliMode = mode;
86
+ }
87
+ static get CLI_MODE() {
88
+ return Environment.cliMode;
89
+ }
84
90
  }
85
91
  exports.Environment = Environment;
92
+ Environment.cliMode = false;
@@ -1,6 +1,6 @@
1
1
  export declare class FileCache<T> {
2
2
  private cacheDir;
3
- constructor(relativeFilePath: string);
3
+ constructor(relativeFilePath: string, baseDir?: string);
4
4
  private ensureDirectoryExists;
5
5
  private getCacheFilePath;
6
6
  get(key: string): T | null;
@@ -1 +1 @@
1
- {"version":3,"file":"FileCache.d.ts","sourceRoot":"","sources":["../../src/utils/FileCache.ts"],"names":[],"mappings":"AAIA,qBAAa,SAAS,CAAC,CAAC;IACtB,OAAO,CAAC,QAAQ,CAAS;gBAEb,gBAAgB,EAAE,MAAM;IAMpC,OAAO,CAAC,qBAAqB;IAO7B,OAAO,CAAC,gBAAgB;IAKjB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,IAAI;IAY1B,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,GAAG,IAAI;IAO/B,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IASzB,aAAa,IAAI,MAAM,EAAE;CAUjC"}
1
+ {"version":3,"file":"FileCache.d.ts","sourceRoot":"","sources":["../../src/utils/FileCache.ts"],"names":[],"mappings":"AAIA,qBAAa,SAAS,CAAC,CAAC;IACtB,OAAO,CAAC,QAAQ,CAAS;gBAEb,gBAAgB,EAAE,MAAM,EAAE,OAAO,GAAE,MAAwB;IAMvE,OAAO,CAAC,qBAAqB;IAO7B,OAAO,CAAC,gBAAgB;IAKjB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,IAAI;IAY1B,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,GAAG,IAAI;IAO/B,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IASzB,aAAa,IAAI,MAAM,EAAE;CAUjC"}
@@ -8,8 +8,8 @@ const fs_1 = __importDefault(require("fs"));
8
8
  const path_1 = __importDefault(require("path"));
9
9
  const config_1 = require("./config");
10
10
  class FileCache {
11
- constructor(relativeFilePath) {
12
- this.cacheDir = path_1.default.join(config_1.DIG_FOLDER_PATH, relativeFilePath);
11
+ constructor(relativeFilePath, baseDir = config_1.DIG_FOLDER_PATH) {
12
+ this.cacheDir = path_1.default.join(baseDir, relativeFilePath);
13
13
  this.ensureDirectoryExists();
14
14
  }
15
15
  // Ensure the directory exists or create it
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dignetwork/dig-sdk",
3
- "version": "0.0.1-alpha.110",
3
+ "version": "0.0.1-alpha.112",
4
4
  "description": "",
5
5
  "type": "commonjs",
6
6
  "main": "./dist/index.js",
@@ -25,7 +25,7 @@
25
25
  "LICENSE"
26
26
  ],
27
27
  "dependencies": {
28
- "@dignetwork/datalayer-driver": "^0.1.28",
28
+ "@dignetwork/datalayer-driver": "^0.1.29",
29
29
  "archiver": "^7.0.1",
30
30
  "axios": "^1.7.7",
31
31
  "bip39": "^3.1.0",