@wishknish/knishio-client-ts 0.7.4 → 0.7.6

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 (43) hide show
  1. package/dist/index.cjs +2670 -1039
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +336 -105
  4. package/dist/index.d.ts +336 -105
  5. package/dist/index.iife.js +22097 -20047
  6. package/dist/index.iife.js.map +1 -1
  7. package/dist/index.js +2667 -1040
  8. package/dist/index.js.map +1 -1
  9. package/package.json +10 -4
  10. package/src/AuthToken.ts +8 -2
  11. package/src/KnishIOClient.ts +306 -50
  12. package/src/constants.ts +5 -3
  13. package/src/core/Atom.ts +167 -100
  14. package/src/core/AtomMeta.ts +11 -28
  15. package/src/core/Meta.ts +18 -15
  16. package/src/core/Molecule.ts +582 -140
  17. package/src/core/Wallet.ts +19 -24
  18. package/src/index.ts +8 -0
  19. package/src/instance/rules/Rule.ts +128 -19
  20. package/src/libraries/CheckMolecule.ts +88 -1
  21. package/src/libraries/crypto.ts +14 -30
  22. package/src/libraries/strings.ts +26 -25
  23. package/src/mutation/MutationAppendRequest.ts +52 -0
  24. package/src/mutation/MutationCreateRule.ts +2 -2
  25. package/src/mutation/MutationPeering.ts +37 -0
  26. package/src/mutation/MutationRequestAuthorization.ts +3 -3
  27. package/src/query/QueryActiveSession.ts +0 -1
  28. package/src/query/QueryContinuId.ts +8 -0
  29. package/src/query/QueryMetaTypeViaMolecule.ts +221 -0
  30. package/src/query/QueryWalletList.ts +2 -2
  31. package/src/response/ResponseAppendRequest.ts +17 -0
  32. package/src/response/ResponseBalance.ts +8 -3
  33. package/src/response/ResponseContinuId.ts +1 -1
  34. package/src/response/ResponseMetaType.ts +32 -19
  35. package/src/response/ResponseMetaTypeViaMolecule.ts +224 -0
  36. package/src/response/ResponsePeering.ts +17 -0
  37. package/src/response/ResponsePolicy.ts +2 -3
  38. package/src/response/ResponseProposeMolecule.ts +0 -1
  39. package/src/response/ResponseRequestAuthorization.ts +32 -2
  40. package/src/response/ResponseRequestAuthorizationGuest.ts +25 -1
  41. package/src/response/ResponseWalletList.ts +1 -1
  42. package/src/types/guards.ts +18 -5
  43. package/src/types/index.ts +3 -3
package/dist/index.js CHANGED
@@ -898,9 +898,19 @@ var init_UnauthenticatedException = __esm({
898
898
  });
899
899
 
900
900
  // src/exception/AuthorizationRejectedException.ts
901
+ var AuthorizationRejectedException, AuthorizationRejectedException_default;
901
902
  var init_AuthorizationRejectedException = __esm({
902
903
  "src/exception/AuthorizationRejectedException.ts"() {
903
904
  init_BaseException();
905
+ AuthorizationRejectedException = class extends BaseException {
906
+ /**
907
+ * Constructor
908
+ */
909
+ constructor(message = "Authorization attempt rejected by ledger.") {
910
+ super("AUTHORIZATION_REJECTED_ERROR", message);
911
+ }
912
+ };
913
+ AuthorizationRejectedException_default = AuthorizationRejectedException;
904
914
  }
905
915
  });
906
916
 
@@ -1295,7 +1305,7 @@ var init_Dot = __esm({
1295
1305
  };
1296
1306
  }
1297
1307
  });
1298
- var ResponseErrorSchema, ValidationResultSchema;
1308
+ var ResponseErrorSchema, ValidationResultSchema2;
1299
1309
  var init_response = __esm({
1300
1310
  "src/types/response.ts"() {
1301
1311
  ResponseErrorSchema = z.object({
@@ -1306,7 +1316,7 @@ var init_response = __esm({
1306
1316
  timestamp: z.string().optional(),
1307
1317
  operation: z.string().optional()
1308
1318
  });
1309
- ValidationResultSchema = z.object({
1319
+ ValidationResultSchema2 = z.object({
1310
1320
  success: z.boolean(),
1311
1321
  data: z.any().optional(),
1312
1322
  error: ResponseErrorSchema.optional(),
@@ -1496,7 +1506,7 @@ var init_EnhancedResponse = __esm({
1496
1506
  // Enhanced response validation
1497
1507
  validate() {
1498
1508
  try {
1499
- ValidationResultSchema.parse(this.toValidationResult());
1509
+ ValidationResultSchema2.parse(this.toValidationResult());
1500
1510
  return {
1501
1511
  success: true,
1502
1512
  data: this._payload,
@@ -1747,7 +1757,7 @@ function chunkSubstr(str, size) {
1747
1757
  }
1748
1758
  return chunks;
1749
1759
  }
1750
- function randomString(length = 32, alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") {
1760
+ function randomString(length = 32, alphabet = "abcdef0123456789") {
1751
1761
  if (length <= 0) return "";
1752
1762
  let result = "";
1753
1763
  if (typeof crypto !== "undefined" && crypto.getRandomValues) {
@@ -1768,26 +1778,26 @@ function charsetBaseConvert(src, fromBase, toBase, srcSymbolTable = "0123456789a
1768
1778
  return false;
1769
1779
  }
1770
1780
  try {
1771
- let decimalValue = 0;
1772
- const srcLength = src.length;
1773
- for (let i = 0; i < srcLength; i++) {
1774
- const char = src.charAt(srcLength - 1 - i);
1775
- const charIndex = srcSymbolTable.indexOf(char);
1776
- if (charIndex === -1) {
1781
+ let val = BigInt(0);
1782
+ const bigFromBase = BigInt(fromBase);
1783
+ for (let charIndex = 0; charIndex < src.length; charIndex++) {
1784
+ const symbolIndex = srcSymbolTable.indexOf(src.charAt(charIndex));
1785
+ if (symbolIndex === -1) {
1777
1786
  return false;
1778
1787
  }
1779
- decimalValue += charIndex * Math.pow(fromBase, i);
1788
+ val = val * bigFromBase + BigInt(symbolIndex);
1780
1789
  }
1781
- if (decimalValue === 0) {
1790
+ if (val === BigInt(0)) {
1782
1791
  return destSymbolTable.charAt(0);
1783
1792
  }
1793
+ const bigToBase = BigInt(toBase);
1784
1794
  let result = "";
1785
- while (decimalValue > 0) {
1786
- const remainder = decimalValue % toBase;
1787
- result = destSymbolTable.charAt(remainder) + result;
1788
- decimalValue = Math.floor(decimalValue / toBase);
1795
+ while (val > BigInt(0)) {
1796
+ const remainder = val % bigToBase;
1797
+ result = destSymbolTable.charAt(Number(remainder)) + result;
1798
+ val = val / bigToBase;
1789
1799
  }
1790
- return result;
1800
+ return result || "0";
1791
1801
  } catch (error) {
1792
1802
  return false;
1793
1803
  }
@@ -1912,15 +1922,11 @@ function generateSecret(seed = null, length = CRYPTO_CONSTANTS.SECRET_LENGTH) {
1912
1922
  return randomString(length);
1913
1923
  }
1914
1924
  }
1915
- function generateBundleHash(secret, source = null) {
1925
+ function generateBundleHash(secret, _source = null) {
1916
1926
  if (!secret || secret.length === 0) {
1917
1927
  throw new Error("Secret is required for bundle hash generation");
1918
1928
  }
1919
- let input = secret;
1920
- if (source) {
1921
- input = secret + source;
1922
- }
1923
- const hash = shake256(input, CRYPTO_CONSTANTS.BUNDLE_HASH_LENGTH * 4);
1929
+ const hash = shake256(secret, CRYPTO_CONSTANTS.BUNDLE_HASH_LENGTH * 4);
1924
1930
  return hash;
1925
1931
  }
1926
1932
  function generatePosition() {
@@ -1931,17 +1937,10 @@ function generateBatchId({
1931
1937
  molecularHash = null,
1932
1938
  index = null
1933
1939
  } = {}) {
1934
- let input = "";
1935
- if (molecularHash) {
1936
- input += molecularHash;
1937
- }
1938
- if (index !== null) {
1939
- input += index.toString();
1940
- }
1941
- if (input === "") {
1942
- input = randomString(32);
1940
+ if (molecularHash && index !== null) {
1941
+ return shake256(molecularHash + index, 256);
1943
1942
  }
1944
- return shake256(input, 64);
1943
+ return randomString(64);
1945
1944
  }
1946
1945
  function generateWalletKey({
1947
1946
  secret,
@@ -2249,63 +2248,134 @@ function runExtendedCompatibilityTests() {
2249
2248
  return { passed: allPassed, results };
2250
2249
  }
2251
2250
 
2252
- // src/constants.ts
2253
- var ISOTOPES = ["C", "V", "U", "T", "M", "I", "R", "B", "F"];
2254
- var ERROR_TYPES = [
2255
- "ATOM_INDEX_ERROR",
2256
- "ATOMS_MISSING_ERROR",
2257
- "AUTHORIZATION_REJECTED_ERROR",
2258
- "BALANCE_INSUFFICIENT_ERROR",
2259
- "BATCH_ID_ERROR",
2260
- "CODE_ERROR",
2261
- "DECRYPTION_KEY_ERROR",
2262
- "INVALID_RESPONSE_ERROR",
2263
- "META_MISSING_ERROR",
2264
- "MOLECULAR_HASH_MISMATCH_ERROR",
2265
- "MOLECULAR_HASH_MISSING_ERROR",
2266
- "NEGATIVE_AMOUNT_ERROR",
2267
- "POLICY_INVALID_ERROR",
2268
- "RULE_ARGUMENT_ERROR",
2269
- "SIGNATURE_MALFORMED_ERROR",
2270
- "SIGNATURE_MISMATCH_ERROR",
2271
- "STACKABLE_UNIT_AMOUNT_ERROR",
2272
- "STACKABLE_UNIT_DECIMALS_ERROR",
2273
- "TRANSFER_BALANCE_ERROR",
2274
- "TRANSFER_MALFORMED_ERROR",
2275
- "TRANSFER_MISMATCHED_ERROR",
2276
- "TRANSFER_REMAINDER_ERROR",
2277
- "TRANSFER_TO_SELF_ERROR",
2278
- "TRANSFER_UNBALANCED_ERROR",
2279
- "UNAUTHENTICATED_ERROR",
2280
- "WALLET_CREDENTIAL_ERROR",
2281
- "WALLET_SHADOW_ERROR",
2282
- "WRONG_TOKEN_TYPE_ERROR"
2283
- ];
2284
- var PROTOCOL_CONFIG = {
2285
- DEFAULT_SDK_VERSION: 4};
2286
- var QUERY_TYPES = [
2287
- "Balance",
2288
- "WalletBundle",
2289
- "WalletList",
2290
- "Atom",
2291
- "MetaType",
2292
- "MetaTypeViaAtom",
2293
- "ContinuId",
2294
- "Batch",
2295
- "ActiveSession",
2296
- "Policy",
2297
- "Token",
2298
- "UserActivity"
2299
- ];
2300
- function createLookup(values) {
2301
- return values.reduce((acc, value) => {
2302
- acc[value] = value;
2303
- return acc;
2304
- }, {});
2251
+ // src/versions/HashAtom.ts
2252
+ function isObject(value) {
2253
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2305
2254
  }
2306
- var ISOTOPE_LOOKUP = createLookup(ISOTOPES);
2307
- createLookup(ERROR_TYPES);
2308
- createLookup(QUERY_TYPES);
2255
+ function isArray(value) {
2256
+ return Array.isArray(value);
2257
+ }
2258
+ function isPrimitive(value) {
2259
+ return value === null || value === void 0 || ["string", "number", "boolean"].includes(typeof value);
2260
+ }
2261
+ var HashAtom = class _HashAtom {
2262
+ /**
2263
+ * Creates a HashAtom instance from an Atom with proper typing
2264
+ */
2265
+ static create(atom) {
2266
+ const parameters = {};
2267
+ for (const key of Object.keys(atom)) {
2268
+ if (Object.prototype.hasOwnProperty.call(atom, key)) {
2269
+ parameters[key] = atom[key];
2270
+ }
2271
+ }
2272
+ return new this(parameters);
2273
+ }
2274
+ /**
2275
+ * Recursively structures an object or array for hashing consistency
2276
+ * Eliminates any types with proper generic constraints
2277
+ */
2278
+ static structure(object) {
2279
+ if (isPrimitive(object)) {
2280
+ return object;
2281
+ }
2282
+ if (isArray(object)) {
2283
+ const result = [];
2284
+ for (const value of object) {
2285
+ result.push(_HashAtom.isStructure(value) ? _HashAtom.structure(value) : value);
2286
+ }
2287
+ return result;
2288
+ }
2289
+ if (isObject(object)) {
2290
+ const result = [];
2291
+ const keys = Object.keys(object).sort((first, second) => {
2292
+ if (first === second) {
2293
+ return 0;
2294
+ }
2295
+ return first < second ? -1 : 1;
2296
+ });
2297
+ for (const key of keys) {
2298
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
2299
+ const item = {};
2300
+ const value = object[key];
2301
+ item[key] = _HashAtom.isStructure(value) ? _HashAtom.structure(value) : value;
2302
+ result.push(item);
2303
+ }
2304
+ }
2305
+ if (result.length > 0) {
2306
+ return result;
2307
+ }
2308
+ }
2309
+ return object;
2310
+ }
2311
+ /**
2312
+ * Type guard to determine if a value needs recursive structure processing
2313
+ */
2314
+ static isStructure(structure) {
2315
+ return isObject(structure) || isArray(structure);
2316
+ }
2317
+ /**
2318
+ * Returns the structured view of this HashAtom instance
2319
+ */
2320
+ view() {
2321
+ return _HashAtom.structure(this);
2322
+ }
2323
+ /**
2324
+ * Protected constructor to support subclass instantiation
2325
+ */
2326
+ constructor(params = {}) {
2327
+ Object.assign(this, params);
2328
+ }
2329
+ };
2330
+
2331
+ // src/versions/Version4.ts
2332
+ var Version4 = class extends HashAtom {
2333
+ position;
2334
+ walletAddress;
2335
+ isotope;
2336
+ token;
2337
+ value;
2338
+ batchId;
2339
+ metaType;
2340
+ metaId;
2341
+ meta;
2342
+ index;
2343
+ createdAt;
2344
+ version;
2345
+ constructor({
2346
+ position = null,
2347
+ walletAddress = null,
2348
+ isotope = null,
2349
+ token = null,
2350
+ value = null,
2351
+ batchId = null,
2352
+ metaType = null,
2353
+ metaId = null,
2354
+ meta = null,
2355
+ index = null,
2356
+ createdAt = null,
2357
+ version = null
2358
+ } = {}) {
2359
+ super();
2360
+ this.position = position;
2361
+ this.walletAddress = walletAddress;
2362
+ this.isotope = isotope;
2363
+ this.token = token;
2364
+ this.value = value;
2365
+ this.batchId = batchId;
2366
+ this.metaType = metaType;
2367
+ this.metaId = metaId;
2368
+ this.meta = meta;
2369
+ this.index = index;
2370
+ this.createdAt = createdAt;
2371
+ this.version = version;
2372
+ }
2373
+ };
2374
+
2375
+ // src/versions/index.ts
2376
+ var versions_default = {
2377
+ 4: Version4
2378
+ };
2309
2379
 
2310
2380
  // src/types/guards.ts
2311
2381
  function assertNever(value) {
@@ -2331,6 +2401,10 @@ function handleIsotope(isotope, handlers) {
2331
2401
  return handlers.B();
2332
2402
  case "F":
2333
2403
  return handlers.F();
2404
+ case "P":
2405
+ return handlers.P();
2406
+ case "A":
2407
+ return handlers.A();
2334
2408
  default:
2335
2409
  return assertNever(isotope);
2336
2410
  }
@@ -2342,126 +2416,537 @@ function isPosition(value) {
2342
2416
  return typeof value === "string" && value.length === 64 && /^[0-9a-fA-F]{64}$/.test(value);
2343
2417
  }
2344
2418
 
2345
- // src/core/Atom.ts
2346
- var ATOM_DEFAULTS = {
2347
- POSITION: "",
2348
- WALLET_ADDRESS: "",
2349
- ISOTOPE: "C",
2350
- TOKEN: "USER",
2351
- VALUE: null,
2352
- BATCH_ID: null,
2353
- META_TYPE: null,
2354
- META_ID: null,
2355
- META: [],
2356
- OTS_FRAGMENT: null,
2357
- INDEX: null,
2358
- VERSION: PROTOCOL_CONFIG.DEFAULT_SDK_VERSION
2359
- };
2360
- var Atom = class _Atom {
2361
- // Core properties matching JS SDK exactly
2362
- position;
2363
- walletAddress;
2364
- isotope;
2365
- token;
2366
- value;
2367
- batchId;
2368
- metaType;
2369
- metaId;
2370
- meta;
2371
- otsFragment;
2372
- index;
2373
- createdAt;
2374
- version;
2419
+ // src/core/Meta.ts
2420
+ var Meta = class {
2421
+ // No instance properties - this class only provides static methods
2375
2422
  /**
2376
- * Create a new Atom instance
2377
- * Constructor signature matches JavaScript SDK exactly
2423
+ * Normalize metadata to consistent format
2424
+ * Matches JavaScript SDK Meta.normalizeMeta exactly
2378
2425
  */
2379
- constructor({
2380
- position = ATOM_DEFAULTS.POSITION,
2381
- walletAddress = ATOM_DEFAULTS.WALLET_ADDRESS,
2382
- isotope = ATOM_DEFAULTS.ISOTOPE,
2383
- token = ATOM_DEFAULTS.TOKEN,
2384
- value = ATOM_DEFAULTS.VALUE,
2385
- batchId = ATOM_DEFAULTS.BATCH_ID,
2386
- metaType = ATOM_DEFAULTS.META_TYPE,
2387
- metaId = ATOM_DEFAULTS.META_ID,
2388
- meta = null,
2389
- otsFragment = ATOM_DEFAULTS.OTS_FRAGMENT,
2390
- index = ATOM_DEFAULTS.INDEX,
2391
- createdAt = null,
2392
- version = ATOM_DEFAULTS.VERSION
2393
- } = {}) {
2394
- this.position = position ?? ATOM_DEFAULTS.POSITION;
2395
- this.walletAddress = walletAddress ?? ATOM_DEFAULTS.WALLET_ADDRESS;
2396
- this.isotope = isotope ?? ATOM_DEFAULTS.ISOTOPE;
2397
- this.token = token ?? ATOM_DEFAULTS.TOKEN;
2398
- this.value = value;
2399
- this.batchId = batchId;
2400
- this.metaType = metaType;
2401
- this.metaId = metaId;
2402
- this.meta = meta ? [...meta] : [...ATOM_DEFAULTS.META];
2403
- this.otsFragment = otsFragment;
2404
- this.index = index;
2405
- this.version = version ?? ATOM_DEFAULTS.VERSION;
2406
- this.createdAt = createdAt || String(+/* @__PURE__ */ new Date());
2426
+ static normalizeMeta(meta) {
2427
+ if (!meta) {
2428
+ return [];
2429
+ }
2430
+ if (Array.isArray(meta)) {
2431
+ return meta.map((item) => {
2432
+ if (typeof item === "object" && item !== null && "key" in item) {
2433
+ return {
2434
+ key: String(item.key),
2435
+ value: item.value == null ? null : String(item.value)
2436
+ };
2437
+ }
2438
+ return {
2439
+ key: "unknown",
2440
+ value: String(item)
2441
+ };
2442
+ });
2443
+ }
2444
+ if (typeof meta === "object" && meta !== null) {
2445
+ const target = [];
2446
+ for (const property in meta) {
2447
+ if (Object.prototype.hasOwnProperty.call(meta, property)) {
2448
+ const raw = meta[property];
2449
+ target.push({ key: property, value: raw == null ? null : String(raw) });
2450
+ }
2451
+ }
2452
+ return target;
2453
+ }
2454
+ return [{
2455
+ key: "value",
2456
+ value: String(meta)
2457
+ }];
2407
2458
  }
2408
- // =============================================================================
2409
- // INSTANCE METHODS - MATCH JAVASCRIPT SDK
2410
- // =============================================================================
2411
2459
  /**
2412
- * Get aggregated metadata for this atom
2413
- * Matches JavaScript SDK Meta.aggregateMeta functionality
2460
+ * Aggregate metadata into single object
2461
+ * Matches JavaScript SDK Meta.aggregateMeta exactly
2414
2462
  */
2415
- aggregatedMeta() {
2463
+ static aggregateMeta(metaItems) {
2464
+ if (!metaItems || !Array.isArray(metaItems)) {
2465
+ return {};
2466
+ }
2416
2467
  const aggregated = {};
2417
- for (const metaItem of this.meta) {
2418
- if (metaItem && typeof metaItem === "object" && "key" in metaItem) {
2419
- aggregated[metaItem.key] = metaItem.value;
2468
+ for (const item of metaItems) {
2469
+ if (item && typeof item === "object" && "key" in item) {
2470
+ const key = String(item.key);
2471
+ if ("value" in item) {
2472
+ aggregated[key] = item.value;
2473
+ } else {
2474
+ const { key: itemKey, ...restOfItem } = item;
2475
+ aggregated[key] = Object.keys(restOfItem).length === 1 && "value" in restOfItem ? restOfItem.value : restOfItem;
2476
+ }
2420
2477
  }
2421
2478
  }
2422
2479
  return aggregated;
2423
2480
  }
2424
2481
  /**
2425
- * Get values that will be used for hashing
2426
- * Must match JavaScript SDK getHashableValues exactly - returns array of strings!
2482
+ * Merge multiple metadata arrays
2483
+ * Combines arrays while preserving order and handling duplicates
2427
2484
  */
2428
- getHashableValues() {
2429
- const hashableValues = [];
2430
- for (const property of _Atom.getHashableProps()) {
2431
- const value = this[property];
2432
- if (value === null && !["position", "walletAddress"].includes(property)) {
2485
+ static mergeMeta(...metaArrays) {
2486
+ const merged = [];
2487
+ const keysSeen = /* @__PURE__ */ new Set();
2488
+ for (const metaArray of metaArrays) {
2489
+ if (!metaArray || !Array.isArray(metaArray)) {
2433
2490
  continue;
2434
2491
  }
2435
- if (property === "meta") {
2436
- for (const meta of value) {
2437
- if (typeof meta.value !== "undefined" && meta.value !== null) {
2438
- hashableValues.push(String(meta.key));
2439
- hashableValues.push(String(meta.value));
2440
- }
2492
+ const normalized = this.normalizeMeta(metaArray);
2493
+ for (const item of normalized) {
2494
+ let finalKey = item.key;
2495
+ let counter = 1;
2496
+ while (keysSeen.has(finalKey)) {
2497
+ finalKey = `${item.key}_${counter}`;
2498
+ counter++;
2441
2499
  }
2442
- } else {
2443
- hashableValues.push(value === null ? "" : String(value));
2500
+ keysSeen.add(finalKey);
2501
+ merged.push({
2502
+ ...item,
2503
+ key: finalKey
2504
+ });
2444
2505
  }
2445
2506
  }
2446
- return hashableValues;
2507
+ return merged;
2447
2508
  }
2448
2509
  /**
2449
- * Get structured data for JSON serialization
2450
- * Separate from hashable values to maintain proper typing
2510
+ * Filter metadata by key pattern or predicate
2451
2511
  */
2452
- getStructuredData() {
2453
- return {
2454
- position: this.position || "",
2455
- walletAddress: this.walletAddress?.toString() || "",
2456
- isotope: this.isotope,
2457
- token: this.token?.toString() || "",
2458
- value: this.value !== null ? this.value.toString() : null,
2512
+ static filterMeta(metaItems, filter) {
2513
+ if (!metaItems || !Array.isArray(metaItems)) {
2514
+ return [];
2515
+ }
2516
+ const normalized = this.normalizeMeta(metaItems);
2517
+ if (typeof filter === "string") {
2518
+ return normalized.filter((item) => item.key.includes(filter));
2519
+ }
2520
+ if (filter instanceof RegExp) {
2521
+ return normalized.filter((item) => filter.test(item.key));
2522
+ }
2523
+ if (typeof filter === "function") {
2524
+ return normalized.filter(filter);
2525
+ }
2526
+ return normalized;
2527
+ }
2528
+ /**
2529
+ * Find metadata item by key
2530
+ */
2531
+ static findMeta(metaItems, key) {
2532
+ if (!metaItems || !Array.isArray(metaItems)) {
2533
+ return null;
2534
+ }
2535
+ const normalized = this.normalizeMeta(metaItems);
2536
+ return normalized.find((item) => item.key === key) || null;
2537
+ }
2538
+ /**
2539
+ * Get metadata value by key
2540
+ */
2541
+ static getMetaValue(metaItems, key, defaultValue = null) {
2542
+ const item = this.findMeta(metaItems, key);
2543
+ return item ? item.value : defaultValue;
2544
+ }
2545
+ /**
2546
+ * Set or update metadata item by key
2547
+ */
2548
+ static setMeta(metaItems, key, value) {
2549
+ const normalized = this.normalizeMeta(metaItems);
2550
+ const existingIndex = normalized.findIndex((item) => item.key === key);
2551
+ const newItem = {
2552
+ key,
2553
+ value: value == null ? null : String(value)
2554
+ };
2555
+ if (existingIndex >= 0) {
2556
+ normalized[existingIndex] = newItem;
2557
+ } else {
2558
+ normalized.push(newItem);
2559
+ }
2560
+ return normalized;
2561
+ }
2562
+ /**
2563
+ * Remove metadata item by key
2564
+ */
2565
+ static removeMeta(metaItems, key) {
2566
+ if (!metaItems || !Array.isArray(metaItems)) {
2567
+ return [];
2568
+ }
2569
+ const normalized = this.normalizeMeta(metaItems);
2570
+ return normalized.filter((item) => item.key !== key);
2571
+ }
2572
+ /**
2573
+ * Convert metadata to JSON-serializable format
2574
+ */
2575
+ static toJSON(metaItems) {
2576
+ return this.aggregateMeta(this.normalizeMeta(metaItems));
2577
+ }
2578
+ /**
2579
+ * Create metadata from JSON object
2580
+ */
2581
+ static fromJSON(jsonData) {
2582
+ if (!jsonData || typeof jsonData !== "object") {
2583
+ return [];
2584
+ }
2585
+ return Object.entries(jsonData).map(([key, value]) => ({
2586
+ key,
2587
+ value: value == null ? null : String(value)
2588
+ }));
2589
+ }
2590
+ /**
2591
+ * Validate metadata structure
2592
+ */
2593
+ static validateMeta(metaItems) {
2594
+ if (!Array.isArray(metaItems)) {
2595
+ return false;
2596
+ }
2597
+ return metaItems.every(
2598
+ (item) => item && typeof item === "object" && "key" in item && typeof item.key === "string"
2599
+ );
2600
+ }
2601
+ /**
2602
+ * Get all unique keys from metadata
2603
+ */
2604
+ static getKeys(metaItems) {
2605
+ if (!metaItems || !Array.isArray(metaItems)) {
2606
+ return [];
2607
+ }
2608
+ const normalized = this.normalizeMeta(metaItems);
2609
+ const keys = /* @__PURE__ */ new Set();
2610
+ for (const item of normalized) {
2611
+ keys.add(item.key);
2612
+ }
2613
+ return Array.from(keys);
2614
+ }
2615
+ /**
2616
+ * Check if metadata contains specific key
2617
+ */
2618
+ static hasKey(metaItems, key) {
2619
+ return this.getKeys(metaItems).includes(key);
2620
+ }
2621
+ /**
2622
+ * Get metadata statistics
2623
+ */
2624
+ static getStats(metaItems) {
2625
+ if (!metaItems || !Array.isArray(metaItems)) {
2626
+ return {
2627
+ totalItems: 0,
2628
+ uniqueKeys: 0,
2629
+ keys: [],
2630
+ valueTypes: {}
2631
+ };
2632
+ }
2633
+ const normalized = this.normalizeMeta(metaItems);
2634
+ const keys = this.getKeys(normalized);
2635
+ const valueTypes = {};
2636
+ for (const item of normalized) {
2637
+ const type = item.value === null ? "null" : typeof item.value;
2638
+ valueTypes[type] = (valueTypes[type] || 0) + 1;
2639
+ }
2640
+ return {
2641
+ totalItems: normalized.length,
2642
+ uniqueKeys: keys.length,
2643
+ keys,
2644
+ valueTypes
2645
+ };
2646
+ }
2647
+ /**
2648
+ * Deep clone metadata array
2649
+ */
2650
+ static clone(metaItems) {
2651
+ if (!metaItems || !Array.isArray(metaItems)) {
2652
+ return [];
2653
+ }
2654
+ const normalized = this.normalizeMeta(metaItems);
2655
+ return normalized.map((item) => ({ ...item }));
2656
+ }
2657
+ /**
2658
+ * Sort metadata by key
2659
+ */
2660
+ static sort(metaItems, descending = false) {
2661
+ if (!metaItems || !Array.isArray(metaItems)) {
2662
+ return [];
2663
+ }
2664
+ const normalized = this.normalizeMeta(metaItems);
2665
+ return normalized.sort((a, b) => {
2666
+ const comparison = a.key.localeCompare(b.key);
2667
+ return descending ? -comparison : comparison;
2668
+ });
2669
+ }
2670
+ };
2671
+ var AtomMeta = class _AtomMeta {
2672
+ meta;
2673
+ /**
2674
+ * Create new AtomMeta instance
2675
+ * @param meta - Initial metadata (object or array)
2676
+ */
2677
+ constructor(meta = null) {
2678
+ this.meta = Meta.normalizeMeta(meta);
2679
+ }
2680
+ /**
2681
+ * Merge additional metadata
2682
+ * @param meta - Metadata to merge
2683
+ * @return This instance for chaining
2684
+ */
2685
+ merge(meta) {
2686
+ this.meta = [...this.meta, ...Meta.normalizeMeta(meta)];
2687
+ return this;
2688
+ }
2689
+ /**
2690
+ * Add context metadata if enabled
2691
+ * @param context - Context URL or null for default
2692
+ * @return This instance for chaining
2693
+ */
2694
+ addContext(context = null) {
2695
+ return this;
2696
+ }
2697
+ /**
2698
+ * Set atom wallet metadata
2699
+ * @param wallet - Wallet to extract metadata from
2700
+ * @return This instance for chaining
2701
+ */
2702
+ setAtomWallet(wallet) {
2703
+ const walletMeta = {};
2704
+ if (wallet.tokenUnits && wallet.tokenUnits.length) {
2705
+ walletMeta.tokenUnits = JSON.stringify(wallet.getTokenUnitsData ? wallet.getTokenUnitsData() : wallet.tokenUnits);
2706
+ }
2707
+ if (wallet.tradeRates && wallet.tradeRates.length) {
2708
+ walletMeta.tradeRates = JSON.stringify(wallet.tradeRates);
2709
+ }
2710
+ if (Object.keys(walletMeta).length > 0) {
2711
+ this.merge(walletMeta);
2712
+ }
2713
+ return this;
2714
+ }
2715
+ /**
2716
+ * Set full NEW wallet metadata
2717
+ * Used for shadow wallet claim & wallet creation & token creation
2718
+ * @param wallet - Wallet with full metadata
2719
+ * @return This instance for chaining
2720
+ */
2721
+ setMetaWallet(wallet) {
2722
+ this.merge({
2723
+ walletTokenSlug: wallet.token,
2724
+ walletBundleHash: wallet.bundle,
2725
+ walletAddress: wallet.address,
2726
+ walletPosition: wallet.position,
2727
+ walletBatchId: wallet.batchId,
2728
+ walletPubkey: wallet.pubkey,
2729
+ walletCharacters: wallet.characters
2730
+ });
2731
+ return this;
2732
+ }
2733
+ /**
2734
+ * Set shadow wallet claim flag
2735
+ * @param shadowWalletClaim - Claim flag (converted to number)
2736
+ * @return This instance for chaining
2737
+ */
2738
+ setShadowWalletClaim(shadowWalletClaim) {
2739
+ this.merge({ shadowWalletClaim: Number(shadowWalletClaim) });
2740
+ return this;
2741
+ }
2742
+ /**
2743
+ * Set signing wallet metadata
2744
+ * @param signingWallet - Wallet used for signing
2745
+ * @return This instance for chaining
2746
+ */
2747
+ setSigningWallet(signingWallet) {
2748
+ this.merge({
2749
+ signingWallet: JSON.stringify({
2750
+ tokenSlug: signingWallet.token,
2751
+ bundleHash: signingWallet.bundle,
2752
+ address: signingWallet.address,
2753
+ position: signingWallet.position,
2754
+ pubkey: signingWallet.pubkey,
2755
+ characters: signingWallet.characters
2756
+ })
2757
+ });
2758
+ return this;
2759
+ }
2760
+ /**
2761
+ * Add policy metadata
2762
+ * @param policy - Policy object to add
2763
+ * @return This instance for chaining
2764
+ */
2765
+ addPolicy(policy) {
2766
+ this.merge({
2767
+ policy: JSON.stringify(policy)
2768
+ });
2769
+ return this;
2770
+ }
2771
+ /**
2772
+ * Get the normalized metadata array
2773
+ * @return Array of normalized metadata items
2774
+ */
2775
+ get() {
2776
+ return this.meta;
2777
+ }
2778
+ /**
2779
+ * Convert metadata to plain object
2780
+ * @return Aggregated metadata object
2781
+ */
2782
+ toObject() {
2783
+ return Meta.aggregateMeta(this.meta);
2784
+ }
2785
+ /**
2786
+ * Convert metadata to JSON string
2787
+ * @return JSON string representation
2788
+ */
2789
+ toJSON() {
2790
+ return JSON.stringify(this.toObject());
2791
+ }
2792
+ /**
2793
+ * Get metadata value by key
2794
+ * @param key - Key to lookup
2795
+ * @param defaultValue - Default if not found
2796
+ * @return Value or default
2797
+ */
2798
+ getValue(key, defaultValue = null) {
2799
+ return Meta.getMetaValue(this.meta, key, defaultValue);
2800
+ }
2801
+ /**
2802
+ * Check if metadata has a key
2803
+ * @param key - Key to check
2804
+ * @return True if key exists
2805
+ */
2806
+ hasKey(key) {
2807
+ return Meta.hasKey(this.meta, key);
2808
+ }
2809
+ /**
2810
+ * Remove metadata by key
2811
+ * @param key - Key to remove
2812
+ * @return This instance for chaining
2813
+ */
2814
+ remove(key) {
2815
+ this.meta = Meta.removeMeta(this.meta, key);
2816
+ return this;
2817
+ }
2818
+ /**
2819
+ * Clear all metadata
2820
+ * @return This instance for chaining
2821
+ */
2822
+ clear() {
2823
+ this.meta = [];
2824
+ return this;
2825
+ }
2826
+ /**
2827
+ * Get count of metadata items
2828
+ * @return Number of items
2829
+ */
2830
+ count() {
2831
+ return this.meta.length;
2832
+ }
2833
+ /**
2834
+ * Clone this AtomMeta instance
2835
+ * @return New AtomMeta with same data
2836
+ */
2837
+ clone() {
2838
+ return new _AtomMeta(Meta.clone(this.meta));
2839
+ }
2840
+ };
2841
+ var Atom = class _Atom {
2842
+ // Core properties matching JS SDK exactly (all default to null)
2843
+ position;
2844
+ walletAddress;
2845
+ isotope;
2846
+ token;
2847
+ value;
2848
+ batchId;
2849
+ metaType;
2850
+ metaId;
2851
+ meta;
2852
+ otsFragment;
2853
+ index;
2854
+ createdAt;
2855
+ version;
2856
+ /**
2857
+ * Create a new Atom instance
2858
+ * Constructor signature matches JavaScript SDK exactly
2859
+ */
2860
+ constructor({
2861
+ position = null,
2862
+ walletAddress = null,
2863
+ isotope = null,
2864
+ token = null,
2865
+ value = null,
2866
+ batchId = null,
2867
+ metaType = null,
2868
+ metaId = null,
2869
+ meta = null,
2870
+ otsFragment = null,
2871
+ index = null,
2872
+ createdAt = null,
2873
+ version = null
2874
+ } = {}) {
2875
+ this.position = position;
2876
+ this.walletAddress = walletAddress;
2877
+ this.isotope = isotope;
2878
+ this.token = token;
2879
+ this.value = value !== null && value !== void 0 ? String(value) : null;
2880
+ this.batchId = batchId;
2881
+ this.metaType = metaType;
2882
+ this.metaId = metaId;
2883
+ this.meta = meta ? Meta.normalizeMeta(meta) : [];
2884
+ this.otsFragment = otsFragment;
2885
+ this.index = index;
2886
+ if (version !== null && version !== void 0 && Object.prototype.hasOwnProperty.call(versions_default, version)) {
2887
+ this.version = String(version);
2888
+ }
2889
+ this.createdAt = createdAt || String(+/* @__PURE__ */ new Date());
2890
+ }
2891
+ // =============================================================================
2892
+ // INSTANCE METHODS - MATCH JAVASCRIPT SDK
2893
+ // =============================================================================
2894
+ /**
2895
+ * Get aggregated metadata for this atom
2896
+ * Matches JavaScript SDK Meta.aggregateMeta functionality
2897
+ */
2898
+ aggregatedMeta() {
2899
+ const aggregated = {};
2900
+ for (const metaItem of this.meta) {
2901
+ if (metaItem && typeof metaItem === "object" && "key" in metaItem) {
2902
+ aggregated[metaItem.key] = metaItem.value;
2903
+ }
2904
+ }
2905
+ return aggregated;
2906
+ }
2907
+ /**
2908
+ * Get values that will be used for hashing
2909
+ * Must match JavaScript SDK getHashableValues exactly - returns array of strings!
2910
+ */
2911
+ getHashableValues() {
2912
+ const hashableValues = [];
2913
+ for (const property of _Atom.getHashableProps()) {
2914
+ const value = this[property];
2915
+ if (value === null && !["position", "walletAddress"].includes(property)) {
2916
+ continue;
2917
+ }
2918
+ if (property === "meta") {
2919
+ for (const meta of value) {
2920
+ if (typeof meta.value !== "undefined" && meta.value !== null) {
2921
+ hashableValues.push(String(meta.key));
2922
+ hashableValues.push(String(meta.value));
2923
+ }
2924
+ }
2925
+ } else {
2926
+ hashableValues.push(value === null ? "" : String(value));
2927
+ }
2928
+ }
2929
+ return hashableValues;
2930
+ }
2931
+ /**
2932
+ * Get structured data for JSON serialization
2933
+ * Separate from hashable values to maintain proper typing
2934
+ */
2935
+ getStructuredData() {
2936
+ return {
2937
+ position: this.position || "",
2938
+ walletAddress: this.walletAddress?.toString() || "",
2939
+ isotope: this.isotope || "C",
2940
+ token: this.token?.toString() || "",
2941
+ value: this.value !== null ? this.value.toString() : null,
2459
2942
  batchId: this.batchId?.toString() || null,
2460
2943
  metaType: this.metaType?.toString() || null,
2461
2944
  metaId: this.metaId?.toString() || null,
2462
- meta: this.meta.length > 0 ? [...this.meta] : null,
2945
+ // Always return array for meta (server expects Vec<MetaItemInput>, not null)
2946
+ meta: this.meta.length > 0 ? [...this.meta] : [],
2463
2947
  createdAt: this.createdAt,
2464
- index: this.index !== null ? this.index : 0
2948
+ index: this.index !== null ? this.index : 0,
2949
+ version: this.version ?? null
2465
2950
  };
2466
2951
  }
2467
2952
  /**
@@ -2490,9 +2975,19 @@ var Atom = class _Atom {
2490
2975
  }
2491
2976
  }
2492
2977
  }
2493
- const structuredData = this.getStructuredData();
2494
2978
  const serialized = {
2495
- ...structuredData
2979
+ position: this.position ?? "",
2980
+ walletAddress: this.walletAddress ?? "",
2981
+ isotope: this.isotope,
2982
+ token: this.token ?? "",
2983
+ value: this.value,
2984
+ batchId: this.batchId,
2985
+ metaType: this.metaType,
2986
+ metaId: this.metaId,
2987
+ meta: this.meta || [],
2988
+ index: this.index,
2989
+ createdAt: this.createdAt,
2990
+ version: this.version
2496
2991
  };
2497
2992
  if (includeOtsFragments && this.otsFragment) {
2498
2993
  serialized.otsFragment = this.otsFragment;
@@ -2529,6 +3024,7 @@ var Atom = class _Atom {
2529
3024
  if (!isPosition(this.position) || !isWalletAddress(this.walletAddress)) {
2530
3025
  return false;
2531
3026
  }
3027
+ if (!this.isotope) return false;
2532
3028
  return handleIsotope(this.isotope, {
2533
3029
  V: () => this.value !== null && !isNaN(Number(this.value)),
2534
3030
  // Value atoms must have numeric value
@@ -2546,8 +3042,12 @@ var Atom = class _Atom {
2546
3042
  // Rule atoms
2547
3043
  B: () => true,
2548
3044
  // Buffer atoms
2549
- F: () => true
3045
+ F: () => true,
2550
3046
  // Fuse atoms
3047
+ P: () => true,
3048
+ // Peer atoms
3049
+ A: () => Boolean(this.metaType && this.metaId)
3050
+ // Append atoms must have metaType and metaId
2551
3051
  });
2552
3052
  }
2553
3053
  // =============================================================================
@@ -2577,24 +3077,48 @@ var Atom = class _Atom {
2577
3077
  */
2578
3078
  static getUnclaimedProps() {
2579
3079
  return [
2580
- "position",
2581
- "walletAddress",
2582
- "isotope",
2583
- "token",
2584
- "value",
2585
- "batchId",
2586
- "metaType",
2587
- "metaId",
2588
- "meta",
2589
- "createdAt"
3080
+ "otsFragment"
2590
3081
  ];
2591
3082
  }
2592
3083
  /**
2593
3084
  * Create atom from parameters - factory method
2594
- * Matches JavaScript SDK Atom.create static method
3085
+ * Matches JavaScript SDK Atom.create static method exactly
3086
+ * Processes wallet meta, extracts wallet fields, normalizes meta
2595
3087
  */
2596
- static create(params) {
2597
- return new _Atom(params);
3088
+ static create({
3089
+ isotope,
3090
+ wallet = null,
3091
+ value = null,
3092
+ metaType = null,
3093
+ metaId = null,
3094
+ meta = null,
3095
+ batchId = null
3096
+ }) {
3097
+ let atomMeta;
3098
+ if (!meta) {
3099
+ atomMeta = new AtomMeta();
3100
+ } else if (meta instanceof AtomMeta) {
3101
+ atomMeta = meta;
3102
+ } else {
3103
+ atomMeta = new AtomMeta(meta);
3104
+ }
3105
+ if (wallet) {
3106
+ atomMeta.setAtomWallet(wallet);
3107
+ if (!batchId) {
3108
+ batchId = wallet.batchId;
3109
+ }
3110
+ }
3111
+ return new _Atom({
3112
+ position: wallet ? wallet.position : null,
3113
+ walletAddress: wallet ? wallet.address : null,
3114
+ isotope,
3115
+ token: wallet ? wallet.token : null,
3116
+ value,
3117
+ batchId,
3118
+ metaType,
3119
+ metaId,
3120
+ meta: atomMeta.get()
3121
+ });
2598
3122
  }
2599
3123
  /**
2600
3124
  * Creates an Atom instance from JSON data (2025 TS best practices)
@@ -2670,15 +3194,22 @@ var Atom = class _Atom {
2670
3194
  return "";
2671
3195
  }
2672
3196
  const atomList = _Atom.sortAtoms(atoms);
2673
- const numberOfAtoms = String(atoms.length);
2674
- let hashableValues = [];
2675
- for (const atom of atomList) {
2676
- hashableValues.push(numberOfAtoms);
2677
- hashableValues = hashableValues.concat(atom.getHashableValues());
2678
- }
2679
3197
  const molecularSponge = new JsSHA("SHAKE256", "TEXT");
2680
- for (const hashableValue of hashableValues) {
2681
- molecularSponge.update(hashableValue);
3198
+ const versionRegistry = versions_default;
3199
+ if (atomList.every((atom) => atom.version && Object.prototype.hasOwnProperty.call(versionRegistry, atom.version))) {
3200
+ molecularSponge.update(JSON.stringify(
3201
+ atomList.map((atom) => versionRegistry[atom.version].create(atom).view())
3202
+ ));
3203
+ } else {
3204
+ const numberOfAtoms = String(atoms.length);
3205
+ let hashableValues = [];
3206
+ for (const atom of atomList) {
3207
+ hashableValues.push(numberOfAtoms);
3208
+ hashableValues = hashableValues.concat(atom.getHashableValues());
3209
+ }
3210
+ for (const hashableValue of hashableValues) {
3211
+ molecularSponge.update(hashableValue);
3212
+ }
2682
3213
  }
2683
3214
  const hexHash = molecularSponge.getHash("HEX", { outputLen: 256 });
2684
3215
  return convertToBase17(hexHash.toLowerCase());
@@ -2688,10 +3219,8 @@ var Atom = class _Atom {
2688
3219
  * Matches JavaScript SDK sortAtoms method
2689
3220
  */
2690
3221
  static sortAtoms(atoms) {
2691
- return [...atoms].sort((a, b) => {
2692
- const indexA = a.index !== null ? a.index : 0;
2693
- const indexB = b.index !== null ? b.index : 0;
2694
- return indexA - indexB;
3222
+ return [...atoms].sort((first, second) => {
3223
+ return first.index < second.index ? -1 : 1;
2695
3224
  });
2696
3225
  }
2697
3226
  /**
@@ -2699,11 +3228,7 @@ var Atom = class _Atom {
2699
3228
  * Matches JavaScript SDK generateNextAtomIndex method
2700
3229
  */
2701
3230
  static generateNextAtomIndex(atoms) {
2702
- if (!atoms || atoms.length === 0) {
2703
- return 0;
2704
- }
2705
- const indices = atoms.map((atom) => atom.index !== null ? atom.index : 0).filter((index) => typeof index === "number");
2706
- return indices.length > 0 ? Math.max(...indices) + 1 : 0;
3231
+ return atoms.length;
2707
3232
  }
2708
3233
  /**
2709
3234
  * Filter atoms by isotope(s)
@@ -2711,7 +3236,7 @@ var Atom = class _Atom {
2711
3236
  */
2712
3237
  static isotopeFilter(isotopes, atoms) {
2713
3238
  const targetIsotopes = Array.isArray(isotopes) ? isotopes : [isotopes];
2714
- return atoms.filter((atom) => targetIsotopes.includes(atom.isotope));
3239
+ return atoms.filter((atom) => atom.isotope !== null && targetIsotopes.includes(atom.isotope));
2715
3240
  }
2716
3241
  // =============================================================================
2717
3242
  // VALIDATION AND UTILITY METHODS
@@ -2738,7 +3263,9 @@ var Atom = class _Atom {
2738
3263
  static getUniqueIsotopes(atoms) {
2739
3264
  const isotopes = /* @__PURE__ */ new Set();
2740
3265
  for (const atom of atoms) {
2741
- isotopes.add(atom.isotope);
3266
+ if (atom.isotope !== null) {
3267
+ isotopes.add(atom.isotope);
3268
+ }
2742
3269
  }
2743
3270
  return Array.from(isotopes);
2744
3271
  }
@@ -2754,16 +3281,74 @@ var Atom = class _Atom {
2754
3281
  static groupByIsotope(atoms) {
2755
3282
  const groups = {};
2756
3283
  for (const atom of atoms) {
2757
- if (!groups[atom.isotope]) {
2758
- groups[atom.isotope] = [];
3284
+ const iso = atom.isotope;
3285
+ if (iso === null) continue;
3286
+ if (!groups[iso]) {
3287
+ groups[iso] = [];
2759
3288
  }
2760
- groups[atom.isotope].push(atom);
3289
+ groups[iso].push(atom);
2761
3290
  }
2762
3291
  return groups;
2763
3292
  }
2764
3293
  };
2765
3294
  init_WalletCredentialException();
2766
3295
 
3296
+ // src/constants.ts
3297
+ var ISOTOPES = ["C", "V", "U", "T", "M", "I", "R", "B", "F", "P", "A"];
3298
+ var ERROR_TYPES = [
3299
+ "ATOM_INDEX_ERROR",
3300
+ "ATOMS_MISSING_ERROR",
3301
+ "AUTHORIZATION_REJECTED_ERROR",
3302
+ "BALANCE_INSUFFICIENT_ERROR",
3303
+ "BATCH_ID_ERROR",
3304
+ "CODE_ERROR",
3305
+ "DECRYPTION_KEY_ERROR",
3306
+ "INVALID_RESPONSE_ERROR",
3307
+ "META_MISSING_ERROR",
3308
+ "MOLECULAR_HASH_MISMATCH_ERROR",
3309
+ "MOLECULAR_HASH_MISSING_ERROR",
3310
+ "NEGATIVE_AMOUNT_ERROR",
3311
+ "POLICY_INVALID_ERROR",
3312
+ "RULE_ARGUMENT_ERROR",
3313
+ "SIGNATURE_MALFORMED_ERROR",
3314
+ "SIGNATURE_MISMATCH_ERROR",
3315
+ "STACKABLE_UNIT_AMOUNT_ERROR",
3316
+ "STACKABLE_UNIT_DECIMALS_ERROR",
3317
+ "TRANSFER_BALANCE_ERROR",
3318
+ "TRANSFER_MALFORMED_ERROR",
3319
+ "TRANSFER_MISMATCHED_ERROR",
3320
+ "TRANSFER_REMAINDER_ERROR",
3321
+ "TRANSFER_TO_SELF_ERROR",
3322
+ "TRANSFER_UNBALANCED_ERROR",
3323
+ "UNAUTHENTICATED_ERROR",
3324
+ "WALLET_CREDENTIAL_ERROR",
3325
+ "WALLET_SHADOW_ERROR",
3326
+ "WRONG_TOKEN_TYPE_ERROR"
3327
+ ];
3328
+ var QUERY_TYPES = [
3329
+ "Balance",
3330
+ "WalletBundle",
3331
+ "WalletList",
3332
+ "Atom",
3333
+ "MetaType",
3334
+ "MetaTypeViaAtom",
3335
+ "ContinuId",
3336
+ "Batch",
3337
+ "ActiveSession",
3338
+ "Policy",
3339
+ "Token",
3340
+ "UserActivity"
3341
+ ];
3342
+ function createLookup(values) {
3343
+ return values.reduce((acc, value) => {
3344
+ acc[value] = value;
3345
+ return acc;
3346
+ }, {});
3347
+ }
3348
+ var ISOTOPE_LOOKUP = createLookup(ISOTOPES);
3349
+ createLookup(ERROR_TYPES);
3350
+ createLookup(QUERY_TYPES);
3351
+
2767
3352
  // src/types/index.ts
2768
3353
  function isHexString(value) {
2769
3354
  return /^[0-9a-fA-F]+$/.test(value);
@@ -2842,17 +3427,8 @@ var Wallet = class _Wallet {
2842
3427
  batchId = null,
2843
3428
  characters = null
2844
3429
  } = {}) {
2845
- if (address !== null && !isWalletAddress2(address)) {
2846
- throw new WalletCredentialException("Invalid wallet address format");
2847
- }
2848
- if (bundle !== null && !isBundleHash(bundle)) {
2849
- throw new WalletCredentialException("Invalid bundle hash format");
2850
- }
2851
- if (position !== null && !isPosition2(position)) {
2852
- throw new WalletCredentialException("Invalid position format");
2853
- }
2854
3430
  this.token = token;
2855
- this.balance = 0;
3431
+ this.balance = "0";
2856
3432
  this.molecules = {};
2857
3433
  this.key = null;
2858
3434
  this.privkey = null;
@@ -2914,8 +3490,10 @@ var Wallet = class _Wallet {
2914
3490
  token,
2915
3491
  position
2916
3492
  }) {
2917
- const bigIntSecret = BigInt(`0x${secret}`);
2918
- const indexedKey = bigIntSecret + BigInt(`0x${position}`);
3493
+ const secretHex = isHex(secret) ? secret : shake256(secret, 1024);
3494
+ const positionHex = isHex(position) ? position : shake256(position, 256);
3495
+ const bigIntSecret = BigInt(`0x${secretHex}`);
3496
+ const indexedKey = bigIntSecret + BigInt(`0x${positionHex}`);
2919
3497
  const intermediateKeySponge = new JsSHA("SHAKE256", "TEXT");
2920
3498
  intermediateKeySponge.update(indexedKey.toString(16));
2921
3499
  if (token) {
@@ -3040,7 +3618,7 @@ var Wallet = class _Wallet {
3040
3618
  * Initializes the ML-KEM key pair (matches JavaScript SDK exactly)
3041
3619
  */
3042
3620
  initializeMLKEM() {
3043
- const seedHex = generateSecret(this.key, 64);
3621
+ const seedHex = generateSecret(this.key, 128);
3044
3622
  const seed = new Uint8Array(64);
3045
3623
  for (let i = 0; i < 64; i++) {
3046
3624
  seed[i] = parseInt(seedHex.substr(i * 2, 2), 16);
@@ -3158,287 +3736,632 @@ var Wallet = class _Wallet {
3158
3736
  return new Uint8Array([...binaryString].map((char) => char.charCodeAt(0)));
3159
3737
  }
3160
3738
  };
3739
+ var hexStringRegex = /^[0-9a-fA-F]+$/;
3740
+ var base17HashRegex = /^[0-9a-g]+$/;
3741
+ z.string().regex(hexStringRegex, "Must be a valid hexadecimal string").brand();
3742
+ var WalletAddressSchema = z.string().regex(hexStringRegex, "Wallet address must be hexadecimal").length(64, "Wallet address must be exactly 64 characters").brand();
3743
+ var BundleHashSchema = z.string().regex(hexStringRegex, "Bundle hash must be hexadecimal").length(64, "Bundle hash must be exactly 64 characters").brand();
3744
+ var PositionSchema = z.string().regex(hexStringRegex, "Position must be hexadecimal").length(64, "Position must be exactly 64 characters").brand();
3745
+ z.string().regex(base17HashRegex, "Molecular hash must be base17 format (0-9,a-g)").min(1, "Molecular hash cannot be empty").brand();
3746
+ var TokenSlugSchema = z.string().min(1, "Token slug cannot be empty").max(64, "Token slug cannot exceed 64 characters").transform((val) => val.toUpperCase()).brand();
3747
+ var MetaTypeSchema = z.string().min(1, "Meta type cannot be empty").max(256, "Meta type cannot exceed 256 characters").brand();
3748
+ var MetaIdSchema = z.string().min(1, "Meta ID cannot be empty").brand();
3749
+ var BatchIdSchema = z.string().min(1, "Batch ID cannot be empty").brand();
3750
+ var CellSlugSchema = z.string().min(1, "Cell slug cannot be empty").max(64, "Cell slug cannot exceed 64 characters").brand();
3751
+ var AtomIsotopeSchema = z.enum(["C", "V", "U", "T", "M", "I", "R", "B", "F"], {
3752
+ errorMap: () => ({ message: "Invalid atom isotope. Must be one of: C, V, U, T, M, I, R, B, F" })
3753
+ });
3754
+ var MetaDataValueSchema = z.union([
3755
+ z.string(),
3756
+ z.number(),
3757
+ z.boolean(),
3758
+ z.null()
3759
+ ]);
3760
+ var AtomMetaDataSchema = z.object({
3761
+ key: z.string().min(1, "Meta key cannot be empty"),
3762
+ value: MetaDataValueSchema
3763
+ }).strict();
3764
+ var MetaDataSchema = z.lazy(
3765
+ () => z.record(z.union([
3766
+ MetaDataValueSchema,
3767
+ MetaDataSchema,
3768
+ z.array(MetaDataSchema)
3769
+ ]))
3770
+ );
3771
+ z.object({
3772
+ position: z.union([z.string(), z.null()]).optional(),
3773
+ walletAddress: z.union([WalletAddressSchema, z.string(), z.null()]).optional(),
3774
+ isotope: AtomIsotopeSchema.optional(),
3775
+ token: z.union([TokenSlugSchema, z.string()]).optional(),
3776
+ value: z.union([z.string(), z.number(), z.null()]).optional(),
3777
+ batchId: z.union([BatchIdSchema, z.string(), z.null()]).optional(),
3778
+ metaType: z.union([MetaTypeSchema, z.string(), z.null()]).optional(),
3779
+ metaId: z.union([MetaIdSchema, z.string(), z.null()]).optional(),
3780
+ meta: z.union([z.array(AtomMetaDataSchema), z.null()]).optional(),
3781
+ otsFragment: z.union([z.string(), z.null()]).optional(),
3782
+ index: z.union([z.number().int().min(0), z.null()]).optional(),
3783
+ createdAt: z.union([z.string(), z.null()]).optional(),
3784
+ version: z.union([z.number().int().min(1), z.null()]).optional()
3785
+ }).strict();
3786
+ var WalletParamsSchema = z.object({
3787
+ secret: z.union([z.string(), z.null()]).optional(),
3788
+ bundle: z.union([BundleHashSchema, z.string(), z.null()]).optional(),
3789
+ token: z.union([TokenSlugSchema, z.string()]).optional(),
3790
+ address: z.union([WalletAddressSchema, z.string(), z.null()]).optional(),
3791
+ position: z.union([PositionSchema, z.string(), z.null()]).optional(),
3792
+ batchId: z.union([BatchIdSchema, z.string(), z.null()]).optional(),
3793
+ characters: z.union([z.string(), z.null()]).optional()
3794
+ }).strict();
3795
+ z.object({
3796
+ secret: z.union([z.string(), z.null()]).optional(),
3797
+ bundle: z.union([BundleHashSchema, z.string(), z.null()]).optional(),
3798
+ sourceWallet: z.union([WalletParamsSchema, z.null()]).optional(),
3799
+ remainderWallet: z.union([WalletParamsSchema, z.null()]).optional(),
3800
+ cellSlug: z.union([CellSlugSchema, z.string(), z.null()]).optional(),
3801
+ version: z.number().int().min(1).optional()
3802
+ }).strict();
3803
+ z.object({
3804
+ uri: z.union([z.string().url(), z.array(z.string().url())]).optional(),
3805
+ cellSlug: z.union([CellSlugSchema, z.string(), z.null()]).optional(),
3806
+ client: z.unknown().optional(),
3807
+ socket: z.unknown().optional(),
3808
+ serverSdkVersion: z.number().int().min(1).optional(),
3809
+ logging: z.boolean().optional()
3810
+ }).strict();
3811
+ z.object({
3812
+ token: z.string().min(1, "Auth token cannot be empty"),
3813
+ expiresAt: z.number().int().min(0, "Expiration time must be positive"),
3814
+ encrypt: z.boolean(),
3815
+ pubkey: z.string().min(1, "Public key cannot be empty")
3816
+ }).strict();
3817
+ z.object({
3818
+ cellSlug: z.union([CellSlugSchema, z.string(), z.null()]).optional(),
3819
+ encrypt: z.boolean().optional(),
3820
+ callback: z.function().args(z.unknown()).returns(z.void()).optional()
3821
+ }).strict();
3822
+ z.object({
3823
+ cellSlug: z.union([CellSlugSchema, z.string(), z.null()]).optional()
3824
+ }).strict();
3825
+ z.object({
3826
+ recipient: z.union([WalletAddressSchema, z.string()]),
3827
+ amount: z.union([z.number().positive(), z.string().min(1)]),
3828
+ token: z.union([TokenSlugSchema, z.string()]).optional(),
3829
+ callbackUrl: z.union([z.string().url(), z.null()]).optional(),
3830
+ metaType: z.union([MetaTypeSchema, z.string(), z.null()]).optional(),
3831
+ metaId: z.union([MetaIdSchema, z.string(), z.null()]).optional(),
3832
+ meta: z.union([MetaDataSchema, z.null()]).optional()
3833
+ }).strict();
3834
+ z.object({
3835
+ token: z.union([TokenSlugSchema, z.string()]),
3836
+ amount: z.union([z.number().positive(), z.string().min(1)]),
3837
+ metaType: z.union([MetaTypeSchema, z.string(), z.null()]).optional(),
3838
+ metaId: z.union([MetaIdSchema, z.string(), z.null()]).optional(),
3839
+ meta: z.union([MetaDataSchema, z.null()]).optional(),
3840
+ fungible: z.boolean().optional(),
3841
+ splittable: z.number().int().min(0).optional(),
3842
+ supplyToken: z.union([TokenSlugSchema, z.string(), z.null()]).optional()
3843
+ }).strict();
3844
+ z.object({
3845
+ amount: z.union([z.number().positive(), z.string().min(1)]),
3846
+ token: z.union([TokenSlugSchema, z.string()]).optional(),
3847
+ metaType: z.union([MetaTypeSchema, z.string(), z.null()]).optional(),
3848
+ metaId: z.union([MetaIdSchema, z.string(), z.null()]).optional(),
3849
+ meta: z.union([MetaDataSchema, z.null()]).optional()
3850
+ }).strict();
3851
+ var MetaFilterSchema = z.object({
3852
+ key: z.string(),
3853
+ value: z.string(),
3854
+ comparison: z.string().optional(),
3855
+ criterion: z.string().optional()
3856
+ }).strict();
3857
+ z.object({
3858
+ address: z.union([WalletAddressSchema, z.string(), z.null()]).optional(),
3859
+ bundleHash: z.union([BundleHashSchema, z.string(), z.null()]).optional(),
3860
+ token: z.union([TokenSlugSchema, z.string(), z.null()]).optional(),
3861
+ type: z.enum(["token", "user"]).nullable().optional()
3862
+ }).strict();
3863
+ z.object({
3864
+ metaType: z.union([MetaTypeSchema, z.string()]),
3865
+ metaId: z.union([MetaIdSchema, z.string(), z.null()]).optional(),
3866
+ key: z.union([z.string(), z.null()]).optional(),
3867
+ value: z.union([z.string(), z.null()]).optional(),
3868
+ latest: z.union([z.boolean(), z.null()]).optional(),
3869
+ filter: z.union([z.array(MetaFilterSchema), z.null()]).optional(),
3870
+ queryArgs: z.union([z.record(z.unknown()), z.null()]).optional(),
3871
+ count: z.union([z.number().int().min(1), z.null()]).optional(),
3872
+ countBy: z.union([z.string(), z.null()]).optional(),
3873
+ cellSlug: z.union([CellSlugSchema, z.string(), z.null()]).optional()
3874
+ }).strict();
3875
+ z.object({
3876
+ bundleHash: z.union([BundleHashSchema, z.string(), z.null()]).optional(),
3877
+ tokenSlug: z.union([TokenSlugSchema, z.string(), z.null()]).optional(),
3878
+ unspent: z.union([z.boolean(), z.null()]).optional()
3879
+ }).strict();
3880
+ z.object({
3881
+ seed: z.union([z.string(), z.null()]).optional(),
3882
+ length: z.number().int().min(1).optional(),
3883
+ outputLength: z.number().int().min(1).optional()
3884
+ }).strict();
3885
+ z.object({
3886
+ privateKey: z.string().min(1, "Private key cannot be empty"),
3887
+ publicKey: z.string().min(1, "Public key cannot be empty")
3888
+ }).strict();
3889
+ z.object({
3890
+ signature: z.string().min(1, "Signature cannot be empty"),
3891
+ otsFragments: z.array(z.string()).optional()
3892
+ }).strict();
3893
+ z.object({
3894
+ query: z.string().min(1, "GraphQL query cannot be empty"),
3895
+ variables: z.record(z.unknown()).optional(),
3896
+ operationName: z.union([z.string(), z.null()]).optional()
3897
+ }).strict();
3898
+ var GraphQLErrorSchema = z.object({
3899
+ message: z.string(),
3900
+ locations: z.array(z.object({
3901
+ line: z.number().int().min(1),
3902
+ column: z.number().int().min(1)
3903
+ })).optional(),
3904
+ path: z.array(z.union([z.string(), z.number()])).optional(),
3905
+ extensions: z.record(z.unknown()).optional()
3906
+ }).strict();
3907
+ z.object({
3908
+ data: z.unknown().optional(),
3909
+ errors: z.array(GraphQLErrorSchema).nullable().optional(),
3910
+ extensions: z.record(z.unknown()).optional()
3911
+ }).strict();
3912
+ z.object({
3913
+ operationName: z.string().optional(),
3914
+ query: z.string().optional(),
3915
+ variables: z.record(z.unknown()).optional(),
3916
+ callback: z.function().args(z.unknown()).returns(z.void()).optional()
3917
+ }).strict();
3918
+ z.object({
3919
+ valid: z.boolean(),
3920
+ error: z.union([z.string(), z.null()]).optional(),
3921
+ expected: z.string().optional(),
3922
+ actual: z.unknown().optional()
3923
+ }).strict();
3924
+ z.object({
3925
+ operation: z.string().optional(),
3926
+ parameters: z.record(z.unknown()).optional(),
3927
+ timestamp: z.number().int().min(0).optional(),
3928
+ stack: z.string().optional()
3929
+ }).strict();
3930
+ z.enum([
3931
+ "ATOM_INDEX_ERROR",
3932
+ "ATOMS_MISSING_ERROR",
3933
+ "AUTHORIZATION_REJECTED_ERROR",
3934
+ "BALANCE_INSUFFICIENT_ERROR",
3935
+ "BATCH_ID_ERROR",
3936
+ "CODE_ERROR",
3937
+ "DECRYPTION_KEY_ERROR",
3938
+ "INVALID_RESPONSE_ERROR",
3939
+ "META_MISSING_ERROR",
3940
+ "MOLECULAR_HASH_MISMATCH_ERROR",
3941
+ "MOLECULAR_HASH_MISSING_ERROR",
3942
+ "NEGATIVE_AMOUNT_ERROR",
3943
+ "POLICY_INVALID_ERROR",
3944
+ "SIGNATURE_MALFORMED_ERROR",
3945
+ "SIGNATURE_MISMATCH_ERROR",
3946
+ "STACKABLE_UNIT_AMOUNT_ERROR",
3947
+ "STACKABLE_UNIT_DECIMALS_ERROR",
3948
+ "TRANSFER_BALANCE_ERROR",
3949
+ "TRANSFER_MALFORMED_ERROR",
3950
+ "TRANSFER_MISMATCHED_ERROR",
3951
+ "TRANSFER_REMAINDER_ERROR",
3952
+ "TRANSFER_TO_SELF_ERROR",
3953
+ "TRANSFER_UNBALANCED_ERROR",
3954
+ "UNAUTHENTICATED_ERROR",
3955
+ "WALLET_CREDENTIAL_ERROR",
3956
+ "WALLET_SHADOW_ERROR",
3957
+ "WRONG_TOKEN_TYPE_ERROR"
3958
+ ]);
3959
+ function parseWithSchema(schema, data, context) {
3960
+ const result = schema.safeParse(data);
3961
+ if (!result.success) {
3962
+ const errorMessage = context ? `${context}: ${result.error.message}` : result.error.message;
3963
+ throw new Error(errorMessage);
3964
+ }
3965
+ return result.data;
3966
+ }
3161
3967
 
3162
- // src/libraries/CheckMolecule.ts
3163
- init_exception();
3164
-
3165
- // src/core/Meta.ts
3166
- var Meta = class {
3167
- // No instance properties - this class only provides static methods
3968
+ // src/instance/rules/Meta.ts
3969
+ var Meta2 = class _Meta {
3970
+ __data = /* @__PURE__ */ new Map();
3971
+ constructor(args = {}) {
3972
+ const validatedArgs = parseWithSchema(MetaDataSchema, args, "Meta constructor");
3973
+ for (const [key, value] of Object.entries(validatedArgs)) {
3974
+ this.__data.set(`__${key}`, value);
3975
+ }
3976
+ }
3168
3977
  /**
3169
- * Normalize metadata to consistent format
3170
- * Matches JavaScript SDK Meta.normalizeMeta exactly
3978
+ * Creates a Meta object from a plain object with runtime validation
3171
3979
  */
3172
- static normalizeMeta(meta) {
3173
- if (!meta) {
3174
- return [];
3175
- }
3176
- if (Array.isArray(meta)) {
3177
- return meta.map((item) => {
3178
- if (typeof item === "object" && item !== null && "key" in item) {
3179
- return {
3180
- ...item,
3181
- key: String(item.key),
3182
- value: item.value
3183
- };
3184
- }
3185
- return {
3186
- key: "unknown",
3187
- value: String(item)
3188
- };
3189
- });
3190
- }
3191
- if (typeof meta === "object" && meta !== null) {
3192
- return Object.entries(meta).map(([key, value]) => ({
3193
- key,
3194
- value
3195
- }));
3196
- }
3197
- return [{
3198
- key: "value",
3199
- value: meta
3200
- }];
3980
+ static toObject(object) {
3981
+ return new _Meta(object);
3201
3982
  }
3202
3983
  /**
3203
- * Aggregate metadata into single object
3204
- * Matches JavaScript SDK Meta.aggregateMeta exactly
3984
+ * Gets a metadata value by key
3205
3985
  */
3206
- static aggregateMeta(metaItems) {
3207
- if (!metaItems || !Array.isArray(metaItems)) {
3208
- return {};
3209
- }
3210
- const aggregated = {};
3211
- for (const item of metaItems) {
3212
- if (item && typeof item === "object" && "key" in item) {
3213
- const key = String(item.key);
3214
- if ("value" in item) {
3215
- aggregated[key] = item.value;
3216
- } else {
3217
- const { key: itemKey, ...restOfItem } = item;
3218
- aggregated[key] = Object.keys(restOfItem).length === 1 && "value" in restOfItem ? restOfItem.value : restOfItem;
3219
- }
3220
- }
3221
- }
3222
- return aggregated;
3986
+ get(key) {
3987
+ return this.__data.get(`__${String(key)}`);
3223
3988
  }
3224
3989
  /**
3225
- * Merge multiple metadata arrays
3226
- * Combines arrays while preserving order and handling duplicates
3990
+ * Sets a metadata value by key
3227
3991
  */
3228
- static mergeMeta(...metaArrays) {
3229
- const merged = [];
3230
- const keysSeen = /* @__PURE__ */ new Set();
3231
- for (const metaArray of metaArrays) {
3232
- if (!metaArray || !Array.isArray(metaArray)) {
3233
- continue;
3234
- }
3235
- const normalized = this.normalizeMeta(metaArray);
3236
- for (const item of normalized) {
3237
- let finalKey = item.key;
3238
- let counter = 1;
3239
- while (keysSeen.has(finalKey)) {
3240
- finalKey = `${item.key}_${counter}`;
3241
- counter++;
3242
- }
3243
- keysSeen.add(finalKey);
3244
- merged.push({
3245
- ...item,
3246
- key: finalKey
3247
- });
3248
- }
3249
- }
3250
- return merged;
3992
+ set(key, value) {
3993
+ this.__data.set(`__${String(key)}`, value);
3251
3994
  }
3252
3995
  /**
3253
- * Filter metadata by key pattern or predicate
3996
+ * Checks if a key exists
3254
3997
  */
3255
- static filterMeta(metaItems, filter) {
3256
- if (!metaItems || !Array.isArray(metaItems)) {
3257
- return [];
3258
- }
3259
- const normalized = this.normalizeMeta(metaItems);
3260
- if (typeof filter === "string") {
3261
- return normalized.filter((item) => item.key.includes(filter));
3262
- }
3263
- if (filter instanceof RegExp) {
3264
- return normalized.filter((item) => filter.test(item.key));
3265
- }
3266
- if (typeof filter === "function") {
3267
- return normalized.filter(filter);
3268
- }
3269
- return normalized;
3998
+ has(key) {
3999
+ return this.__data.has(`__${String(key)}`);
3270
4000
  }
3271
4001
  /**
3272
- * Find metadata item by key
4002
+ * Gets all keys
3273
4003
  */
3274
- static findMeta(metaItems, key) {
3275
- if (!metaItems || !Array.isArray(metaItems)) {
3276
- return null;
4004
+ keys() {
4005
+ return Array.from(this.__data.keys()).map(
4006
+ (key) => key.startsWith("__") ? key.substring(2) : key
4007
+ );
4008
+ }
4009
+ /**
4010
+ * Converts Meta object back to plain object
4011
+ */
4012
+ toJSON() {
4013
+ const object = {};
4014
+ for (const [key, value] of this.__data.entries()) {
4015
+ if (key.startsWith("__")) {
4016
+ const plainKey = key.substring(2);
4017
+ object[plainKey] = value;
4018
+ }
3277
4019
  }
3278
- const normalized = this.normalizeMeta(metaItems);
3279
- return normalized.find((item) => item.key === key) || null;
4020
+ return object;
3280
4021
  }
3281
4022
  /**
3282
- * Get metadata value by key
4023
+ * Creates a typed copy of this Meta object
3283
4024
  */
3284
- static getMetaValue(metaItems, key, defaultValue = null) {
3285
- const item = this.findMeta(metaItems, key);
3286
- return item ? item.value : defaultValue;
4025
+ clone() {
4026
+ return new _Meta(this.toJSON());
3287
4027
  }
3288
4028
  /**
3289
- * Set or update metadata item by key
4029
+ * Merges another Meta object into this one
3290
4030
  */
3291
- static setMeta(metaItems, key, value) {
3292
- const normalized = this.normalizeMeta(metaItems);
3293
- const existingIndex = normalized.findIndex((item) => item.key === key);
3294
- const newItem = {
3295
- key,
3296
- value
3297
- };
3298
- if (existingIndex >= 0) {
3299
- normalized[existingIndex] = newItem;
3300
- } else {
3301
- normalized.push(newItem);
3302
- }
3303
- return normalized;
4031
+ merge(other) {
4032
+ const combined = { ...this.toJSON(), ...other.toJSON() };
4033
+ return new _Meta(combined);
3304
4034
  }
3305
4035
  /**
3306
- * Remove metadata item by key
4036
+ * Type-safe iteration over metadata entries
3307
4037
  */
3308
- static removeMeta(metaItems, key) {
3309
- if (!metaItems || !Array.isArray(metaItems)) {
3310
- return [];
4038
+ forEach(callback) {
4039
+ for (const [key, value] of this.__data.entries()) {
4040
+ if (key.startsWith("__")) {
4041
+ const plainKey = key.substring(2);
4042
+ callback(value, plainKey);
4043
+ }
3311
4044
  }
3312
- const normalized = this.normalizeMeta(metaItems);
3313
- return normalized.filter((item) => item.key !== key);
3314
4045
  }
3315
4046
  /**
3316
- * Convert metadata to JSON-serializable format
4047
+ * Returns the size of the metadata object
3317
4048
  */
3318
- static toJSON(metaItems) {
3319
- return this.aggregateMeta(this.normalizeMeta(metaItems));
4049
+ get size() {
4050
+ return this.__data.size;
3320
4051
  }
3321
4052
  /**
3322
- * Create metadata from JSON object
4053
+ * Clears all metadata
3323
4054
  */
3324
- static fromJSON(jsonData) {
3325
- if (!jsonData || typeof jsonData !== "object") {
3326
- return [];
3327
- }
3328
- return Object.entries(jsonData).map(([key, value]) => ({
3329
- key,
3330
- value
3331
- }));
4055
+ clear() {
4056
+ this.__data.clear();
3332
4057
  }
4058
+ };
4059
+
4060
+ // src/instance/rules/exception/RuleArgumentException.ts
4061
+ init_BaseException();
4062
+ var RuleArgumentException = class extends BaseException {
3333
4063
  /**
3334
- * Validate metadata structure
4064
+ * Constructor
3335
4065
  */
3336
- static validateMeta(metaItems) {
3337
- if (!Array.isArray(metaItems)) {
3338
- return false;
4066
+ constructor(message = "An incorrect argument!") {
4067
+ super("RULE_ARGUMENT_ERROR", message);
4068
+ }
4069
+ };
4070
+ var RuleArgumentException_default = RuleArgumentException;
4071
+
4072
+ // src/libraries/array.ts
4073
+ function deepCloning(o, h) {
4074
+ let i;
4075
+ let r;
4076
+ let x;
4077
+ const t = [Array, Date, Number, String, Boolean];
4078
+ const s = Object.prototype.toString;
4079
+ h = h || [];
4080
+ for (i = 0; i < h.length; i += 2) {
4081
+ if (o === h[i]) {
4082
+ return h[i + 1];
3339
4083
  }
3340
- return metaItems.every(
3341
- (item) => item && typeof item === "object" && "key" in item && typeof item.key === "string"
3342
- );
3343
4084
  }
3344
- /**
3345
- * Get all unique keys from metadata
3346
- */
3347
- static getKeys(metaItems) {
3348
- if (!metaItems || !Array.isArray(metaItems)) {
3349
- return [];
4085
+ if (!r && o && typeof o === "object") {
4086
+ r = {};
4087
+ for (i = 0; i < t.length; i++) {
4088
+ if (s.call(o) === s.call(x = new t[i](o))) {
4089
+ r = i ? x : [];
4090
+ }
3350
4091
  }
3351
- const normalized = this.normalizeMeta(metaItems);
3352
- const keys = /* @__PURE__ */ new Set();
3353
- for (const item of normalized) {
3354
- keys.add(item.key);
4092
+ h.push(o, r);
4093
+ for (i in o) {
4094
+ if (Object.prototype.hasOwnProperty.call(o, i)) {
4095
+ r[i] = deepCloning(o[i], h);
4096
+ }
3355
4097
  }
3356
- return Array.from(keys);
4098
+ }
4099
+ return r || o;
4100
+ }
4101
+ function chunkArray(arr, size) {
4102
+ if (!arr.length) {
4103
+ return [];
4104
+ }
4105
+ return [arr.slice(0, size)].concat(chunkArray(arr.slice(size), size));
4106
+ }
4107
+ function diff(...arrays) {
4108
+ return [].concat(...arrays.map((arr, i) => {
4109
+ const others = arrays.slice(0);
4110
+ others.splice(i, 1);
4111
+ const unique = [...new Set([].concat(...others))];
4112
+ return arr.filter((item) => !unique.includes(item));
4113
+ }));
4114
+ }
4115
+ function intersect(...arrays) {
4116
+ if (arrays.length === 0) return [];
4117
+ if (arrays.length === 1) return arrays[0];
4118
+ return arrays.reduce(
4119
+ (first, second) => first.filter((item) => second.includes(item))
4120
+ );
4121
+ }
4122
+
4123
+ // src/instance/rules/Callback.ts
4124
+ init_exception();
4125
+ var CallbackParamsSchema = z.object({
4126
+ action: z.string().min(1, "Action cannot be empty"),
4127
+ metaType: z.union([z.string(), z.null()]).optional(),
4128
+ metaId: z.union([z.string(), z.null()]).optional(),
4129
+ meta: z.union([z.instanceof(Meta2), z.record(z.unknown()), z.null()]).optional(),
4130
+ address: z.union([z.string(), z.null()]).optional(),
4131
+ token: z.union([z.string(), z.null()]).optional(),
4132
+ amount: z.union([z.string(), z.null()]).optional(),
4133
+ comparison: z.union([z.string(), z.null()]).optional()
4134
+ }).strict();
4135
+ var Callback = class _Callback {
4136
+ __action;
4137
+ __metaType;
4138
+ __metaId;
4139
+ __meta;
4140
+ __address;
4141
+ __token;
4142
+ __amount;
4143
+ __comparison;
4144
+ constructor(params) {
4145
+ const validatedParams = parseWithSchema(CallbackParamsSchema, params, "Callback constructor");
4146
+ if (!validatedParams.action) {
4147
+ throw new RuleArgumentException_default('Callback structure violated, missing mandatory "action" parameter.');
4148
+ }
4149
+ this.__action = validatedParams.action;
4150
+ this.__metaType = validatedParams.metaType ?? null;
4151
+ this.__metaId = validatedParams.metaId ?? null;
4152
+ this.__address = validatedParams.address ?? null;
4153
+ this.__token = validatedParams.token ?? null;
4154
+ this.__amount = validatedParams.amount ?? null;
4155
+ this.__comparison = validatedParams.comparison ?? null;
4156
+ if (validatedParams.meta) {
4157
+ this.__meta = validatedParams.meta instanceof Meta2 ? validatedParams.meta : Meta2.toObject(validatedParams.meta);
4158
+ }
4159
+ }
4160
+ // Setters
4161
+ set comparison(comparison) {
4162
+ this.__comparison = comparison;
4163
+ }
4164
+ set amount(amount) {
4165
+ if (!isNumeric(amount)) {
4166
+ throw new CodeException("Parameter amount should be a string containing numbers");
4167
+ }
4168
+ this.__amount = amount;
4169
+ }
4170
+ set token(token) {
4171
+ this.__token = token;
4172
+ }
4173
+ set address(address) {
4174
+ this.__address = address;
4175
+ }
4176
+ set meta(meta) {
4177
+ this.__meta = meta instanceof Meta2 ? meta : Meta2.toObject(meta);
4178
+ }
4179
+ set metaType(metaType) {
4180
+ this.__metaType = metaType;
4181
+ }
4182
+ set metaId(metaId) {
4183
+ this.__metaId = metaId;
3357
4184
  }
3358
4185
  /**
3359
- * Check if metadata contains specific key
4186
+ * Creates a Callback from a plain object with validation
3360
4187
  */
3361
- static hasKey(metaItems, key) {
3362
- return this.getKeys(metaItems).includes(key);
4188
+ static toObject(object) {
4189
+ return new _Callback(object);
3363
4190
  }
3364
4191
  /**
3365
- * Get metadata statistics
4192
+ * Converts to JSON representation
3366
4193
  */
3367
- static getStats(metaItems) {
3368
- if (!metaItems || !Array.isArray(metaItems)) {
3369
- return {
3370
- totalItems: 0,
3371
- uniqueKeys: 0,
3372
- keys: [],
3373
- valueTypes: {}
3374
- };
4194
+ toJSON() {
4195
+ const meta = {
4196
+ action: this.__action
4197
+ };
4198
+ if (this.__metaType) {
4199
+ meta.metaType = this.__metaType;
3375
4200
  }
3376
- const normalized = this.normalizeMeta(metaItems);
3377
- const keys = this.getKeys(normalized);
3378
- const valueTypes = {};
3379
- for (const item of normalized) {
3380
- const type = item.value === null ? "null" : typeof item.value;
3381
- valueTypes[type] = (valueTypes[type] || 0) + 1;
4201
+ if (this.__metaId) {
4202
+ meta.metaId = this.__metaId;
3382
4203
  }
3383
- return {
3384
- totalItems: normalized.length,
3385
- uniqueKeys: keys.length,
3386
- keys,
3387
- valueTypes
3388
- };
4204
+ if (this.__meta) {
4205
+ meta.meta = this.__meta.toJSON();
4206
+ }
4207
+ if (this.__address) {
4208
+ meta.address = this.__address;
4209
+ }
4210
+ if (this.__token) {
4211
+ meta.token = this.__token;
4212
+ }
4213
+ if (this.__amount) {
4214
+ meta.amount = this.__amount;
4215
+ }
4216
+ if (this.__comparison) {
4217
+ meta.comparison = this.__comparison;
4218
+ }
4219
+ return meta;
4220
+ }
4221
+ // Action type checkers using discriminated unions
4222
+ isReject() {
4223
+ return this._is("reject");
4224
+ }
4225
+ isMeta() {
4226
+ const prop = intersect(Object.keys(this.toJSON()), ["action", "metaId", "metaType", "meta"]);
4227
+ return prop.length === 4 && this._is("meta");
4228
+ }
4229
+ isCollect() {
4230
+ const prop = intersect(Object.keys(this.toJSON()), ["action", "address", "token", "amount", "comparison"]);
4231
+ return prop.length === 5 && this._is("collect");
4232
+ }
4233
+ isBuffer() {
4234
+ const prop = intersect(Object.keys(this.toJSON()), ["action", "address", "token", "amount", "comparison"]);
4235
+ return prop.length === 5 && this._is("buffer");
4236
+ }
4237
+ isRemit() {
4238
+ const prop = intersect(Object.keys(this.toJSON()), ["action", "token", "amount"]);
4239
+ return prop.length === 3 && this._is("remit");
4240
+ }
4241
+ isBurn() {
4242
+ const prop = intersect(Object.keys(this.toJSON()), ["action", "token", "amount", "comparison"]);
4243
+ return prop.length === 4 && this._is("burn");
3389
4244
  }
3390
4245
  /**
3391
- * Deep clone metadata array
4246
+ * Private helper to check action type with type narrowing
3392
4247
  */
3393
- static clone(metaItems) {
3394
- if (!metaItems || !Array.isArray(metaItems)) {
3395
- return [];
3396
- }
3397
- const normalized = this.normalizeMeta(metaItems);
3398
- return normalized.map((item) => ({ ...item }));
4248
+ _is(type) {
4249
+ return this.__action.toLowerCase() === type.toLowerCase();
3399
4250
  }
3400
4251
  /**
3401
- * Sort metadata by key
4252
+ * Type-safe getter for action
3402
4253
  */
3403
- static sort(metaItems, descending = false) {
3404
- if (!metaItems || !Array.isArray(metaItems)) {
3405
- return [];
3406
- }
3407
- const normalized = this.normalizeMeta(metaItems);
3408
- return normalized.sort((a, b) => {
3409
- const comparison = a.key.localeCompare(b.key);
3410
- return descending ? -comparison : comparison;
4254
+ get action() {
4255
+ return this.__action;
4256
+ }
4257
+ };
4258
+
4259
+ // src/instance/rules/Condition.ts
4260
+ var Condition = class {
4261
+ __key;
4262
+ __value;
4263
+ __comparison;
4264
+ constructor({ key, value, comparison }) {
4265
+ if ([key, value, comparison].some((item) => !item)) {
4266
+ throw new RuleArgumentException_default("Condition::constructor( { key, value, comparison } ) - not all class parameters are initialised!");
4267
+ }
4268
+ this.__key = key;
4269
+ this.__value = value;
4270
+ this.__comparison = comparison;
4271
+ }
4272
+ /**
4273
+ * Creates a Condition from a plain object
4274
+ */
4275
+ static toObject(object) {
4276
+ return new this({
4277
+ key: object.key,
4278
+ value: object.value,
4279
+ comparison: object.comparison
3411
4280
  });
3412
4281
  }
4282
+ /**
4283
+ * Converts to JSON representation
4284
+ */
4285
+ toJSON() {
4286
+ return {
4287
+ key: this.__key,
4288
+ value: this.__value,
4289
+ comparison: this.__comparison
4290
+ };
4291
+ }
3413
4292
  };
3414
4293
 
3415
4294
  // src/instance/rules/Rule.ts
4295
+ init_exception();
3416
4296
  var Rule = class _Rule {
3417
- name;
3418
- conditions;
3419
- actions;
3420
- constructor(data = {}) {
3421
- this.name = data.name || "";
3422
- this.conditions = data.conditions || [];
3423
- this.actions = data.actions || [];
4297
+ __condition;
4298
+ __callback;
4299
+ constructor({ condition = [], callback = [] }) {
4300
+ for (const element of condition) {
4301
+ if (!(element instanceof Condition)) {
4302
+ throw new RuleArgumentException_default();
4303
+ }
4304
+ }
4305
+ for (const element of callback) {
4306
+ if (!(element instanceof Callback)) {
4307
+ throw new RuleArgumentException_default();
4308
+ }
4309
+ }
4310
+ this.__condition = condition;
4311
+ this.__callback = callback;
4312
+ }
4313
+ /**
4314
+ * Adds a condition to this rule
4315
+ */
4316
+ set comparison(condition) {
4317
+ this.__condition.push(
4318
+ condition instanceof Condition ? condition : Condition.toObject(condition)
4319
+ );
4320
+ }
4321
+ /**
4322
+ * Adds a callback to this rule
4323
+ */
4324
+ set callback(callback) {
4325
+ this.__callback.push(
4326
+ callback instanceof Callback ? callback : Callback.toObject(callback)
4327
+ );
3424
4328
  }
3425
4329
  /**
3426
4330
  * Convert rule data to Rule object
3427
- * @param data - Rule data to convert
4331
+ * @param object - Rule data to convert
3428
4332
  * @return Rule instance
3429
4333
  */
3430
- static toObject(data) {
3431
- if (data instanceof _Rule) {
3432
- return data;
4334
+ static toObject(object) {
4335
+ if (!object.condition) {
4336
+ throw new MetaMissingException("Rule::toObject() - Incorrect rule format! There is no condition field.");
3433
4337
  }
3434
- return new _Rule(data);
4338
+ if (!object.callback) {
4339
+ throw new MetaMissingException("Rule::toObject() - Incorrect rule format! There is no callback field.");
4340
+ }
4341
+ const rule = new _Rule({});
4342
+ for (const condition of object.condition) {
4343
+ rule.comparison = condition;
4344
+ }
4345
+ for (const callback of object.callback) {
4346
+ rule.callback = callback;
4347
+ }
4348
+ return rule;
4349
+ }
4350
+ /**
4351
+ * Converts to JSON representation
4352
+ */
4353
+ toJSON() {
4354
+ return {
4355
+ condition: this.__condition,
4356
+ callback: this.__callback
4357
+ };
3435
4358
  }
3436
- // TODO: Implement remaining Rule methods
3437
4359
  };
3438
4360
 
3439
4361
  // src/libraries/CheckMolecule.ts
4362
+ init_exception();
3440
4363
  init_Dot();
3441
- var CheckMolecule = class {
4364
+ var CheckMolecule = class _CheckMolecule {
3442
4365
  molecule;
3443
4366
  /**
3444
4367
  * Initialize CheckMolecule with a molecule to validate
@@ -3718,7 +4641,7 @@ var CheckMolecule = class {
3718
4641
  if (Number.isNaN(firstValue)) {
3719
4642
  throw new TypeError('Invalid isotope "V" values');
3720
4643
  }
3721
- const remainder = senderWallet.balance + firstValue;
4644
+ const remainder = Number(senderWallet.balance) + firstValue;
3722
4645
  if (remainder < 0) {
3723
4646
  throw new TransferBalanceException();
3724
4647
  }
@@ -3793,6 +4716,77 @@ var CheckMolecule = class {
3793
4716
  }
3794
4717
  return true;
3795
4718
  }
4719
+ /**
4720
+ * Reconstructs a Molecule instance from server-side GraphQL data.
4721
+ * Maps server atom field names to SDK-expected format and parses metasJson.
4722
+ */
4723
+ static fromServerData({
4724
+ molecularHash,
4725
+ bundleHash,
4726
+ cellSlug = null,
4727
+ status = null,
4728
+ createdAt = null,
4729
+ atoms = []
4730
+ }) {
4731
+ const mappedAtoms = atoms.map((serverAtom) => {
4732
+ let meta = [];
4733
+ if (serverAtom.metasJson) {
4734
+ try {
4735
+ const parsed = JSON.parse(serverAtom.metasJson);
4736
+ if (Array.isArray(parsed)) {
4737
+ meta = parsed;
4738
+ } else if (parsed && typeof parsed === "object") {
4739
+ meta = Object.entries(parsed).map(([key, value]) => ({ key, value: String(value) }));
4740
+ }
4741
+ } catch (e) {
4742
+ meta = [];
4743
+ }
4744
+ }
4745
+ return {
4746
+ position: serverAtom.position || null,
4747
+ walletAddress: serverAtom.walletAddress || null,
4748
+ isotope: serverAtom.isotope || null,
4749
+ token: serverAtom.tokenSlug || serverAtom.token || null,
4750
+ value: serverAtom.value != null ? String(serverAtom.value) : null,
4751
+ batchId: serverAtom.batchId || null,
4752
+ metaType: serverAtom.metaType || null,
4753
+ metaId: serverAtom.metaId || null,
4754
+ meta,
4755
+ index: serverAtom.index != null ? serverAtom.index : null,
4756
+ otsFragment: serverAtom.otsFragment || null,
4757
+ createdAt: serverAtom.createdAt || null
4758
+ };
4759
+ });
4760
+ return Molecule.fromJSON({
4761
+ molecularHash,
4762
+ bundle: bundleHash,
4763
+ cellSlug,
4764
+ status,
4765
+ createdAt,
4766
+ atoms: mappedAtoms
4767
+ });
4768
+ }
4769
+ /**
4770
+ * Verifies a molecule reconstructed from server-side GraphQL data.
4771
+ * Returns an object with verification result and any error details.
4772
+ */
4773
+ static verifyFromServerData(moleculeData) {
4774
+ try {
4775
+ const molecule = _CheckMolecule.fromServerData(moleculeData);
4776
+ new _CheckMolecule(molecule).verify();
4777
+ return {
4778
+ molecularHash: moleculeData.molecularHash,
4779
+ verified: true,
4780
+ error: null
4781
+ };
4782
+ } catch (error) {
4783
+ return {
4784
+ molecularHash: moleculeData.molecularHash || null,
4785
+ verified: false,
4786
+ error: error.message || String(error)
4787
+ };
4788
+ }
4789
+ }
3796
4790
  };
3797
4791
 
3798
4792
  // src/core/Molecule.ts
@@ -3809,6 +4803,7 @@ var Molecule = class _Molecule {
3809
4803
  remainderWallet;
3810
4804
  atoms;
3811
4805
  version;
4806
+ parentHashes;
3812
4807
  local;
3813
4808
  /**
3814
4809
  * Create new Molecule instance
@@ -3830,10 +4825,10 @@ var Molecule = class _Molecule {
3830
4825
  this.bundle = bundle;
3831
4826
  this.sourceWallet = sourceWallet;
3832
4827
  this.atoms = [];
3833
- if (version !== null) {
4828
+ this.parentHashes = [];
4829
+ const versionRegistry = versions_default;
4830
+ if (version !== null && Object.prototype.hasOwnProperty.call(versionRegistry, version)) {
3834
4831
  this.version = String(version);
3835
- } else {
3836
- this.version = null;
3837
4832
  }
3838
4833
  if (remainderWallet || sourceWallet) {
3839
4834
  this.remainderWallet = remainderWallet || Wallet.create({
@@ -3868,7 +4863,7 @@ var Molecule = class _Molecule {
3868
4863
  if (!Array.isArray(isotopes)) {
3869
4864
  isotopes = [isotopes];
3870
4865
  }
3871
- return atoms.filter((atom) => isotopes.includes(atom.isotope));
4866
+ return atoms.filter((atom) => atom.isotope !== null && isotopes.includes(atom.isotope));
3872
4867
  }
3873
4868
  /**
3874
4869
  * Generates the next atomic index
@@ -3889,25 +4884,63 @@ var Molecule = class _Molecule {
3889
4884
  addAtom(atom) {
3890
4885
  this.molecularHash = null;
3891
4886
  atom.index = this.generateIndex();
3892
- atom.version = this.version ? Number(this.version) : 4;
4887
+ atom.version = this.version ?? void 0;
3893
4888
  this.atoms.push(atom);
3894
4889
  this.atoms = Atom.sortAtoms(this.atoms);
3895
4890
  return this;
3896
4891
  }
3897
4892
  /**
3898
4893
  * Add user remainder atom for ContinuID
4894
+ * Matches JavaScript SDK addContinuIdAtom exactly
3899
4895
  */
3900
4896
  addContinuIdAtom() {
3901
- if (!this.remainderWallet) {
3902
- throw new Error("Remainder wallet required for ContinuID atom");
4897
+ if (!this.remainderWallet || this.remainderWallet.token !== "USER") {
4898
+ this.remainderWallet = Wallet.create({
4899
+ secret: this.secret,
4900
+ bundle: this.bundle
4901
+ });
4902
+ }
4903
+ const continuIdMeta = {};
4904
+ if (this.sourceWallet && this.sourceWallet.position) {
4905
+ continuIdMeta.previousPosition = this.sourceWallet.position;
4906
+ }
4907
+ if (this.remainderWallet.pubkey) {
4908
+ continuIdMeta.pubkey = this.remainderWallet.pubkey;
4909
+ }
4910
+ if (this.remainderWallet.characters) {
4911
+ continuIdMeta.characters = this.remainderWallet.characters;
3903
4912
  }
3904
- this.addAtom(new Atom({
4913
+ this.addAtom(Atom.create({
3905
4914
  isotope: "I",
3906
- position: this.remainderWallet.position,
3907
- walletAddress: this.remainderWallet.address,
3908
- token: "USER",
4915
+ wallet: this.remainderWallet,
3909
4916
  metaType: "walletBundle",
3910
- metaId: this.remainderWallet.bundle
4917
+ metaId: this.remainderWallet.bundle,
4918
+ meta: new AtomMeta(continuIdMeta)
4919
+ }));
4920
+ return this;
4921
+ }
4922
+ /**
4923
+ * Add a policy R-isotope atom (matching JS SDK)
4924
+ */
4925
+ addPolicyAtom({
4926
+ metaType,
4927
+ metaId,
4928
+ meta = {},
4929
+ policy = {}
4930
+ }) {
4931
+ const atomMeta = new AtomMeta(meta);
4932
+ atomMeta.addPolicy(policy);
4933
+ const wallet = Wallet.create({
4934
+ secret: this.secret,
4935
+ bundle: this.sourceWallet.bundle,
4936
+ token: "USER"
4937
+ });
4938
+ this.addAtom(Atom.create({
4939
+ wallet,
4940
+ isotope: "R",
4941
+ metaType,
4942
+ metaId,
4943
+ meta: atomMeta
3911
4944
  }));
3912
4945
  return this;
3913
4946
  }
@@ -3922,34 +4955,25 @@ var Molecule = class _Molecule {
3922
4955
  if (!this.sourceWallet) {
3923
4956
  throw new Error("Source wallet required for value transfer");
3924
4957
  }
3925
- if (this.sourceWallet.balance - amount < 0) {
4958
+ if (Number(this.sourceWallet.balance) - amount < 0) {
3926
4959
  throw new BalanceInsufficientException();
3927
4960
  }
3928
- this.addAtom(new Atom({
4961
+ this.addAtom(Atom.create({
3929
4962
  isotope: "V",
3930
- position: this.sourceWallet.position,
3931
- walletAddress: this.sourceWallet.address,
3932
- token: this.sourceWallet.token,
3933
- value: -this.sourceWallet.balance
4963
+ wallet: this.sourceWallet,
4964
+ value: -Number(this.sourceWallet.balance)
3934
4965
  }));
3935
- this.addAtom(new Atom({
4966
+ this.addAtom(Atom.create({
3936
4967
  isotope: "V",
3937
- position: recipientWallet.position,
3938
- walletAddress: recipientWallet.address,
3939
- token: recipientWallet.token,
4968
+ wallet: recipientWallet,
3940
4969
  value: amount,
3941
4970
  metaType: "walletBundle",
3942
4971
  metaId: recipientWallet.bundle
3943
4972
  }));
3944
- if (!this.remainderWallet) {
3945
- throw new Error("Remainder wallet required for value transfer");
3946
- }
3947
- this.addAtom(new Atom({
4973
+ this.addAtom(Atom.create({
3948
4974
  isotope: "V",
3949
- position: this.remainderWallet.position,
3950
- walletAddress: this.remainderWallet.address,
3951
- token: this.remainderWallet.token,
3952
- value: this.sourceWallet.balance - amount,
4975
+ wallet: this.remainderWallet,
4976
+ value: Number(this.sourceWallet.balance) - amount,
3953
4977
  metaType: "walletBundle",
3954
4978
  metaId: this.remainderWallet.bundle
3955
4979
  }));
@@ -3978,6 +5002,17 @@ var Molecule = class _Molecule {
3978
5002
  throw new SignatureMalformedException("No atoms available for signing!");
3979
5003
  }
3980
5004
  let signingPosition = signingAtom.position;
5005
+ const signingWalletMeta = signingAtom.aggregatedMeta ? signingAtom.aggregatedMeta() : null;
5006
+ const signingWalletJson = signingWalletMeta?.signingWallet;
5007
+ if (signingWalletJson) {
5008
+ try {
5009
+ const parsedSigningWallet = JSON.parse(signingWalletJson);
5010
+ if (parsedSigningWallet.position) {
5011
+ signingPosition = parsedSigningWallet.position;
5012
+ }
5013
+ } catch {
5014
+ }
5015
+ }
3981
5016
  if (!signingPosition) {
3982
5017
  throw new SignatureMalformedException("Signing wallet must have a position!");
3983
5018
  }
@@ -4096,7 +5131,7 @@ var Molecule = class _Molecule {
4096
5131
  */
4097
5132
  toJSON(options = {}) {
4098
5133
  const {
4099
- includeValidationContext = true,
5134
+ includeValidationContext = false,
4100
5135
  includeOtsFragments = true,
4101
5136
  secureMode = false
4102
5137
  } = options;
@@ -4109,21 +5144,24 @@ var Molecule = class _Molecule {
4109
5144
  molecularHash: this.molecularHash,
4110
5145
  createdAt: this.createdAt,
4111
5146
  cellSlug: this.cellSlug,
4112
- cellSlugOrigin: this.cellSlugOrigin,
4113
- version: this.version,
4114
5147
  bundle: this.bundle,
4115
5148
  // Serialized atoms array with optional OTS fragments
4116
5149
  atoms: this.atoms.map((atom) => atom.toJSON({
4117
5150
  includeOtsFragments
4118
5151
  }))
4119
5152
  };
5153
+ if (this.parentHashes && this.parentHashes.length > 0) {
5154
+ serialized.parentHashes = this.parentHashes;
5155
+ }
4120
5156
  if (includeValidationContext) {
5157
+ serialized.cellSlugOrigin = this.cellSlugOrigin;
5158
+ serialized.version = this.version;
4121
5159
  if (this.sourceWallet) {
4122
5160
  serialized.sourceWallet = {
4123
5161
  address: this.sourceWallet.address,
4124
5162
  position: this.sourceWallet.position,
4125
5163
  token: this.sourceWallet.token,
4126
- balance: this.sourceWallet.balance || 0,
5164
+ balance: this.sourceWallet.balance || "0",
4127
5165
  bundle: this.sourceWallet.bundle,
4128
5166
  batchId: this.sourceWallet.batchId || null,
4129
5167
  characters: this.sourceWallet.characters || "BASE64",
@@ -4139,7 +5177,7 @@ var Molecule = class _Molecule {
4139
5177
  address: this.remainderWallet.address,
4140
5178
  position: this.remainderWallet.position,
4141
5179
  token: this.remainderWallet.token,
4142
- balance: this.remainderWallet.balance || 0,
5180
+ balance: this.remainderWallet.balance || "0",
4143
5181
  bundle: this.remainderWallet.bundle,
4144
5182
  batchId: this.remainderWallet.batchId || null,
4145
5183
  characters: this.remainderWallet.characters || "BASE64",
@@ -4167,30 +5205,26 @@ var Molecule = class _Molecule {
4167
5205
  // =============================================================================
4168
5206
  /**
4169
5207
  * Initialize token creation
5208
+ * Matches JavaScript SDK initTokenCreation implementation
4170
5209
  */
4171
5210
  initTokenCreation({
4172
5211
  recipientWallet,
4173
5212
  amount,
4174
5213
  meta
4175
5214
  }) {
4176
- this.addAtom(new Atom({
4177
- isotope: "T",
4178
- position: recipientWallet.position,
4179
- walletAddress: recipientWallet.address,
4180
- token: recipientWallet.token,
5215
+ if (!this.sourceWallet) {
5216
+ throw new Error("Source wallet required for token creation");
5217
+ }
5218
+ const atomMeta = new AtomMeta(meta);
5219
+ atomMeta.setMetaWallet(recipientWallet);
5220
+ this.addAtom(Atom.create({
5221
+ isotope: "C",
5222
+ wallet: this.sourceWallet,
4181
5223
  value: amount,
4182
5224
  metaType: "token",
4183
5225
  metaId: recipientWallet.token,
4184
- meta: meta ? [{ key: "tokenMeta", value: JSON.stringify(meta) }] : []
4185
- }));
4186
- this.addAtom(new Atom({
4187
- isotope: "M",
4188
- position: recipientWallet.position,
4189
- walletAddress: recipientWallet.address,
4190
- token: recipientWallet.token,
4191
- metaType: "walletBundle",
4192
- metaId: recipientWallet.bundle,
4193
- meta: meta ? [{ key: "tokenMeta", value: JSON.stringify(meta) }] : []
5226
+ meta: atomMeta,
5227
+ batchId: recipientWallet.batchId
4194
5228
  }));
4195
5229
  this.addContinuIdAtom();
4196
5230
  return this;
@@ -4200,28 +5234,48 @@ var Molecule = class _Molecule {
4200
5234
  */
4201
5235
  burnToken({
4202
5236
  amount,
4203
- walletBundle = null
5237
+ walletBundle: _walletBundle = null
4204
5238
  }) {
4205
5239
  if (!this.sourceWallet) {
4206
5240
  throw new Error("Source wallet required for token burning");
4207
5241
  }
4208
- if (amount <= 0) {
4209
- throw new NegativeAmountException();
5242
+ if (amount < 0) {
5243
+ throw new NegativeAmountException("Molecule::burnToken() - Amount to burn must be positive!");
4210
5244
  }
4211
- if (this.sourceWallet.balance - amount < 0) {
5245
+ if (Number(this.sourceWallet.balance) - amount < 0) {
4212
5246
  throw new BalanceInsufficientException();
4213
5247
  }
4214
- this.addAtom(new Atom({
5248
+ this.addAtom(Atom.create({
4215
5249
  isotope: "V",
4216
- position: this.sourceWallet.position,
4217
- walletAddress: this.sourceWallet.address,
4218
- token: this.sourceWallet.token,
4219
- value: -amount,
4220
- metaType: walletBundle ? "walletBundle" : null,
4221
- metaId: walletBundle || null
5250
+ wallet: this.sourceWallet,
5251
+ value: -amount
5252
+ }));
5253
+ this.addAtom(Atom.create({
5254
+ isotope: "V",
5255
+ wallet: this.remainderWallet,
5256
+ value: Number(this.sourceWallet.balance) - amount,
5257
+ metaType: "walletBundle",
5258
+ metaId: this.remainderWallet.bundle
4222
5259
  }));
4223
5260
  return this;
4224
5261
  }
5262
+ /**
5263
+ * Initialize authorization request
5264
+ * Creates U-isotope (authorization) atom for requesting auth token
5265
+ * Matches JavaScript SDK Molecule.initAuthorization
5266
+ */
5267
+ initAuthorization({ meta }) {
5268
+ if (!this.sourceWallet) {
5269
+ throw new Error("Source wallet required for authorization");
5270
+ }
5271
+ this.addAtom(Atom.create({
5272
+ isotope: "U",
5273
+ wallet: this.sourceWallet,
5274
+ meta: new AtomMeta(meta)
5275
+ }));
5276
+ this.addContinuIdAtom();
5277
+ return this;
5278
+ }
4225
5279
  /**
4226
5280
  * Initialize meta
4227
5281
  */
@@ -4234,59 +5288,123 @@ var Molecule = class _Molecule {
4234
5288
  if (!this.sourceWallet) {
4235
5289
  throw new Error("Source wallet required for meta creation");
4236
5290
  }
4237
- const metaArray = [];
4238
- if (meta) {
4239
- if (Array.isArray(meta)) {
4240
- metaArray.push(...meta);
4241
- } else if (typeof meta === "object") {
4242
- for (const [key, value] of Object.entries(meta)) {
4243
- metaArray.push({ key, value });
4244
- }
4245
- } else {
4246
- metaArray.push({ key: "value", value: meta });
4247
- }
4248
- }
4249
- if (policy) {
4250
- metaArray.push({ key: "policy", value: JSON.stringify(policy) });
4251
- }
4252
- this.addAtom(new Atom({
5291
+ this.addAtom(Atom.create({
4253
5292
  isotope: "M",
4254
- position: this.sourceWallet.position,
4255
- walletAddress: this.sourceWallet.address,
4256
- token: this.sourceWallet.token,
5293
+ wallet: this.sourceWallet,
4257
5294
  metaType,
4258
5295
  metaId,
4259
- meta: metaArray
5296
+ meta: new AtomMeta(meta)
4260
5297
  }));
5298
+ if (policy && Object.keys(policy).length > 0) {
5299
+ this.addPolicyAtom({
5300
+ metaType,
5301
+ metaId,
5302
+ meta,
5303
+ policy
5304
+ });
5305
+ }
4261
5306
  this.addContinuIdAtom();
4262
5307
  return this;
4263
5308
  }
4264
5309
  /**
4265
5310
  * Initialize wallet creation
5311
+ * Uses source wallet for atom properties (matching JavaScript SDK)
5312
+ * The wallet being created is stored in metadata
4266
5313
  */
4267
5314
  initWalletCreation(wallet, atomMeta = null) {
4268
- const atom = new Atom({
5315
+ if (!this.sourceWallet) {
5316
+ throw new Error("Source wallet required for wallet creation");
5317
+ }
5318
+ if (!atomMeta) {
5319
+ atomMeta = new AtomMeta();
5320
+ }
5321
+ atomMeta.setMetaWallet(wallet);
5322
+ const creationAtom = Atom.create({
4269
5323
  isotope: "C",
4270
- position: wallet.position,
4271
- walletAddress: wallet.address,
4272
- token: wallet.token,
5324
+ wallet: this.sourceWallet,
4273
5325
  metaType: "wallet",
4274
5326
  metaId: wallet.address,
4275
- meta: atomMeta ? atomMeta.get() : []
5327
+ meta: atomMeta,
5328
+ batchId: wallet.batchId
4276
5329
  });
4277
- if (!atomMeta) {
4278
- atom.meta.push(
4279
- { key: "position", value: wallet.position },
4280
- { key: "bundle", value: wallet.bundle },
4281
- { key: "token", value: wallet.token },
4282
- { key: "batchId", value: wallet.batchId || "" },
4283
- { key: "characters", value: wallet.characters || "" }
4284
- );
4285
- if (wallet.pubkey) {
4286
- atom.meta.push({ key: "pubkey", value: wallet.pubkey });
4287
- }
5330
+ this.addAtom(creationAtom);
5331
+ this.addContinuIdAtom();
5332
+ return this;
5333
+ }
5334
+ /**
5335
+ * Creates atoms for rule definition
5336
+ * Matches JavaScript SDK Molecule.createRule method
5337
+ *
5338
+ * @param metaType - The meta type for the rule
5339
+ * @param metaId - The meta ID for the rule
5340
+ * @param rule - Array of Rule objects or rule data
5341
+ * @param policy - Optional policy object
5342
+ * @return This molecule instance for chaining
5343
+ */
5344
+ createRule({
5345
+ metaType,
5346
+ metaId,
5347
+ rule,
5348
+ policy = {}
5349
+ }) {
5350
+ if (!this.sourceWallet) {
5351
+ throw new Error("Source wallet required for createRule");
5352
+ }
5353
+ const ruleArray = Array.isArray(rule) ? rule : [rule];
5354
+ const rules = [];
5355
+ for (const r of ruleArray) {
5356
+ rules.push(r instanceof Rule ? r : Rule.toObject(r));
5357
+ }
5358
+ const atomMeta = new AtomMeta({
5359
+ rule: JSON.stringify(rules)
5360
+ });
5361
+ if (policy && Object.keys(policy).length > 0) {
5362
+ atomMeta.addPolicy(policy);
5363
+ }
5364
+ this.addAtom(Atom.create({
5365
+ isotope: "R",
5366
+ wallet: this.sourceWallet,
5367
+ metaType,
5368
+ metaId,
5369
+ meta: atomMeta
5370
+ }));
5371
+ this.addContinuIdAtom();
5372
+ return this;
5373
+ }
5374
+ /**
5375
+ * Initializes a token request molecule
5376
+ * Matches JavaScript SDK Molecule.initTokenRequest method
5377
+ *
5378
+ * @param token - Token slug to request
5379
+ * @param amount - Amount of tokens to request
5380
+ * @param metaType - Meta type (typically 'walletBundle')
5381
+ * @param metaId - Meta ID (typically recipient bundle hash)
5382
+ * @param meta - Optional additional metadata
5383
+ * @param batchId - Optional batch ID
5384
+ * @return This molecule instance for chaining
5385
+ */
5386
+ initTokenRequest({
5387
+ token,
5388
+ amount,
5389
+ metaType,
5390
+ metaId,
5391
+ meta = {},
5392
+ batchId = null
5393
+ }) {
5394
+ if (!this.sourceWallet) {
5395
+ throw new Error("Source wallet required for initTokenRequest");
4288
5396
  }
4289
- this.addAtom(atom);
5397
+ const metaWithToken = { ...meta, token, amount: String(amount) };
5398
+ this.local = 1;
5399
+ this.addAtom(Atom.create({
5400
+ isotope: "T",
5401
+ wallet: this.sourceWallet,
5402
+ value: amount,
5403
+ metaType,
5404
+ metaId,
5405
+ meta: new AtomMeta(metaWithToken),
5406
+ batchId
5407
+ }));
4290
5408
  this.addContinuIdAtom();
4291
5409
  return this;
4292
5410
  }
@@ -4336,6 +5454,7 @@ var Molecule = class _Molecule {
4336
5454
  }
4337
5455
  });
4338
5456
  }
5457
+ molecule.parentHashes = Array.isArray(data.parentHashes) ? [...data.parentHashes] : [];
4339
5458
  if (includeValidationContext) {
4340
5459
  if (data.sourceWallet) {
4341
5460
  molecule.sourceWallet = new Wallet({
@@ -4346,7 +5465,7 @@ var Molecule = class _Molecule {
4346
5465
  batchId: data.sourceWallet.batchId,
4347
5466
  characters: data.sourceWallet.characters
4348
5467
  });
4349
- molecule.sourceWallet.balance = data.sourceWallet.balance || 0;
5468
+ molecule.sourceWallet.balance = String(data.sourceWallet.balance != null ? data.sourceWallet.balance : 0);
4350
5469
  molecule.sourceWallet.address = data.sourceWallet.address;
4351
5470
  if (data.sourceWallet.pubkey) {
4352
5471
  molecule.sourceWallet.pubkey = data.sourceWallet.pubkey;
@@ -4364,7 +5483,7 @@ var Molecule = class _Molecule {
4364
5483
  batchId: data.remainderWallet.batchId,
4365
5484
  characters: data.remainderWallet.characters
4366
5485
  });
4367
- molecule.remainderWallet.balance = data.remainderWallet.balance || 0;
5486
+ molecule.remainderWallet.balance = String(data.remainderWallet.balance != null ? data.remainderWallet.balance : 0);
4368
5487
  molecule.remainderWallet.address = data.remainderWallet.address;
4369
5488
  if (data.remainderWallet.pubkey) {
4370
5489
  molecule.remainderWallet.pubkey = data.remainderWallet.pubkey;
@@ -4385,245 +5504,208 @@ var Molecule = class _Molecule {
4385
5504
  static jsonToObject(json) {
4386
5505
  return _Molecule.fromJSON(json);
4387
5506
  }
4388
- };
4389
- var AtomMeta = class _AtomMeta {
4390
- meta;
4391
- /**
4392
- * Create new AtomMeta instance
4393
- * @param meta - Initial metadata (object or array)
4394
- */
4395
- constructor(meta = null) {
4396
- this.meta = Meta.normalizeMeta(meta);
4397
- }
5507
+ // =============================================================================
5508
+ // ISOTOPE INIT METHODS - MATCHING JAVASCRIPT SDK PARITY
5509
+ // =============================================================================
4398
5510
  /**
4399
- * Merge additional metadata
4400
- * @param meta - Metadata to merge
4401
- * @return This instance for chaining
5511
+ * Initialize a P-type molecule for peer registration
5512
+ * Matches JavaScript SDK Molecule.initPeering implementation exactly
5513
+ *
5514
+ * @param host - The peer host URL to register
5515
+ * @return This molecule instance for chaining
4402
5516
  */
4403
- merge(meta) {
4404
- const normalized = Meta.normalizeMeta(meta);
4405
- const existingKeys = new Set(this.meta.map((m) => m.key));
4406
- for (const item of normalized) {
4407
- if (existingKeys.has(item.key)) {
4408
- const index = this.meta.findIndex((m) => m.key === item.key);
4409
- if (index !== -1) {
4410
- this.meta[index] = item;
4411
- }
4412
- } else {
4413
- this.meta.push(item);
4414
- existingKeys.add(item.key);
4415
- }
5517
+ initPeering({ host }) {
5518
+ if (!this.sourceWallet) {
5519
+ throw new Error("Source wallet required for peer registration");
4416
5520
  }
5521
+ this.addAtom(Atom.create({
5522
+ isotope: "P",
5523
+ wallet: this.sourceWallet,
5524
+ metaType: "walletBundle",
5525
+ metaId: this.bundle,
5526
+ meta: new AtomMeta({ peerHost: host })
5527
+ }));
5528
+ this.addContinuIdAtom();
4417
5529
  return this;
4418
5530
  }
4419
5531
  /**
4420
- * Add context metadata if enabled
4421
- * @param context - Context URL or null for default
4422
- * @return This instance for chaining
5532
+ * Initialize an A-type molecule for an append request
5533
+ * Matches JavaScript SDK Molecule.initAppendRequest implementation exactly
5534
+ *
5535
+ * @param metaType - The target MetaType to append to
5536
+ * @param metaId - The target MetaId to append to
5537
+ * @param action - The action to perform
5538
+ * @param meta - Additional metadata
5539
+ * @return This molecule instance for chaining
4423
5540
  */
4424
- addContext(context = null) {
5541
+ initAppendRequest({
5542
+ metaType,
5543
+ metaId,
5544
+ action,
5545
+ meta = {}
5546
+ }) {
5547
+ if (!this.sourceWallet) {
5548
+ throw new Error("Source wallet required for append request");
5549
+ }
5550
+ this.addAtom(Atom.create({
5551
+ isotope: "A",
5552
+ wallet: this.sourceWallet,
5553
+ metaType,
5554
+ metaId,
5555
+ meta: new AtomMeta({ action, ...meta })
5556
+ }));
5557
+ this.addContinuIdAtom();
4425
5558
  return this;
4426
5559
  }
4427
5560
  /**
4428
- * Set atom wallet metadata
4429
- * @param wallet - Wallet to extract metadata from
4430
- * @return This instance for chaining
5561
+ * Initialize a deposit buffer operation (B-isotope)
5562
+ * Matches JavaScript SDK Molecule.initDepositBuffer implementation exactly
5563
+ *
5564
+ * @param amount - Amount to deposit into buffer
5565
+ * @param tradeRates - Trade rates for the buffer wallet
5566
+ * @return This molecule instance for chaining
4431
5567
  */
4432
- setAtomWallet(wallet) {
4433
- const walletMeta = {
4434
- pubkey: wallet.pubkey,
4435
- characters: wallet.characters
4436
- };
4437
- if (wallet.tokenUnits && wallet.tokenUnits.length) {
4438
- walletMeta.tokenUnits = JSON.stringify(wallet.getTokenUnitsData ? wallet.getTokenUnitsData() : wallet.tokenUnits);
5568
+ initDepositBuffer({
5569
+ amount,
5570
+ tradeRates
5571
+ }) {
5572
+ if (!this.sourceWallet) {
5573
+ throw new Error("Source wallet required for buffer deposit");
4439
5574
  }
4440
- if (wallet.tradeRates && Object.keys(wallet.tradeRates).length) {
4441
- walletMeta.tradeRates = JSON.stringify(wallet.tradeRates);
5575
+ if (Number(this.sourceWallet.balance) - amount < 0) {
5576
+ throw new BalanceInsufficientException();
4442
5577
  }
4443
- this.merge(walletMeta);
4444
- return this;
4445
- }
4446
- /**
4447
- * Set full NEW wallet metadata
4448
- * Used for shadow wallet claim & wallet creation & token creation
4449
- * @param wallet - Wallet with full metadata
4450
- * @return This instance for chaining
4451
- */
4452
- setMetaWallet(wallet) {
4453
- this.merge({
4454
- walletTokenSlug: wallet.token,
4455
- walletBundleHash: wallet.bundle,
4456
- walletAddress: wallet.address,
4457
- walletPosition: wallet.position,
4458
- walletBatchId: wallet.batchId,
4459
- walletPubkey: wallet.pubkey,
4460
- walletCharacters: wallet.characters
4461
- });
4462
- return this;
4463
- }
4464
- /**
4465
- * Set shadow wallet claim flag
4466
- * @param shadowWalletClaim - Claim flag (converted to number)
4467
- * @return This instance for chaining
4468
- */
4469
- setShadowWalletClaim(shadowWalletClaim) {
4470
- this.merge({ shadowWalletClaim: Number(shadowWalletClaim) });
4471
- return this;
4472
- }
4473
- /**
4474
- * Set signing wallet metadata
4475
- * @param signingWallet - Wallet used for signing
4476
- * @return This instance for chaining
4477
- */
4478
- setSigningWallet(signingWallet) {
4479
- this.merge({
4480
- signingWallet: JSON.stringify({
4481
- tokenSlug: signingWallet.token,
4482
- bundleHash: signingWallet.bundle,
4483
- address: signingWallet.address,
4484
- position: signingWallet.position,
4485
- pubkey: signingWallet.pubkey,
4486
- characters: signingWallet.characters
4487
- })
4488
- });
4489
- return this;
4490
- }
4491
- /**
4492
- * Add policy metadata
4493
- * @param policy - Policy object to add
4494
- * @return This instance for chaining
4495
- */
4496
- addPolicy(policy) {
4497
- this.merge({
4498
- policy: JSON.stringify(policy)
5578
+ const bufferWallet = Wallet.create({
5579
+ secret: this.secret,
5580
+ bundle: this.bundle,
5581
+ token: this.sourceWallet.token,
5582
+ batchId: this.sourceWallet.batchId
4499
5583
  });
5584
+ if (tradeRates) {
5585
+ bufferWallet.tradeRates = tradeRates;
5586
+ }
5587
+ this.addAtom(Atom.create({
5588
+ isotope: "V",
5589
+ wallet: this.sourceWallet,
5590
+ value: -Number(this.sourceWallet.balance)
5591
+ }));
5592
+ this.addAtom(Atom.create({
5593
+ isotope: "B",
5594
+ wallet: bufferWallet,
5595
+ value: amount,
5596
+ metaType: "walletBundle",
5597
+ metaId: this.sourceWallet.bundle
5598
+ }));
5599
+ this.addAtom(Atom.create({
5600
+ isotope: "V",
5601
+ wallet: this.remainderWallet,
5602
+ value: Number(this.sourceWallet.balance) - amount,
5603
+ metaType: "walletBundle",
5604
+ metaId: this.sourceWallet.bundle
5605
+ }));
4500
5606
  return this;
4501
5607
  }
4502
5608
  /**
4503
- * Get the normalized metadata array
4504
- * @return Array of normalized metadata items
4505
- */
4506
- get() {
4507
- return this.meta;
4508
- }
4509
- /**
4510
- * Convert metadata to plain object
4511
- * @return Aggregated metadata object
4512
- */
4513
- toObject() {
4514
- return Meta.aggregateMeta(this.meta);
4515
- }
4516
- /**
4517
- * Convert metadata to JSON string
4518
- * @return JSON string representation
4519
- */
4520
- toJSON() {
4521
- return JSON.stringify(this.toObject());
4522
- }
4523
- /**
4524
- * Get metadata value by key
4525
- * @param key - Key to lookup
4526
- * @param defaultValue - Default if not found
4527
- * @return Value or default
4528
- */
4529
- getValue(key, defaultValue = null) {
4530
- return Meta.getMetaValue(this.meta, key, defaultValue);
4531
- }
4532
- /**
4533
- * Check if metadata has a key
4534
- * @param key - Key to check
4535
- * @return True if key exists
4536
- */
4537
- hasKey(key) {
4538
- return Meta.hasKey(this.meta, key);
4539
- }
4540
- /**
4541
- * Remove metadata by key
4542
- * @param key - Key to remove
4543
- * @return This instance for chaining
4544
- */
4545
- remove(key) {
4546
- this.meta = Meta.removeMeta(this.meta, key);
4547
- return this;
4548
- }
4549
- /**
4550
- * Clear all metadata
4551
- * @return This instance for chaining
5609
+ * Initialize a withdraw buffer operation (B-isotope)
5610
+ * Matches JavaScript SDK Molecule.initWithdrawBuffer implementation exactly
5611
+ *
5612
+ * @param recipients - Map of recipientBundle → amount
5613
+ * @param signingWallet - Optional signing wallet for reconciliation
5614
+ * @return This molecule instance for chaining
4552
5615
  */
4553
- clear() {
4554
- this.meta = [];
5616
+ initWithdrawBuffer({
5617
+ recipients,
5618
+ signingWallet = null
5619
+ }) {
5620
+ if (!this.sourceWallet) {
5621
+ throw new Error("Source wallet required for buffer withdrawal");
5622
+ }
5623
+ let amount = 0;
5624
+ for (const recipientAmount of Object.values(recipients || {})) {
5625
+ amount += recipientAmount;
5626
+ }
5627
+ if (Number(this.sourceWallet.balance) - amount < 0) {
5628
+ throw new BalanceInsufficientException();
5629
+ }
5630
+ const firstAtomMeta = new AtomMeta();
5631
+ if (signingWallet) {
5632
+ firstAtomMeta.setSigningWallet(signingWallet);
5633
+ }
5634
+ this.addAtom(Atom.create({
5635
+ isotope: "B",
5636
+ wallet: this.sourceWallet,
5637
+ value: -Number(this.sourceWallet.balance),
5638
+ meta: firstAtomMeta,
5639
+ metaType: "walletBundle",
5640
+ metaId: this.sourceWallet.bundle
5641
+ }));
5642
+ for (const [recipientBundle, recipientAmount] of Object.entries(recipients || {})) {
5643
+ this.addAtom(new Atom({
5644
+ isotope: "V",
5645
+ token: this.sourceWallet.token,
5646
+ value: recipientAmount,
5647
+ batchId: this.sourceWallet.batchId ? generateBatchId({}) : null,
5648
+ metaType: "walletBundle",
5649
+ metaId: recipientBundle
5650
+ }));
5651
+ }
5652
+ this.addAtom(Atom.create({
5653
+ isotope: "B",
5654
+ wallet: this.remainderWallet,
5655
+ value: Number(this.sourceWallet.balance) - amount,
5656
+ metaType: "walletBundle",
5657
+ metaId: this.remainderWallet.bundle
5658
+ }));
4555
5659
  return this;
4556
5660
  }
4557
5661
  /**
4558
- * Get count of metadata items
4559
- * @return Number of items
5662
+ * Initialize shadow wallet claim
5663
+ * Matches JavaScript SDK Molecule.initShadowWalletClaim implementation exactly
5664
+ *
5665
+ * @param wallet - The shadow wallet to claim
5666
+ * @return This molecule instance for chaining
4560
5667
  */
4561
- count() {
4562
- return this.meta.length;
5668
+ initShadowWalletClaim(wallet) {
5669
+ const atomMeta = new AtomMeta();
5670
+ atomMeta.setShadowWalletClaim(true);
5671
+ return this.initWalletCreation(wallet, atomMeta);
4563
5672
  }
4564
5673
  /**
4565
- * Clone this AtomMeta instance
4566
- * @return New AtomMeta with same data
5674
+ * Initialize identifier creation
5675
+ * Matches JavaScript SDK Molecule.initIdentifierCreation implementation exactly
5676
+ *
5677
+ * @param type - Identifier type (phone or email)
5678
+ * @param contact - Phone number or email string
5679
+ * @param code - Verification code
5680
+ * @return This molecule instance for chaining
4567
5681
  */
4568
- clone() {
4569
- return new _AtomMeta(Meta.clone(this.meta));
5682
+ initIdentifierCreation({
5683
+ type,
5684
+ contact,
5685
+ code
5686
+ }) {
5687
+ if (!this.sourceWallet) {
5688
+ throw new Error("Source wallet required for identifier creation");
5689
+ }
5690
+ const meta = {
5691
+ code,
5692
+ hash: generateBundleHash(contact.trim(), "Molecule::initIdentifierCreation")
5693
+ };
5694
+ this.addAtom(Atom.create({
5695
+ isotope: "C",
5696
+ wallet: this.sourceWallet,
5697
+ metaType: "identifier",
5698
+ metaId: type,
5699
+ meta: new AtomMeta(meta)
5700
+ }));
5701
+ this.addContinuIdAtom();
5702
+ return this;
4570
5703
  }
4571
5704
  };
4572
5705
 
4573
5706
  // src/index.ts
4574
5707
  init_Dot();
4575
5708
 
4576
- // src/libraries/array.ts
4577
- function deepCloning(o, h) {
4578
- let i;
4579
- let r;
4580
- let x;
4581
- const t = [Array, Date, Number, String, Boolean];
4582
- const s = Object.prototype.toString;
4583
- h = h || [];
4584
- for (i = 0; i < h.length; i += 2) {
4585
- if (o === h[i]) {
4586
- return h[i + 1];
4587
- }
4588
- }
4589
- if (!r && o && typeof o === "object") {
4590
- r = {};
4591
- for (i = 0; i < t.length; i++) {
4592
- if (s.call(o) === s.call(x = new t[i](o))) {
4593
- r = i ? x : [];
4594
- }
4595
- }
4596
- h.push(o, r);
4597
- for (i in o) {
4598
- if (Object.prototype.hasOwnProperty.call(o, i)) {
4599
- r[i] = deepCloning(o[i], h);
4600
- }
4601
- }
4602
- }
4603
- return r || o;
4604
- }
4605
- function chunkArray(arr, size) {
4606
- if (!arr.length) {
4607
- return [];
4608
- }
4609
- return [arr.slice(0, size)].concat(chunkArray(arr.slice(size), size));
4610
- }
4611
- function diff(...arrays) {
4612
- return [].concat(...arrays.map((arr, i) => {
4613
- const others = arrays.slice(0);
4614
- others.splice(i, 1);
4615
- const unique = [...new Set([].concat(...others))];
4616
- return arr.filter((item) => !unique.includes(item));
4617
- }));
4618
- }
4619
- function intersect(...arrays) {
4620
- if (arrays.length === 0) return [];
4621
- if (arrays.length === 1) return arrays[0];
4622
- return arrays.reduce(
4623
- (first, second) => first.filter((item) => second.includes(item))
4624
- );
4625
- }
4626
-
4627
5709
  // src/libraries/Decimal.ts
4628
5710
  var MULTIPLIER = 10 ** 18;
4629
5711
  var Decimal = class _Decimal {
@@ -4835,6 +5917,129 @@ var GraphQLClient = class {
4835
5917
  }
4836
5918
  };
4837
5919
 
5920
+ // src/AuthToken.ts
5921
+ var AuthToken = class _AuthToken {
5922
+ $__token;
5923
+ $__expiresAt;
5924
+ $__pubkey;
5925
+ $__encrypt;
5926
+ $__wallet;
5927
+ /**
5928
+ * Create new AuthToken instance
5929
+ */
5930
+ constructor({
5931
+ token,
5932
+ expiresAt,
5933
+ encrypt,
5934
+ pubkey
5935
+ }) {
5936
+ this.$__token = token;
5937
+ this.$__expiresAt = expiresAt;
5938
+ this.$__pubkey = pubkey;
5939
+ this.$__encrypt = encrypt;
5940
+ }
5941
+ /**
5942
+ * Static factory method to create AuthToken with wallet
5943
+ */
5944
+ static create(data, wallet) {
5945
+ const authToken = new _AuthToken(data);
5946
+ authToken.setWallet(wallet);
5947
+ return authToken;
5948
+ }
5949
+ /**
5950
+ * Restore AuthToken from snapshot
5951
+ */
5952
+ static restore(snapshot, secret) {
5953
+ const wallet = new Wallet({
5954
+ secret,
5955
+ token: "AUTH",
5956
+ position: snapshot.wallet.position,
5957
+ characters: snapshot.wallet.characters
5958
+ });
5959
+ return _AuthToken.create({
5960
+ token: snapshot.token,
5961
+ expiresAt: snapshot.expiresAt,
5962
+ pubkey: snapshot.pubkey,
5963
+ encrypt: snapshot.encrypt
5964
+ }, wallet);
5965
+ }
5966
+ /**
5967
+ * Set wallet for this auth token
5968
+ */
5969
+ setWallet(wallet) {
5970
+ this.$__wallet = wallet;
5971
+ }
5972
+ /**
5973
+ * Get wallet
5974
+ */
5975
+ getWallet() {
5976
+ return this.$__wallet;
5977
+ }
5978
+ /**
5979
+ * Get auth token
5980
+ */
5981
+ getToken() {
5982
+ return this.$__token;
5983
+ }
5984
+ /**
5985
+ * Get expiration timestamp
5986
+ */
5987
+ getExpiresAt() {
5988
+ return this.$__expiresAt;
5989
+ }
5990
+ /**
5991
+ * Get public key
5992
+ */
5993
+ getPubkey() {
5994
+ return this.$__pubkey;
5995
+ }
5996
+ /**
5997
+ * Check if encryption is enabled
5998
+ */
5999
+ isEncrypted() {
6000
+ return this.$__encrypt;
6001
+ }
6002
+ /**
6003
+ * Get expire interval in milliseconds (matching JS SDK pattern)
6004
+ */
6005
+ getExpireInterval() {
6006
+ return this.$__expiresAt * 1e3 - Date.now();
6007
+ }
6008
+ /**
6009
+ * Check if token is expired
6010
+ */
6011
+ isExpired() {
6012
+ return !this.$__expiresAt || this.getExpireInterval() < 0;
6013
+ }
6014
+ /**
6015
+ * Get auth data for GraphQL client
6016
+ */
6017
+ getAuthData() {
6018
+ return {
6019
+ token: this.$__token,
6020
+ pubkey: this.$__pubkey,
6021
+ wallet: this.$__wallet
6022
+ };
6023
+ }
6024
+ /**
6025
+ * Create snapshot for persistence
6026
+ */
6027
+ toSnapshot() {
6028
+ return {
6029
+ token: this.$__token,
6030
+ expiresAt: this.$__expiresAt,
6031
+ pubkey: this.$__pubkey,
6032
+ encrypt: this.$__encrypt,
6033
+ ...this.$__wallet ? {
6034
+ wallet: {
6035
+ position: this.$__wallet.position,
6036
+ characters: this.$__wallet.characters
6037
+ }
6038
+ } : {}
6039
+ };
6040
+ }
6041
+ };
6042
+
4838
6043
  // src/query/Query.ts
4839
6044
  init_exception();
4840
6045
  var Query = class {
@@ -4998,36 +6203,36 @@ var Mutation = class extends Query {
4998
6203
  function createBrandedSchema(name, baseSchema = z.string()) {
4999
6204
  return baseSchema.brand(name);
5000
6205
  }
5001
- var WalletAddressSchema = createBrandedSchema(
6206
+ var WalletAddressSchema2 = createBrandedSchema(
5002
6207
  "WalletAddress",
5003
6208
  z.string().regex(/^[0-9a-fA-F]{64}$/, "Invalid wallet address format")
5004
6209
  );
5005
- var BundleHashSchema = createBrandedSchema(
6210
+ var BundleHashSchema2 = createBrandedSchema(
5006
6211
  "BundleHash",
5007
6212
  z.string().regex(/^[0-9a-fA-F]{64}$/, "Invalid bundle hash format")
5008
6213
  );
5009
- var PositionSchema = createBrandedSchema(
6214
+ var PositionSchema2 = createBrandedSchema(
5010
6215
  "Position",
5011
6216
  z.string().regex(/^[0-9a-fA-F]{64}$/, "Invalid position format")
5012
6217
  );
5013
- var MolecularHashSchema = createBrandedSchema(
6218
+ var MolecularHashSchema2 = createBrandedSchema(
5014
6219
  "MolecularHash",
5015
6220
  z.string().regex(/^[0-9a-g]+$/, "Invalid molecular hash format (base17)")
5016
6221
  );
5017
- var TokenSlugSchema = createBrandedSchema(
6222
+ var TokenSlugSchema2 = createBrandedSchema(
5018
6223
  "TokenSlug",
5019
6224
  z.string().min(1).max(32).regex(/^[A-Z0-9_]+$/, "Token slug must be uppercase alphanumeric")
5020
6225
  );
5021
- var BatchIdSchema = createBrandedSchema(
6226
+ var BatchIdSchema2 = createBrandedSchema(
5022
6227
  "BatchId",
5023
6228
  z.string().uuid("Invalid batch ID format")
5024
6229
  );
5025
- var CellSlugSchema = createBrandedSchema(
6230
+ var CellSlugSchema2 = createBrandedSchema(
5026
6231
  "CellSlug",
5027
6232
  z.string().min(1).max(64).regex(/^[a-zA-Z0-9\-_.]+$/, "Invalid cell slug format")
5028
6233
  );
5029
6234
  var ISOTOPES2 = ["C", "V", "U", "T", "M", "I", "R", "B", "F"];
5030
- var AtomIsotopeSchema = z.enum(ISOTOPES2);
6235
+ var AtomIsotopeSchema2 = z.enum(ISOTOPES2);
5031
6236
  z.object({
5032
6237
  isotope: z.literal("V"),
5033
6238
  value: z.union([z.string(), z.number()]).refine(
@@ -5047,17 +6252,17 @@ z.object({
5047
6252
  z.object({
5048
6253
  isotope: z.literal("C")
5049
6254
  }).strict();
5050
- var MetaDataSchema = z.lazy(
6255
+ var MetaDataSchema2 = z.lazy(
5051
6256
  () => z.union([
5052
6257
  z.string(),
5053
6258
  z.number(),
5054
6259
  z.boolean(),
5055
6260
  z.null(),
5056
- z.record(z.string(), MetaDataSchema),
5057
- z.array(MetaDataSchema)
6261
+ z.record(z.string(), MetaDataSchema2),
6262
+ z.array(MetaDataSchema2)
5058
6263
  ])
5059
6264
  );
5060
- var AtomMetaDataSchema = z.object({
6265
+ var AtomMetaDataSchema2 = z.object({
5061
6266
  key: z.string().min(1),
5062
6267
  value: z.union([z.string(), z.number(), z.boolean(), z.null()])
5063
6268
  }).strict();
@@ -5065,44 +6270,44 @@ z.object({
5065
6270
  key: z.string(),
5066
6271
  value: z.union([z.string(), z.number(), z.boolean(), z.null()])
5067
6272
  }).passthrough();
5068
- var AtomParamsSchema = z.object({
6273
+ var AtomParamsSchema2 = z.object({
5069
6274
  position: z.string().optional(),
5070
- walletAddress: z.union([WalletAddressSchema, z.string()]).optional(),
5071
- isotope: AtomIsotopeSchema.default("C"),
5072
- token: z.union([TokenSlugSchema, z.string()]).default("USER"),
6275
+ walletAddress: z.union([WalletAddressSchema2, z.string()]).optional(),
6276
+ isotope: AtomIsotopeSchema2.default("C"),
6277
+ token: z.union([TokenSlugSchema2, z.string()]).default("USER"),
5073
6278
  value: z.union([z.string(), z.number(), z.null()]).optional(),
5074
- batchId: z.union([BatchIdSchema, z.string(), z.null()]).optional(),
6279
+ batchId: z.union([BatchIdSchema2, z.string(), z.null()]).optional(),
5075
6280
  metaType: z.string().optional(),
5076
6281
  metaId: z.string().optional(),
5077
- meta: z.array(AtomMetaDataSchema).optional(),
6282
+ meta: z.array(AtomMetaDataSchema2).optional(),
5078
6283
  otsFragment: z.string().optional(),
5079
6284
  index: z.number().int().min(0).optional(),
5080
6285
  createdAt: z.string().optional(),
5081
6286
  version: z.number().int().min(1).optional()
5082
6287
  }).strict();
5083
- var WalletParamsSchema = z.object({
6288
+ var WalletParamsSchema2 = z.object({
5084
6289
  secret: z.string().optional(),
5085
- bundle: z.union([BundleHashSchema, z.string()]).optional(),
5086
- token: z.union([TokenSlugSchema, z.string()]).default("USER"),
5087
- address: z.union([WalletAddressSchema, z.string()]).optional(),
5088
- position: z.union([PositionSchema, z.string()]).optional(),
5089
- batchId: z.union([BatchIdSchema, z.string()]).optional(),
6290
+ bundle: z.union([BundleHashSchema2, z.string()]).optional(),
6291
+ token: z.union([TokenSlugSchema2, z.string()]).default("USER"),
6292
+ address: z.union([WalletAddressSchema2, z.string()]).optional(),
6293
+ position: z.union([PositionSchema2, z.string()]).optional(),
6294
+ batchId: z.union([BatchIdSchema2, z.string()]).optional(),
5090
6295
  characters: z.string().optional()
5091
6296
  }).strict();
5092
- var MoleculeParamsSchema = z.object({
6297
+ var MoleculeParamsSchema2 = z.object({
5093
6298
  secret: z.string().optional(),
5094
- bundle: z.union([BundleHashSchema, z.string()]).optional(),
5095
- sourceWallet: WalletParamsSchema.optional(),
5096
- remainderWallet: WalletParamsSchema.optional(),
5097
- cellSlug: z.union([CellSlugSchema, z.string()]).optional(),
6299
+ bundle: z.union([BundleHashSchema2, z.string()]).optional(),
6300
+ sourceWallet: WalletParamsSchema2.optional(),
6301
+ remainderWallet: WalletParamsSchema2.optional(),
6302
+ cellSlug: z.union([CellSlugSchema2, z.string()]).optional(),
5098
6303
  version: z.number().int().min(1).optional()
5099
6304
  }).strict();
5100
- var KnishIOClientConfigSchema = z.object({
6305
+ var KnishIOClientConfigSchema2 = z.object({
5101
6306
  uri: z.union([
5102
6307
  z.string().url("Invalid URI format"),
5103
6308
  z.array(z.string().url("Invalid URI format")).min(1)
5104
6309
  ]).optional(),
5105
- cellSlug: z.union([CellSlugSchema, z.string()]).optional(),
6310
+ cellSlug: z.union([CellSlugSchema2, z.string()]).optional(),
5106
6311
  client: z.unknown().optional(),
5107
6312
  socket: z.unknown().optional(),
5108
6313
  serverSdkVersion: z.number().int().min(1).max(10).default(4),
@@ -5115,48 +6320,48 @@ var EnvironmentConfigSchema = z.object({
5115
6320
  KNISHIO_LOGGING: z.string().transform((val) => val === "true").default("false"),
5116
6321
  KNISHIO_SERVER_SDK_VERSION: z.string().transform((val) => parseInt(val, 10)).default("4")
5117
6322
  }).partial();
5118
- var TransferParamsSchema = z.object({
5119
- recipient: z.union([WalletAddressSchema, z.string()]),
6323
+ var TransferParamsSchema2 = z.object({
6324
+ recipient: z.union([WalletAddressSchema2, z.string()]),
5120
6325
  amount: z.union([z.number(), z.string()]).refine(
5121
6326
  (val) => Number(val) > 0,
5122
6327
  "Amount must be positive"
5123
6328
  ),
5124
- token: z.union([TokenSlugSchema, z.string()]).optional(),
6329
+ token: z.union([TokenSlugSchema2, z.string()]).optional(),
5125
6330
  callbackUrl: z.string().url().optional(),
5126
6331
  metaType: z.string().optional(),
5127
6332
  metaId: z.string().optional(),
5128
- meta: MetaDataSchema.optional()
6333
+ meta: MetaDataSchema2.optional()
5129
6334
  }).strict();
5130
- var CreateTokenParamsSchema = z.object({
5131
- token: z.union([TokenSlugSchema, z.string()]),
6335
+ var CreateTokenParamsSchema2 = z.object({
6336
+ token: z.union([TokenSlugSchema2, z.string()]),
5132
6337
  amount: z.union([z.number(), z.string()]).refine(
5133
6338
  (val) => Number(val) > 0,
5134
6339
  "Amount must be positive"
5135
6340
  ),
5136
6341
  metaType: z.string().optional(),
5137
6342
  metaId: z.string().optional(),
5138
- meta: MetaDataSchema.optional(),
6343
+ meta: MetaDataSchema2.optional(),
5139
6344
  fungible: z.boolean().default(true),
5140
6345
  splittable: z.number().int().min(0).optional(),
5141
- supplyToken: z.union([TokenSlugSchema, z.string()]).optional()
6346
+ supplyToken: z.union([TokenSlugSchema2, z.string()]).optional()
5142
6347
  }).strict();
5143
- var RequestTokensParamsSchema = z.object({
6348
+ var RequestTokensParamsSchema2 = z.object({
5144
6349
  amount: z.union([z.number(), z.string()]).refine(
5145
6350
  (val) => Number(val) > 0,
5146
6351
  "Amount must be positive"
5147
6352
  ),
5148
- token: z.union([TokenSlugSchema, z.string()]).optional(),
6353
+ token: z.union([TokenSlugSchema2, z.string()]).optional(),
5149
6354
  metaType: z.string().optional(),
5150
6355
  metaId: z.string().optional(),
5151
- meta: MetaDataSchema.optional()
6356
+ meta: MetaDataSchema2.optional()
5152
6357
  }).strict();
5153
- var BalanceQueryParamsSchema = z.object({
5154
- address: z.union([WalletAddressSchema, z.string()]).optional(),
5155
- bundleHash: z.union([BundleHashSchema, z.string()]).optional(),
5156
- token: z.union([TokenSlugSchema, z.string()]).optional(),
6358
+ var BalanceQueryParamsSchema2 = z.object({
6359
+ address: z.union([WalletAddressSchema2, z.string()]).optional(),
6360
+ bundleHash: z.union([BundleHashSchema2, z.string()]).optional(),
6361
+ token: z.union([TokenSlugSchema2, z.string()]).optional(),
5157
6362
  type: z.enum(["token", "user"]).optional()
5158
6363
  }).strict();
5159
- var MetaQueryParamsSchema = z.object({
6364
+ var MetaQueryParamsSchema2 = z.object({
5160
6365
  metaType: z.string().min(1),
5161
6366
  metaId: z.string().optional(),
5162
6367
  key: z.string().optional(),
@@ -5166,33 +6371,33 @@ var MetaQueryParamsSchema = z.object({
5166
6371
  queryArgs: z.record(z.unknown()).optional(),
5167
6372
  count: z.number().int().min(0).optional(),
5168
6373
  countBy: z.string().optional(),
5169
- cellSlug: z.union([CellSlugSchema, z.string()]).optional()
6374
+ cellSlug: z.union([CellSlugSchema2, z.string()]).optional()
5170
6375
  }).strict();
5171
- var WalletQueryParamsSchema = z.object({
5172
- bundleHash: z.union([BundleHashSchema, z.string()]).optional(),
5173
- tokenSlug: z.union([TokenSlugSchema, z.string()]).optional(),
6376
+ var WalletQueryParamsSchema2 = z.object({
6377
+ bundleHash: z.union([BundleHashSchema2, z.string()]).optional(),
6378
+ tokenSlug: z.union([TokenSlugSchema2, z.string()]).optional(),
5174
6379
  unspent: z.boolean().optional()
5175
6380
  }).strict();
5176
- var AuthTokenParamsSchema = z.object({
6381
+ var AuthTokenParamsSchema2 = z.object({
5177
6382
  token: z.string().min(1),
5178
6383
  expiresAt: z.number().int().min(0),
5179
6384
  encrypt: z.boolean(),
5180
6385
  pubkey: z.string().min(1)
5181
6386
  }).strict();
5182
- var AuthParamsSchema = z.object({
5183
- cellSlug: z.union([CellSlugSchema, z.string()]).optional(),
6387
+ var AuthParamsSchema2 = z.object({
6388
+ cellSlug: z.union([CellSlugSchema2, z.string()]).optional(),
5184
6389
  encrypt: z.boolean().optional(),
5185
6390
  callback: z.function().optional()
5186
6391
  }).strict();
5187
- var GuestAuthParamsSchema = z.object({
5188
- cellSlug: z.union([CellSlugSchema, z.string()]).optional()
6392
+ var GuestAuthParamsSchema2 = z.object({
6393
+ cellSlug: z.union([CellSlugSchema2, z.string()]).optional()
5189
6394
  }).strict();
5190
- var GraphQLRequestSchema = z.object({
6395
+ var GraphQLRequestSchema2 = z.object({
5191
6396
  query: z.string().min(1),
5192
6397
  variables: z.record(z.unknown()).optional(),
5193
6398
  operationName: z.string().optional()
5194
6399
  }).strict();
5195
- var GraphQLErrorSchema = z.object({
6400
+ var GraphQLErrorSchema2 = z.object({
5196
6401
  message: z.string(),
5197
6402
  locations: z.array(z.object({
5198
6403
  line: z.number().int(),
@@ -5201,9 +6406,9 @@ var GraphQLErrorSchema = z.object({
5201
6406
  path: z.array(z.union([z.string(), z.number()])).optional(),
5202
6407
  extensions: z.record(z.unknown()).optional()
5203
6408
  }).strict();
5204
- var GraphQLResponseSchema = z.object({
6409
+ var GraphQLResponseSchema2 = z.object({
5205
6410
  data: z.unknown().optional(),
5206
- errors: z.array(GraphQLErrorSchema).optional(),
6411
+ errors: z.array(GraphQLErrorSchema2).optional(),
5207
6412
  extensions: z.record(z.unknown()).optional()
5208
6413
  }).strict();
5209
6414
  function safeParse(schema, data) {
@@ -5230,35 +6435,35 @@ function createTypeGuard(schema) {
5230
6435
  }
5231
6436
  var Schemas = {
5232
6437
  // Core types
5233
- WalletAddress: WalletAddressSchema,
5234
- BundleHash: BundleHashSchema,
5235
- Position: PositionSchema,
5236
- MolecularHash: MolecularHashSchema,
5237
- TokenSlug: TokenSlugSchema,
5238
- BatchId: BatchIdSchema,
5239
- CellSlug: CellSlugSchema,
6438
+ WalletAddress: WalletAddressSchema2,
6439
+ BundleHash: BundleHashSchema2,
6440
+ Position: PositionSchema2,
6441
+ MolecularHash: MolecularHashSchema2,
6442
+ TokenSlug: TokenSlugSchema2,
6443
+ BatchId: BatchIdSchema2,
6444
+ CellSlug: CellSlugSchema2,
5240
6445
  // Entities
5241
- AtomParams: AtomParamsSchema,
5242
- WalletParams: WalletParamsSchema,
5243
- MoleculeParams: MoleculeParamsSchema,
6446
+ AtomParams: AtomParamsSchema2,
6447
+ WalletParams: WalletParamsSchema2,
6448
+ MoleculeParams: MoleculeParamsSchema2,
5244
6449
  // Configuration
5245
- ClientConfig: KnishIOClientConfigSchema,
6450
+ ClientConfig: KnishIOClientConfigSchema2,
5246
6451
  EnvironmentConfig: EnvironmentConfigSchema,
5247
6452
  // Operations
5248
- TransferParams: TransferParamsSchema,
5249
- CreateTokenParams: CreateTokenParamsSchema,
5250
- RequestTokensParams: RequestTokensParamsSchema,
6453
+ TransferParams: TransferParamsSchema2,
6454
+ CreateTokenParams: CreateTokenParamsSchema2,
6455
+ RequestTokensParams: RequestTokensParamsSchema2,
5251
6456
  // Queries
5252
- BalanceQueryParams: BalanceQueryParamsSchema,
5253
- MetaQueryParams: MetaQueryParamsSchema,
5254
- WalletQueryParams: WalletQueryParamsSchema,
6457
+ BalanceQueryParams: BalanceQueryParamsSchema2,
6458
+ MetaQueryParams: MetaQueryParamsSchema2,
6459
+ WalletQueryParams: WalletQueryParamsSchema2,
5255
6460
  // Auth
5256
- AuthTokenParams: AuthTokenParamsSchema,
5257
- AuthParams: AuthParamsSchema,
5258
- GuestAuthParams: GuestAuthParamsSchema,
6461
+ AuthTokenParams: AuthTokenParamsSchema2,
6462
+ AuthParams: AuthParamsSchema2,
6463
+ GuestAuthParams: GuestAuthParamsSchema2,
5259
6464
  // GraphQL
5260
- GraphQLRequest: GraphQLRequestSchema,
5261
- GraphQLResponse: GraphQLResponseSchema
6465
+ GraphQLRequest: GraphQLRequestSchema2,
6466
+ GraphQLResponse: GraphQLResponseSchema2
5262
6467
  };
5263
6468
 
5264
6469
  // src/validation/ValidationService.ts
@@ -5937,7 +7142,8 @@ var ResponseBalance = class _ResponseBalance extends Response {
5937
7142
  * Matches JavaScript SDK payload() method exactly
5938
7143
  */
5939
7144
  payload() {
5940
- const walletData = this.data();
7145
+ const balanceData = this.data();
7146
+ const walletData = Array.isArray(balanceData) ? balanceData[0] : balanceData;
5941
7147
  if (!walletData || !walletData.bundleHash || !walletData.tokenSlug) {
5942
7148
  return null;
5943
7149
  }
@@ -5955,7 +7161,7 @@ var ResponseBalance = class _ResponseBalance extends Response {
5955
7161
  secret = null
5956
7162
  }) {
5957
7163
  let wallet;
5958
- if (data.position === null || typeof data.position === "undefined") {
7164
+ if (!data.position) {
5959
7165
  wallet = Wallet.create({
5960
7166
  bundle: data.bundleHash,
5961
7167
  token: data.tokenSlug,
@@ -5984,7 +7190,7 @@ var ResponseBalance = class _ResponseBalance extends Response {
5984
7190
  wallet.tradeRates[tradeRate.tokenSlug] = tradeRate.amount;
5985
7191
  }
5986
7192
  }
5987
- wallet.balance = Number(data.amount || 0);
7193
+ wallet.balance = String(data.amount != null ? data.amount : 0);
5988
7194
  wallet.pubkey = data.pubkey;
5989
7195
  wallet.createdAt = data.createdAt;
5990
7196
  return wallet;
@@ -6177,7 +7383,7 @@ var ResponseWalletList = class _ResponseWalletList extends Response {
6177
7383
  wallet.tradeRates[tradeRate.tokenSlug] = tradeRate.amount;
6178
7384
  }
6179
7385
  }
6180
- wallet.balance = Number(data.amount);
7386
+ wallet.balance = String(data.amount != null ? data.amount : 0);
6181
7387
  wallet.pubkey = data.pubkey;
6182
7388
  wallet.createdAt = data.createdAt;
6183
7389
  return wallet;
@@ -6215,8 +7421,8 @@ var QueryWalletList = class extends Query {
6215
7421
  */
6216
7422
  constructor(graphQLClient, knishIOClient) {
6217
7423
  super(graphQLClient, knishIOClient);
6218
- this.$__query = gql`query( $bundleHash: String, $tokenSlug: String ) {
6219
- Wallet( bundleHash: $bundleHash, tokenSlug: $tokenSlug ) {
7424
+ this.$__query = gql`query( $bundleHash: String, $token: String ) {
7425
+ Wallet( bundleHash: $bundleHash, token: $token ) {
6220
7426
  address,
6221
7427
  bundleHash,
6222
7428
  token {
@@ -6358,7 +7564,7 @@ var ResponseContinuId = class extends Response {
6358
7564
  wallet.batchId = continuId.batchId;
6359
7565
  wallet.characters = continuId.characters;
6360
7566
  wallet.pubkey = continuId.pubkey;
6361
- wallet.balance = continuId.amount * 1;
7567
+ wallet.balance = String(continuId.amount != null ? continuId.amount : 0);
6362
7568
  }
6363
7569
  return wallet;
6364
7570
  }
@@ -6384,6 +7590,13 @@ var QueryContinuId = class extends Query {
6384
7590
  }
6385
7591
  }`;
6386
7592
  }
7593
+ /**
7594
+ * Force network-only for ContinuID queries to prevent URQL cache from
7595
+ * returning stale wallet positions after mutations advance the ContinuID chain
7596
+ */
7597
+ createQueryContext() {
7598
+ return { requestPolicy: "network-only" };
7599
+ }
6387
7600
  /**
6388
7601
  * Returns a Response object
6389
7602
  * Matches JavaScript SDK createResponse method exactly
@@ -6413,31 +7626,40 @@ var ResponseMetaType = class extends Response {
6413
7626
  dataKey: "data.MetaType"
6414
7627
  });
6415
7628
  }
7629
+ /**
7630
+ * Extracts payload from metaData object
7631
+ */
7632
+ extractPayload(metaData) {
7633
+ return {
7634
+ instances: metaData?.instances || [],
7635
+ instanceCount: metaData?.instanceCount || [],
7636
+ paginatorInfo: metaData?.paginatorInfo || {}
7637
+ };
7638
+ }
6416
7639
  /**
6417
7640
  * Returns meta type instance results
6418
- * Matches JavaScript SDK payload method exactly
7641
+ * Handles various response formats from server:
7642
+ * - Array of results (normal case)
7643
+ * - Single object (filtered queries)
7644
+ * - null/undefined (no results)
7645
+ * - Empty array (no matching data)
6419
7646
  */
6420
7647
  payload() {
6421
7648
  const metaTypeData = this.data();
6422
- if (!metaTypeData || metaTypeData.length === 0) {
7649
+ if (metaTypeData === null || metaTypeData === void 0) {
6423
7650
  return null;
6424
7651
  }
6425
- const response = {
6426
- instances: {},
6427
- instanceCount: {},
6428
- paginatorInfo: {}
6429
- };
6430
- const metaData = metaTypeData.pop();
6431
- if (metaData.instances) {
6432
- response.instances = metaData.instances;
6433
- }
6434
- if (metaData.instanceCount) {
6435
- response.instanceCount = metaData.instanceCount;
6436
- }
6437
- if (metaData.paginatorInfo) {
6438
- response.paginatorInfo = metaData.paginatorInfo;
7652
+ if (Array.isArray(metaTypeData)) {
7653
+ if (metaTypeData.length === 0) {
7654
+ return this.extractPayload(null);
7655
+ }
7656
+ const metaData = metaTypeData[metaTypeData.length - 1];
7657
+ return this.extractPayload(metaData);
6439
7658
  }
6440
- return response;
7659
+ if (typeof metaTypeData === "object") {
7660
+ return this.extractPayload(metaTypeData);
7661
+ }
7662
+ return null;
6441
7663
  }
6442
7664
  };
6443
7665
  var QueryMetaType = class extends Query {
@@ -6905,10 +8127,9 @@ var ResponsePolicy = class extends Response {
6905
8127
  }) {
6906
8128
  super({
6907
8129
  query,
6908
- json
8130
+ json,
8131
+ dataKey: "data.Policy"
6909
8132
  });
6910
- this.dataKey = "data.Policy";
6911
- this.init();
6912
8133
  }
6913
8134
  /**
6914
8135
  * Returns the policy payload
@@ -7011,7 +8232,6 @@ var QueryActiveSession = class extends Query {
7011
8232
  metaId
7012
8233
  jsonData
7013
8234
  createdAt
7014
- updatedAt
7015
8235
  }
7016
8236
  }
7017
8237
  `;
@@ -7344,6 +8564,252 @@ var QueryMetaTypeViaAtom = class extends Query {
7344
8564
  }
7345
8565
  };
7346
8566
 
8567
+ // src/response/ResponseMetaTypeViaMolecule.ts
8568
+ init_Response();
8569
+ var ResponseMetaTypeViaMolecule = class _ResponseMetaTypeViaMolecule extends Response {
8570
+ /**
8571
+ * Class constructor
8572
+ */
8573
+ constructor({
8574
+ query,
8575
+ json
8576
+ }) {
8577
+ super({
8578
+ query,
8579
+ json,
8580
+ dataKey: "data.MetaTypeViaAtom"
8581
+ });
8582
+ }
8583
+ /**
8584
+ * Extracts metas from a molecule's atoms' metasJson for a specific instance.
8585
+ * Filters atoms by matching metaType and metaId, then parses metasJson.
8586
+ */
8587
+ static extractMetasFromMolecule(molecule, metaType, metaId) {
8588
+ if (!molecule || !molecule.atoms) {
8589
+ return [];
8590
+ }
8591
+ const metas = [];
8592
+ for (const atom of molecule.atoms) {
8593
+ if (atom.metaType !== metaType || atom.metaId !== metaId) {
8594
+ continue;
8595
+ }
8596
+ if (!atom.metasJson) {
8597
+ continue;
8598
+ }
8599
+ let parsed;
8600
+ try {
8601
+ parsed = JSON.parse(atom.metasJson);
8602
+ if (!Array.isArray(parsed)) {
8603
+ continue;
8604
+ }
8605
+ } catch (e) {
8606
+ continue;
8607
+ }
8608
+ for (const entry of parsed) {
8609
+ metas.push({
8610
+ molecularHash: molecule.molecularHash,
8611
+ position: atom.position,
8612
+ key: entry.key,
8613
+ value: entry.value,
8614
+ createdAt: atom.createdAt
8615
+ });
8616
+ }
8617
+ }
8618
+ return metas;
8619
+ }
8620
+ /**
8621
+ * Returns meta type instance results with metas synthesized from molecule data.
8622
+ * Produces the same payload format as ResponseMetaType and ResponseMetaTypeViaAtom:
8623
+ * { instances, instanceCount, paginatorInfo }
8624
+ */
8625
+ payload() {
8626
+ const metaTypeData = this.data();
8627
+ if (!metaTypeData || metaTypeData.length === 0) {
8628
+ return null;
8629
+ }
8630
+ const response = {
8631
+ instances: {},
8632
+ instanceCount: {},
8633
+ paginatorInfo: {}
8634
+ };
8635
+ const metaData = metaTypeData.pop();
8636
+ if (metaData.instances) {
8637
+ response.instances = metaData.instances.map((instance) => {
8638
+ let metas = instance.metas;
8639
+ if (!metas || metas.length === 0) {
8640
+ metas = _ResponseMetaTypeViaMolecule.extractMetasFromMolecule(
8641
+ instance.molecule,
8642
+ instance.metaType,
8643
+ instance.metaId
8644
+ );
8645
+ }
8646
+ return {
8647
+ ...instance,
8648
+ metas
8649
+ };
8650
+ });
8651
+ }
8652
+ if (metaData.instanceCount) {
8653
+ response.instanceCount = metaData.instanceCount;
8654
+ }
8655
+ if (metaData.paginatorInfo) {
8656
+ response.paginatorInfo = metaData.paginatorInfo;
8657
+ }
8658
+ return response;
8659
+ }
8660
+ /**
8661
+ * Verifies the cryptographic integrity of all molecules associated
8662
+ * with meta instances in this response.
8663
+ */
8664
+ verifyIntegrity() {
8665
+ const results = [];
8666
+ const metaTypeData = this.data();
8667
+ if (!metaTypeData || metaTypeData.length === 0) {
8668
+ return { verified: true, molecules: results };
8669
+ }
8670
+ const instances = metaTypeData[metaTypeData.length - 1]?.instances || [];
8671
+ for (const instance of instances) {
8672
+ if (!instance.molecule) continue;
8673
+ results.push(CheckMolecule.verifyFromServerData(instance.molecule));
8674
+ }
8675
+ return {
8676
+ verified: results.length === 0 || results.every((r) => r.verified),
8677
+ molecules: results
8678
+ };
8679
+ }
8680
+ };
8681
+ var QueryMetaTypeViaMolecule = class extends Query {
8682
+ /**
8683
+ * Create new QueryMetaTypeViaMolecule instance
8684
+ */
8685
+ constructor(graphQLClient, knishIOClient) {
8686
+ super(graphQLClient, knishIOClient);
8687
+ this.$__query = gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
8688
+ MetaTypeViaAtom(
8689
+ metaTypes: $metaTypes
8690
+ metaIds: $metaIds
8691
+ atomValues: $atomValues
8692
+ cellSlugs: $cellSlugs
8693
+ filter: $filter,
8694
+ latest: $latest,
8695
+ queryArgs: $queryArgs
8696
+ countBy: $countBy
8697
+ ) {
8698
+ metaType,
8699
+ instanceCount {
8700
+ key,
8701
+ value
8702
+ },
8703
+ instances {
8704
+ metaType,
8705
+ metaId,
8706
+ createdAt,
8707
+ metas( values: $values, keys: $keys ) {
8708
+ molecularHash,
8709
+ position,
8710
+ key,
8711
+ value,
8712
+ createdAt
8713
+ },
8714
+ molecule {
8715
+ molecularHash,
8716
+ bundleHash,
8717
+ cellSlug,
8718
+ status,
8719
+ createdAt,
8720
+ atoms {
8721
+ position,
8722
+ walletAddress,
8723
+ isotope,
8724
+ tokenSlug,
8725
+ value,
8726
+ batchId,
8727
+ metaType,
8728
+ metaId,
8729
+ index,
8730
+ createdAt,
8731
+ otsFragment,
8732
+ metasJson
8733
+ }
8734
+ }
8735
+ },
8736
+ paginatorInfo {
8737
+ currentPage,
8738
+ total
8739
+ }
8740
+ }
8741
+ }`;
8742
+ }
8743
+ /**
8744
+ * Builds a GraphQL-friendly variables object based on input fields
8745
+ */
8746
+ static createVariables({
8747
+ metaType = null,
8748
+ metaId = null,
8749
+ key = null,
8750
+ value = null,
8751
+ keys = null,
8752
+ values = null,
8753
+ atomValues = null,
8754
+ latest = null,
8755
+ filter = null,
8756
+ queryArgs = null,
8757
+ countBy = null,
8758
+ cellSlug = null
8759
+ } = {}) {
8760
+ const variables = {};
8761
+ if (atomValues) {
8762
+ variables.atomValues = atomValues;
8763
+ }
8764
+ if (keys) {
8765
+ variables.keys = keys;
8766
+ }
8767
+ if (values) {
8768
+ variables.values = values;
8769
+ }
8770
+ if (metaType) {
8771
+ variables.metaTypes = typeof metaType === "string" ? [metaType] : metaType;
8772
+ }
8773
+ if (metaId) {
8774
+ variables.metaIds = typeof metaId === "string" ? [metaId] : metaId;
8775
+ }
8776
+ if (cellSlug) {
8777
+ variables.cellSlugs = typeof cellSlug === "string" ? [cellSlug] : cellSlug;
8778
+ }
8779
+ if (countBy) {
8780
+ variables.countBy = countBy;
8781
+ }
8782
+ if (filter) {
8783
+ variables.filter = filter;
8784
+ }
8785
+ if (key && value) {
8786
+ variables.filter = variables.filter || [];
8787
+ variables.filter.push({
8788
+ key,
8789
+ value,
8790
+ comparison: "="
8791
+ });
8792
+ }
8793
+ variables.latest = latest === true;
8794
+ if (queryArgs) {
8795
+ if (typeof queryArgs.limit === "undefined" || queryArgs.limit === 0) {
8796
+ queryArgs.limit = "*";
8797
+ }
8798
+ variables.queryArgs = queryArgs;
8799
+ }
8800
+ return variables;
8801
+ }
8802
+ /**
8803
+ * Returns a Response object
8804
+ */
8805
+ createResponse(json) {
8806
+ return new ResponseMetaTypeViaMolecule({
8807
+ query: this,
8808
+ json
8809
+ });
8810
+ }
8811
+ };
8812
+
7347
8813
  // src/response/ResponseProposeMolecule.ts
7348
8814
  init_Response();
7349
8815
  init_Dot();
@@ -7362,7 +8828,6 @@ var ResponseProposeMolecule = class extends Response {
7362
8828
  dataKey: "data.ProposeMolecule"
7363
8829
  });
7364
8830
  this.$__clientMolecule = query.molecule();
7365
- this.init();
7366
8831
  }
7367
8832
  /**
7368
8833
  * Initialize response object with payload data
@@ -7926,12 +9391,31 @@ var ResponseRequestAuthorization = class extends ResponseProposeMolecule {
7926
9391
  return this.payloadKey("token");
7927
9392
  }
7928
9393
  /**
7929
- * Returns timestamp
7930
- * Matches JavaScript SDK time method exactly
9394
+ * Returns raw time value from payload
7931
9395
  */
7932
9396
  time() {
7933
9397
  return this.payloadKey("time");
7934
9398
  }
9399
+ /**
9400
+ * Returns the expiration timestamp as Unix seconds.
9401
+ * Handles both server formats:
9402
+ * - PHP server: time = lifetime in ms, expiresAt = Unix timestamp in payload
9403
+ * - Rust server: time = Unix timestamp in seconds
9404
+ */
9405
+ expiresAt() {
9406
+ try {
9407
+ const ea = this.payloadKey("expiresAt");
9408
+ if (ea) {
9409
+ return Number(ea);
9410
+ }
9411
+ } catch (_e) {
9412
+ }
9413
+ const timeValue = Number(this.time());
9414
+ if (timeValue >= 1577836800) {
9415
+ return timeValue;
9416
+ }
9417
+ return Math.floor(Date.now() / 1e3) + Math.floor(timeValue / 1e3);
9418
+ }
7935
9419
  /**
7936
9420
  * Returns encryption info
7937
9421
  * Matches JavaScript SDK encrypt method exactly
@@ -8023,11 +9507,31 @@ var ResponseRequestAuthorizationGuest = class extends Response {
8023
9507
  return this.payloadKey("token");
8024
9508
  }
8025
9509
  /**
8026
- * Returns timestamp
9510
+ * Returns raw time value from payload
8027
9511
  */
8028
9512
  time() {
8029
9513
  return this.payloadKey("time");
8030
9514
  }
9515
+ /**
9516
+ * Returns the expiration timestamp as Unix seconds.
9517
+ * Handles both server formats:
9518
+ * - PHP server: time = lifetime in ms, expiresAt = Unix timestamp in payload
9519
+ * - Rust server: time = Unix timestamp in seconds
9520
+ */
9521
+ expiresAt() {
9522
+ try {
9523
+ const ea = this.payloadKey("expiresAt");
9524
+ if (ea) {
9525
+ return Number(ea);
9526
+ }
9527
+ } catch (_e) {
9528
+ }
9529
+ const timeValue = Number(this.time());
9530
+ if (timeValue >= 1577836800) {
9531
+ return timeValue;
9532
+ }
9533
+ return Math.floor(Date.now() / 1e3) + Math.floor(timeValue / 1e3);
9534
+ }
8031
9535
  /**
8032
9536
  * Returns public key
8033
9537
  */
@@ -8100,27 +9604,91 @@ var ResponseLinkIdentifier = class extends Response {
8100
9604
  };
8101
9605
  var MutationLinkIdentifier = class extends Mutation {
8102
9606
  /**
8103
- * Constructor
9607
+ * Constructor
9608
+ */
9609
+ constructor(graphQLClient, knishIOClient) {
9610
+ super(graphQLClient, knishIOClient);
9611
+ this.$__query = gql`
9612
+ mutation($bundle: String!, $type: String!, $content: String!) {
9613
+ LinkIdentifier(bundle: $bundle, type: $type, content: $content) {
9614
+ type
9615
+ bundle
9616
+ content
9617
+ set
9618
+ message
9619
+ }
9620
+ }
9621
+ `;
9622
+ }
9623
+ /**
9624
+ * Returns a Response object
9625
+ */
9626
+ createResponse(json) {
9627
+ return new ResponseLinkIdentifier({
9628
+ query: this,
9629
+ json
9630
+ });
9631
+ }
9632
+ };
9633
+
9634
+ // src/response/ResponsePeering.ts
9635
+ var ResponsePeering = class extends ResponseProposeMolecule {
9636
+ };
9637
+
9638
+ // src/mutation/MutationPeering.ts
9639
+ var MutationPeering = class extends MutationProposeMolecule {
9640
+ /**
9641
+ * Fills a molecule with a P-isotope peering atom
9642
+ * Matches JavaScript SDK fillMolecule method exactly
9643
+ */
9644
+ fillMolecule({ host }) {
9645
+ this.$__molecule.initPeering({ host });
9646
+ this.$__molecule.sign({});
9647
+ this.$__molecule.check();
9648
+ }
9649
+ /**
9650
+ * Builds a Response object out of a JSON object
9651
+ * Matches JavaScript SDK createResponse method exactly
9652
+ */
9653
+ createResponse(json) {
9654
+ return new ResponsePeering({
9655
+ query: this,
9656
+ json
9657
+ });
9658
+ }
9659
+ };
9660
+
9661
+ // src/response/ResponseAppendRequest.ts
9662
+ var ResponseAppendRequest = class extends ResponseProposeMolecule {
9663
+ };
9664
+
9665
+ // src/mutation/MutationAppendRequest.ts
9666
+ var MutationAppendRequest = class extends MutationProposeMolecule {
9667
+ /**
9668
+ * Fills a molecule with an A-isotope append request atom
9669
+ * Matches JavaScript SDK fillMolecule method exactly
8104
9670
  */
8105
- constructor(graphQLClient, knishIOClient) {
8106
- super(graphQLClient, knishIOClient);
8107
- this.$__query = gql`
8108
- mutation($bundle: String!, $type: String!, $content: String!) {
8109
- LinkIdentifier(bundle: $bundle, type: $type, content: $content) {
8110
- type
8111
- bundle
8112
- content
8113
- set
8114
- message
8115
- }
8116
- }
8117
- `;
9671
+ fillMolecule({
9672
+ metaType,
9673
+ metaId,
9674
+ action,
9675
+ meta = {}
9676
+ }) {
9677
+ this.$__molecule.initAppendRequest({
9678
+ metaType,
9679
+ metaId,
9680
+ action,
9681
+ meta
9682
+ });
9683
+ this.$__molecule.sign({});
9684
+ this.$__molecule.check();
8118
9685
  }
8119
9686
  /**
8120
- * Returns a Response object
9687
+ * Builds a Response object out of a JSON object
9688
+ * Matches JavaScript SDK createResponse method exactly
8121
9689
  */
8122
9690
  createResponse(json) {
8123
- return new ResponseLinkIdentifier({
9691
+ return new ResponseAppendRequest({
8124
9692
  query: this,
8125
9693
  json
8126
9694
  });
@@ -8349,6 +9917,7 @@ var KnishIOClient = class {
8349
9917
  $__logging = false;
8350
9918
  $__authTokenObjects = {};
8351
9919
  $__authToken = null;
9920
+ $__authInProcess = false;
8352
9921
  $__remainderWallet = null;
8353
9922
  lastMoleculeQuery = null;
8354
9923
  abortControllers = /* @__PURE__ */ new Map();
@@ -8492,6 +10061,9 @@ var KnishIOClient = class {
8492
10061
  } else {
8493
10062
  this.$__uris = uri;
8494
10063
  }
10064
+ if (this.$__client && "setUri" in this.$__client) {
10065
+ this.$__client.setUri(this.getRandomUri());
10066
+ }
8495
10067
  }
8496
10068
  /**
8497
10069
  * Gets the Knish.IO server URIs
@@ -8554,7 +10126,8 @@ var KnishIOClient = class {
8554
10126
  return this.$__remainderWallet;
8555
10127
  }
8556
10128
  /**
8557
- * Creates a new molecule for a transaction
10129
+ * Instantiates a new Molecule and prepares this client session to operate on it
10130
+ * Matches JavaScript SDK createMolecule implementation
8558
10131
  */
8559
10132
  async createMolecule({
8560
10133
  secret = null,
@@ -8567,15 +10140,24 @@ var KnishIOClient = class {
8567
10140
  bundle = bundle || this.getBundle();
8568
10141
  if (!sourceWallet && this.lastMoleculeQuery && this.getRemainderWallet()?.token === "USER" && this.lastMoleculeQuery.response() && this.lastMoleculeQuery.response()?.success()) {
8569
10142
  sourceWallet = this.getRemainderWallet();
10143
+ this.log("info", `KnishIOClient::createMolecule() - Using carry-forward remainder wallet at position ${sourceWallet?.position?.substring(0, 16)}...`);
8570
10144
  }
8571
10145
  if (!sourceWallet) {
8572
10146
  sourceWallet = await this.getSourceWallet();
8573
10147
  }
8574
- return new Molecule({
10148
+ this.setRemainderWallet(remainderWallet || Wallet.create({
8575
10149
  secret,
8576
10150
  bundle,
10151
+ token: "USER",
10152
+ batchId: sourceWallet.batchId,
10153
+ characters: sourceWallet.characters
10154
+ }));
10155
+ return new Molecule({
10156
+ secret,
8577
10157
  sourceWallet,
8578
- remainderWallet
10158
+ remainderWallet: this.getRemainderWallet(),
10159
+ cellSlug: this.getCellSlug(),
10160
+ version: this.getServerSdkVersion()
8579
10161
  });
8580
10162
  }
8581
10163
  /**
@@ -8598,7 +10180,7 @@ var KnishIOClient = class {
8598
10180
  * Executes a query or mutation
8599
10181
  */
8600
10182
  async executeQuery(query, variables = null) {
8601
- if (this.$__authToken && this.$__authToken.isExpired()) {
10183
+ if (this.$__authToken && this.$__authToken.isExpired() && !this.$__authInProcess) {
8602
10184
  this.log("info", "KnishIOClient::executeQuery() - Access token is expired. Getting new one...");
8603
10185
  await this.requestAuthToken({
8604
10186
  secret: this.$__secret,
@@ -8625,14 +10207,26 @@ var KnishIOClient = class {
8625
10207
  }
8626
10208
  }
8627
10209
  /**
8628
- * Gets source wallet - basic implementation
10210
+ * Retrieves this session's wallet used for signing the next Molecule
10211
+ * Queries ContinuID from the server to get the authoritative position
10212
+ * Matches JavaScript SDK getSourceWallet implementation
8629
10213
  */
8630
10214
  async getSourceWallet() {
8631
- return Wallet.create({
8632
- secret: this.getSecret(),
8633
- bundle: this.getBundle(),
8634
- token: "USER"
8635
- });
10215
+ let sourceWallet = (await this.queryContinuId({
10216
+ bundle: this.getBundle()
10217
+ }))?.payload();
10218
+ if (!sourceWallet) {
10219
+ sourceWallet = new Wallet({
10220
+ secret: this.getSecret()
10221
+ });
10222
+ } else {
10223
+ sourceWallet.key = Wallet.generateKey({
10224
+ secret: this.getSecret(),
10225
+ token: sourceWallet.token,
10226
+ position: sourceWallet.position
10227
+ });
10228
+ }
10229
+ return sourceWallet;
8636
10230
  }
8637
10231
  /**
8638
10232
  * Transfer tokens between wallets
@@ -8661,7 +10255,7 @@ var KnishIOClient = class {
8661
10255
  amount
8662
10256
  });
8663
10257
  }
8664
- if (sourceWallet === null || Decimal.cmp(sourceWallet.balance, amount) < 0) {
10258
+ if (sourceWallet === null || Decimal.cmp(Number(sourceWallet.balance), amount) < 0) {
8665
10259
  throw new TransferBalanceException();
8666
10260
  }
8667
10261
  const recipientWallet = Wallet.create({
@@ -8696,19 +10290,48 @@ var KnishIOClient = class {
8696
10290
  return await this.executeQuery(query);
8697
10291
  }
8698
10292
  /**
8699
- * Request authorization token
10293
+ * Request authorization token (guest or profile)
10294
+ *
10295
+ * @param secret - User secret for profile auth (null for guest)
10296
+ * @param seed - Seed to generate secret (alternative to secret)
10297
+ * @param cellSlug - Cell slug for scoped access
10298
+ * @param encrypt - Whether to use encryption
8700
10299
  */
8701
10300
  async requestAuthToken({
8702
- secret: _secret = null,
8703
- seed: _seed = null,
8704
- cellSlug: _cellSlug = null,
8705
- encrypt: _encrypt = false
10301
+ secret = null,
10302
+ seed = null,
10303
+ cellSlug = null,
10304
+ encrypt = false
8706
10305
  } = {}) {
8707
10306
  if (this.$__serverSdkVersion < 3) {
8708
- this.log("warn", "KnishIOClient::authorize() - Server SDK version does not require an authorization...");
10307
+ this.log("warn", "KnishIOClient::requestAuthToken() - Server SDK version does not require authorization...");
8709
10308
  return null;
8710
10309
  }
8711
- return null;
10310
+ if (secret === null && seed) {
10311
+ secret = generateSecret(seed);
10312
+ }
10313
+ if (cellSlug) {
10314
+ this.setCellSlug(cellSlug);
10315
+ }
10316
+ this.$__authInProcess = true;
10317
+ let response;
10318
+ if (secret) {
10319
+ response = await this.requestProfileAuthToken({
10320
+ secret,
10321
+ encrypt
10322
+ });
10323
+ } else {
10324
+ response = await this.requestGuestAuthToken({
10325
+ cellSlug: cellSlug || this.getCellSlug(),
10326
+ encrypt
10327
+ });
10328
+ }
10329
+ if (this.$__authToken) {
10330
+ this.log("info", `KnishIOClient::requestAuthToken() - Successfully retrieved auth token...`);
10331
+ }
10332
+ this.switchEncryption(encrypt);
10333
+ this.$__authInProcess = false;
10334
+ return response;
8712
10335
  }
8713
10336
  /**
8714
10337
  * Logging utility
@@ -8806,7 +10429,7 @@ var KnishIOClient = class {
8806
10429
  });
8807
10430
  const sourceWallet = response.payload();
8808
10431
  const amountNum = typeof amount === "string" ? Number(amount) : amount;
8809
- if (sourceWallet === null || Decimal.cmp(sourceWallet.balance || 0, amountNum) < 0) {
10432
+ if (sourceWallet === null || Decimal.cmp(Number(sourceWallet.balance || 0), amountNum) < 0) {
8810
10433
  throw new TransferBalanceException();
8811
10434
  }
8812
10435
  if (!sourceWallet.position || !sourceWallet.address) {
@@ -8826,7 +10449,7 @@ var KnishIOClient = class {
8826
10449
  const walletQuery = this.createQuery(QueryWalletList);
8827
10450
  const response = await this.executeQuery(walletQuery, {
8828
10451
  bundleHash: bundle || this.getBundle(),
8829
- tokenSlug: token,
10452
+ token,
8830
10453
  unspent
8831
10454
  });
8832
10455
  return response?.payload() || [];
@@ -8876,6 +10499,7 @@ var KnishIOClient = class {
8876
10499
  count = null,
8877
10500
  countBy = null,
8878
10501
  throughAtom = true,
10502
+ throughMolecule = false,
8879
10503
  values = null,
8880
10504
  keys = null,
8881
10505
  atomValues = null
@@ -8883,7 +10507,23 @@ var KnishIOClient = class {
8883
10507
  this.log("info", `KnishIOClient::queryMeta() - Querying metaType: ${metaType}, metaId: ${metaId}...`);
8884
10508
  let query;
8885
10509
  let variables;
8886
- if (throughAtom) {
10510
+ if (throughMolecule) {
10511
+ query = this.createQuery(QueryMetaTypeViaMolecule);
10512
+ variables = QueryMetaTypeViaMolecule.createVariables({
10513
+ metaType,
10514
+ metaId,
10515
+ key,
10516
+ value,
10517
+ latest,
10518
+ filter,
10519
+ queryArgs,
10520
+ countBy,
10521
+ values,
10522
+ keys,
10523
+ atomValues,
10524
+ cellSlug: this.getCellSlug()
10525
+ });
10526
+ } else if (throughAtom) {
8887
10527
  query = this.createQuery(QueryMetaTypeViaAtom);
8888
10528
  variables = QueryMetaTypeViaAtom.createVariables({
8889
10529
  metaType,
@@ -8916,6 +10556,19 @@ var KnishIOClient = class {
8916
10556
  }
8917
10557
  return this.executeQuery(query, variables);
8918
10558
  }
10559
+ /**
10560
+ * Queries meta assets and verifies cryptographic integrity of associated molecules.
10561
+ * Forces throughMolecule=true to ensure molecule data is available for verification.
10562
+ * Returns the same response as queryMeta(), with an additional `integrity` field on the payload.
10563
+ */
10564
+ async queryMetaVerified(params) {
10565
+ const response = await this.queryMeta({ ...params, throughMolecule: true });
10566
+ const payload = response.payload();
10567
+ if (payload && typeof response.verifyIntegrity === "function") {
10568
+ payload.integrity = response.verifyIntegrity();
10569
+ }
10570
+ return response;
10571
+ }
8919
10572
  /**
8920
10573
  * Query cascading meta instances for batchId
8921
10574
  */
@@ -9178,7 +10831,7 @@ var KnishIOClient = class {
9178
10831
  const recipientWallet = new Wallet({
9179
10832
  secret: this.getSecret(),
9180
10833
  bundle: this.getBundle(),
9181
- token: token.toUpperCase(),
10834
+ token,
9182
10835
  batchId
9183
10836
  });
9184
10837
  await mutation.fillMolecule({
@@ -9206,7 +10859,7 @@ var KnishIOClient = class {
9206
10859
  this.log("info", `KnishIOClient::requestTokens() - Requesting ${amount || "units"} of ${token}...`);
9207
10860
  const mutation = await this.createMoleculeMutation({ mutationClass: MutationRequestTokens });
9208
10861
  await mutation.fillMolecule({
9209
- token: token.toUpperCase(),
10862
+ token,
9210
10863
  amount: amount ?? 0,
9211
10864
  metaType: to || "",
9212
10865
  metaId: to || "",
@@ -9235,11 +10888,17 @@ var KnishIOClient = class {
9235
10888
  amount: amount || 0
9236
10889
  });
9237
10890
  }
9238
- const mutation = await this.createMoleculeMutation({ mutationClass: MutationTransferTokens });
10891
+ const molecule = await this.createMolecule({
10892
+ sourceWallet
10893
+ });
10894
+ const mutation = await this.createMoleculeMutation({
10895
+ mutationClass: MutationTransferTokens,
10896
+ molecule
10897
+ });
9239
10898
  const recipientWallet = new Wallet({
9240
10899
  secret: this.getSecret(),
9241
10900
  bundle: "0000000000000000000000000000000000000000000000000000000000000000",
9242
- token: token.toUpperCase()
10901
+ token
9243
10902
  });
9244
10903
  await mutation.fillMolecule({
9245
10904
  recipientWallet,
@@ -9294,7 +10953,7 @@ var KnishIOClient = class {
9294
10953
  const newWallet = new Wallet({
9295
10954
  secret: this.getSecret(),
9296
10955
  bundle: this.getBundle(),
9297
- token: token.toUpperCase()
10956
+ token
9298
10957
  });
9299
10958
  await mutation.fillMolecule(newWallet);
9300
10959
  const response = await this.executeQuery(mutation);
@@ -9325,7 +10984,7 @@ var KnishIOClient = class {
9325
10984
  }
9326
10985
  const mutation = await this.createMoleculeMutation({ mutationClass: MutationClaimShadowWallet });
9327
10986
  await mutation.fillMolecule({
9328
- token: token.toUpperCase(),
10987
+ token,
9329
10988
  batchId: shadowWallet.batchId
9330
10989
  });
9331
10990
  const response = await this.executeQuery(mutation);
@@ -9373,11 +11032,16 @@ var KnishIOClient = class {
9373
11032
  policy = null
9374
11033
  }) {
9375
11034
  this.log("info", `KnishIOClient::createMeta() - Creating metadata for ${metaType}:${metaId}...`);
9376
- const mutation = await this.createMoleculeMutation({ mutationClass: MutationCreateMeta });
11035
+ const mutation = await this.createMoleculeMutation({
11036
+ mutationClass: MutationCreateMeta,
11037
+ molecule: await this.createMolecule({
11038
+ secret: this.getSecret()
11039
+ })
11040
+ });
9377
11041
  await mutation.fillMolecule({
9378
- metaType: metaType.toUpperCase(),
11042
+ metaType,
9379
11043
  metaId,
9380
- meta,
11044
+ meta: meta || {},
9381
11045
  policy
9382
11046
  });
9383
11047
  const response = await this.executeQuery(mutation);
@@ -9396,9 +11060,14 @@ var KnishIOClient = class {
9396
11060
  policy = null
9397
11061
  }) {
9398
11062
  this.log("info", `KnishIOClient::createRule() - Creating rule for ${metaType}:${metaId}...`);
9399
- const mutation = await this.createMoleculeMutation({ mutationClass: MutationCreateRule });
11063
+ const mutation = await this.createMoleculeMutation({
11064
+ mutationClass: MutationCreateRule,
11065
+ molecule: await this.createMolecule({
11066
+ secret: this.getSecret()
11067
+ })
11068
+ });
9400
11069
  await mutation.fillMolecule({
9401
- metaType: metaType.toUpperCase(),
11070
+ metaType,
9402
11071
  metaId,
9403
11072
  rule,
9404
11073
  policy
@@ -9485,8 +11154,8 @@ var KnishIOClient = class {
9485
11154
  this.log("info", `KnishIOClient::activeSession() - Declaring active session for ${metaType}:${metaId}...`);
9486
11155
  const mutation = this.createQuery(MutationActiveSession);
9487
11156
  const response = await this.executeQuery(mutation, {
9488
- bundle: bundle || this.getBundle(),
9489
- metaType: metaType.toUpperCase(),
11157
+ bundleHash: bundle || this.getBundle(),
11158
+ metaType,
9490
11159
  metaId,
9491
11160
  ipAddress,
9492
11161
  browser,
@@ -9579,6 +11248,7 @@ var KnishIOClient = class {
9579
11248
  }
9580
11249
  /**
9581
11250
  * Request profile authentication token
11251
+ * Matches JavaScript SDK requestProfileAuthToken implementation
9582
11252
  */
9583
11253
  async requestProfileAuthToken({
9584
11254
  secret,
@@ -9586,151 +11256,108 @@ var KnishIOClient = class {
9586
11256
  }) {
9587
11257
  this.log("info", "KnishIOClient::requestProfileAuthToken() - Requesting profile auth token...");
9588
11258
  this.setSecret(secret);
9589
- const mutation = await this.createMoleculeMutation({ mutationClass: MutationRequestAuthorization });
9590
- await mutation.fillMolecule({
11259
+ const wallet = new Wallet({
11260
+ secret,
11261
+ token: "AUTH"
11262
+ });
11263
+ const molecule = await this.createMolecule({
11264
+ secret,
11265
+ sourceWallet: wallet
11266
+ });
11267
+ const mutation = await this.createMoleculeMutation({
11268
+ mutationClass: MutationRequestAuthorization,
11269
+ molecule
11270
+ });
11271
+ mutation.fillMolecule({
9591
11272
  meta: { encrypt: encrypt ? "true" : "false" }
9592
11273
  });
9593
11274
  const response = await this.executeQuery(mutation);
9594
11275
  if (!response) {
9595
11276
  throw new CodeException("Profile auth token request failed");
9596
11277
  }
11278
+ if (response.success()) {
11279
+ const authToken = AuthToken.create({
11280
+ token: response.token(),
11281
+ expiresAt: response.expiresAt(),
11282
+ encrypt: String(response.encrypt()) === "true",
11283
+ pubkey: response.pubKey()
11284
+ }, wallet);
11285
+ this.setAuthToken(authToken);
11286
+ } else {
11287
+ throw new AuthorizationRejectedException_default(
11288
+ `KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${response.reason()}`
11289
+ );
11290
+ }
9597
11291
  if (encrypt) {
9598
11292
  this.switchEncryption(true);
9599
11293
  }
9600
11294
  return response;
9601
11295
  }
9602
11296
  // =============================================================================
9603
- // LEGACY/DEPRECATED METHODS
11297
+ // MUTATION METHODS - PEERING & APPEND REQUEST
9604
11298
  // =============================================================================
9605
11299
  /**
9606
- * @deprecated Use getCellSlug() instead
9607
- */
9608
- cellSlug() {
9609
- return this.getCellSlug();
9610
- }
9611
- /**
9612
- * @deprecated Use getUri() instead
11300
+ * Register a peer node via P-isotope
11301
+ * Matches JavaScript SDK registerPeer implementation exactly
9613
11302
  */
9614
- uri() {
9615
- return this.getUri();
11303
+ async registerPeer({ host }) {
11304
+ this.log("info", `KnishIOClient::registerPeer() - Registering peer at ${host}...`);
11305
+ const mutation = await this.createMoleculeMutation({
11306
+ mutationClass: MutationPeering,
11307
+ molecule: await this.createMolecule({
11308
+ secret: this.getSecret()
11309
+ })
11310
+ });
11311
+ mutation.fillMolecule({ host });
11312
+ const response = await this.executeQuery(mutation);
11313
+ if (!response) {
11314
+ throw new CodeException("Peer registration failed");
11315
+ }
11316
+ return response;
9616
11317
  }
9617
- };
9618
-
9619
- // src/AuthToken.ts
9620
- var AuthToken = class _AuthToken {
9621
- $__token;
9622
- $__expiresAt;
9623
- $__pubkey;
9624
- $__encrypt;
9625
- $__wallet;
9626
11318
  /**
9627
- * Create new AuthToken instance
11319
+ * Submit an append request via A-isotope
11320
+ * Matches JavaScript SDK appendRequest implementation exactly
9628
11321
  */
9629
- constructor({
9630
- token,
9631
- expiresAt,
9632
- encrypt,
9633
- pubkey
11322
+ async appendRequest({
11323
+ metaType,
11324
+ metaId,
11325
+ action,
11326
+ meta = {}
9634
11327
  }) {
9635
- this.$__token = token;
9636
- this.$__expiresAt = expiresAt;
9637
- this.$__pubkey = pubkey;
9638
- this.$__encrypt = encrypt;
9639
- }
9640
- /**
9641
- * Static factory method to create AuthToken with wallet
9642
- */
9643
- static create(data, wallet) {
9644
- const authToken = new _AuthToken(data);
9645
- authToken.setWallet(wallet);
9646
- return authToken;
9647
- }
9648
- /**
9649
- * Restore AuthToken from snapshot
9650
- */
9651
- static restore(snapshot, secret) {
9652
- const wallet = new Wallet({
9653
- secret,
9654
- token: "AUTH",
9655
- position: snapshot.wallet.position,
9656
- characters: snapshot.wallet.characters
11328
+ this.log("info", `KnishIOClient::appendRequest() - Submitting append request for ${metaType}:${metaId}...`);
11329
+ const mutation = await this.createMoleculeMutation({
11330
+ mutationClass: MutationAppendRequest,
11331
+ molecule: await this.createMolecule({
11332
+ secret: this.getSecret()
11333
+ })
9657
11334
  });
9658
- return _AuthToken.create({
9659
- token: snapshot.token,
9660
- expiresAt: snapshot.expiresAt,
9661
- pubkey: snapshot.pubkey,
9662
- encrypt: snapshot.encrypt
9663
- }, wallet);
9664
- }
9665
- /**
9666
- * Set wallet for this auth token
9667
- */
9668
- setWallet(wallet) {
9669
- this.$__wallet = wallet;
9670
- }
9671
- /**
9672
- * Get wallet
9673
- */
9674
- getWallet() {
9675
- return this.$__wallet;
9676
- }
9677
- /**
9678
- * Get auth token
9679
- */
9680
- getToken() {
9681
- return this.$__token;
9682
- }
9683
- /**
9684
- * Get expiration timestamp
9685
- */
9686
- getExpiresAt() {
9687
- return this.$__expiresAt;
9688
- }
9689
- /**
9690
- * Get public key
9691
- */
9692
- getPubkey() {
9693
- return this.$__pubkey;
9694
- }
9695
- /**
9696
- * Check if encryption is enabled
9697
- */
9698
- isEncrypted() {
9699
- return this.$__encrypt;
9700
- }
9701
- /**
9702
- * Check if token is expired
9703
- */
9704
- isExpired() {
9705
- const now = Math.floor(Date.now() / 1e3);
9706
- return now >= this.$__expiresAt;
11335
+ mutation.fillMolecule({
11336
+ metaType,
11337
+ metaId,
11338
+ action,
11339
+ meta
11340
+ });
11341
+ const response = await this.executeQuery(mutation);
11342
+ if (!response) {
11343
+ throw new CodeException("Append request failed");
11344
+ }
11345
+ return response;
9707
11346
  }
11347
+ // =============================================================================
11348
+ // LEGACY/DEPRECATED METHODS
11349
+ // =============================================================================
9708
11350
  /**
9709
- * Get auth data for GraphQL client
11351
+ * @deprecated Use getCellSlug() instead
9710
11352
  */
9711
- getAuthData() {
9712
- return {
9713
- token: this.$__token,
9714
- pubkey: this.$__pubkey,
9715
- wallet: this.$__wallet
9716
- };
11353
+ cellSlug() {
11354
+ return this.getCellSlug();
9717
11355
  }
9718
11356
  /**
9719
- * Create snapshot for persistence
11357
+ * @deprecated Use getUri() instead
9720
11358
  */
9721
- toSnapshot() {
9722
- return {
9723
- token: this.$__token,
9724
- expiresAt: this.$__expiresAt,
9725
- pubkey: this.$__pubkey,
9726
- encrypt: this.$__encrypt,
9727
- ...this.$__wallet ? {
9728
- wallet: {
9729
- position: this.$__wallet.position,
9730
- characters: this.$__wallet.characters
9731
- }
9732
- } : {}
9733
- };
11359
+ uri() {
11360
+ return this.getUri();
9734
11361
  }
9735
11362
  };
9736
11363
 
@@ -9894,6 +11521,6 @@ var KnishIO = {
9894
11521
  SDK_INFO
9895
11522
  };
9896
11523
 
9897
- export { Atom, AtomIndexException, AtomMeta, AtomsMissingException, AuthToken, BaseException, COMPATIBLE_SERVER_VERSIONS, CRYPTO_CONSTANTS, CheckMolecule, DevUtils, Dot, EXCEPTION_CODES, EXCEPTION_TYPES, EXTENDED_COMPATIBILITY_TEST_VECTORS, ExceptionFactory, GraphQLClient, InvalidResponseException, KnishIO, KnishIOClient, Meta, MolecularHashMismatchException, Molecule, Mutation, MutationCreateMeta, MutationCreateToken, MutationCreateWallet, MutationProposeMolecule, MutationRequestAuthorization, MutationRequestTokens, MutationTransferTokens, PolicyMeta, Query, QueryAtom, QueryBalance, QueryBatch, QueryContinuId, QueryMetaType, QueryMetaTypeViaAtom, QueryWalletBundle, QueryWalletList, Response, ResponseAtom, ResponseBalance, ResponseContinuId, ResponseCreateMeta, ResponseCreateToken, ResponseCreateWallet, ResponseMetaType, ResponseMetaTypeViaAtom, ResponseProposeMolecule, ResponseRequestAuthorization, ResponseRequestTokens, ResponseTransferTokens, ResponseWalletBundle, ResponseWalletList, SDK_INFO, SDK_NAME, SDK_VERSION, SignatureMismatchException, TokenUnit, TransferBalanceException, Wallet, WalletCredentialException, base64ToHex, bufferToHexString, capitalize, charsetBaseConvert, chunkArray, chunkSubstr, configureSDK, convertToBase17, createBundleHash, createMolecularHash, createPosition, createTokenSlug, createWalletAddress, deepCloning, diff, enumerateMolecularHash, generateBatchId, generateBundleHash, generateOTSSignature, generatePosition, generateSecret, generateWalletAddress, generateWalletKey, getSDKConfig, hexStringToBuffer, hexToBase64, intersect, isAtomIsotope, isBundleHash, isHex, isHexString, isMolecularHash, isNumeric, isPosition2 as isPosition, isWalletAddress2 as isWalletAddress, normalizeMolecularHash, randomString, runCompatibilityTests, runExtendedCompatibilityTests, shake256, toCamelCase, toSnakeCase, truncate, validateBundleHash, validateMolecularHashForSignature, validateOTSSignature, validatePosition, validateSecret, validateWalletAddress, verifyOTSSignature };
11524
+ export { Atom, AtomIndexException, AtomMeta, AtomsMissingException, AuthToken, BaseException, COMPATIBLE_SERVER_VERSIONS, CRYPTO_CONSTANTS, CheckMolecule, DevUtils, Dot, EXCEPTION_CODES, EXCEPTION_TYPES, EXTENDED_COMPATIBILITY_TEST_VECTORS, ExceptionFactory, GraphQLClient, InvalidResponseException, KnishIO, KnishIOClient, Meta, MolecularHashMismatchException, Molecule, Mutation, MutationAppendRequest, MutationCreateMeta, MutationCreateToken, MutationCreateWallet, MutationPeering, MutationProposeMolecule, MutationRequestAuthorization, MutationRequestTokens, MutationTransferTokens, PolicyMeta, Query, QueryAtom, QueryBalance, QueryBatch, QueryContinuId, QueryMetaType, QueryMetaTypeViaAtom, QueryWalletBundle, QueryWalletList, Response, ResponseAppendRequest, ResponseAtom, ResponseBalance, ResponseContinuId, ResponseCreateMeta, ResponseCreateToken, ResponseCreateWallet, ResponseMetaType, ResponseMetaTypeViaAtom, ResponsePeering, ResponseProposeMolecule, ResponseRequestAuthorization, ResponseRequestTokens, ResponseTransferTokens, ResponseWalletBundle, ResponseWalletList, SDK_INFO, SDK_NAME, SDK_VERSION, SignatureMismatchException, TokenUnit, TransferBalanceException, Wallet, WalletCredentialException, base64ToHex, bufferToHexString, capitalize, charsetBaseConvert, chunkArray, chunkSubstr, configureSDK, convertToBase17, createBundleHash, createMolecularHash, createPosition, createTokenSlug, createWalletAddress, deepCloning, diff, enumerateMolecularHash, generateBatchId, generateBundleHash, generateOTSSignature, generatePosition, generateSecret, generateWalletAddress, generateWalletKey, getSDKConfig, hexStringToBuffer, hexToBase64, intersect, isAtomIsotope, isBundleHash, isHex, isHexString, isMolecularHash, isNumeric, isPosition2 as isPosition, isWalletAddress2 as isWalletAddress, normalizeMolecularHash, randomString, runCompatibilityTests, runExtendedCompatibilityTests, shake256, toCamelCase, toSnakeCase, truncate, validateBundleHash, validateMolecularHashForSignature, validateOTSSignature, validatePosition, validateSecret, validateWalletAddress, verifyOTSSignature };
9898
11525
  //# sourceMappingURL=index.js.map
9899
11526
  //# sourceMappingURL=index.js.map