@wishknish/knishio-client-ts 0.8.3 → 0.9.1

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 (35) hide show
  1. package/dist/index.cjs +399 -258
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +37 -16
  4. package/dist/index.d.ts +37 -16
  5. package/dist/index.iife.js +3700 -602
  6. package/dist/index.iife.js.map +1 -1
  7. package/dist/index.js +421 -280
  8. package/dist/index.js.map +1 -1
  9. package/package.json +18 -20
  10. package/src/KnishIOClient.ts +135 -53
  11. package/src/constants.ts +1 -2
  12. package/src/core/Molecule.ts +53 -0
  13. package/src/core/Wallet.ts +96 -3
  14. package/src/libraries/Decimal.ts +1 -1
  15. package/src/libraries/GraphQLClient.ts +83 -0
  16. package/src/libraries/Hex.ts +4 -3
  17. package/src/libraries/UrqlClientWrapper.ts +13 -13
  18. package/src/libraries/crypto.ts +4 -4
  19. package/src/mutation/MutationClaimShadowWallet.ts +3 -1
  20. package/src/mutation/MutationTransferTokens.ts +18 -0
  21. package/src/query/QueryActiveSession.ts +0 -1
  22. package/src/query/QueryPolicy.ts +0 -1
  23. package/src/response/ResponseAuthorizationGuest.ts +2 -2
  24. package/src/response/ResponseBalance.ts +9 -6
  25. package/src/response/ResponseLinkIdentifier.ts +1 -1
  26. package/src/response/ResponseRequestAuthorizationGuest.ts +2 -2
  27. package/src/subscribe/Subscribe.ts +3 -2
  28. package/src/types/assertions.ts +1 -6
  29. package/src/types/client.ts +12 -19
  30. package/src/types/guards.ts +2 -3
  31. package/src/validation/UNIVERSAL_CONFIGURATION_INTERFACES.ts +3 -5
  32. package/src/validation/ValidationService.ts +6 -15
  33. package/src/versions/HashAtom.ts +11 -9
  34. package/src/query/QueryUserActivity.ts +0 -153
  35. package/src/response/ResponseQueryUserActivity.ts +0 -89
package/dist/index.cjs CHANGED
@@ -945,9 +945,19 @@ var init_StackableUnitAmountException = __esm({
945
945
  });
946
946
 
947
947
  // src/exception/StackableUnitDecimalsException.ts
948
+ var StackableUnitDecimalsException, StackableUnitDecimalsException_default;
948
949
  var init_StackableUnitDecimalsException = __esm({
949
950
  "src/exception/StackableUnitDecimalsException.ts"() {
950
951
  init_BaseException();
952
+ StackableUnitDecimalsException = class extends exports.BaseException {
953
+ /**
954
+ * Constructor using proper error type
955
+ */
956
+ constructor(message = "Stackable tokens with unit IDs cannot have decimal places!") {
957
+ super("STACKABLE_UNIT_DECIMALS_ERROR", message);
958
+ }
959
+ };
960
+ StackableUnitDecimalsException_default = StackableUnitDecimalsException;
951
961
  }
952
962
  });
953
963
 
@@ -1929,9 +1939,6 @@ function generateSecret(seed = null, length = CRYPTO_CONSTANTS.SECRET_LENGTH) {
1929
1939
  }
1930
1940
  }
1931
1941
  function generateBundleHash(secret, _source = null) {
1932
- if (!secret || secret.length === 0) {
1933
- throw new Error("Secret is required for bundle hash generation");
1934
- }
1935
1942
  const hash = shake256(secret, CRYPTO_CONSTANTS.BUNDLE_HASH_LENGTH * 4);
1936
1943
  return hash;
1937
1944
  }
@@ -3342,8 +3349,7 @@ var QUERY_TYPES = [
3342
3349
  "Batch",
3343
3350
  "ActiveSession",
3344
3351
  "Policy",
3345
- "Token",
3346
- "UserActivity"
3352
+ "Token"
3347
3353
  ];
3348
3354
  function createLookup(values) {
3349
3355
  return values.reduce((acc, value) => {
@@ -3602,6 +3608,29 @@ var Wallet = class _Wallet {
3602
3608
  }
3603
3609
  remainderWallet.tokenUnits = remainderTokenUnits;
3604
3610
  }
3611
+ /**
3612
+ * Split token units across MULTIPLE recipients (N-way sibling of splitUnits).
3613
+ *
3614
+ * The source retains the SENT union (all units leaving), each recipient gets its own
3615
+ * subset, and the remainder keeps the KEPT units (those not assigned to any recipient).
3616
+ * recipientUnitLists is parallel to recipientWallets. No-op when no units are sent.
3617
+ *
3618
+ * @param recipientUnitLists - per-recipient arrays of token unit IDs (parallel to recipientWallets)
3619
+ * @param recipientWallets - destination wallets
3620
+ * @param remainderWallet - wallet to receive the KEPT units
3621
+ */
3622
+ splitUnitsMulti(recipientUnitLists, recipientWallets, remainderWallet) {
3623
+ const sentIds = new Set(recipientUnitLists.flat());
3624
+ if (sentIds.size === 0) {
3625
+ return;
3626
+ }
3627
+ recipientWallets.forEach((recipientWallet, i) => {
3628
+ const ids = recipientUnitLists[i] ?? [];
3629
+ recipientWallet.tokenUnits = this.tokenUnits.filter((tokenUnit) => ids.includes(tokenUnit.id));
3630
+ });
3631
+ remainderWallet.tokenUnits = this.tokenUnits.filter((tokenUnit) => !sentIds.has(tokenUnit.id));
3632
+ this.tokenUnits = this.tokenUnits.filter((tokenUnit) => sentIds.has(tokenUnit.id));
3633
+ }
3605
3634
  /**
3606
3635
  * Get token units data
3607
3636
  * Stub for compatibility
@@ -3640,6 +3669,12 @@ var Wallet = class _Wallet {
3640
3669
  const messageString = JSON.stringify(message);
3641
3670
  const messageUint8 = new TextEncoder().encode(messageString);
3642
3671
  const deserializedPubkey = this.deserializeKey(recipientPubkey);
3672
+ const ML_KEM_768_PUBLIC_KEY_BYTES = 1184;
3673
+ if (deserializedPubkey.length !== ML_KEM_768_PUBLIC_KEY_BYTES) {
3674
+ throw new Error(
3675
+ `KnishIO: cannot ML-KEM-encrypt \u2014 recipient public key is ${deserializedPubkey.length} bytes, expected ${ML_KEM_768_PUBLIC_KEY_BYTES} (ML-KEM-768). The node likely did not advertise an ML-KEM public key (upgrade the validator to a PQ-transport build), or authenticate with { encrypt: false }.`
3676
+ );
3677
+ }
3643
3678
  const { cipherText, sharedSecret } = mlKem_js.ml_kem768.encapsulate(deserializedPubkey);
3644
3679
  const encryptedMessage = await this.encryptWithSharedSecret(messageUint8, sharedSecret);
3645
3680
  return {
@@ -3648,6 +3683,15 @@ var Wallet = class _Wallet {
3648
3683
  };
3649
3684
  }
3650
3685
  async decryptMessage(encryptedData) {
3686
+ const decryptedString = await this._mlkemDecryptToString(encryptedData);
3687
+ return decryptedString === null ? null : JSON.parse(decryptedString);
3688
+ }
3689
+ /**
3690
+ * ML-KEM768 decapsulate + AES-256-GCM decrypt → the RAW decrypted UTF-8 string (no JSON.parse).
3691
+ * Shared by {@link decryptMessage} (which JSON.parses the result) and the PQ CipherHash transport
3692
+ * ({@link decryptMyMessageML768}, which needs the raw response JSON text). PQ-transport Phase E.
3693
+ */
3694
+ async _mlkemDecryptToString(encryptedData) {
3651
3695
  const { cipherText, encryptedMessage } = encryptedData;
3652
3696
  let sharedSecret;
3653
3697
  try {
@@ -3676,9 +3720,8 @@ var Wallet = class _Wallet {
3676
3720
  console.info("Wallet::decryptMessage() - deserialized encrypted message", deserializedEncryptedMessage);
3677
3721
  return null;
3678
3722
  }
3679
- let decryptedString;
3680
3723
  try {
3681
- decryptedString = new TextDecoder().decode(decryptedUint8);
3724
+ return new TextDecoder().decode(decryptedUint8);
3682
3725
  } catch (e) {
3683
3726
  console.warn("Wallet::decryptMessage() - Decoding failed", e);
3684
3727
  console.info("Wallet::decryptMessage() - my public key", this.pubkey);
@@ -3687,7 +3730,40 @@ var Wallet = class _Wallet {
3687
3730
  console.info("Wallet::decryptMessage() - decrypted Uint8Array", decryptedUint8);
3688
3731
  return null;
3689
3732
  }
3690
- return JSON.parse(decryptedString);
3733
+ }
3734
+ /**
3735
+ * Canonical cross-SDK hashShare for a public key: standard base64 of SHAKE256(pubkey_utf8, 8 bytes)
3736
+ * — byte-matches the validator's hash_share and the JS/Kotlin/PHP hashShare. `shake256(pubkey, 64)`
3737
+ * = 64 bits = 8 bytes (hex) → hex-decode → standard base64 via serializeKey. PQ-transport Phase E.
3738
+ */
3739
+ hashShare(pubkey) {
3740
+ const hex = shake256(pubkey, 64);
3741
+ const bytes = new Uint8Array(hex.length / 2);
3742
+ for (let i = 0; i < bytes.length; i++) {
3743
+ bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
3744
+ }
3745
+ return this.serializeKey(bytes);
3746
+ }
3747
+ /**
3748
+ * Post-quantum (ML-KEM768) CipherHash request envelope: a stringified single-recipient map
3749
+ * `{ "<hashShare(recipientPubkey)>": {cipherText, encryptedMessage} }` (object-valued, via
3750
+ * {@link encryptMessage}). Matches the Rust validator's CipherHash handler. PQ-transport Phase E.
3751
+ */
3752
+ async encryptStringML768(message, recipientPubkey) {
3753
+ const envelope = await this.encryptMessage(message, recipientPubkey);
3754
+ return JSON.stringify({ [this.hashShare(recipientPubkey)]: envelope });
3755
+ }
3756
+ /**
3757
+ * Decrypt a CipherHash response map addressed to THIS wallet's ML-KEM pubkey
3758
+ * (`hashShare(this.pubkey)`) → the RAW decrypted GraphQL response JSON text (NOT JSON.parsed;
3759
+ * it replaces the HTTP response body for the normal parser). `null` if no entry / decrypt fails.
3760
+ */
3761
+ async decryptMyMessageML768(map) {
3762
+ const envelope = map[this.hashShare(this.pubkey)];
3763
+ if (!envelope) {
3764
+ return null;
3765
+ }
3766
+ return this._mlkemDecryptToString(envelope);
3691
3767
  }
3692
3768
  // =============================================================================
3693
3769
  // SYMMETRIC ENCRYPTION HELPERS (AES-GCM with shared secret)
@@ -4986,6 +5062,46 @@ var Molecule = class _Molecule {
4986
5062
  }));
4987
5063
  return this;
4988
5064
  }
5065
+ /**
5066
+ * Initialize a MULTI-recipient V-type molecule: one source debits its FULL balance to fund
5067
+ * N recipients (each its own amount + stackable units) plus a remainder back to the sender.
5068
+ * Multi-recipient sibling of initValue (WP line 544: fund multiple recipients with one
5069
+ * transaction). recipientWallets is parallel to amounts.
5070
+ */
5071
+ initValues({
5072
+ recipientWallets,
5073
+ amounts
5074
+ }) {
5075
+ if (!this.sourceWallet) {
5076
+ throw new Error("Source wallet required for value transfer");
5077
+ }
5078
+ const total = amounts.reduce((sum, amount) => sum + amount, 0);
5079
+ if (Number(this.sourceWallet.balance) - total < 0) {
5080
+ throw new BalanceInsufficientException();
5081
+ }
5082
+ this.addAtom(Atom.create({
5083
+ isotope: "V",
5084
+ wallet: this.sourceWallet,
5085
+ value: -Number(this.sourceWallet.balance)
5086
+ }));
5087
+ recipientWallets.forEach((recipientWallet, i) => {
5088
+ this.addAtom(Atom.create({
5089
+ isotope: "V",
5090
+ wallet: recipientWallet,
5091
+ value: amounts[i],
5092
+ metaType: "walletBundle",
5093
+ metaId: recipientWallet.bundle
5094
+ }));
5095
+ });
5096
+ this.addAtom(Atom.create({
5097
+ isotope: "V",
5098
+ wallet: this.remainderWallet,
5099
+ value: Number(this.sourceWallet.balance) - total,
5100
+ metaType: "walletBundle",
5101
+ metaId: this.remainderWallet.bundle
5102
+ }));
5103
+ return this;
5104
+ }
4989
5105
  /**
4990
5106
  * Sign the molecule with one-time signature
4991
5107
  * Matches JavaScript SDK sign method
@@ -5743,7 +5859,7 @@ var Decimal = class _Decimal {
5743
5859
  * @param debug Enable debug logging
5744
5860
  * @returns 0 if equal, 1 if value1 > value2, -1 if value1 < value2
5745
5861
  */
5746
- static cmp(value1, value2, debug = false) {
5862
+ static cmp(value1, value2, _debug = false) {
5747
5863
  const val1 = _Decimal.val(value1) * MULTIPLIER;
5748
5864
  const val2 = _Decimal.val(value2) * MULTIPLIER;
5749
5865
  if (Math.abs(val1 - val2) < 1) {
@@ -5758,6 +5874,14 @@ var Decimal = class _Decimal {
5758
5874
  return _Decimal.cmp(value1, value2) === 0;
5759
5875
  }
5760
5876
  };
5877
+ var CIPHER_HASH_QUERY = "query ( $Hash: String! ) { CipherHash ( Hash: $Hash ) { hash } }";
5878
+ function parseOperation(query) {
5879
+ const typeMatch = (query || "").match(/\b(query|mutation|subscription)\b/i);
5880
+ const type = typeMatch?.[1]?.toLowerCase() ?? "query";
5881
+ const braceIdx = (query || "").indexOf("{");
5882
+ const nameMatch = braceIdx >= 0 ? query.slice(braceIdx + 1).match(/[A-Za-z_][A-Za-z0-9_]*/) : null;
5883
+ return { type, name: nameMatch?.[0] ?? "" };
5884
+ }
5761
5885
  var GraphQLClient = class {
5762
5886
  $__client;
5763
5887
  $__authToken = "";
@@ -5803,6 +5927,10 @@ var GraphQLClient = class {
5803
5927
  return core.createClient({
5804
5928
  url: serverUri,
5805
5929
  exchanges,
5930
+ // PQ-transport Phase E: when encryption is on, route fetch through the CipherHash wrapper
5931
+ // (encrypt the request body to the validator's ML-KEM pubkey, decrypt the response).
5932
+ // Omitted → urql uses the global fetch (plaintext).
5933
+ ...this.cipherLink ? { fetch: ((input, init) => this.cipherFetch(input, init)) } : {},
5806
5934
  fetchOptions: () => ({
5807
5935
  headers: {
5808
5936
  "X-Auth-Token": this.$__authToken
@@ -5812,6 +5940,62 @@ var GraphQLClient = class {
5812
5940
  })
5813
5941
  });
5814
5942
  }
5943
+ /**
5944
+ * Whether an outgoing GraphQL request body should be wrapped in CipherHash. Bypass (plaintext):
5945
+ * introspection `__schema`, `ContinuId`, the `AccessToken` mutation, and the U-isotope
5946
+ * `ProposeMolecule` (auth bootstrap — the key exchange itself can't be encrypted). Mirrors the
5947
+ * Kotlin/PHP/validator bypass set.
5948
+ */
5949
+ shouldEncrypt(body) {
5950
+ let parsed;
5951
+ try {
5952
+ parsed = JSON.parse(body);
5953
+ } catch (e) {
5954
+ return false;
5955
+ }
5956
+ const { type, name } = parseOperation(parsed.query);
5957
+ if (type === "query" && (name === "__schema" || name === "ContinuId")) return false;
5958
+ if (type === "mutation" && name === "AccessToken") return false;
5959
+ if (type === "mutation" && name === "ProposeMolecule") {
5960
+ const isotope = parsed.variables?.molecule?.atoms?.[0]?.isotope;
5961
+ if (isotope === "U") return false;
5962
+ }
5963
+ return true;
5964
+ }
5965
+ /**
5966
+ * Custom `fetch` that wraps a GraphQL request in the ML-KEM CipherHash envelope and decrypts the
5967
+ * response (PQ-transport Phase E). Operates on the raw POST body (mirrors the JS/Kotlin transform).
5968
+ * Reads the CURRENT client wallet + validator pubkey from auth.
5969
+ */
5970
+ async cipherFetch(input, init) {
5971
+ const wallet = this.$__wallet;
5972
+ const serverPubkey = this.$__pubkey;
5973
+ let encryptedRequest = false;
5974
+ let requestInit = init;
5975
+ if (wallet && serverPubkey && init && typeof init.body === "string" && this.shouldEncrypt(init.body)) {
5976
+ const hashVar = await wallet.encryptStringML768(init.body, serverPubkey);
5977
+ requestInit = { ...init, body: JSON.stringify({ query: CIPHER_HASH_QUERY, variables: { Hash: hashVar } }) };
5978
+ encryptedRequest = true;
5979
+ }
5980
+ const response = await fetch(input, requestInit);
5981
+ if (!encryptedRequest) {
5982
+ return response;
5983
+ }
5984
+ const text = await response.text();
5985
+ const init2 = { status: response.status, statusText: response.statusText, headers: response.headers };
5986
+ let parsed;
5987
+ try {
5988
+ parsed = JSON.parse(text);
5989
+ } catch (e) {
5990
+ return new Response(text, init2);
5991
+ }
5992
+ const hash = parsed?.data?.CipherHash?.hash;
5993
+ if (typeof hash !== "string") {
5994
+ return new Response(text, init2);
5995
+ }
5996
+ const decrypted = await wallet.decryptMyMessageML768(JSON.parse(hash));
5997
+ return new Response(decrypted != null ? decrypted : text, init2);
5998
+ }
5815
5999
  setAuthData({
5816
6000
  token,
5817
6001
  pubkey,
@@ -6106,8 +6290,8 @@ var Query = class {
6106
6290
  * Returns a Response object
6107
6291
  */
6108
6292
  createResponse(json) {
6109
- const Response2 = (init_Response(), __toCommonJS(Response_exports)).default;
6110
- return new Response2({
6293
+ const Response3 = (init_Response(), __toCommonJS(Response_exports)).default;
6294
+ return new Response3({
6111
6295
  query: this,
6112
6296
  json
6113
6297
  });
@@ -6177,8 +6361,8 @@ var Query = class {
6177
6361
  } catch (error) {
6178
6362
  if (error.name === "AbortError") {
6179
6363
  this.knishIOClient.log("warn", "Query was cancelled");
6180
- const Response2 = (init_Response(), __toCommonJS(Response_exports)).default;
6181
- return new Response2({
6364
+ const Response3 = (init_Response(), __toCommonJS(Response_exports)).default;
6365
+ return new Response3({
6182
6366
  query: this,
6183
6367
  json: { data: null, errors: [{ message: "Query was cancelled" }] }
6184
6368
  });
@@ -6222,8 +6406,8 @@ var Mutation = class extends Query {
6222
6406
  } catch (error) {
6223
6407
  if (error.name === "AbortError") {
6224
6408
  this.knishIOClient.log("warn", "Mutation was cancelled");
6225
- const Response2 = (init_Response(), __toCommonJS(Response_exports)).default;
6226
- return new Response2({
6409
+ const Response3 = (init_Response(), __toCommonJS(Response_exports)).default;
6410
+ return new Response3({
6227
6411
  query: this,
6228
6412
  json: { data: null, errors: [{ message: "Mutation was cancelled" }] }
6229
6413
  });
@@ -6829,6 +7013,7 @@ var ValidationChainBuilder = class {
6829
7013
  constructor(service) {
6830
7014
  this.service = service;
6831
7015
  }
7016
+ service;
6832
7017
  validators = [];
6833
7018
  /**
6834
7019
  * Add a schema validation step
@@ -7159,6 +7344,89 @@ var ConfigValidator = class _ConfigValidator {
7159
7344
 
7160
7345
  // src/response/ResponseBalance.ts
7161
7346
  init_Response();
7347
+
7348
+ // src/core/TokenUnit.ts
7349
+ var TokenUnit = class _TokenUnit {
7350
+ id;
7351
+ name;
7352
+ metas;
7353
+ /**
7354
+ * Create new TokenUnit instance
7355
+ * Matches JavaScript SDK constructor signature exactly
7356
+ */
7357
+ constructor(id, name, metas) {
7358
+ this.id = id;
7359
+ this.name = name;
7360
+ this.metas = metas || {};
7361
+ }
7362
+ /**
7363
+ * Create TokenUnit from GraphQL response data
7364
+ * Matches JavaScript SDK createFromGraphQL method exactly
7365
+ */
7366
+ static createFromGraphQL(data) {
7367
+ let metas = data.metas || {};
7368
+ if (Array.isArray(metas) && metas.length) {
7369
+ try {
7370
+ metas = JSON.parse(metas);
7371
+ if (!metas) {
7372
+ metas = {};
7373
+ }
7374
+ } catch (error) {
7375
+ metas = {};
7376
+ }
7377
+ }
7378
+ return new _TokenUnit(
7379
+ data.id,
7380
+ data.name,
7381
+ metas
7382
+ );
7383
+ }
7384
+ /**
7385
+ * Create TokenUnit from database array data
7386
+ * Matches JavaScript SDK createFromDB method exactly
7387
+ */
7388
+ static createFromDB(data) {
7389
+ return new _TokenUnit(
7390
+ data[0],
7391
+ data[1],
7392
+ data.length > 2 ? data[2] : {}
7393
+ );
7394
+ }
7395
+ /**
7396
+ * Get fragment zone from metadata
7397
+ * Matches JavaScript SDK getFragmentZone method exactly
7398
+ */
7399
+ getFragmentZone() {
7400
+ return this.metas.fragmentZone || null;
7401
+ }
7402
+ /**
7403
+ * Get fused token units from metadata
7404
+ * Matches JavaScript SDK getFusedTokenUnits method exactly
7405
+ */
7406
+ getFusedTokenUnits() {
7407
+ return this.metas.fusedTokenUnits || null;
7408
+ }
7409
+ /**
7410
+ * Convert to data array format
7411
+ * Matches JavaScript SDK toData method exactly
7412
+ */
7413
+ toData() {
7414
+ return [this.id, this.name, this.metas];
7415
+ }
7416
+ /**
7417
+ * Convert to GraphQL response format
7418
+ * Matches JavaScript SDK toGraphQLResponse method exactly
7419
+ */
7420
+ toGraphQLResponse() {
7421
+ return {
7422
+ id: this.id,
7423
+ name: this.name,
7424
+ metas: JSON.stringify(this.metas)
7425
+ };
7426
+ }
7427
+ };
7428
+
7429
+ // src/response/ResponseBalance.ts
7162
7430
  var ResponseBalance = class _ResponseBalance extends exports.Response {
7163
7431
  /**
7164
7432
  * Class constructor
@@ -7221,6 +7489,11 @@ var ResponseBalance = class _ResponseBalance extends exports.Response {
7221
7489
  wallet.tokenSupply = data.token.supply;
7222
7490
  wallet.tokenFungibility = data.token.fungibility;
7223
7491
  }
7492
+ if (data.tokenUnits && data.tokenUnits.length) {
7493
+ for (const tokenUnitData of data.tokenUnits) {
7494
+ wallet.tokenUnits.push(TokenUnit.createFromGraphQL(tokenUnitData));
7495
+ }
7496
+ }
7224
7497
  if (data.tradeRates && data.tradeRates.length) {
7225
7498
  for (const tradeRate of data.tradeRates) {
7226
7499
  wallet.tradeRates[tradeRate.tokenSlug] = tradeRate.amount;
@@ -7278,89 +7551,6 @@ var QueryBalance = class extends Query {
7278
7551
 
7279
7552
  // src/response/ResponseWalletList.ts
7280
7553
  init_Response();
7281
-
7282
- // src/core/TokenUnit.ts
7283
- var TokenUnit = class _TokenUnit {
7284
- id;
7285
- name;
7286
- metas;
7287
- /**
7288
- * Create new TokenUnit instance
7289
- * Matches JavaScript SDK constructor signature exactly
7290
- */
7291
- constructor(id, name, metas) {
7292
- this.id = id;
7293
- this.name = name;
7294
- this.metas = metas || {};
7295
- }
7296
- /**
7297
- * Create TokenUnit from GraphQL response data
7298
- * Matches JavaScript SDK createFromGraphQL method exactly
7299
- */
7300
- static createFromGraphQL(data) {
7301
- let metas = data.metas || {};
7302
- if (Array.isArray(metas) && metas.length) {
7303
- try {
7304
- metas = JSON.parse(metas);
7305
- if (!metas) {
7306
- metas = {};
7307
- }
7308
- } catch (error) {
7309
- metas = {};
7310
- }
7311
- }
7312
- return new _TokenUnit(
7313
- data.id,
7314
- data.name,
7315
- metas
7316
- );
7317
- }
7318
- /**
7319
- * Create TokenUnit from database array data
7320
- * Matches JavaScript SDK createFromDB method exactly
7321
- */
7322
- static createFromDB(data) {
7323
- return new _TokenUnit(
7324
- data[0],
7325
- data[1],
7326
- data.length > 2 ? data[2] : {}
7327
- );
7328
- }
7329
- /**
7330
- * Get fragment zone from metadata
7331
- * Matches JavaScript SDK getFragmentZone method exactly
7332
- */
7333
- getFragmentZone() {
7334
- return this.metas.fragmentZone || null;
7335
- }
7336
- /**
7337
- * Get fused token units from metadata
7338
- * Matches JavaScript SDK getFusedTokenUnits method exactly
7339
- */
7340
- getFusedTokenUnits() {
7341
- return this.metas.fusedTokenUnits || null;
7342
- }
7343
- /**
7344
- * Convert to data array format
7345
- * Matches JavaScript SDK toData method exactly
7346
- */
7347
- toData() {
7348
- return [this.id, this.name, this.metas];
7349
- }
7350
- /**
7351
- * Convert to GraphQL response format
7352
- * Matches JavaScript SDK toGraphQLResponse method exactly
7353
- */
7354
- toGraphQLResponse() {
7355
- return {
7356
- id: this.id,
7357
- name: this.name,
7358
- metas: JSON.stringify(this.metas)
7359
- };
7360
- }
7361
- };
7362
-
7363
- // src/response/ResponseWalletList.ts
7364
7554
  var ResponseWalletList = class _ResponseWalletList extends exports.Response {
7365
7555
  /**
7366
7556
  * Class constructor
@@ -8284,131 +8474,6 @@ var QueryActiveSession = class extends Query {
8284
8474
  }
8285
8475
  };
8286
8476
 
8287
- // src/response/ResponseQueryUserActivity.ts
8288
- init_Response();
8289
- var ResponseQueryUserActivity = class extends exports.Response {
8290
- /**
8291
- * Constructor
8292
- */
8293
- constructor({
8294
- query,
8295
- json
8296
- }) {
8297
- super({
8298
- query,
8299
- json,
8300
- dataKey: "data.UserActivity"
8301
- });
8302
- }
8303
- /**
8304
- * Returns processed user activity data
8305
- */
8306
- payload() {
8307
- const data = JSON.parse(JSON.stringify(this.data()));
8308
- if (data.instances) {
8309
- for (const datum of data.instances) {
8310
- if (datum.jsonData) {
8311
- datum.jsonData = JSON.parse(datum.jsonData);
8312
- }
8313
- }
8314
- }
8315
- return data;
8316
- }
8317
- };
8318
- var QueryUserActivity = class extends Query {
8319
- /**
8320
- * Constructor
8321
- */
8322
- constructor(graphQLClient, knishIOClient) {
8323
- super(graphQLClient, knishIOClient);
8324
- this.$__query = core.gql`
8325
- query UserActivity(
8326
- $bundleHash: String
8327
- $metaType: String
8328
- $metaId: String
8329
- $ipAddress: String
8330
- $browser: String
8331
- $osCpu: String
8332
- $resolution: String
8333
- $timeZone: String
8334
- $countBy: [CountByUserActivity]
8335
- $interval: span
8336
- ) {
8337
- UserActivity(
8338
- bundleHash: $bundleHash
8339
- metaType: $metaType
8340
- metaId: $metaId
8341
- ipAddress: $ipAddress
8342
- browser: $browser
8343
- osCpu: $osCpu
8344
- resolution: $resolution
8345
- timeZone: $timeZone
8346
- countBy: $countBy
8347
- interval: $interval
8348
- ) {
8349
- createdAt
8350
- bundleHash
8351
- metaType
8352
- metaId
8353
- instances {
8354
- bundleHash
8355
- metaType
8356
- metaId
8357
- jsonData
8358
- createdAt
8359
- updatedAt
8360
- }
8361
- instanceCount {
8362
- ...SubFields
8363
- ...Recursive
8364
- }
8365
- }
8366
- }
8367
-
8368
- fragment SubFields on InstanceCountType {
8369
- id
8370
- count
8371
- }
8372
-
8373
- fragment Recursive on InstanceCountType {
8374
- instances {
8375
- ...SubFields
8376
- instances {
8377
- ...SubFields
8378
- instances {
8379
- ...SubFields
8380
- instances {
8381
- ...SubFields
8382
- instances {
8383
- ...SubFields
8384
- instances {
8385
- ...SubFields
8386
- instances {
8387
- ...SubFields
8388
- instances {
8389
- ...SubFields
8390
- }
8391
- }
8392
- }
8393
- }
8394
- }
8395
- }
8396
- }
8397
- }
8398
- }
8399
- `;
8400
- }
8401
- /**
8402
- * Returns a Response object
8403
- */
8404
- createResponse(json) {
8405
- return new ResponseQueryUserActivity({
8406
- query: this,
8407
- json
8408
- });
8409
- }
8410
- };
8411
-
8412
8477
  // src/query/QueryToken.ts
8413
8478
  init_Response();
8414
8479
  var QueryToken = class extends Query {
@@ -9242,6 +9307,20 @@ var MutationTransferTokens = class extends MutationProposeMolecule {
9242
9307
  this.$__molecule.sign({});
9243
9308
  this.$__molecule.check(this.$__molecule.sourceWallet);
9244
9309
  }
9310
+ /**
9311
+ * Fills the Molecule for a MULTI-recipient transfer (one source funds N recipients)
9312
+ */
9313
+ fillMoleculeMulti({
9314
+ recipientWallets,
9315
+ amounts
9316
+ }) {
9317
+ this.$__molecule.initValues({
9318
+ recipientWallets,
9319
+ amounts
9320
+ });
9321
+ this.$__molecule.sign({});
9322
+ this.$__molecule.check(this.$__molecule.sourceWallet);
9323
+ }
9245
9324
  /**
9246
9325
  * Builds a Response object out of a JSON object
9247
9326
  * Matches JavaScript SDK createResponse method signature exactly
@@ -9302,7 +9381,8 @@ var MutationClaimShadowWallet = class extends MutationProposeMolecule {
9302
9381
  bundle: this.$__molecule.bundle,
9303
9382
  token,
9304
9383
  batchId
9305
- })(this.$__molecule).initShadowWalletClaim(wallet);
9384
+ });
9385
+ this.$__molecule.initShadowWalletClaim(wallet);
9306
9386
  this.$__molecule.sign({});
9307
9387
  this.$__molecule.check();
9308
9388
  }
@@ -10548,6 +10628,75 @@ var KnishIOClient = class {
10548
10628
  });
10549
10629
  return await this.executeQuery(query);
10550
10630
  }
10631
+ /**
10632
+ * Fund N recipients from a single source in ONE molecule (multi-recipient sibling of
10633
+ * transferToken). Each recipient gets its own subset of stackable units (or a fungible
10634
+ * amount); a remainder returns the rest to the sender. Conserves:
10635
+ * -balance + Σamounts + (balance - Σ) === 0.
10636
+ *
10637
+ * @param token - token slug
10638
+ * @param recipients - destinations (bundleHash + units OR amount + optional batchId)
10639
+ * @param sourceWallet - optional pre-resolved source (defaults to the client's own wallet)
10640
+ */
10641
+ async transferTokens({
10642
+ token,
10643
+ recipients,
10644
+ sourceWallet = null
10645
+ }) {
10646
+ const amounts = recipients.map((recipient) => {
10647
+ const unitCount = recipient.units ? recipient.units.length : 0;
10648
+ if (unitCount > 0) {
10649
+ if (recipient.amount !== null && recipient.amount !== void 0 && recipient.amount > 0) {
10650
+ throw new StackableUnitAmountException_default();
10651
+ }
10652
+ return unitCount;
10653
+ }
10654
+ return recipient.amount ?? 0;
10655
+ });
10656
+ const total = amounts.reduce((sum, amount) => sum + amount, 0);
10657
+ if (sourceWallet === null) {
10658
+ sourceWallet = await this.querySourceWallet({
10659
+ token,
10660
+ amount: total
10661
+ });
10662
+ }
10663
+ if (sourceWallet === null || Decimal.cmp(Number(sourceWallet.balance), total) < 0) {
10664
+ throw new exports.TransferBalanceException();
10665
+ }
10666
+ const recipientWallets = recipients.map((recipient) => {
10667
+ const recipientWallet = Wallet.create({
10668
+ bundle: recipient.bundleHash,
10669
+ token
10670
+ });
10671
+ if (recipient.batchId !== null && recipient.batchId !== void 0) {
10672
+ recipientWallet.batchId = recipient.batchId;
10673
+ } else {
10674
+ recipientWallet.initBatchId({ sourceWallet });
10675
+ }
10676
+ return recipientWallet;
10677
+ });
10678
+ const remainderWallet = sourceWallet.createRemainder(this.getSecret());
10679
+ if (recipients.some((recipient) => recipient.units && recipient.units.length > 0)) {
10680
+ sourceWallet.splitUnitsMulti(
10681
+ recipients.map((recipient) => recipient.units ?? []),
10682
+ recipientWallets,
10683
+ remainderWallet
10684
+ );
10685
+ }
10686
+ const molecule = await this.createMolecule({
10687
+ sourceWallet,
10688
+ remainderWallet
10689
+ });
10690
+ const query = await this.createMoleculeMutation({
10691
+ mutationClass: MutationTransferTokens,
10692
+ molecule
10693
+ });
10694
+ query.fillMoleculeMulti({
10695
+ recipientWallets,
10696
+ amounts
10697
+ });
10698
+ return await this.executeQuery(query);
10699
+ }
10551
10700
  /**
10552
10701
  * Request authorization token (guest or profile)
10553
10702
  *
@@ -11004,36 +11153,6 @@ var KnishIOClient = class {
11004
11153
  metaId
11005
11154
  });
11006
11155
  }
11007
- /**
11008
- * Query user activity
11009
- */
11010
- async queryUserActivity({
11011
- bundleHash,
11012
- metaType,
11013
- metaId,
11014
- ipAddress = null,
11015
- browser = null,
11016
- osCpu = null,
11017
- resolution = null,
11018
- timeZone = null,
11019
- countBy = null,
11020
- interval = null
11021
- }) {
11022
- const query = this.createQuery(QueryUserActivity);
11023
- const variables = {
11024
- bundleHash,
11025
- metaType,
11026
- metaId
11027
- };
11028
- if (ipAddress !== null) variables.ipAddress = ipAddress;
11029
- if (browser !== null) variables.browser = browser;
11030
- if (osCpu !== null) variables.osCpu = osCpu;
11031
- if (resolution !== null) variables.resolution = resolution;
11032
- if (timeZone !== null) variables.timeZone = timeZone;
11033
- if (countBy !== null) variables.countBy = countBy;
11034
- if (interval !== null) variables.interval = interval;
11035
- return this.executeQuery(query, variables);
11036
- }
11037
11156
  /**
11038
11157
  * Query token information
11039
11158
  */
@@ -11142,9 +11261,27 @@ var KnishIOClient = class {
11142
11261
  amount = null,
11143
11262
  meta = null,
11144
11263
  batchId = null,
11145
- units: _units = null
11264
+ units = null
11146
11265
  }) {
11147
11266
  this.log("info", `KnishIOClient::createToken() - Creating token ${token}...`);
11267
+ const tokenMeta = meta || {};
11268
+ const fungibility = tokenMeta.fungibility;
11269
+ let resolvedAmount = amount ?? 0;
11270
+ if (fungibility === "stackable") {
11271
+ tokenMeta.batchId = batchId || generateBatchId({});
11272
+ }
11273
+ if ((fungibility === "stackable" || fungibility === "nonfungible" || fungibility === "non-fungible") && units && units.length > 0) {
11274
+ if (Number(tokenMeta.decimals ?? 0) > 0) {
11275
+ throw new StackableUnitDecimalsException_default();
11276
+ }
11277
+ if (Number(amount ?? 0) > 0) {
11278
+ throw new StackableUnitAmountException_default();
11279
+ }
11280
+ resolvedAmount = units.length;
11281
+ tokenMeta.splittable = "1";
11282
+ tokenMeta.decimals = "0";
11283
+ tokenMeta.tokenUnits = JSON.stringify(units);
11284
+ }
11148
11285
  const mutation = await this.createMoleculeMutation({ mutationClass: MutationCreateToken });
11149
11286
  const recipientWallet = new Wallet({
11150
11287
  secret: this.getSecret(),
@@ -11154,8 +11291,8 @@ var KnishIOClient = class {
11154
11291
  });
11155
11292
  await mutation.fillMolecule({
11156
11293
  recipientWallet,
11157
- amount: amount ?? 0,
11158
- meta
11294
+ amount: resolvedAmount,
11295
+ meta: tokenMeta
11159
11296
  });
11160
11297
  const response = await this.executeQuery(mutation);
11161
11298
  if (!response) {
@@ -11596,8 +11733,12 @@ var KnishIOClient = class {
11596
11733
  mutationClass: MutationRequestAuthorization,
11597
11734
  molecule
11598
11735
  });
11736
+ const authMeta = { encrypt: encrypt ? "true" : "false" };
11737
+ if (wallet.pubkey) {
11738
+ authMeta.walletPubkey = wallet.pubkey;
11739
+ }
11599
11740
  mutation.fillMolecule({
11600
- meta: { encrypt: encrypt ? "true" : "false" }
11741
+ meta: authMeta
11601
11742
  });
11602
11743
  const response = await this.executeQuery(mutation);
11603
11744
  if (!response) {