@wishknish/knishio-client-ts 0.7.4 → 0.7.7

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 +2702 -1033
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +339 -106
  4. package/dist/index.d.ts +339 -106
  5. package/dist/index.iife.js +22052 -19964
  6. package/dist/index.iife.js.map +1 -1
  7. package/dist/index.js +2699 -1034
  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 +346 -51
  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 +607 -141
  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)}`);
4000
+ }
4001
+ /**
4002
+ * Gets all keys
4003
+ */
4004
+ keys() {
4005
+ return Array.from(this.__data.keys()).map(
4006
+ (key) => key.startsWith("__") ? key.substring(2) : key
4007
+ );
3270
4008
  }
3271
4009
  /**
3272
- * Find metadata item by key
4010
+ * Converts Meta object back to plain object
3273
4011
  */
3274
- static findMeta(metaItems, key) {
3275
- if (!metaItems || !Array.isArray(metaItems)) {
3276
- return null;
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,8 @@ var Molecule = class _Molecule {
3809
4803
  remainderWallet;
3810
4804
  atoms;
3811
4805
  version;
4806
+ continuIdPosition;
4807
+ parentHashes;
3812
4808
  local;
3813
4809
  /**
3814
4810
  * Create new Molecule instance
@@ -3820,7 +4816,8 @@ var Molecule = class _Molecule {
3820
4816
  sourceWallet = null,
3821
4817
  remainderWallet = null,
3822
4818
  cellSlug = null,
3823
- version = null
4819
+ version = null,
4820
+ continuIdPosition = null
3824
4821
  } = {}) {
3825
4822
  this.status = null;
3826
4823
  this.molecularHash = null;
@@ -3829,11 +4826,12 @@ var Molecule = class _Molecule {
3829
4826
  this.secret = secret;
3830
4827
  this.bundle = bundle;
3831
4828
  this.sourceWallet = sourceWallet;
4829
+ this.continuIdPosition = continuIdPosition;
3832
4830
  this.atoms = [];
3833
- if (version !== null) {
4831
+ this.parentHashes = [];
4832
+ const versionRegistry = versions_default;
4833
+ if (version !== null && Object.prototype.hasOwnProperty.call(versionRegistry, version)) {
3834
4834
  this.version = String(version);
3835
- } else {
3836
- this.version = null;
3837
4835
  }
3838
4836
  if (remainderWallet || sourceWallet) {
3839
4837
  this.remainderWallet = remainderWallet || Wallet.create({
@@ -3868,7 +4866,7 @@ var Molecule = class _Molecule {
3868
4866
  if (!Array.isArray(isotopes)) {
3869
4867
  isotopes = [isotopes];
3870
4868
  }
3871
- return atoms.filter((atom) => isotopes.includes(atom.isotope));
4869
+ return atoms.filter((atom) => atom.isotope !== null && isotopes.includes(atom.isotope));
3872
4870
  }
3873
4871
  /**
3874
4872
  * Generates the next atomic index
@@ -3889,25 +4887,65 @@ var Molecule = class _Molecule {
3889
4887
  addAtom(atom) {
3890
4888
  this.molecularHash = null;
3891
4889
  atom.index = this.generateIndex();
3892
- atom.version = this.version ? Number(this.version) : 4;
4890
+ atom.version = this.version ?? void 0;
3893
4891
  this.atoms.push(atom);
3894
4892
  this.atoms = Atom.sortAtoms(this.atoms);
3895
4893
  return this;
3896
4894
  }
3897
4895
  /**
3898
- * Add user remainder atom for ContinuID
4896
+ * Add user remainder atom for ContinuID
4897
+ * Matches JavaScript SDK addContinuIdAtom exactly
4898
+ */
4899
+ addContinuIdAtom() {
4900
+ if (!this.remainderWallet || this.remainderWallet.token !== "USER") {
4901
+ this.remainderWallet = Wallet.create({
4902
+ secret: this.secret,
4903
+ bundle: this.bundle
4904
+ });
4905
+ }
4906
+ const continuIdMeta = {};
4907
+ if (this.continuIdPosition) {
4908
+ continuIdMeta.previousPosition = this.continuIdPosition;
4909
+ } else if (this.sourceWallet && this.sourceWallet.position) {
4910
+ continuIdMeta.previousPosition = this.sourceWallet.position;
4911
+ }
4912
+ if (this.remainderWallet.pubkey) {
4913
+ continuIdMeta.pubkey = this.remainderWallet.pubkey;
4914
+ }
4915
+ if (this.remainderWallet.characters) {
4916
+ continuIdMeta.characters = this.remainderWallet.characters;
4917
+ }
4918
+ this.addAtom(Atom.create({
4919
+ isotope: "I",
4920
+ wallet: this.remainderWallet,
4921
+ metaType: "walletBundle",
4922
+ metaId: this.remainderWallet.bundle,
4923
+ meta: new AtomMeta(continuIdMeta)
4924
+ }));
4925
+ return this;
4926
+ }
4927
+ /**
4928
+ * Add a policy R-isotope atom (matching JS SDK)
3899
4929
  */
3900
- addContinuIdAtom() {
3901
- if (!this.remainderWallet) {
3902
- throw new Error("Remainder wallet required for ContinuID atom");
3903
- }
3904
- this.addAtom(new Atom({
3905
- isotope: "I",
3906
- position: this.remainderWallet.position,
3907
- walletAddress: this.remainderWallet.address,
3908
- token: "USER",
3909
- metaType: "walletBundle",
3910
- metaId: this.remainderWallet.bundle
4930
+ addPolicyAtom({
4931
+ metaType,
4932
+ metaId,
4933
+ meta = {},
4934
+ policy = {}
4935
+ }) {
4936
+ const atomMeta = new AtomMeta(meta);
4937
+ atomMeta.addPolicy(policy);
4938
+ const wallet = Wallet.create({
4939
+ secret: this.secret,
4940
+ bundle: this.sourceWallet.bundle,
4941
+ token: "USER"
4942
+ });
4943
+ this.addAtom(Atom.create({
4944
+ wallet,
4945
+ isotope: "R",
4946
+ metaType,
4947
+ metaId,
4948
+ meta: atomMeta
3911
4949
  }));
3912
4950
  return this;
3913
4951
  }
@@ -3922,34 +4960,25 @@ var Molecule = class _Molecule {
3922
4960
  if (!this.sourceWallet) {
3923
4961
  throw new Error("Source wallet required for value transfer");
3924
4962
  }
3925
- if (this.sourceWallet.balance - amount < 0) {
4963
+ if (Number(this.sourceWallet.balance) - amount < 0) {
3926
4964
  throw new BalanceInsufficientException();
3927
4965
  }
3928
- this.addAtom(new Atom({
4966
+ this.addAtom(Atom.create({
3929
4967
  isotope: "V",
3930
- position: this.sourceWallet.position,
3931
- walletAddress: this.sourceWallet.address,
3932
- token: this.sourceWallet.token,
3933
- value: -this.sourceWallet.balance
4968
+ wallet: this.sourceWallet,
4969
+ value: -Number(this.sourceWallet.balance)
3934
4970
  }));
3935
- this.addAtom(new Atom({
4971
+ this.addAtom(Atom.create({
3936
4972
  isotope: "V",
3937
- position: recipientWallet.position,
3938
- walletAddress: recipientWallet.address,
3939
- token: recipientWallet.token,
4973
+ wallet: recipientWallet,
3940
4974
  value: amount,
3941
4975
  metaType: "walletBundle",
3942
4976
  metaId: recipientWallet.bundle
3943
4977
  }));
3944
- if (!this.remainderWallet) {
3945
- throw new Error("Remainder wallet required for value transfer");
3946
- }
3947
- this.addAtom(new Atom({
4978
+ this.addAtom(Atom.create({
3948
4979
  isotope: "V",
3949
- position: this.remainderWallet.position,
3950
- walletAddress: this.remainderWallet.address,
3951
- token: this.remainderWallet.token,
3952
- value: this.sourceWallet.balance - amount,
4980
+ wallet: this.remainderWallet,
4981
+ value: Number(this.sourceWallet.balance) - amount,
3953
4982
  metaType: "walletBundle",
3954
4983
  metaId: this.remainderWallet.bundle
3955
4984
  }));
@@ -3978,6 +5007,17 @@ var Molecule = class _Molecule {
3978
5007
  throw new SignatureMalformedException("No atoms available for signing!");
3979
5008
  }
3980
5009
  let signingPosition = signingAtom.position;
5010
+ const signingWalletMeta = signingAtom.aggregatedMeta ? signingAtom.aggregatedMeta() : null;
5011
+ const signingWalletJson = signingWalletMeta?.signingWallet;
5012
+ if (signingWalletJson) {
5013
+ try {
5014
+ const parsedSigningWallet = JSON.parse(signingWalletJson);
5015
+ if (parsedSigningWallet.position) {
5016
+ signingPosition = parsedSigningWallet.position;
5017
+ }
5018
+ } catch {
5019
+ }
5020
+ }
3981
5021
  if (!signingPosition) {
3982
5022
  throw new SignatureMalformedException("Signing wallet must have a position!");
3983
5023
  }
@@ -4096,7 +5136,7 @@ var Molecule = class _Molecule {
4096
5136
  */
4097
5137
  toJSON(options = {}) {
4098
5138
  const {
4099
- includeValidationContext = true,
5139
+ includeValidationContext = false,
4100
5140
  includeOtsFragments = true,
4101
5141
  secureMode = false
4102
5142
  } = options;
@@ -4109,21 +5149,24 @@ var Molecule = class _Molecule {
4109
5149
  molecularHash: this.molecularHash,
4110
5150
  createdAt: this.createdAt,
4111
5151
  cellSlug: this.cellSlug,
4112
- cellSlugOrigin: this.cellSlugOrigin,
4113
- version: this.version,
4114
5152
  bundle: this.bundle,
4115
5153
  // Serialized atoms array with optional OTS fragments
4116
5154
  atoms: this.atoms.map((atom) => atom.toJSON({
4117
5155
  includeOtsFragments
4118
5156
  }))
4119
5157
  };
5158
+ if (this.parentHashes && this.parentHashes.length > 0) {
5159
+ serialized.parentHashes = this.parentHashes;
5160
+ }
4120
5161
  if (includeValidationContext) {
5162
+ serialized.cellSlugOrigin = this.cellSlugOrigin;
5163
+ serialized.version = this.version;
4121
5164
  if (this.sourceWallet) {
4122
5165
  serialized.sourceWallet = {
4123
5166
  address: this.sourceWallet.address,
4124
5167
  position: this.sourceWallet.position,
4125
5168
  token: this.sourceWallet.token,
4126
- balance: this.sourceWallet.balance || 0,
5169
+ balance: this.sourceWallet.balance || "0",
4127
5170
  bundle: this.sourceWallet.bundle,
4128
5171
  batchId: this.sourceWallet.batchId || null,
4129
5172
  characters: this.sourceWallet.characters || "BASE64",
@@ -4139,7 +5182,7 @@ var Molecule = class _Molecule {
4139
5182
  address: this.remainderWallet.address,
4140
5183
  position: this.remainderWallet.position,
4141
5184
  token: this.remainderWallet.token,
4142
- balance: this.remainderWallet.balance || 0,
5185
+ balance: this.remainderWallet.balance || "0",
4143
5186
  bundle: this.remainderWallet.bundle,
4144
5187
  batchId: this.remainderWallet.batchId || null,
4145
5188
  characters: this.remainderWallet.characters || "BASE64",
@@ -4167,30 +5210,26 @@ var Molecule = class _Molecule {
4167
5210
  // =============================================================================
4168
5211
  /**
4169
5212
  * Initialize token creation
5213
+ * Matches JavaScript SDK initTokenCreation implementation
4170
5214
  */
4171
5215
  initTokenCreation({
4172
5216
  recipientWallet,
4173
5217
  amount,
4174
5218
  meta
4175
5219
  }) {
4176
- this.addAtom(new Atom({
4177
- isotope: "T",
4178
- position: recipientWallet.position,
4179
- walletAddress: recipientWallet.address,
4180
- token: recipientWallet.token,
5220
+ if (!this.sourceWallet) {
5221
+ throw new Error("Source wallet required for token creation");
5222
+ }
5223
+ const atomMeta = new AtomMeta(meta);
5224
+ atomMeta.setMetaWallet(recipientWallet);
5225
+ this.addAtom(Atom.create({
5226
+ isotope: "C",
5227
+ wallet: this.sourceWallet,
4181
5228
  value: amount,
4182
5229
  metaType: "token",
4183
5230
  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) }] : []
5231
+ meta: atomMeta,
5232
+ batchId: recipientWallet.batchId
4194
5233
  }));
4195
5234
  this.addContinuIdAtom();
4196
5235
  return this;
@@ -4200,26 +5239,57 @@ var Molecule = class _Molecule {
4200
5239
  */
4201
5240
  burnToken({
4202
5241
  amount,
4203
- walletBundle = null
5242
+ walletBundle: _walletBundle = null
4204
5243
  }) {
4205
5244
  if (!this.sourceWallet) {
4206
5245
  throw new Error("Source wallet required for token burning");
4207
5246
  }
4208
- if (amount <= 0) {
4209
- throw new NegativeAmountException();
5247
+ if (amount < 0) {
5248
+ throw new NegativeAmountException("Molecule::burnToken() - Amount to burn must be positive!");
4210
5249
  }
4211
- if (this.sourceWallet.balance - amount < 0) {
5250
+ if (Number(this.sourceWallet.balance) - amount < 0) {
4212
5251
  throw new BalanceInsufficientException();
4213
5252
  }
4214
- this.addAtom(new Atom({
5253
+ const burnWallet = new Wallet({
5254
+ bundle: "0000000000000000000000000000000000000000000000000000000000000000",
5255
+ token: this.sourceWallet.token
5256
+ });
5257
+ this.addAtom(Atom.create({
4215
5258
  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
5259
+ wallet: this.sourceWallet,
5260
+ value: -Number(this.sourceWallet.balance)
5261
+ }));
5262
+ this.addAtom(Atom.create({
5263
+ isotope: "V",
5264
+ wallet: burnWallet,
5265
+ value: amount,
5266
+ metaType: "walletBundle",
5267
+ metaId: burnWallet.bundle
5268
+ }));
5269
+ this.addAtom(Atom.create({
5270
+ isotope: "V",
5271
+ wallet: this.remainderWallet,
5272
+ value: Number(this.sourceWallet.balance) - amount,
5273
+ metaType: "walletBundle",
5274
+ metaId: this.remainderWallet.bundle
5275
+ }));
5276
+ return this;
5277
+ }
5278
+ /**
5279
+ * Initialize authorization request
5280
+ * Creates U-isotope (authorization) atom for requesting auth token
5281
+ * Matches JavaScript SDK Molecule.initAuthorization
5282
+ */
5283
+ initAuthorization({ meta }) {
5284
+ if (!this.sourceWallet) {
5285
+ throw new Error("Source wallet required for authorization");
5286
+ }
5287
+ this.addAtom(Atom.create({
5288
+ isotope: "U",
5289
+ wallet: this.sourceWallet,
5290
+ meta: new AtomMeta(meta)
4222
5291
  }));
5292
+ this.addContinuIdAtom();
4223
5293
  return this;
4224
5294
  }
4225
5295
  /**
@@ -4234,59 +5304,123 @@ var Molecule = class _Molecule {
4234
5304
  if (!this.sourceWallet) {
4235
5305
  throw new Error("Source wallet required for meta creation");
4236
5306
  }
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({
5307
+ this.addAtom(Atom.create({
4253
5308
  isotope: "M",
4254
- position: this.sourceWallet.position,
4255
- walletAddress: this.sourceWallet.address,
4256
- token: this.sourceWallet.token,
5309
+ wallet: this.sourceWallet,
4257
5310
  metaType,
4258
5311
  metaId,
4259
- meta: metaArray
5312
+ meta: new AtomMeta(meta)
4260
5313
  }));
5314
+ if (policy && Object.keys(policy).length > 0) {
5315
+ this.addPolicyAtom({
5316
+ metaType,
5317
+ metaId,
5318
+ meta,
5319
+ policy
5320
+ });
5321
+ }
4261
5322
  this.addContinuIdAtom();
4262
5323
  return this;
4263
5324
  }
4264
5325
  /**
4265
5326
  * Initialize wallet creation
5327
+ * Uses source wallet for atom properties (matching JavaScript SDK)
5328
+ * The wallet being created is stored in metadata
4266
5329
  */
4267
5330
  initWalletCreation(wallet, atomMeta = null) {
4268
- const atom = new Atom({
5331
+ if (!this.sourceWallet) {
5332
+ throw new Error("Source wallet required for wallet creation");
5333
+ }
5334
+ if (!atomMeta) {
5335
+ atomMeta = new AtomMeta();
5336
+ }
5337
+ atomMeta.setMetaWallet(wallet);
5338
+ const creationAtom = Atom.create({
4269
5339
  isotope: "C",
4270
- position: wallet.position,
4271
- walletAddress: wallet.address,
4272
- token: wallet.token,
5340
+ wallet: this.sourceWallet,
4273
5341
  metaType: "wallet",
4274
5342
  metaId: wallet.address,
4275
- meta: atomMeta ? atomMeta.get() : []
5343
+ meta: atomMeta,
5344
+ batchId: wallet.batchId
4276
5345
  });
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
- }
5346
+ this.addAtom(creationAtom);
5347
+ this.addContinuIdAtom();
5348
+ return this;
5349
+ }
5350
+ /**
5351
+ * Creates atoms for rule definition
5352
+ * Matches JavaScript SDK Molecule.createRule method
5353
+ *
5354
+ * @param metaType - The meta type for the rule
5355
+ * @param metaId - The meta ID for the rule
5356
+ * @param rule - Array of Rule objects or rule data
5357
+ * @param policy - Optional policy object
5358
+ * @return This molecule instance for chaining
5359
+ */
5360
+ createRule({
5361
+ metaType,
5362
+ metaId,
5363
+ rule,
5364
+ policy = {}
5365
+ }) {
5366
+ if (!this.sourceWallet) {
5367
+ throw new Error("Source wallet required for createRule");
5368
+ }
5369
+ const ruleArray = Array.isArray(rule) ? rule : [rule];
5370
+ const rules = [];
5371
+ for (const r of ruleArray) {
5372
+ rules.push(r instanceof Rule ? r : Rule.toObject(r));
5373
+ }
5374
+ const atomMeta = new AtomMeta({
5375
+ rule: JSON.stringify(rules)
5376
+ });
5377
+ if (policy && Object.keys(policy).length > 0) {
5378
+ atomMeta.addPolicy(policy);
5379
+ }
5380
+ this.addAtom(Atom.create({
5381
+ isotope: "R",
5382
+ wallet: this.sourceWallet,
5383
+ metaType,
5384
+ metaId,
5385
+ meta: atomMeta
5386
+ }));
5387
+ this.addContinuIdAtom();
5388
+ return this;
5389
+ }
5390
+ /**
5391
+ * Initializes a token request molecule
5392
+ * Matches JavaScript SDK Molecule.initTokenRequest method
5393
+ *
5394
+ * @param token - Token slug to request
5395
+ * @param amount - Amount of tokens to request
5396
+ * @param metaType - Meta type (typically 'walletBundle')
5397
+ * @param metaId - Meta ID (typically recipient bundle hash)
5398
+ * @param meta - Optional additional metadata
5399
+ * @param batchId - Optional batch ID
5400
+ * @return This molecule instance for chaining
5401
+ */
5402
+ initTokenRequest({
5403
+ token,
5404
+ amount,
5405
+ metaType,
5406
+ metaId,
5407
+ meta = {},
5408
+ batchId = null
5409
+ }) {
5410
+ if (!this.sourceWallet) {
5411
+ throw new Error("Source wallet required for initTokenRequest");
4288
5412
  }
4289
- this.addAtom(atom);
5413
+ const metaWithToken = { ...meta, token, amount: String(amount) };
5414
+ this.local = 1;
5415
+ this.addAtom(Atom.create({
5416
+ isotope: "T",
5417
+ wallet: this.sourceWallet,
5418
+ value: amount,
5419
+ metaType,
5420
+ metaId,
5421
+ meta: new AtomMeta(metaWithToken),
5422
+ batchId
5423
+ }));
4290
5424
  this.addContinuIdAtom();
4291
5425
  return this;
4292
5426
  }
@@ -4336,6 +5470,7 @@ var Molecule = class _Molecule {
4336
5470
  }
4337
5471
  });
4338
5472
  }
5473
+ molecule.parentHashes = Array.isArray(data.parentHashes) ? [...data.parentHashes] : [];
4339
5474
  if (includeValidationContext) {
4340
5475
  if (data.sourceWallet) {
4341
5476
  molecule.sourceWallet = new Wallet({
@@ -4346,7 +5481,7 @@ var Molecule = class _Molecule {
4346
5481
  batchId: data.sourceWallet.batchId,
4347
5482
  characters: data.sourceWallet.characters
4348
5483
  });
4349
- molecule.sourceWallet.balance = data.sourceWallet.balance || 0;
5484
+ molecule.sourceWallet.balance = String(data.sourceWallet.balance != null ? data.sourceWallet.balance : 0);
4350
5485
  molecule.sourceWallet.address = data.sourceWallet.address;
4351
5486
  if (data.sourceWallet.pubkey) {
4352
5487
  molecule.sourceWallet.pubkey = data.sourceWallet.pubkey;
@@ -4364,7 +5499,7 @@ var Molecule = class _Molecule {
4364
5499
  batchId: data.remainderWallet.batchId,
4365
5500
  characters: data.remainderWallet.characters
4366
5501
  });
4367
- molecule.remainderWallet.balance = data.remainderWallet.balance || 0;
5502
+ molecule.remainderWallet.balance = String(data.remainderWallet.balance != null ? data.remainderWallet.balance : 0);
4368
5503
  molecule.remainderWallet.address = data.remainderWallet.address;
4369
5504
  if (data.remainderWallet.pubkey) {
4370
5505
  molecule.remainderWallet.pubkey = data.remainderWallet.pubkey;
@@ -4385,245 +5520,208 @@ var Molecule = class _Molecule {
4385
5520
  static jsonToObject(json) {
4386
5521
  return _Molecule.fromJSON(json);
4387
5522
  }
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
- }
5523
+ // =============================================================================
5524
+ // ISOTOPE INIT METHODS - MATCHING JAVASCRIPT SDK PARITY
5525
+ // =============================================================================
4398
5526
  /**
4399
- * Merge additional metadata
4400
- * @param meta - Metadata to merge
4401
- * @return This instance for chaining
5527
+ * Initialize a P-type molecule for peer registration
5528
+ * Matches JavaScript SDK Molecule.initPeering implementation exactly
5529
+ *
5530
+ * @param host - The peer host URL to register
5531
+ * @return This molecule instance for chaining
4402
5532
  */
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
- }
5533
+ initPeering({ host }) {
5534
+ if (!this.sourceWallet) {
5535
+ throw new Error("Source wallet required for peer registration");
4416
5536
  }
5537
+ this.addAtom(Atom.create({
5538
+ isotope: "P",
5539
+ wallet: this.sourceWallet,
5540
+ metaType: "walletBundle",
5541
+ metaId: this.bundle,
5542
+ meta: new AtomMeta({ peerHost: host })
5543
+ }));
5544
+ this.addContinuIdAtom();
4417
5545
  return this;
4418
5546
  }
4419
5547
  /**
4420
- * Add context metadata if enabled
4421
- * @param context - Context URL or null for default
4422
- * @return This instance for chaining
4423
- */
4424
- addContext(context = null) {
4425
- return this;
4426
- }
4427
- /**
4428
- * Set atom wallet metadata
4429
- * @param wallet - Wallet to extract metadata from
4430
- * @return This instance for chaining
5548
+ * Initialize an A-type molecule for an append request
5549
+ * Matches JavaScript SDK Molecule.initAppendRequest implementation exactly
5550
+ *
5551
+ * @param metaType - The target MetaType to append to
5552
+ * @param metaId - The target MetaId to append to
5553
+ * @param action - The action to perform
5554
+ * @param meta - Additional metadata
5555
+ * @return This molecule instance for chaining
4431
5556
  */
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);
4439
- }
4440
- if (wallet.tradeRates && Object.keys(wallet.tradeRates).length) {
4441
- walletMeta.tradeRates = JSON.stringify(wallet.tradeRates);
5557
+ initAppendRequest({
5558
+ metaType,
5559
+ metaId,
5560
+ action,
5561
+ meta = {}
5562
+ }) {
5563
+ if (!this.sourceWallet) {
5564
+ throw new Error("Source wallet required for append request");
4442
5565
  }
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)
4499
- });
5566
+ this.addAtom(Atom.create({
5567
+ isotope: "A",
5568
+ wallet: this.sourceWallet,
5569
+ metaType,
5570
+ metaId,
5571
+ meta: new AtomMeta({ action, ...meta })
5572
+ }));
5573
+ this.addContinuIdAtom();
4500
5574
  return this;
4501
5575
  }
4502
5576
  /**
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
5577
+ * Initialize a deposit buffer operation (B-isotope)
5578
+ * Matches JavaScript SDK Molecule.initDepositBuffer implementation exactly
5579
+ *
5580
+ * @param amount - Amount to deposit into buffer
5581
+ * @param tradeRates - Trade rates for the buffer wallet
5582
+ * @return This molecule instance for chaining
4544
5583
  */
4545
- remove(key) {
4546
- this.meta = Meta.removeMeta(this.meta, key);
5584
+ initDepositBuffer({
5585
+ amount,
5586
+ tradeRates
5587
+ }) {
5588
+ if (!this.sourceWallet) {
5589
+ throw new Error("Source wallet required for buffer deposit");
5590
+ }
5591
+ if (Number(this.sourceWallet.balance) - amount < 0) {
5592
+ throw new BalanceInsufficientException();
5593
+ }
5594
+ const bufferWallet = Wallet.create({
5595
+ secret: this.secret,
5596
+ bundle: this.bundle,
5597
+ token: this.sourceWallet.token,
5598
+ batchId: this.sourceWallet.batchId
5599
+ });
5600
+ if (tradeRates) {
5601
+ bufferWallet.tradeRates = tradeRates;
5602
+ }
5603
+ this.addAtom(Atom.create({
5604
+ isotope: "V",
5605
+ wallet: this.sourceWallet,
5606
+ value: -Number(this.sourceWallet.balance)
5607
+ }));
5608
+ this.addAtom(Atom.create({
5609
+ isotope: "B",
5610
+ wallet: bufferWallet,
5611
+ value: amount,
5612
+ metaType: "walletBundle",
5613
+ metaId: this.sourceWallet.bundle
5614
+ }));
5615
+ this.addAtom(Atom.create({
5616
+ isotope: "V",
5617
+ wallet: this.remainderWallet,
5618
+ value: Number(this.sourceWallet.balance) - amount,
5619
+ metaType: "walletBundle",
5620
+ metaId: this.sourceWallet.bundle
5621
+ }));
4547
5622
  return this;
4548
5623
  }
4549
5624
  /**
4550
- * Clear all metadata
4551
- * @return This instance for chaining
5625
+ * Initialize a withdraw buffer operation (B-isotope)
5626
+ * Matches JavaScript SDK Molecule.initWithdrawBuffer implementation exactly
5627
+ *
5628
+ * @param recipients - Map of recipientBundle → amount
5629
+ * @param signingWallet - Optional signing wallet for reconciliation
5630
+ * @return This molecule instance for chaining
4552
5631
  */
4553
- clear() {
4554
- this.meta = [];
5632
+ initWithdrawBuffer({
5633
+ recipients,
5634
+ signingWallet = null
5635
+ }) {
5636
+ if (!this.sourceWallet) {
5637
+ throw new Error("Source wallet required for buffer withdrawal");
5638
+ }
5639
+ let amount = 0;
5640
+ for (const recipientAmount of Object.values(recipients || {})) {
5641
+ amount += recipientAmount;
5642
+ }
5643
+ if (Number(this.sourceWallet.balance) - amount < 0) {
5644
+ throw new BalanceInsufficientException();
5645
+ }
5646
+ const firstAtomMeta = new AtomMeta();
5647
+ if (signingWallet) {
5648
+ firstAtomMeta.setSigningWallet(signingWallet);
5649
+ }
5650
+ this.addAtom(Atom.create({
5651
+ isotope: "B",
5652
+ wallet: this.sourceWallet,
5653
+ value: -Number(this.sourceWallet.balance),
5654
+ meta: firstAtomMeta,
5655
+ metaType: "walletBundle",
5656
+ metaId: this.sourceWallet.bundle
5657
+ }));
5658
+ for (const [recipientBundle, recipientAmount] of Object.entries(recipients || {})) {
5659
+ this.addAtom(new Atom({
5660
+ isotope: "V",
5661
+ token: this.sourceWallet.token,
5662
+ value: recipientAmount,
5663
+ batchId: this.sourceWallet.batchId ? generateBatchId({}) : null,
5664
+ metaType: "walletBundle",
5665
+ metaId: recipientBundle
5666
+ }));
5667
+ }
5668
+ this.addAtom(Atom.create({
5669
+ isotope: "B",
5670
+ wallet: this.remainderWallet,
5671
+ value: Number(this.sourceWallet.balance) - amount,
5672
+ metaType: "walletBundle",
5673
+ metaId: this.remainderWallet.bundle
5674
+ }));
4555
5675
  return this;
4556
5676
  }
4557
5677
  /**
4558
- * Get count of metadata items
4559
- * @return Number of items
5678
+ * Initialize shadow wallet claim
5679
+ * Matches JavaScript SDK Molecule.initShadowWalletClaim implementation exactly
5680
+ *
5681
+ * @param wallet - The shadow wallet to claim
5682
+ * @return This molecule instance for chaining
4560
5683
  */
4561
- count() {
4562
- return this.meta.length;
5684
+ initShadowWalletClaim(wallet) {
5685
+ const atomMeta = new AtomMeta();
5686
+ atomMeta.setShadowWalletClaim(true);
5687
+ return this.initWalletCreation(wallet, atomMeta);
4563
5688
  }
4564
5689
  /**
4565
- * Clone this AtomMeta instance
4566
- * @return New AtomMeta with same data
5690
+ * Initialize identifier creation
5691
+ * Matches JavaScript SDK Molecule.initIdentifierCreation implementation exactly
5692
+ *
5693
+ * @param type - Identifier type (phone or email)
5694
+ * @param contact - Phone number or email string
5695
+ * @param code - Verification code
5696
+ * @return This molecule instance for chaining
4567
5697
  */
4568
- clone() {
4569
- return new _AtomMeta(Meta.clone(this.meta));
5698
+ initIdentifierCreation({
5699
+ type,
5700
+ contact,
5701
+ code
5702
+ }) {
5703
+ if (!this.sourceWallet) {
5704
+ throw new Error("Source wallet required for identifier creation");
5705
+ }
5706
+ const meta = {
5707
+ code,
5708
+ hash: generateBundleHash(contact.trim(), "Molecule::initIdentifierCreation")
5709
+ };
5710
+ this.addAtom(Atom.create({
5711
+ isotope: "C",
5712
+ wallet: this.sourceWallet,
5713
+ metaType: "identifier",
5714
+ metaId: type,
5715
+ meta: new AtomMeta(meta)
5716
+ }));
5717
+ this.addContinuIdAtom();
5718
+ return this;
4570
5719
  }
4571
5720
  };
4572
5721
 
4573
5722
  // src/index.ts
4574
5723
  init_Dot();
4575
5724
 
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
5725
  // src/libraries/Decimal.ts
4628
5726
  var MULTIPLIER = 10 ** 18;
4629
5727
  var Decimal = class _Decimal {
@@ -4835,6 +5933,129 @@ var GraphQLClient = class {
4835
5933
  }
4836
5934
  };
4837
5935
 
5936
+ // src/AuthToken.ts
5937
+ var AuthToken = class _AuthToken {
5938
+ $__token;
5939
+ $__expiresAt;
5940
+ $__pubkey;
5941
+ $__encrypt;
5942
+ $__wallet;
5943
+ /**
5944
+ * Create new AuthToken instance
5945
+ */
5946
+ constructor({
5947
+ token,
5948
+ expiresAt,
5949
+ encrypt,
5950
+ pubkey
5951
+ }) {
5952
+ this.$__token = token;
5953
+ this.$__expiresAt = expiresAt;
5954
+ this.$__pubkey = pubkey;
5955
+ this.$__encrypt = encrypt;
5956
+ }
5957
+ /**
5958
+ * Static factory method to create AuthToken with wallet
5959
+ */
5960
+ static create(data, wallet) {
5961
+ const authToken = new _AuthToken(data);
5962
+ authToken.setWallet(wallet);
5963
+ return authToken;
5964
+ }
5965
+ /**
5966
+ * Restore AuthToken from snapshot
5967
+ */
5968
+ static restore(snapshot, secret) {
5969
+ const wallet = new Wallet({
5970
+ secret,
5971
+ token: "AUTH",
5972
+ position: snapshot.wallet.position,
5973
+ characters: snapshot.wallet.characters
5974
+ });
5975
+ return _AuthToken.create({
5976
+ token: snapshot.token,
5977
+ expiresAt: snapshot.expiresAt,
5978
+ pubkey: snapshot.pubkey,
5979
+ encrypt: snapshot.encrypt
5980
+ }, wallet);
5981
+ }
5982
+ /**
5983
+ * Set wallet for this auth token
5984
+ */
5985
+ setWallet(wallet) {
5986
+ this.$__wallet = wallet;
5987
+ }
5988
+ /**
5989
+ * Get wallet
5990
+ */
5991
+ getWallet() {
5992
+ return this.$__wallet;
5993
+ }
5994
+ /**
5995
+ * Get auth token
5996
+ */
5997
+ getToken() {
5998
+ return this.$__token;
5999
+ }
6000
+ /**
6001
+ * Get expiration timestamp
6002
+ */
6003
+ getExpiresAt() {
6004
+ return this.$__expiresAt;
6005
+ }
6006
+ /**
6007
+ * Get public key
6008
+ */
6009
+ getPubkey() {
6010
+ return this.$__pubkey;
6011
+ }
6012
+ /**
6013
+ * Check if encryption is enabled
6014
+ */
6015
+ isEncrypted() {
6016
+ return this.$__encrypt;
6017
+ }
6018
+ /**
6019
+ * Get expire interval in milliseconds (matching JS SDK pattern)
6020
+ */
6021
+ getExpireInterval() {
6022
+ return this.$__expiresAt * 1e3 - Date.now();
6023
+ }
6024
+ /**
6025
+ * Check if token is expired
6026
+ */
6027
+ isExpired() {
6028
+ return !this.$__expiresAt || this.getExpireInterval() < 0;
6029
+ }
6030
+ /**
6031
+ * Get auth data for GraphQL client
6032
+ */
6033
+ getAuthData() {
6034
+ return {
6035
+ token: this.$__token,
6036
+ pubkey: this.$__pubkey,
6037
+ wallet: this.$__wallet
6038
+ };
6039
+ }
6040
+ /**
6041
+ * Create snapshot for persistence
6042
+ */
6043
+ toSnapshot() {
6044
+ return {
6045
+ token: this.$__token,
6046
+ expiresAt: this.$__expiresAt,
6047
+ pubkey: this.$__pubkey,
6048
+ encrypt: this.$__encrypt,
6049
+ ...this.$__wallet ? {
6050
+ wallet: {
6051
+ position: this.$__wallet.position,
6052
+ characters: this.$__wallet.characters
6053
+ }
6054
+ } : {}
6055
+ };
6056
+ }
6057
+ };
6058
+
4838
6059
  // src/query/Query.ts
4839
6060
  init_exception();
4840
6061
  var Query = class {
@@ -4998,36 +6219,36 @@ var Mutation = class extends Query {
4998
6219
  function createBrandedSchema(name, baseSchema = z.string()) {
4999
6220
  return baseSchema.brand(name);
5000
6221
  }
5001
- var WalletAddressSchema = createBrandedSchema(
6222
+ var WalletAddressSchema2 = createBrandedSchema(
5002
6223
  "WalletAddress",
5003
6224
  z.string().regex(/^[0-9a-fA-F]{64}$/, "Invalid wallet address format")
5004
6225
  );
5005
- var BundleHashSchema = createBrandedSchema(
6226
+ var BundleHashSchema2 = createBrandedSchema(
5006
6227
  "BundleHash",
5007
6228
  z.string().regex(/^[0-9a-fA-F]{64}$/, "Invalid bundle hash format")
5008
6229
  );
5009
- var PositionSchema = createBrandedSchema(
6230
+ var PositionSchema2 = createBrandedSchema(
5010
6231
  "Position",
5011
6232
  z.string().regex(/^[0-9a-fA-F]{64}$/, "Invalid position format")
5012
6233
  );
5013
- var MolecularHashSchema = createBrandedSchema(
6234
+ var MolecularHashSchema2 = createBrandedSchema(
5014
6235
  "MolecularHash",
5015
6236
  z.string().regex(/^[0-9a-g]+$/, "Invalid molecular hash format (base17)")
5016
6237
  );
5017
- var TokenSlugSchema = createBrandedSchema(
6238
+ var TokenSlugSchema2 = createBrandedSchema(
5018
6239
  "TokenSlug",
5019
6240
  z.string().min(1).max(32).regex(/^[A-Z0-9_]+$/, "Token slug must be uppercase alphanumeric")
5020
6241
  );
5021
- var BatchIdSchema = createBrandedSchema(
6242
+ var BatchIdSchema2 = createBrandedSchema(
5022
6243
  "BatchId",
5023
6244
  z.string().uuid("Invalid batch ID format")
5024
6245
  );
5025
- var CellSlugSchema = createBrandedSchema(
6246
+ var CellSlugSchema2 = createBrandedSchema(
5026
6247
  "CellSlug",
5027
6248
  z.string().min(1).max(64).regex(/^[a-zA-Z0-9\-_.]+$/, "Invalid cell slug format")
5028
6249
  );
5029
6250
  var ISOTOPES2 = ["C", "V", "U", "T", "M", "I", "R", "B", "F"];
5030
- var AtomIsotopeSchema = z.enum(ISOTOPES2);
6251
+ var AtomIsotopeSchema2 = z.enum(ISOTOPES2);
5031
6252
  z.object({
5032
6253
  isotope: z.literal("V"),
5033
6254
  value: z.union([z.string(), z.number()]).refine(
@@ -5047,17 +6268,17 @@ z.object({
5047
6268
  z.object({
5048
6269
  isotope: z.literal("C")
5049
6270
  }).strict();
5050
- var MetaDataSchema = z.lazy(
6271
+ var MetaDataSchema2 = z.lazy(
5051
6272
  () => z.union([
5052
6273
  z.string(),
5053
6274
  z.number(),
5054
6275
  z.boolean(),
5055
6276
  z.null(),
5056
- z.record(z.string(), MetaDataSchema),
5057
- z.array(MetaDataSchema)
6277
+ z.record(z.string(), MetaDataSchema2),
6278
+ z.array(MetaDataSchema2)
5058
6279
  ])
5059
6280
  );
5060
- var AtomMetaDataSchema = z.object({
6281
+ var AtomMetaDataSchema2 = z.object({
5061
6282
  key: z.string().min(1),
5062
6283
  value: z.union([z.string(), z.number(), z.boolean(), z.null()])
5063
6284
  }).strict();
@@ -5065,44 +6286,44 @@ z.object({
5065
6286
  key: z.string(),
5066
6287
  value: z.union([z.string(), z.number(), z.boolean(), z.null()])
5067
6288
  }).passthrough();
5068
- var AtomParamsSchema = z.object({
6289
+ var AtomParamsSchema2 = z.object({
5069
6290
  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"),
6291
+ walletAddress: z.union([WalletAddressSchema2, z.string()]).optional(),
6292
+ isotope: AtomIsotopeSchema2.default("C"),
6293
+ token: z.union([TokenSlugSchema2, z.string()]).default("USER"),
5073
6294
  value: z.union([z.string(), z.number(), z.null()]).optional(),
5074
- batchId: z.union([BatchIdSchema, z.string(), z.null()]).optional(),
6295
+ batchId: z.union([BatchIdSchema2, z.string(), z.null()]).optional(),
5075
6296
  metaType: z.string().optional(),
5076
6297
  metaId: z.string().optional(),
5077
- meta: z.array(AtomMetaDataSchema).optional(),
6298
+ meta: z.array(AtomMetaDataSchema2).optional(),
5078
6299
  otsFragment: z.string().optional(),
5079
6300
  index: z.number().int().min(0).optional(),
5080
6301
  createdAt: z.string().optional(),
5081
6302
  version: z.number().int().min(1).optional()
5082
6303
  }).strict();
5083
- var WalletParamsSchema = z.object({
6304
+ var WalletParamsSchema2 = z.object({
5084
6305
  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(),
6306
+ bundle: z.union([BundleHashSchema2, z.string()]).optional(),
6307
+ token: z.union([TokenSlugSchema2, z.string()]).default("USER"),
6308
+ address: z.union([WalletAddressSchema2, z.string()]).optional(),
6309
+ position: z.union([PositionSchema2, z.string()]).optional(),
6310
+ batchId: z.union([BatchIdSchema2, z.string()]).optional(),
5090
6311
  characters: z.string().optional()
5091
6312
  }).strict();
5092
- var MoleculeParamsSchema = z.object({
6313
+ var MoleculeParamsSchema2 = z.object({
5093
6314
  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(),
6315
+ bundle: z.union([BundleHashSchema2, z.string()]).optional(),
6316
+ sourceWallet: WalletParamsSchema2.optional(),
6317
+ remainderWallet: WalletParamsSchema2.optional(),
6318
+ cellSlug: z.union([CellSlugSchema2, z.string()]).optional(),
5098
6319
  version: z.number().int().min(1).optional()
5099
6320
  }).strict();
5100
- var KnishIOClientConfigSchema = z.object({
6321
+ var KnishIOClientConfigSchema2 = z.object({
5101
6322
  uri: z.union([
5102
6323
  z.string().url("Invalid URI format"),
5103
6324
  z.array(z.string().url("Invalid URI format")).min(1)
5104
6325
  ]).optional(),
5105
- cellSlug: z.union([CellSlugSchema, z.string()]).optional(),
6326
+ cellSlug: z.union([CellSlugSchema2, z.string()]).optional(),
5106
6327
  client: z.unknown().optional(),
5107
6328
  socket: z.unknown().optional(),
5108
6329
  serverSdkVersion: z.number().int().min(1).max(10).default(4),
@@ -5115,48 +6336,48 @@ var EnvironmentConfigSchema = z.object({
5115
6336
  KNISHIO_LOGGING: z.string().transform((val) => val === "true").default("false"),
5116
6337
  KNISHIO_SERVER_SDK_VERSION: z.string().transform((val) => parseInt(val, 10)).default("4")
5117
6338
  }).partial();
5118
- var TransferParamsSchema = z.object({
5119
- recipient: z.union([WalletAddressSchema, z.string()]),
6339
+ var TransferParamsSchema2 = z.object({
6340
+ recipient: z.union([WalletAddressSchema2, z.string()]),
5120
6341
  amount: z.union([z.number(), z.string()]).refine(
5121
6342
  (val) => Number(val) > 0,
5122
6343
  "Amount must be positive"
5123
6344
  ),
5124
- token: z.union([TokenSlugSchema, z.string()]).optional(),
6345
+ token: z.union([TokenSlugSchema2, z.string()]).optional(),
5125
6346
  callbackUrl: z.string().url().optional(),
5126
6347
  metaType: z.string().optional(),
5127
6348
  metaId: z.string().optional(),
5128
- meta: MetaDataSchema.optional()
6349
+ meta: MetaDataSchema2.optional()
5129
6350
  }).strict();
5130
- var CreateTokenParamsSchema = z.object({
5131
- token: z.union([TokenSlugSchema, z.string()]),
6351
+ var CreateTokenParamsSchema2 = z.object({
6352
+ token: z.union([TokenSlugSchema2, z.string()]),
5132
6353
  amount: z.union([z.number(), z.string()]).refine(
5133
6354
  (val) => Number(val) > 0,
5134
6355
  "Amount must be positive"
5135
6356
  ),
5136
6357
  metaType: z.string().optional(),
5137
6358
  metaId: z.string().optional(),
5138
- meta: MetaDataSchema.optional(),
6359
+ meta: MetaDataSchema2.optional(),
5139
6360
  fungible: z.boolean().default(true),
5140
6361
  splittable: z.number().int().min(0).optional(),
5141
- supplyToken: z.union([TokenSlugSchema, z.string()]).optional()
6362
+ supplyToken: z.union([TokenSlugSchema2, z.string()]).optional()
5142
6363
  }).strict();
5143
- var RequestTokensParamsSchema = z.object({
6364
+ var RequestTokensParamsSchema2 = z.object({
5144
6365
  amount: z.union([z.number(), z.string()]).refine(
5145
6366
  (val) => Number(val) > 0,
5146
6367
  "Amount must be positive"
5147
6368
  ),
5148
- token: z.union([TokenSlugSchema, z.string()]).optional(),
6369
+ token: z.union([TokenSlugSchema2, z.string()]).optional(),
5149
6370
  metaType: z.string().optional(),
5150
6371
  metaId: z.string().optional(),
5151
- meta: MetaDataSchema.optional()
6372
+ meta: MetaDataSchema2.optional()
5152
6373
  }).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(),
6374
+ var BalanceQueryParamsSchema2 = z.object({
6375
+ address: z.union([WalletAddressSchema2, z.string()]).optional(),
6376
+ bundleHash: z.union([BundleHashSchema2, z.string()]).optional(),
6377
+ token: z.union([TokenSlugSchema2, z.string()]).optional(),
5157
6378
  type: z.enum(["token", "user"]).optional()
5158
6379
  }).strict();
5159
- var MetaQueryParamsSchema = z.object({
6380
+ var MetaQueryParamsSchema2 = z.object({
5160
6381
  metaType: z.string().min(1),
5161
6382
  metaId: z.string().optional(),
5162
6383
  key: z.string().optional(),
@@ -5166,33 +6387,33 @@ var MetaQueryParamsSchema = z.object({
5166
6387
  queryArgs: z.record(z.unknown()).optional(),
5167
6388
  count: z.number().int().min(0).optional(),
5168
6389
  countBy: z.string().optional(),
5169
- cellSlug: z.union([CellSlugSchema, z.string()]).optional()
6390
+ cellSlug: z.union([CellSlugSchema2, z.string()]).optional()
5170
6391
  }).strict();
5171
- var WalletQueryParamsSchema = z.object({
5172
- bundleHash: z.union([BundleHashSchema, z.string()]).optional(),
5173
- tokenSlug: z.union([TokenSlugSchema, z.string()]).optional(),
6392
+ var WalletQueryParamsSchema2 = z.object({
6393
+ bundleHash: z.union([BundleHashSchema2, z.string()]).optional(),
6394
+ tokenSlug: z.union([TokenSlugSchema2, z.string()]).optional(),
5174
6395
  unspent: z.boolean().optional()
5175
6396
  }).strict();
5176
- var AuthTokenParamsSchema = z.object({
6397
+ var AuthTokenParamsSchema2 = z.object({
5177
6398
  token: z.string().min(1),
5178
6399
  expiresAt: z.number().int().min(0),
5179
6400
  encrypt: z.boolean(),
5180
6401
  pubkey: z.string().min(1)
5181
6402
  }).strict();
5182
- var AuthParamsSchema = z.object({
5183
- cellSlug: z.union([CellSlugSchema, z.string()]).optional(),
6403
+ var AuthParamsSchema2 = z.object({
6404
+ cellSlug: z.union([CellSlugSchema2, z.string()]).optional(),
5184
6405
  encrypt: z.boolean().optional(),
5185
6406
  callback: z.function().optional()
5186
6407
  }).strict();
5187
- var GuestAuthParamsSchema = z.object({
5188
- cellSlug: z.union([CellSlugSchema, z.string()]).optional()
6408
+ var GuestAuthParamsSchema2 = z.object({
6409
+ cellSlug: z.union([CellSlugSchema2, z.string()]).optional()
5189
6410
  }).strict();
5190
- var GraphQLRequestSchema = z.object({
6411
+ var GraphQLRequestSchema2 = z.object({
5191
6412
  query: z.string().min(1),
5192
6413
  variables: z.record(z.unknown()).optional(),
5193
6414
  operationName: z.string().optional()
5194
6415
  }).strict();
5195
- var GraphQLErrorSchema = z.object({
6416
+ var GraphQLErrorSchema2 = z.object({
5196
6417
  message: z.string(),
5197
6418
  locations: z.array(z.object({
5198
6419
  line: z.number().int(),
@@ -5201,9 +6422,9 @@ var GraphQLErrorSchema = z.object({
5201
6422
  path: z.array(z.union([z.string(), z.number()])).optional(),
5202
6423
  extensions: z.record(z.unknown()).optional()
5203
6424
  }).strict();
5204
- var GraphQLResponseSchema = z.object({
6425
+ var GraphQLResponseSchema2 = z.object({
5205
6426
  data: z.unknown().optional(),
5206
- errors: z.array(GraphQLErrorSchema).optional(),
6427
+ errors: z.array(GraphQLErrorSchema2).optional(),
5207
6428
  extensions: z.record(z.unknown()).optional()
5208
6429
  }).strict();
5209
6430
  function safeParse(schema, data) {
@@ -5230,35 +6451,35 @@ function createTypeGuard(schema) {
5230
6451
  }
5231
6452
  var Schemas = {
5232
6453
  // Core types
5233
- WalletAddress: WalletAddressSchema,
5234
- BundleHash: BundleHashSchema,
5235
- Position: PositionSchema,
5236
- MolecularHash: MolecularHashSchema,
5237
- TokenSlug: TokenSlugSchema,
5238
- BatchId: BatchIdSchema,
5239
- CellSlug: CellSlugSchema,
6454
+ WalletAddress: WalletAddressSchema2,
6455
+ BundleHash: BundleHashSchema2,
6456
+ Position: PositionSchema2,
6457
+ MolecularHash: MolecularHashSchema2,
6458
+ TokenSlug: TokenSlugSchema2,
6459
+ BatchId: BatchIdSchema2,
6460
+ CellSlug: CellSlugSchema2,
5240
6461
  // Entities
5241
- AtomParams: AtomParamsSchema,
5242
- WalletParams: WalletParamsSchema,
5243
- MoleculeParams: MoleculeParamsSchema,
6462
+ AtomParams: AtomParamsSchema2,
6463
+ WalletParams: WalletParamsSchema2,
6464
+ MoleculeParams: MoleculeParamsSchema2,
5244
6465
  // Configuration
5245
- ClientConfig: KnishIOClientConfigSchema,
6466
+ ClientConfig: KnishIOClientConfigSchema2,
5246
6467
  EnvironmentConfig: EnvironmentConfigSchema,
5247
6468
  // Operations
5248
- TransferParams: TransferParamsSchema,
5249
- CreateTokenParams: CreateTokenParamsSchema,
5250
- RequestTokensParams: RequestTokensParamsSchema,
6469
+ TransferParams: TransferParamsSchema2,
6470
+ CreateTokenParams: CreateTokenParamsSchema2,
6471
+ RequestTokensParams: RequestTokensParamsSchema2,
5251
6472
  // Queries
5252
- BalanceQueryParams: BalanceQueryParamsSchema,
5253
- MetaQueryParams: MetaQueryParamsSchema,
5254
- WalletQueryParams: WalletQueryParamsSchema,
6473
+ BalanceQueryParams: BalanceQueryParamsSchema2,
6474
+ MetaQueryParams: MetaQueryParamsSchema2,
6475
+ WalletQueryParams: WalletQueryParamsSchema2,
5255
6476
  // Auth
5256
- AuthTokenParams: AuthTokenParamsSchema,
5257
- AuthParams: AuthParamsSchema,
5258
- GuestAuthParams: GuestAuthParamsSchema,
6477
+ AuthTokenParams: AuthTokenParamsSchema2,
6478
+ AuthParams: AuthParamsSchema2,
6479
+ GuestAuthParams: GuestAuthParamsSchema2,
5259
6480
  // GraphQL
5260
- GraphQLRequest: GraphQLRequestSchema,
5261
- GraphQLResponse: GraphQLResponseSchema
6481
+ GraphQLRequest: GraphQLRequestSchema2,
6482
+ GraphQLResponse: GraphQLResponseSchema2
5262
6483
  };
5263
6484
 
5264
6485
  // src/validation/ValidationService.ts
@@ -5937,7 +7158,8 @@ var ResponseBalance = class _ResponseBalance extends Response {
5937
7158
  * Matches JavaScript SDK payload() method exactly
5938
7159
  */
5939
7160
  payload() {
5940
- const walletData = this.data();
7161
+ const balanceData = this.data();
7162
+ const walletData = Array.isArray(balanceData) ? balanceData[0] : balanceData;
5941
7163
  if (!walletData || !walletData.bundleHash || !walletData.tokenSlug) {
5942
7164
  return null;
5943
7165
  }
@@ -5955,7 +7177,7 @@ var ResponseBalance = class _ResponseBalance extends Response {
5955
7177
  secret = null
5956
7178
  }) {
5957
7179
  let wallet;
5958
- if (data.position === null || typeof data.position === "undefined") {
7180
+ if (!data.position) {
5959
7181
  wallet = Wallet.create({
5960
7182
  bundle: data.bundleHash,
5961
7183
  token: data.tokenSlug,
@@ -5984,7 +7206,7 @@ var ResponseBalance = class _ResponseBalance extends Response {
5984
7206
  wallet.tradeRates[tradeRate.tokenSlug] = tradeRate.amount;
5985
7207
  }
5986
7208
  }
5987
- wallet.balance = Number(data.amount || 0);
7209
+ wallet.balance = String(data.amount != null ? data.amount : 0);
5988
7210
  wallet.pubkey = data.pubkey;
5989
7211
  wallet.createdAt = data.createdAt;
5990
7212
  return wallet;
@@ -6177,7 +7399,7 @@ var ResponseWalletList = class _ResponseWalletList extends Response {
6177
7399
  wallet.tradeRates[tradeRate.tokenSlug] = tradeRate.amount;
6178
7400
  }
6179
7401
  }
6180
- wallet.balance = Number(data.amount);
7402
+ wallet.balance = String(data.amount != null ? data.amount : 0);
6181
7403
  wallet.pubkey = data.pubkey;
6182
7404
  wallet.createdAt = data.createdAt;
6183
7405
  return wallet;
@@ -6215,8 +7437,8 @@ var QueryWalletList = class extends Query {
6215
7437
  */
6216
7438
  constructor(graphQLClient, knishIOClient) {
6217
7439
  super(graphQLClient, knishIOClient);
6218
- this.$__query = gql`query( $bundleHash: String, $tokenSlug: String ) {
6219
- Wallet( bundleHash: $bundleHash, tokenSlug: $tokenSlug ) {
7440
+ this.$__query = gql`query( $bundleHash: String, $token: String ) {
7441
+ Wallet( bundleHash: $bundleHash, token: $token ) {
6220
7442
  address,
6221
7443
  bundleHash,
6222
7444
  token {
@@ -6358,7 +7580,7 @@ var ResponseContinuId = class extends Response {
6358
7580
  wallet.batchId = continuId.batchId;
6359
7581
  wallet.characters = continuId.characters;
6360
7582
  wallet.pubkey = continuId.pubkey;
6361
- wallet.balance = continuId.amount * 1;
7583
+ wallet.balance = String(continuId.amount != null ? continuId.amount : 0);
6362
7584
  }
6363
7585
  return wallet;
6364
7586
  }
@@ -6384,6 +7606,13 @@ var QueryContinuId = class extends Query {
6384
7606
  }
6385
7607
  }`;
6386
7608
  }
7609
+ /**
7610
+ * Force network-only for ContinuID queries to prevent URQL cache from
7611
+ * returning stale wallet positions after mutations advance the ContinuID chain
7612
+ */
7613
+ createQueryContext() {
7614
+ return { requestPolicy: "network-only" };
7615
+ }
6387
7616
  /**
6388
7617
  * Returns a Response object
6389
7618
  * Matches JavaScript SDK createResponse method exactly
@@ -6413,31 +7642,40 @@ var ResponseMetaType = class extends Response {
6413
7642
  dataKey: "data.MetaType"
6414
7643
  });
6415
7644
  }
7645
+ /**
7646
+ * Extracts payload from metaData object
7647
+ */
7648
+ extractPayload(metaData) {
7649
+ return {
7650
+ instances: metaData?.instances || [],
7651
+ instanceCount: metaData?.instanceCount || [],
7652
+ paginatorInfo: metaData?.paginatorInfo || {}
7653
+ };
7654
+ }
6416
7655
  /**
6417
7656
  * Returns meta type instance results
6418
- * Matches JavaScript SDK payload method exactly
7657
+ * Handles various response formats from server:
7658
+ * - Array of results (normal case)
7659
+ * - Single object (filtered queries)
7660
+ * - null/undefined (no results)
7661
+ * - Empty array (no matching data)
6419
7662
  */
6420
7663
  payload() {
6421
7664
  const metaTypeData = this.data();
6422
- if (!metaTypeData || metaTypeData.length === 0) {
7665
+ if (metaTypeData === null || metaTypeData === void 0) {
6423
7666
  return null;
6424
7667
  }
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;
7668
+ if (Array.isArray(metaTypeData)) {
7669
+ if (metaTypeData.length === 0) {
7670
+ return this.extractPayload(null);
7671
+ }
7672
+ const metaData = metaTypeData[metaTypeData.length - 1];
7673
+ return this.extractPayload(metaData);
6436
7674
  }
6437
- if (metaData.paginatorInfo) {
6438
- response.paginatorInfo = metaData.paginatorInfo;
7675
+ if (typeof metaTypeData === "object") {
7676
+ return this.extractPayload(metaTypeData);
6439
7677
  }
6440
- return response;
7678
+ return null;
6441
7679
  }
6442
7680
  };
6443
7681
  var QueryMetaType = class extends Query {
@@ -6905,10 +8143,9 @@ var ResponsePolicy = class extends Response {
6905
8143
  }) {
6906
8144
  super({
6907
8145
  query,
6908
- json
8146
+ json,
8147
+ dataKey: "data.Policy"
6909
8148
  });
6910
- this.dataKey = "data.Policy";
6911
- this.init();
6912
8149
  }
6913
8150
  /**
6914
8151
  * Returns the policy payload
@@ -7011,7 +8248,6 @@ var QueryActiveSession = class extends Query {
7011
8248
  metaId
7012
8249
  jsonData
7013
8250
  createdAt
7014
- updatedAt
7015
8251
  }
7016
8252
  }
7017
8253
  `;
@@ -7344,6 +8580,252 @@ var QueryMetaTypeViaAtom = class extends Query {
7344
8580
  }
7345
8581
  };
7346
8582
 
8583
+ // src/response/ResponseMetaTypeViaMolecule.ts
8584
+ init_Response();
8585
+ var ResponseMetaTypeViaMolecule = class _ResponseMetaTypeViaMolecule extends Response {
8586
+ /**
8587
+ * Class constructor
8588
+ */
8589
+ constructor({
8590
+ query,
8591
+ json
8592
+ }) {
8593
+ super({
8594
+ query,
8595
+ json,
8596
+ dataKey: "data.MetaTypeViaAtom"
8597
+ });
8598
+ }
8599
+ /**
8600
+ * Extracts metas from a molecule's atoms' metasJson for a specific instance.
8601
+ * Filters atoms by matching metaType and metaId, then parses metasJson.
8602
+ */
8603
+ static extractMetasFromMolecule(molecule, metaType, metaId) {
8604
+ if (!molecule || !molecule.atoms) {
8605
+ return [];
8606
+ }
8607
+ const metas = [];
8608
+ for (const atom of molecule.atoms) {
8609
+ if (atom.metaType !== metaType || atom.metaId !== metaId) {
8610
+ continue;
8611
+ }
8612
+ if (!atom.metasJson) {
8613
+ continue;
8614
+ }
8615
+ let parsed;
8616
+ try {
8617
+ parsed = JSON.parse(atom.metasJson);
8618
+ if (!Array.isArray(parsed)) {
8619
+ continue;
8620
+ }
8621
+ } catch (e) {
8622
+ continue;
8623
+ }
8624
+ for (const entry of parsed) {
8625
+ metas.push({
8626
+ molecularHash: molecule.molecularHash,
8627
+ position: atom.position,
8628
+ key: entry.key,
8629
+ value: entry.value,
8630
+ createdAt: atom.createdAt
8631
+ });
8632
+ }
8633
+ }
8634
+ return metas;
8635
+ }
8636
+ /**
8637
+ * Returns meta type instance results with metas synthesized from molecule data.
8638
+ * Produces the same payload format as ResponseMetaType and ResponseMetaTypeViaAtom:
8639
+ * { instances, instanceCount, paginatorInfo }
8640
+ */
8641
+ payload() {
8642
+ const metaTypeData = this.data();
8643
+ if (!metaTypeData || metaTypeData.length === 0) {
8644
+ return null;
8645
+ }
8646
+ const response = {
8647
+ instances: {},
8648
+ instanceCount: {},
8649
+ paginatorInfo: {}
8650
+ };
8651
+ const metaData = metaTypeData.pop();
8652
+ if (metaData.instances) {
8653
+ response.instances = metaData.instances.map((instance) => {
8654
+ let metas = instance.metas;
8655
+ if (!metas || metas.length === 0) {
8656
+ metas = _ResponseMetaTypeViaMolecule.extractMetasFromMolecule(
8657
+ instance.molecule,
8658
+ instance.metaType,
8659
+ instance.metaId
8660
+ );
8661
+ }
8662
+ return {
8663
+ ...instance,
8664
+ metas
8665
+ };
8666
+ });
8667
+ }
8668
+ if (metaData.instanceCount) {
8669
+ response.instanceCount = metaData.instanceCount;
8670
+ }
8671
+ if (metaData.paginatorInfo) {
8672
+ response.paginatorInfo = metaData.paginatorInfo;
8673
+ }
8674
+ return response;
8675
+ }
8676
+ /**
8677
+ * Verifies the cryptographic integrity of all molecules associated
8678
+ * with meta instances in this response.
8679
+ */
8680
+ verifyIntegrity() {
8681
+ const results = [];
8682
+ const metaTypeData = this.data();
8683
+ if (!metaTypeData || metaTypeData.length === 0) {
8684
+ return { verified: true, molecules: results };
8685
+ }
8686
+ const instances = metaTypeData[metaTypeData.length - 1]?.instances || [];
8687
+ for (const instance of instances) {
8688
+ if (!instance.molecule) continue;
8689
+ results.push(CheckMolecule.verifyFromServerData(instance.molecule));
8690
+ }
8691
+ return {
8692
+ verified: results.length === 0 || results.every((r) => r.verified),
8693
+ molecules: results
8694
+ };
8695
+ }
8696
+ };
8697
+ var QueryMetaTypeViaMolecule = class extends Query {
8698
+ /**
8699
+ * Create new QueryMetaTypeViaMolecule instance
8700
+ */
8701
+ constructor(graphQLClient, knishIOClient) {
8702
+ super(graphQLClient, knishIOClient);
8703
+ this.$__query = gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
8704
+ MetaTypeViaAtom(
8705
+ metaTypes: $metaTypes
8706
+ metaIds: $metaIds
8707
+ atomValues: $atomValues
8708
+ cellSlugs: $cellSlugs
8709
+ filter: $filter,
8710
+ latest: $latest,
8711
+ queryArgs: $queryArgs
8712
+ countBy: $countBy
8713
+ ) {
8714
+ metaType,
8715
+ instanceCount {
8716
+ key,
8717
+ value
8718
+ },
8719
+ instances {
8720
+ metaType,
8721
+ metaId,
8722
+ createdAt,
8723
+ metas( values: $values, keys: $keys ) {
8724
+ molecularHash,
8725
+ position,
8726
+ key,
8727
+ value,
8728
+ createdAt
8729
+ },
8730
+ molecule {
8731
+ molecularHash,
8732
+ bundleHash,
8733
+ cellSlug,
8734
+ status,
8735
+ createdAt,
8736
+ atoms {
8737
+ position,
8738
+ walletAddress,
8739
+ isotope,
8740
+ tokenSlug,
8741
+ value,
8742
+ batchId,
8743
+ metaType,
8744
+ metaId,
8745
+ index,
8746
+ createdAt,
8747
+ otsFragment,
8748
+ metasJson
8749
+ }
8750
+ }
8751
+ },
8752
+ paginatorInfo {
8753
+ currentPage,
8754
+ total
8755
+ }
8756
+ }
8757
+ }`;
8758
+ }
8759
+ /**
8760
+ * Builds a GraphQL-friendly variables object based on input fields
8761
+ */
8762
+ static createVariables({
8763
+ metaType = null,
8764
+ metaId = null,
8765
+ key = null,
8766
+ value = null,
8767
+ keys = null,
8768
+ values = null,
8769
+ atomValues = null,
8770
+ latest = null,
8771
+ filter = null,
8772
+ queryArgs = null,
8773
+ countBy = null,
8774
+ cellSlug = null
8775
+ } = {}) {
8776
+ const variables = {};
8777
+ if (atomValues) {
8778
+ variables.atomValues = atomValues;
8779
+ }
8780
+ if (keys) {
8781
+ variables.keys = keys;
8782
+ }
8783
+ if (values) {
8784
+ variables.values = values;
8785
+ }
8786
+ if (metaType) {
8787
+ variables.metaTypes = typeof metaType === "string" ? [metaType] : metaType;
8788
+ }
8789
+ if (metaId) {
8790
+ variables.metaIds = typeof metaId === "string" ? [metaId] : metaId;
8791
+ }
8792
+ if (cellSlug) {
8793
+ variables.cellSlugs = typeof cellSlug === "string" ? [cellSlug] : cellSlug;
8794
+ }
8795
+ if (countBy) {
8796
+ variables.countBy = countBy;
8797
+ }
8798
+ if (filter) {
8799
+ variables.filter = filter;
8800
+ }
8801
+ if (key && value) {
8802
+ variables.filter = variables.filter || [];
8803
+ variables.filter.push({
8804
+ key,
8805
+ value,
8806
+ comparison: "="
8807
+ });
8808
+ }
8809
+ variables.latest = latest === true;
8810
+ if (queryArgs) {
8811
+ if (typeof queryArgs.limit === "undefined" || queryArgs.limit === 0) {
8812
+ queryArgs.limit = "*";
8813
+ }
8814
+ variables.queryArgs = queryArgs;
8815
+ }
8816
+ return variables;
8817
+ }
8818
+ /**
8819
+ * Returns a Response object
8820
+ */
8821
+ createResponse(json) {
8822
+ return new ResponseMetaTypeViaMolecule({
8823
+ query: this,
8824
+ json
8825
+ });
8826
+ }
8827
+ };
8828
+
7347
8829
  // src/response/ResponseProposeMolecule.ts
7348
8830
  init_Response();
7349
8831
  init_Dot();
@@ -7362,7 +8844,6 @@ var ResponseProposeMolecule = class extends Response {
7362
8844
  dataKey: "data.ProposeMolecule"
7363
8845
  });
7364
8846
  this.$__clientMolecule = query.molecule();
7365
- this.init();
7366
8847
  }
7367
8848
  /**
7368
8849
  * Initialize response object with payload data
@@ -7926,12 +9407,31 @@ var ResponseRequestAuthorization = class extends ResponseProposeMolecule {
7926
9407
  return this.payloadKey("token");
7927
9408
  }
7928
9409
  /**
7929
- * Returns timestamp
7930
- * Matches JavaScript SDK time method exactly
9410
+ * Returns raw time value from payload
7931
9411
  */
7932
9412
  time() {
7933
9413
  return this.payloadKey("time");
7934
9414
  }
9415
+ /**
9416
+ * Returns the expiration timestamp as Unix seconds.
9417
+ * Handles both server formats:
9418
+ * - PHP server: time = lifetime in ms, expiresAt = Unix timestamp in payload
9419
+ * - Rust server: time = Unix timestamp in seconds
9420
+ */
9421
+ expiresAt() {
9422
+ try {
9423
+ const ea = this.payloadKey("expiresAt");
9424
+ if (ea) {
9425
+ return Number(ea);
9426
+ }
9427
+ } catch (_e) {
9428
+ }
9429
+ const timeValue = Number(this.time());
9430
+ if (timeValue >= 1577836800) {
9431
+ return timeValue;
9432
+ }
9433
+ return Math.floor(Date.now() / 1e3) + Math.floor(timeValue / 1e3);
9434
+ }
7935
9435
  /**
7936
9436
  * Returns encryption info
7937
9437
  * Matches JavaScript SDK encrypt method exactly
@@ -8023,11 +9523,31 @@ var ResponseRequestAuthorizationGuest = class extends Response {
8023
9523
  return this.payloadKey("token");
8024
9524
  }
8025
9525
  /**
8026
- * Returns timestamp
9526
+ * Returns raw time value from payload
8027
9527
  */
8028
9528
  time() {
8029
9529
  return this.payloadKey("time");
8030
9530
  }
9531
+ /**
9532
+ * Returns the expiration timestamp as Unix seconds.
9533
+ * Handles both server formats:
9534
+ * - PHP server: time = lifetime in ms, expiresAt = Unix timestamp in payload
9535
+ * - Rust server: time = Unix timestamp in seconds
9536
+ */
9537
+ expiresAt() {
9538
+ try {
9539
+ const ea = this.payloadKey("expiresAt");
9540
+ if (ea) {
9541
+ return Number(ea);
9542
+ }
9543
+ } catch (_e) {
9544
+ }
9545
+ const timeValue = Number(this.time());
9546
+ if (timeValue >= 1577836800) {
9547
+ return timeValue;
9548
+ }
9549
+ return Math.floor(Date.now() / 1e3) + Math.floor(timeValue / 1e3);
9550
+ }
8031
9551
  /**
8032
9552
  * Returns public key
8033
9553
  */
@@ -8117,10 +9637,74 @@ var MutationLinkIdentifier = class extends Mutation {
8117
9637
  `;
8118
9638
  }
8119
9639
  /**
8120
- * Returns a Response object
9640
+ * Returns a Response object
9641
+ */
9642
+ createResponse(json) {
9643
+ return new ResponseLinkIdentifier({
9644
+ query: this,
9645
+ json
9646
+ });
9647
+ }
9648
+ };
9649
+
9650
+ // src/response/ResponsePeering.ts
9651
+ var ResponsePeering = class extends ResponseProposeMolecule {
9652
+ };
9653
+
9654
+ // src/mutation/MutationPeering.ts
9655
+ var MutationPeering = class extends MutationProposeMolecule {
9656
+ /**
9657
+ * Fills a molecule with a P-isotope peering atom
9658
+ * Matches JavaScript SDK fillMolecule method exactly
9659
+ */
9660
+ fillMolecule({ host }) {
9661
+ this.$__molecule.initPeering({ host });
9662
+ this.$__molecule.sign({});
9663
+ this.$__molecule.check();
9664
+ }
9665
+ /**
9666
+ * Builds a Response object out of a JSON object
9667
+ * Matches JavaScript SDK createResponse method exactly
9668
+ */
9669
+ createResponse(json) {
9670
+ return new ResponsePeering({
9671
+ query: this,
9672
+ json
9673
+ });
9674
+ }
9675
+ };
9676
+
9677
+ // src/response/ResponseAppendRequest.ts
9678
+ var ResponseAppendRequest = class extends ResponseProposeMolecule {
9679
+ };
9680
+
9681
+ // src/mutation/MutationAppendRequest.ts
9682
+ var MutationAppendRequest = class extends MutationProposeMolecule {
9683
+ /**
9684
+ * Fills a molecule with an A-isotope append request atom
9685
+ * Matches JavaScript SDK fillMolecule method exactly
9686
+ */
9687
+ fillMolecule({
9688
+ metaType,
9689
+ metaId,
9690
+ action,
9691
+ meta = {}
9692
+ }) {
9693
+ this.$__molecule.initAppendRequest({
9694
+ metaType,
9695
+ metaId,
9696
+ action,
9697
+ meta
9698
+ });
9699
+ this.$__molecule.sign({});
9700
+ this.$__molecule.check();
9701
+ }
9702
+ /**
9703
+ * Builds a Response object out of a JSON object
9704
+ * Matches JavaScript SDK createResponse method exactly
8121
9705
  */
8122
9706
  createResponse(json) {
8123
- return new ResponseLinkIdentifier({
9707
+ return new ResponseAppendRequest({
8124
9708
  query: this,
8125
9709
  json
8126
9710
  });
@@ -8349,6 +9933,7 @@ var KnishIOClient = class {
8349
9933
  $__logging = false;
8350
9934
  $__authTokenObjects = {};
8351
9935
  $__authToken = null;
9936
+ $__authInProcess = false;
8352
9937
  $__remainderWallet = null;
8353
9938
  lastMoleculeQuery = null;
8354
9939
  abortControllers = /* @__PURE__ */ new Map();
@@ -8492,6 +10077,9 @@ var KnishIOClient = class {
8492
10077
  } else {
8493
10078
  this.$__uris = uri;
8494
10079
  }
10080
+ if (this.$__client && "setUri" in this.$__client) {
10081
+ this.$__client.setUri(this.getRandomUri());
10082
+ }
8495
10083
  }
8496
10084
  /**
8497
10085
  * Gets the Knish.IO server URIs
@@ -8554,7 +10142,8 @@ var KnishIOClient = class {
8554
10142
  return this.$__remainderWallet;
8555
10143
  }
8556
10144
  /**
8557
- * Creates a new molecule for a transaction
10145
+ * Instantiates a new Molecule and prepares this client session to operate on it
10146
+ * Matches JavaScript SDK createMolecule implementation
8558
10147
  */
8559
10148
  async createMolecule({
8560
10149
  secret = null,
@@ -8565,17 +10154,38 @@ var KnishIOClient = class {
8565
10154
  this.log("info", "KnishIOClient::createMolecule() - Creating a new molecule...");
8566
10155
  secret = secret || this.getSecret();
8567
10156
  bundle = bundle || this.getBundle();
10157
+ let continuIdPosition = null;
10158
+ if (sourceWallet && sourceWallet.token !== "USER") {
10159
+ if (this.lastMoleculeQuery && this.getRemainderWallet() && this.getRemainderWallet()?.token === "USER" && this.lastMoleculeQuery.response() && this.lastMoleculeQuery.response()?.success()) {
10160
+ continuIdPosition = this.getRemainderWallet()?.position || null;
10161
+ this.log("info", `KnishIOClient::createMolecule() - Captured USER ContinuID position ${continuIdPosition?.substring(0, 16)}... for non-USER source wallet`);
10162
+ } else {
10163
+ const userWallet = await this.getSourceWallet();
10164
+ continuIdPosition = userWallet?.position || null;
10165
+ this.log("info", `KnishIOClient::createMolecule() - Queried USER ContinuID position ${continuIdPosition?.substring(0, 16)}... for non-USER source wallet`);
10166
+ }
10167
+ }
8568
10168
  if (!sourceWallet && this.lastMoleculeQuery && this.getRemainderWallet()?.token === "USER" && this.lastMoleculeQuery.response() && this.lastMoleculeQuery.response()?.success()) {
8569
10169
  sourceWallet = this.getRemainderWallet();
10170
+ this.log("info", `KnishIOClient::createMolecule() - Using carry-forward remainder wallet at position ${sourceWallet?.position?.substring(0, 16)}...`);
8570
10171
  }
8571
10172
  if (!sourceWallet) {
8572
10173
  sourceWallet = await this.getSourceWallet();
8573
10174
  }
8574
- return new Molecule({
10175
+ this.setRemainderWallet(remainderWallet || Wallet.create({
8575
10176
  secret,
8576
10177
  bundle,
10178
+ token: "USER",
10179
+ batchId: sourceWallet.batchId,
10180
+ characters: sourceWallet.characters
10181
+ }));
10182
+ return new Molecule({
10183
+ secret,
8577
10184
  sourceWallet,
8578
- remainderWallet
10185
+ remainderWallet: this.getRemainderWallet(),
10186
+ cellSlug: this.getCellSlug(),
10187
+ version: this.getServerSdkVersion(),
10188
+ continuIdPosition
8579
10189
  });
8580
10190
  }
8581
10191
  /**
@@ -8598,7 +10208,7 @@ var KnishIOClient = class {
8598
10208
  * Executes a query or mutation
8599
10209
  */
8600
10210
  async executeQuery(query, variables = null) {
8601
- if (this.$__authToken && this.$__authToken.isExpired()) {
10211
+ if (this.$__authToken && this.$__authToken.isExpired() && !this.$__authInProcess) {
8602
10212
  this.log("info", "KnishIOClient::executeQuery() - Access token is expired. Getting new one...");
8603
10213
  await this.requestAuthToken({
8604
10214
  secret: this.$__secret,
@@ -8625,14 +10235,26 @@ var KnishIOClient = class {
8625
10235
  }
8626
10236
  }
8627
10237
  /**
8628
- * Gets source wallet - basic implementation
10238
+ * Retrieves this session's wallet used for signing the next Molecule
10239
+ * Queries ContinuID from the server to get the authoritative position
10240
+ * Matches JavaScript SDK getSourceWallet implementation
8629
10241
  */
8630
10242
  async getSourceWallet() {
8631
- return Wallet.create({
8632
- secret: this.getSecret(),
8633
- bundle: this.getBundle(),
8634
- token: "USER"
8635
- });
10243
+ let sourceWallet = (await this.queryContinuId({
10244
+ bundle: this.getBundle()
10245
+ }))?.payload();
10246
+ if (!sourceWallet) {
10247
+ sourceWallet = new Wallet({
10248
+ secret: this.getSecret()
10249
+ });
10250
+ } else {
10251
+ sourceWallet.key = Wallet.generateKey({
10252
+ secret: this.getSecret(),
10253
+ token: sourceWallet.token,
10254
+ position: sourceWallet.position
10255
+ });
10256
+ }
10257
+ return sourceWallet;
8636
10258
  }
8637
10259
  /**
8638
10260
  * Transfer tokens between wallets
@@ -8661,7 +10283,7 @@ var KnishIOClient = class {
8661
10283
  amount
8662
10284
  });
8663
10285
  }
8664
- if (sourceWallet === null || Decimal.cmp(sourceWallet.balance, amount) < 0) {
10286
+ if (sourceWallet === null || Decimal.cmp(Number(sourceWallet.balance), amount) < 0) {
8665
10287
  throw new TransferBalanceException();
8666
10288
  }
8667
10289
  const recipientWallet = Wallet.create({
@@ -8696,19 +10318,48 @@ var KnishIOClient = class {
8696
10318
  return await this.executeQuery(query);
8697
10319
  }
8698
10320
  /**
8699
- * Request authorization token
10321
+ * Request authorization token (guest or profile)
10322
+ *
10323
+ * @param secret - User secret for profile auth (null for guest)
10324
+ * @param seed - Seed to generate secret (alternative to secret)
10325
+ * @param cellSlug - Cell slug for scoped access
10326
+ * @param encrypt - Whether to use encryption
8700
10327
  */
8701
10328
  async requestAuthToken({
8702
- secret: _secret = null,
8703
- seed: _seed = null,
8704
- cellSlug: _cellSlug = null,
8705
- encrypt: _encrypt = false
10329
+ secret = null,
10330
+ seed = null,
10331
+ cellSlug = null,
10332
+ encrypt = false
8706
10333
  } = {}) {
8707
10334
  if (this.$__serverSdkVersion < 3) {
8708
- this.log("warn", "KnishIOClient::authorize() - Server SDK version does not require an authorization...");
10335
+ this.log("warn", "KnishIOClient::requestAuthToken() - Server SDK version does not require authorization...");
8709
10336
  return null;
8710
10337
  }
8711
- return null;
10338
+ if (secret === null && seed) {
10339
+ secret = generateSecret(seed);
10340
+ }
10341
+ if (cellSlug) {
10342
+ this.setCellSlug(cellSlug);
10343
+ }
10344
+ this.$__authInProcess = true;
10345
+ let response;
10346
+ if (secret) {
10347
+ response = await this.requestProfileAuthToken({
10348
+ secret,
10349
+ encrypt
10350
+ });
10351
+ } else {
10352
+ response = await this.requestGuestAuthToken({
10353
+ cellSlug: cellSlug || this.getCellSlug(),
10354
+ encrypt
10355
+ });
10356
+ }
10357
+ if (this.$__authToken) {
10358
+ this.log("info", `KnishIOClient::requestAuthToken() - Successfully retrieved auth token...`);
10359
+ }
10360
+ this.switchEncryption(encrypt);
10361
+ this.$__authInProcess = false;
10362
+ return response;
8712
10363
  }
8713
10364
  /**
8714
10365
  * Logging utility
@@ -8806,7 +10457,7 @@ var KnishIOClient = class {
8806
10457
  });
8807
10458
  const sourceWallet = response.payload();
8808
10459
  const amountNum = typeof amount === "string" ? Number(amount) : amount;
8809
- if (sourceWallet === null || Decimal.cmp(sourceWallet.balance || 0, amountNum) < 0) {
10460
+ if (sourceWallet === null || Decimal.cmp(Number(sourceWallet.balance || 0), amountNum) < 0) {
8810
10461
  throw new TransferBalanceException();
8811
10462
  }
8812
10463
  if (!sourceWallet.position || !sourceWallet.address) {
@@ -8826,7 +10477,7 @@ var KnishIOClient = class {
8826
10477
  const walletQuery = this.createQuery(QueryWalletList);
8827
10478
  const response = await this.executeQuery(walletQuery, {
8828
10479
  bundleHash: bundle || this.getBundle(),
8829
- tokenSlug: token,
10480
+ token,
8830
10481
  unspent
8831
10482
  });
8832
10483
  return response?.payload() || [];
@@ -8876,6 +10527,7 @@ var KnishIOClient = class {
8876
10527
  count = null,
8877
10528
  countBy = null,
8878
10529
  throughAtom = true,
10530
+ throughMolecule = false,
8879
10531
  values = null,
8880
10532
  keys = null,
8881
10533
  atomValues = null
@@ -8883,7 +10535,23 @@ var KnishIOClient = class {
8883
10535
  this.log("info", `KnishIOClient::queryMeta() - Querying metaType: ${metaType}, metaId: ${metaId}...`);
8884
10536
  let query;
8885
10537
  let variables;
8886
- if (throughAtom) {
10538
+ if (throughMolecule) {
10539
+ query = this.createQuery(QueryMetaTypeViaMolecule);
10540
+ variables = QueryMetaTypeViaMolecule.createVariables({
10541
+ metaType,
10542
+ metaId,
10543
+ key,
10544
+ value,
10545
+ latest,
10546
+ filter,
10547
+ queryArgs,
10548
+ countBy,
10549
+ values,
10550
+ keys,
10551
+ atomValues,
10552
+ cellSlug: this.getCellSlug()
10553
+ });
10554
+ } else if (throughAtom) {
8887
10555
  query = this.createQuery(QueryMetaTypeViaAtom);
8888
10556
  variables = QueryMetaTypeViaAtom.createVariables({
8889
10557
  metaType,
@@ -8916,6 +10584,19 @@ var KnishIOClient = class {
8916
10584
  }
8917
10585
  return this.executeQuery(query, variables);
8918
10586
  }
10587
+ /**
10588
+ * Queries meta assets and verifies cryptographic integrity of associated molecules.
10589
+ * Forces throughMolecule=true to ensure molecule data is available for verification.
10590
+ * Returns the same response as queryMeta(), with an additional `integrity` field on the payload.
10591
+ */
10592
+ async queryMetaVerified(params) {
10593
+ const response = await this.queryMeta({ ...params, throughMolecule: true });
10594
+ const payload = response.payload();
10595
+ if (payload && typeof response.verifyIntegrity === "function") {
10596
+ payload.integrity = response.verifyIntegrity();
10597
+ }
10598
+ return response;
10599
+ }
8919
10600
  /**
8920
10601
  * Query cascading meta instances for batchId
8921
10602
  */
@@ -9178,7 +10859,7 @@ var KnishIOClient = class {
9178
10859
  const recipientWallet = new Wallet({
9179
10860
  secret: this.getSecret(),
9180
10861
  bundle: this.getBundle(),
9181
- token: token.toUpperCase(),
10862
+ token,
9182
10863
  batchId
9183
10864
  });
9184
10865
  await mutation.fillMolecule({
@@ -9206,7 +10887,7 @@ var KnishIOClient = class {
9206
10887
  this.log("info", `KnishIOClient::requestTokens() - Requesting ${amount || "units"} of ${token}...`);
9207
10888
  const mutation = await this.createMoleculeMutation({ mutationClass: MutationRequestTokens });
9208
10889
  await mutation.fillMolecule({
9209
- token: token.toUpperCase(),
10890
+ token,
9210
10891
  amount: amount ?? 0,
9211
10892
  metaType: to || "",
9212
10893
  metaId: to || "",
@@ -9235,11 +10916,19 @@ var KnishIOClient = class {
9235
10916
  amount: amount || 0
9236
10917
  });
9237
10918
  }
9238
- const mutation = await this.createMoleculeMutation({ mutationClass: MutationTransferTokens });
10919
+ const remainderWallet = sourceWallet.createRemainder(this.getSecret());
10920
+ const molecule = await this.createMolecule({
10921
+ sourceWallet,
10922
+ remainderWallet
10923
+ });
10924
+ const mutation = await this.createMoleculeMutation({
10925
+ mutationClass: MutationTransferTokens,
10926
+ molecule
10927
+ });
9239
10928
  const recipientWallet = new Wallet({
9240
10929
  secret: this.getSecret(),
9241
10930
  bundle: "0000000000000000000000000000000000000000000000000000000000000000",
9242
- token: token.toUpperCase()
10931
+ token
9243
10932
  });
9244
10933
  await mutation.fillMolecule({
9245
10934
  recipientWallet,
@@ -9294,7 +10983,7 @@ var KnishIOClient = class {
9294
10983
  const newWallet = new Wallet({
9295
10984
  secret: this.getSecret(),
9296
10985
  bundle: this.getBundle(),
9297
- token: token.toUpperCase()
10986
+ token
9298
10987
  });
9299
10988
  await mutation.fillMolecule(newWallet);
9300
10989
  const response = await this.executeQuery(mutation);
@@ -9325,7 +11014,7 @@ var KnishIOClient = class {
9325
11014
  }
9326
11015
  const mutation = await this.createMoleculeMutation({ mutationClass: MutationClaimShadowWallet });
9327
11016
  await mutation.fillMolecule({
9328
- token: token.toUpperCase(),
11017
+ token,
9329
11018
  batchId: shadowWallet.batchId
9330
11019
  });
9331
11020
  const response = await this.executeQuery(mutation);
@@ -9373,11 +11062,16 @@ var KnishIOClient = class {
9373
11062
  policy = null
9374
11063
  }) {
9375
11064
  this.log("info", `KnishIOClient::createMeta() - Creating metadata for ${metaType}:${metaId}...`);
9376
- const mutation = await this.createMoleculeMutation({ mutationClass: MutationCreateMeta });
11065
+ const mutation = await this.createMoleculeMutation({
11066
+ mutationClass: MutationCreateMeta,
11067
+ molecule: await this.createMolecule({
11068
+ secret: this.getSecret()
11069
+ })
11070
+ });
9377
11071
  await mutation.fillMolecule({
9378
- metaType: metaType.toUpperCase(),
11072
+ metaType,
9379
11073
  metaId,
9380
- meta,
11074
+ meta: meta || {},
9381
11075
  policy
9382
11076
  });
9383
11077
  const response = await this.executeQuery(mutation);
@@ -9396,9 +11090,14 @@ var KnishIOClient = class {
9396
11090
  policy = null
9397
11091
  }) {
9398
11092
  this.log("info", `KnishIOClient::createRule() - Creating rule for ${metaType}:${metaId}...`);
9399
- const mutation = await this.createMoleculeMutation({ mutationClass: MutationCreateRule });
11093
+ const mutation = await this.createMoleculeMutation({
11094
+ mutationClass: MutationCreateRule,
11095
+ molecule: await this.createMolecule({
11096
+ secret: this.getSecret()
11097
+ })
11098
+ });
9400
11099
  await mutation.fillMolecule({
9401
- metaType: metaType.toUpperCase(),
11100
+ metaType,
9402
11101
  metaId,
9403
11102
  rule,
9404
11103
  policy
@@ -9485,8 +11184,8 @@ var KnishIOClient = class {
9485
11184
  this.log("info", `KnishIOClient::activeSession() - Declaring active session for ${metaType}:${metaId}...`);
9486
11185
  const mutation = this.createQuery(MutationActiveSession);
9487
11186
  const response = await this.executeQuery(mutation, {
9488
- bundle: bundle || this.getBundle(),
9489
- metaType: metaType.toUpperCase(),
11187
+ bundleHash: bundle || this.getBundle(),
11188
+ metaType,
9490
11189
  metaId,
9491
11190
  ipAddress,
9492
11191
  browser,
@@ -9516,7 +11215,15 @@ var KnishIOClient = class {
9516
11215
  amount
9517
11216
  });
9518
11217
  }
9519
- const mutation = await this.createMoleculeMutation({ mutationClass: MutationDepositBufferToken });
11218
+ const remainderWallet = sourceWallet.createRemainder(this.getSecret());
11219
+ const molecule = await this.createMolecule({
11220
+ sourceWallet,
11221
+ remainderWallet
11222
+ });
11223
+ const mutation = await this.createMoleculeMutation({
11224
+ mutationClass: MutationDepositBufferToken,
11225
+ molecule
11226
+ });
9520
11227
  await mutation.fillMolecule({
9521
11228
  amount: typeof amount === "string" ? Number(amount) : amount,
9522
11229
  tradeRates
@@ -9579,6 +11286,7 @@ var KnishIOClient = class {
9579
11286
  }
9580
11287
  /**
9581
11288
  * Request profile authentication token
11289
+ * Matches JavaScript SDK requestProfileAuthToken implementation
9582
11290
  */
9583
11291
  async requestProfileAuthToken({
9584
11292
  secret,
@@ -9586,151 +11294,108 @@ var KnishIOClient = class {
9586
11294
  }) {
9587
11295
  this.log("info", "KnishIOClient::requestProfileAuthToken() - Requesting profile auth token...");
9588
11296
  this.setSecret(secret);
9589
- const mutation = await this.createMoleculeMutation({ mutationClass: MutationRequestAuthorization });
9590
- await mutation.fillMolecule({
11297
+ const wallet = new Wallet({
11298
+ secret,
11299
+ token: "AUTH"
11300
+ });
11301
+ const molecule = await this.createMolecule({
11302
+ secret,
11303
+ sourceWallet: wallet
11304
+ });
11305
+ const mutation = await this.createMoleculeMutation({
11306
+ mutationClass: MutationRequestAuthorization,
11307
+ molecule
11308
+ });
11309
+ mutation.fillMolecule({
9591
11310
  meta: { encrypt: encrypt ? "true" : "false" }
9592
11311
  });
9593
11312
  const response = await this.executeQuery(mutation);
9594
11313
  if (!response) {
9595
11314
  throw new CodeException("Profile auth token request failed");
9596
11315
  }
11316
+ if (response.success()) {
11317
+ const authToken = AuthToken.create({
11318
+ token: response.token(),
11319
+ expiresAt: response.expiresAt(),
11320
+ encrypt: String(response.encrypt()) === "true",
11321
+ pubkey: response.pubKey()
11322
+ }, wallet);
11323
+ this.setAuthToken(authToken);
11324
+ } else {
11325
+ throw new AuthorizationRejectedException_default(
11326
+ `KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${response.reason()}`
11327
+ );
11328
+ }
9597
11329
  if (encrypt) {
9598
11330
  this.switchEncryption(true);
9599
11331
  }
9600
11332
  return response;
9601
11333
  }
9602
11334
  // =============================================================================
9603
- // LEGACY/DEPRECATED METHODS
11335
+ // MUTATION METHODS - PEERING & APPEND REQUEST
9604
11336
  // =============================================================================
9605
11337
  /**
9606
- * @deprecated Use getCellSlug() instead
9607
- */
9608
- cellSlug() {
9609
- return this.getCellSlug();
9610
- }
9611
- /**
9612
- * @deprecated Use getUri() instead
11338
+ * Register a peer node via P-isotope
11339
+ * Matches JavaScript SDK registerPeer implementation exactly
9613
11340
  */
9614
- uri() {
9615
- return this.getUri();
11341
+ async registerPeer({ host }) {
11342
+ this.log("info", `KnishIOClient::registerPeer() - Registering peer at ${host}...`);
11343
+ const mutation = await this.createMoleculeMutation({
11344
+ mutationClass: MutationPeering,
11345
+ molecule: await this.createMolecule({
11346
+ secret: this.getSecret()
11347
+ })
11348
+ });
11349
+ mutation.fillMolecule({ host });
11350
+ const response = await this.executeQuery(mutation);
11351
+ if (!response) {
11352
+ throw new CodeException("Peer registration failed");
11353
+ }
11354
+ return response;
9616
11355
  }
9617
- };
9618
-
9619
- // src/AuthToken.ts
9620
- var AuthToken = class _AuthToken {
9621
- $__token;
9622
- $__expiresAt;
9623
- $__pubkey;
9624
- $__encrypt;
9625
- $__wallet;
9626
11356
  /**
9627
- * Create new AuthToken instance
11357
+ * Submit an append request via A-isotope
11358
+ * Matches JavaScript SDK appendRequest implementation exactly
9628
11359
  */
9629
- constructor({
9630
- token,
9631
- expiresAt,
9632
- encrypt,
9633
- pubkey
11360
+ async appendRequest({
11361
+ metaType,
11362
+ metaId,
11363
+ action,
11364
+ meta = {}
9634
11365
  }) {
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
11366
+ this.log("info", `KnishIOClient::appendRequest() - Submitting append request for ${metaType}:${metaId}...`);
11367
+ const mutation = await this.createMoleculeMutation({
11368
+ mutationClass: MutationAppendRequest,
11369
+ molecule: await this.createMolecule({
11370
+ secret: this.getSecret()
11371
+ })
9657
11372
  });
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;
11373
+ mutation.fillMolecule({
11374
+ metaType,
11375
+ metaId,
11376
+ action,
11377
+ meta
11378
+ });
11379
+ const response = await this.executeQuery(mutation);
11380
+ if (!response) {
11381
+ throw new CodeException("Append request failed");
11382
+ }
11383
+ return response;
9707
11384
  }
11385
+ // =============================================================================
11386
+ // LEGACY/DEPRECATED METHODS
11387
+ // =============================================================================
9708
11388
  /**
9709
- * Get auth data for GraphQL client
11389
+ * @deprecated Use getCellSlug() instead
9710
11390
  */
9711
- getAuthData() {
9712
- return {
9713
- token: this.$__token,
9714
- pubkey: this.$__pubkey,
9715
- wallet: this.$__wallet
9716
- };
11391
+ cellSlug() {
11392
+ return this.getCellSlug();
9717
11393
  }
9718
11394
  /**
9719
- * Create snapshot for persistence
11395
+ * @deprecated Use getUri() instead
9720
11396
  */
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
- };
11397
+ uri() {
11398
+ return this.getUri();
9734
11399
  }
9735
11400
  };
9736
11401
 
@@ -9894,6 +11559,6 @@ var KnishIO = {
9894
11559
  SDK_INFO
9895
11560
  };
9896
11561
 
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 };
11562
+ 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
11563
  //# sourceMappingURL=index.js.map
9899
11564
  //# sourceMappingURL=index.js.map