@wishknish/knishio-client-ts 0.7.0 → 0.7.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 (47) hide show
  1. package/dist/index.cjs +235 -194
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +1833 -0
  4. package/dist/index.d.ts +1833 -0
  5. package/dist/index.iife.js +238 -181
  6. package/dist/index.iife.js.map +1 -1
  7. package/dist/index.js +235 -194
  8. package/dist/index.js.map +1 -1
  9. package/package.json +5 -7
  10. package/src/KnishIOClient.ts +183 -231
  11. package/src/core/Atom.ts +1 -1
  12. package/src/core/Molecule.ts +0 -1
  13. package/src/core/Wallet.ts +71 -8
  14. package/src/libraries/CheckMolecule.ts +3 -3
  15. package/src/libraries/GraphQLClient.ts +61 -23
  16. package/src/libraries/array.ts +2 -2
  17. package/src/libraries/crypto.ts +28 -25
  18. package/src/libraries/strings.ts +3 -3
  19. package/src/mutation/MutationProposeMolecule.ts +2 -1
  20. package/src/query/Query.ts +2 -1
  21. package/src/query/QueryAtom.ts +4 -3
  22. package/src/query/QueryBalance.ts +2 -1
  23. package/src/query/QueryBatch.ts +4 -3
  24. package/src/query/QueryContinuId.ts +4 -3
  25. package/src/query/QueryMetaType.ts +4 -3
  26. package/src/query/QueryMetaTypeViaAtom.ts +4 -3
  27. package/src/query/QueryWalletBundle.ts +2 -1
  28. package/src/query/QueryWalletList.ts +4 -3
  29. package/src/response/EnhancedResponse.ts +19 -24
  30. package/src/response/Response.ts +3 -3
  31. package/src/response/ResponseAtom.ts +1 -1
  32. package/src/response/ResponseAuthorizationGuest.ts +1 -1
  33. package/src/response/ResponseBalance.ts +1 -1
  34. package/src/response/ResponseContinuId.ts +1 -1
  35. package/src/response/ResponseMetaType.ts +1 -1
  36. package/src/response/ResponseMetaTypeViaAtom.ts +1 -1
  37. package/src/response/ResponsePolicy.ts +1 -1
  38. package/src/response/ResponseProposeMolecule.ts +4 -5
  39. package/src/response/ResponseQueryActiveSession.ts +1 -1
  40. package/src/response/ResponseQueryUserActivity.ts +1 -1
  41. package/src/response/ResponseRequestAuthorizationGuest.ts +1 -1
  42. package/src/response/ResponseTransferTokens.ts +1 -1
  43. package/src/response/ResponseWalletBundle.ts +1 -1
  44. package/src/response/ResponseWalletList.ts +1 -1
  45. package/src/types/graphql.ts +8 -0
  46. package/src/types/index.ts +2 -7
  47. package/src/types/response.ts +12 -7
package/dist/index.js CHANGED
@@ -912,9 +912,19 @@ var init_DecryptionKeyException = __esm({
912
912
  });
913
913
 
914
914
  // src/exception/StackableUnitAmountException.ts
915
+ var StackableUnitAmountException, StackableUnitAmountException_default;
915
916
  var init_StackableUnitAmountException = __esm({
916
917
  "src/exception/StackableUnitAmountException.ts"() {
917
918
  init_BaseException();
919
+ StackableUnitAmountException = class extends BaseException {
920
+ /**
921
+ * Constructor using proper error type
922
+ */
923
+ constructor(message = "Stackable tokens with unit IDs cannot have an amount!") {
924
+ super("STACKABLE_UNIT_AMOUNT_ERROR", message);
925
+ }
926
+ };
927
+ StackableUnitAmountException_default = StackableUnitAmountException;
918
928
  }
919
929
  });
920
930
 
@@ -1486,7 +1496,7 @@ var init_EnhancedResponse = __esm({
1486
1496
  // Enhanced response validation
1487
1497
  validate() {
1488
1498
  try {
1489
- const validationResult = ValidationResultSchema.parse(this.toValidationResult());
1499
+ ValidationResultSchema.parse(this.toValidationResult());
1490
1500
  return {
1491
1501
  success: true,
1492
1502
  data: this._payload,
@@ -1507,14 +1517,14 @@ var init_EnhancedResponse = __esm({
1507
1517
  static createSuccessResponse(payload, operation, rawData, duration) {
1508
1518
  return StandardResponse.success(payload, rawData, {
1509
1519
  operation,
1510
- duration,
1520
+ ...duration !== void 0 ? { duration } : {},
1511
1521
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
1512
1522
  });
1513
1523
  }
1514
1524
  static createErrorResponse(errorMessage, operation, rawData, duration) {
1515
1525
  return StandardResponse.failure(errorMessage, rawData, {
1516
1526
  operation,
1517
- duration,
1527
+ ...duration !== void 0 ? { duration } : {},
1518
1528
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
1519
1529
  });
1520
1530
  }
@@ -1573,7 +1583,7 @@ var init_Response = __esm({
1573
1583
  if (Dot.has(this.$__response, this.errorKey)) {
1574
1584
  const error = Dot.get(this.$__response, this.errorKey);
1575
1585
  if (String(error).includes("Unauthenticated")) {
1576
- throw new UnauthenticatedException();
1586
+ throw new UnauthenticatedException("Unauthenticated request");
1577
1587
  }
1578
1588
  throw new InvalidResponseException();
1579
1589
  }
@@ -1841,7 +1851,7 @@ function isNumeric(str) {
1841
1851
  }
1842
1852
  function toCamelCase(str) {
1843
1853
  if (!str) return "";
1844
- return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (match, chr) => chr.toUpperCase());
1854
+ return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (_match, chr) => chr.toUpperCase());
1845
1855
  }
1846
1856
  function toSnakeCase(str) {
1847
1857
  if (!str) return "";
@@ -2088,13 +2098,14 @@ function normalizeMolecularHash(mappedHashArray) {
2088
2098
  const totalCondition = total < 0;
2089
2099
  while (total !== 0) {
2090
2100
  for (let index = 0; index < normalized.length; index++) {
2091
- const condition = totalCondition ? normalized[index] < 8 : normalized[index] > -8;
2101
+ const value = normalized[index];
2102
+ const condition = totalCondition ? value < 8 : value > -8;
2092
2103
  if (condition) {
2093
2104
  if (totalCondition) {
2094
- normalized[index]++;
2105
+ normalized[index] = value + 1;
2095
2106
  total++;
2096
2107
  } else {
2097
- normalized[index]--;
2108
+ normalized[index] = value - 1;
2098
2109
  total--;
2099
2110
  }
2100
2111
  if (total === 0) break;
@@ -2806,6 +2817,12 @@ var Wallet = class _Wallet {
2806
2817
  tokenUnits;
2807
2818
  tradeRates;
2808
2819
  molecules;
2820
+ // Token metadata (populated from query responses)
2821
+ tokenName;
2822
+ tokenAmount;
2823
+ tokenSupply;
2824
+ tokenFungibility;
2825
+ createdAt;
2809
2826
  constructor({
2810
2827
  secret = null,
2811
2828
  bundle = null,
@@ -2952,6 +2969,45 @@ var Wallet = class _Wallet {
2952
2969
  characters: this.characters
2953
2970
  });
2954
2971
  }
2972
+ /**
2973
+ * Sets up a batch ID - either using the sender's, or a new one
2974
+ * Matches JavaScript SDK Wallet.initBatchId exactly
2975
+ */
2976
+ initBatchId({
2977
+ sourceWallet,
2978
+ isRemainder = false
2979
+ }) {
2980
+ if (sourceWallet.batchId) {
2981
+ this.batchId = isRemainder ? sourceWallet.batchId : generateBatchId({});
2982
+ }
2983
+ }
2984
+ /**
2985
+ * Split token units between wallets
2986
+ * Matches JavaScript SDK Wallet.splitUnits exactly
2987
+ *
2988
+ * @param units - Array of token unit IDs to transfer
2989
+ * @param remainderWallet - Wallet to receive units not being transferred
2990
+ * @param recipientWallet - Wallet to receive the transferred units (optional)
2991
+ */
2992
+ splitUnits(units, remainderWallet, recipientWallet = null) {
2993
+ if (units.length === 0) {
2994
+ return;
2995
+ }
2996
+ const recipientTokenUnits = [];
2997
+ const remainderTokenUnits = [];
2998
+ this.tokenUnits.forEach((tokenUnit) => {
2999
+ if (units.includes(tokenUnit.id)) {
3000
+ recipientTokenUnits.push(tokenUnit);
3001
+ } else {
3002
+ remainderTokenUnits.push(tokenUnit);
3003
+ }
3004
+ });
3005
+ this.tokenUnits = recipientTokenUnits;
3006
+ if (recipientWallet !== null) {
3007
+ recipientWallet.tokenUnits = recipientTokenUnits;
3008
+ }
3009
+ remainderWallet.tokenUnits = remainderTokenUnits;
3010
+ }
2955
3011
  /**
2956
3012
  * Get token units data
2957
3013
  * Stub for compatibility
@@ -2974,7 +3030,7 @@ var Wallet = class _Wallet {
2974
3030
  * Initializes the ML-KEM key pair (matches JavaScript SDK exactly)
2975
3031
  */
2976
3032
  initializeMLKEM() {
2977
- const seedHex = generateSecret(this.key, 128);
3033
+ const seedHex = generateSecret(this.key, 64);
2978
3034
  const seed = new Uint8Array(64);
2979
3035
  for (let i = 0; i < 64; i++) {
2980
3036
  seed[i] = parseInt(seedHex.substr(i * 2, 2), 16);
@@ -3491,9 +3547,9 @@ var CheckMolecule = class {
3491
3547
  }
3492
3548
  const metas = Meta.aggregateMeta(atom.meta);
3493
3549
  for (const key of policyArray) {
3494
- let policy = metas[key];
3495
- if (policy) {
3496
- policy = JSON.parse(policy);
3550
+ const policyRaw = metas[key];
3551
+ if (policyRaw) {
3552
+ const policy = JSON.parse(policyRaw);
3497
3553
  for (const [policyName, policyValue] of Object.entries(policy)) {
3498
3554
  if (!policyArray.includes(policyName)) {
3499
3555
  if (!Object.keys(metas).includes(policyName)) {
@@ -4613,8 +4669,7 @@ var GraphQLClient = class {
4613
4669
  }
4614
4670
  createUrqlClient({
4615
4671
  serverUri,
4616
- socket,
4617
- encrypt
4672
+ socket
4618
4673
  }) {
4619
4674
  const exchanges = [cacheExchange, fetchExchange];
4620
4675
  if (socket?.socketUri) {
@@ -4666,13 +4721,36 @@ var GraphQLClient = class {
4666
4721
  const result = await this.$__client.query(request.query, finalVariables).toPromise();
4667
4722
  return this.formatResponse(result);
4668
4723
  }
4669
- async mutate(request, variables) {
4724
+ async mutation(request, variables) {
4670
4725
  const finalVariables = variables || request.variables || {};
4671
- const result = await this.$__client.mutation(request.mutation, finalVariables).toPromise();
4726
+ const mutationString = request.mutation || request.query;
4727
+ const result = await this.$__client.mutation(mutationString, finalVariables).toPromise();
4672
4728
  return this.formatResponse(result);
4673
4729
  }
4674
- async mutation(request, variables) {
4675
- return this.mutate(request, variables);
4730
+ // Alias for mutation() to match JS SDK interface
4731
+ async mutate(request, variables) {
4732
+ return this.mutation(request, variables);
4733
+ }
4734
+ async *subscription(request, variables) {
4735
+ const finalVariables = variables || request.variables || {};
4736
+ const subscription = this.$__client.subscription(request.query, finalVariables);
4737
+ const results = [];
4738
+ const { unsubscribe } = pipe(
4739
+ subscription,
4740
+ subscribe((result) => {
4741
+ results.push(this.formatResponse(result));
4742
+ })
4743
+ );
4744
+ try {
4745
+ while (true) {
4746
+ if (results.length > 0) {
4747
+ yield results.shift();
4748
+ }
4749
+ await new Promise((resolve) => setTimeout(resolve, 10));
4750
+ }
4751
+ } finally {
4752
+ unsubscribe();
4753
+ }
4676
4754
  }
4677
4755
  subscribe(request, callback) {
4678
4756
  const { query, variables, operationName = "subscription" } = request;
@@ -4701,7 +4779,7 @@ var GraphQLClient = class {
4701
4779
  }
4702
4780
  }
4703
4781
  unsubscribeAll() {
4704
- this.$__subscriptionManager.forEach((subscription, operationName) => {
4782
+ this.$__subscriptionManager.forEach((_subscription, operationName) => {
4705
4783
  this.unsubscribe(operationName);
4706
4784
  });
4707
4785
  }
@@ -5554,7 +5632,6 @@ var ValidationChainBuilder = class {
5554
5632
  };
5555
5633
  var validationService = ValidationService.getInstance();
5556
5634
  var validateClientConfig = (config) => validationService.validateClientConfig(config);
5557
- var validateTransferParams = (params) => validationService.validateTransferParams(params);
5558
5635
  var { typeGuards } = validationService;
5559
5636
 
5560
5637
  // src/validation/UNIVERSAL_CONFIGURATION_INTERFACES.ts
@@ -5903,15 +5980,13 @@ var ResponseBalance = class _ResponseBalance extends Response {
5903
5980
  return wallet;
5904
5981
  }
5905
5982
  };
5906
-
5907
- // src/query/QueryBalance.ts
5908
5983
  var QueryBalance = class extends Query {
5909
5984
  /**
5910
5985
  * Create QueryBalance instance
5911
5986
  */
5912
5987
  constructor(graphQLClient, knishIOClient) {
5913
5988
  super(graphQLClient, knishIOClient);
5914
- this.$__query = `
5989
+ this.$__query = gql`
5915
5990
  query($address: String, $bundleHash: String, $type: String, $token: String, $position: String) {
5916
5991
  Balance(address: $address, bundleHash: $bundleHash, type: $type, token: $token, position: $position) {
5917
5992
  address,
@@ -6123,8 +6198,6 @@ var ResponseWalletList = class _ResponseWalletList extends Response {
6123
6198
  return this.getWallets();
6124
6199
  }
6125
6200
  };
6126
-
6127
- // src/query/QueryWalletList.ts
6128
6201
  var QueryWalletList = class extends Query {
6129
6202
  /**
6130
6203
  * Create new QueryWalletList instance
@@ -6132,7 +6205,7 @@ var QueryWalletList = class extends Query {
6132
6205
  */
6133
6206
  constructor(graphQLClient, knishIOClient) {
6134
6207
  super(graphQLClient, knishIOClient);
6135
- this.$__query = `query( $bundleHash: String, $tokenSlug: String ) {
6208
+ this.$__query = gql`query( $bundleHash: String, $tokenSlug: String ) {
6136
6209
  Wallet( bundleHash: $bundleHash, tokenSlug: $tokenSlug ) {
6137
6210
  address,
6138
6211
  bundleHash,
@@ -6206,15 +6279,13 @@ var ResponseWalletBundle = class extends Response {
6206
6279
  return aggregate;
6207
6280
  }
6208
6281
  };
6209
-
6210
- // src/query/QueryWalletBundle.ts
6211
6282
  var QueryWalletBundle = class extends Query {
6212
6283
  /**
6213
6284
  * Create QueryWalletBundle instance
6214
6285
  */
6215
6286
  constructor(graphQLClient, knishIOClient) {
6216
6287
  super(graphQLClient, knishIOClient);
6217
- this.$__query = `
6288
+ this.$__query = gql`
6218
6289
  query($bundleHashes: [String!]) {
6219
6290
  WalletBundle(bundleHashes: $bundleHashes) {
6220
6291
  bundleHash,
@@ -6282,8 +6353,6 @@ var ResponseContinuId = class extends Response {
6282
6353
  return wallet;
6283
6354
  }
6284
6355
  };
6285
-
6286
- // src/query/QueryContinuId.ts
6287
6356
  var QueryContinuId = class extends Query {
6288
6357
  /**
6289
6358
  * Create new QueryContinuId instance
@@ -6291,7 +6360,7 @@ var QueryContinuId = class extends Query {
6291
6360
  */
6292
6361
  constructor(graphQLClient, knishIOClient) {
6293
6362
  super(graphQLClient, knishIOClient);
6294
- this.$__query = `query ($bundle: String!) {
6363
+ this.$__query = gql`query ($bundle: String!) {
6295
6364
  ContinuId(bundle: $bundle) {
6296
6365
  address,
6297
6366
  bundleHash,
@@ -6361,8 +6430,6 @@ var ResponseMetaType = class extends Response {
6361
6430
  return response;
6362
6431
  }
6363
6432
  };
6364
-
6365
- // src/query/QueryMetaType.ts
6366
6433
  var QueryMetaType = class extends Query {
6367
6434
  /**
6368
6435
  * Create new QueryMetaType instance
@@ -6370,7 +6437,7 @@ var QueryMetaType = class extends Query {
6370
6437
  */
6371
6438
  constructor(graphQLClient, knishIOClient) {
6372
6439
  super(graphQLClient, knishIOClient);
6373
- this.$__query = `query( $metaType: String, $metaTypes: [ String! ], $metaId: String, $metaIds: [ String! ], $key: String, $keys: [ String! ], $value: String, $values: [ String! ], $count: String, $latest: Boolean, $filter: [ MetaFilter! ], $queryArgs: QueryArgs, $countBy: String, $cellSlug: String ) {
6440
+ this.$__query = gql`query( $metaType: String, $metaTypes: [ String! ], $metaId: String, $metaIds: [ String! ], $key: String, $keys: [ String! ], $value: String, $values: [ String! ], $count: String, $latest: Boolean, $filter: [ MetaFilter! ], $queryArgs: QueryArgs, $countBy: String, $cellSlug: String ) {
6374
6441
  MetaType( metaType: $metaType, metaTypes: $metaTypes, metaId: $metaId, metaIds: $metaIds, key: $key, keys: $keys, value: $value, values: $values, count: $count, filter: $filter, queryArgs: $queryArgs, countBy: $countBy, cellSlug: $cellSlug ) {
6375
6442
  metaType,
6376
6443
  instanceCount {
@@ -6467,7 +6534,7 @@ var QueryBatch = class _QueryBatch extends Query {
6467
6534
  */
6468
6535
  constructor(graphQLClient, knishIOClient) {
6469
6536
  super(graphQLClient, knishIOClient);
6470
- this.$__query = `query( $batchId: String ) {
6537
+ this.$__query = gql`query( $batchId: String ) {
6471
6538
  Batch( batchId: $batchId ) {
6472
6539
  ${_QueryBatch.getFields()},
6473
6540
  children {
@@ -6640,8 +6707,6 @@ var ResponseAtom = class extends Response {
6640
6707
  return metas;
6641
6708
  }
6642
6709
  };
6643
-
6644
- // src/query/QueryAtom.ts
6645
6710
  var QueryAtom = class extends Query {
6646
6711
  /**
6647
6712
  * Create new QueryAtom instance
@@ -6649,7 +6714,7 @@ var QueryAtom = class extends Query {
6649
6714
  */
6650
6715
  constructor(graphQLClient, knishIOClient) {
6651
6716
  super(graphQLClient, knishIOClient);
6652
- this.$__query = `query(
6717
+ this.$__query = gql`query(
6653
6718
  $molecularHashes: [String!],
6654
6719
  $bundleHashes: [String!],
6655
6720
  $positions:[String!],
@@ -7155,8 +7220,6 @@ var ResponseMetaTypeViaAtom = class extends Response {
7155
7220
  return response;
7156
7221
  }
7157
7222
  };
7158
-
7159
- // src/query/QueryMetaTypeViaAtom.ts
7160
7223
  var QueryMetaTypeViaAtom = class extends Query {
7161
7224
  /**
7162
7225
  * Create new QueryMetaTypeViaAtom instance
@@ -7164,7 +7227,7 @@ var QueryMetaTypeViaAtom = class extends Query {
7164
7227
  */
7165
7228
  constructor(graphQLClient, knishIOClient) {
7166
7229
  super(graphQLClient, knishIOClient);
7167
- this.$__query = `query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
7230
+ this.$__query = gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
7168
7231
  MetaTypeViaAtom(
7169
7232
  metaTypes: $metaTypes
7170
7233
  metaIds: $metaIds
@@ -7276,7 +7339,6 @@ init_Response();
7276
7339
  init_Dot();
7277
7340
  var ResponseProposeMolecule = class extends Response {
7278
7341
  $__clientMolecule;
7279
- $__payload = null;
7280
7342
  /**
7281
7343
  * Class constructor
7282
7344
  */
@@ -7355,8 +7417,6 @@ var ResponseProposeMolecule = class extends Response {
7355
7417
  return this.$__payload;
7356
7418
  }
7357
7419
  };
7358
-
7359
- // src/mutation/MutationProposeMolecule.ts
7360
7420
  var MutationProposeMolecule = class extends Mutation {
7361
7421
  $__molecule;
7362
7422
  $__remainderWallet = null;
@@ -7367,7 +7427,7 @@ var MutationProposeMolecule = class extends Mutation {
7367
7427
  super(graphQLClient, knishIOClient);
7368
7428
  this.$__molecule = molecule;
7369
7429
  this.$__remainderWallet = null;
7370
- this.$__query = `
7430
+ this.$__query = gql`
7371
7431
  mutation($molecule: MoleculeInput!) {
7372
7432
  ProposeMolecule(molecule: $molecule) {
7373
7433
  molecularHash,
@@ -8353,6 +8413,9 @@ var KnishIOClient = class {
8353
8413
  * Get random uri from specified this.$__uris
8354
8414
  */
8355
8415
  getRandomUri() {
8416
+ if (this.$__uris.length === 0) {
8417
+ throw new Error("No URIs configured");
8418
+ }
8356
8419
  const rand = Math.floor(Math.random() * this.$__uris.length);
8357
8420
  return this.$__uris[rand];
8358
8421
  }
@@ -8513,8 +8576,8 @@ var KnishIOClient = class {
8513
8576
  molecule = null
8514
8577
  }) {
8515
8578
  this.log("info", `KnishIOClient::createMoleculeMutation() - Creating a new ${mutationClass.name} query...`);
8516
- molecule || await this.createMolecule({});
8517
- const mutation = new mutationClass(this.client(), this);
8579
+ const _molecule = molecule || await this.createMolecule({});
8580
+ const mutation = new mutationClass(this.client(), this, _molecule);
8518
8581
  if (!(mutation instanceof Mutation)) {
8519
8582
  throw new CodeException(`${this.constructor.name}::createMoleculeMutation() - This method only accepts Mutation subclasses!`);
8520
8583
  }
@@ -8563,68 +8626,74 @@ var KnishIOClient = class {
8563
8626
  }
8564
8627
  /**
8565
8628
  * Transfer tokens between wallets
8566
- * Enhanced with 2025 TypeScript validation patterns
8629
+ * Matches JavaScript SDK transferToken implementation exactly
8567
8630
  */
8568
- async transferToken(params) {
8569
- const transferParams = {
8570
- recipient: params.bundleHash,
8571
- amount: params.amount || 0,
8572
- token: params.token
8573
- };
8574
- const validationResult = validateTransferParams(transferParams);
8575
- if (!validationResult.success) {
8576
- return {
8577
- success: false,
8578
- error: {
8579
- code: "VALIDATION_ERROR",
8580
- message: "Invalid transfer parameters",
8581
- details: validationResult.error.details,
8582
- context: "transferToken"
8583
- }
8584
- };
8585
- }
8586
- validationResult.data;
8587
- let {
8588
- bundleHash,
8589
- token,
8590
- amount = null,
8591
- units = [],
8592
- batchId = null,
8593
- sourceWallet = null
8594
- } = params;
8631
+ async transferToken({
8632
+ bundleHash,
8633
+ token,
8634
+ amount = null,
8635
+ units = [],
8636
+ batchId = null,
8637
+ sourceWallet = null
8638
+ }) {
8595
8639
  if (units.length > 0) {
8596
- if (amount && amount > 0) {
8597
- throw new CodeException("Cannot specify both amount and units");
8640
+ if (amount !== null && amount > 0) {
8641
+ throw new StackableUnitAmountException_default();
8598
8642
  }
8599
8643
  amount = units.length;
8600
8644
  }
8601
- Wallet.create({
8602
- bundle: bundleHash,
8603
- token,
8604
- batchId
8605
- });
8606
- if (!sourceWallet) {
8607
- sourceWallet = await this.getSourceWallet();
8645
+ if (amount === null) {
8646
+ amount = 0;
8608
8647
  }
8609
- if (!sourceWallet.balance || sourceWallet.balance < (amount || 0)) {
8648
+ if (sourceWallet === null) {
8649
+ sourceWallet = await this.querySourceWallet({
8650
+ token,
8651
+ amount
8652
+ });
8653
+ }
8654
+ if (sourceWallet === null || Decimal.cmp(sourceWallet.balance, amount) < 0) {
8610
8655
  throw new TransferBalanceException();
8611
8656
  }
8657
+ const recipientWallet = Wallet.create({
8658
+ bundle: bundleHash,
8659
+ token
8660
+ });
8661
+ if (batchId !== null) {
8662
+ recipientWallet.batchId = batchId;
8663
+ } else {
8664
+ recipientWallet.initBatchId({
8665
+ sourceWallet
8666
+ });
8667
+ }
8612
8668
  const remainderWallet = sourceWallet.createRemainder(this.getSecret());
8613
- await this.createMolecule({
8669
+ sourceWallet.splitUnits(
8670
+ units,
8671
+ remainderWallet,
8672
+ recipientWallet
8673
+ );
8674
+ const molecule = await this.createMolecule({
8614
8675
  sourceWallet,
8615
8676
  remainderWallet
8616
8677
  });
8617
- return null;
8678
+ const query = await this.createMoleculeMutation({
8679
+ mutationClass: MutationTransferTokens,
8680
+ molecule
8681
+ });
8682
+ query.fillMolecule({
8683
+ recipientWallet,
8684
+ amount
8685
+ });
8686
+ return await this.executeQuery(query);
8618
8687
  }
8619
8688
  /**
8620
8689
  * Request authorization token
8621
8690
  */
8622
8691
  async requestAuthToken({
8623
- secret = null,
8624
- seed = null,
8625
- cellSlug = null,
8626
- encrypt = false
8627
- }) {
8692
+ secret: _secret = null,
8693
+ seed: _seed = null,
8694
+ cellSlug: _cellSlug = null,
8695
+ encrypt: _encrypt = false
8696
+ } = {}) {
8628
8697
  if (this.$__serverSdkVersion < 3) {
8629
8698
  this.log("warn", "KnishIOClient::authorize() - Server SDK version does not require an authorization...");
8630
8699
  return null;
@@ -8726,7 +8795,8 @@ var KnishIOClient = class {
8726
8795
  type
8727
8796
  });
8728
8797
  const sourceWallet = response.payload();
8729
- if (sourceWallet === null || Decimal.cmp(sourceWallet.balance || 0, amount) < 0) {
8798
+ const amountNum = typeof amount === "string" ? Number(amount) : amount;
8799
+ if (sourceWallet === null || Decimal.cmp(sourceWallet.balance || 0, amountNum) < 0) {
8730
8800
  throw new TransferBalanceException();
8731
8801
  }
8732
8802
  if (!sourceWallet.position || !sourceWallet.address) {
@@ -8756,7 +8826,7 @@ var KnishIOClient = class {
8756
8826
  */
8757
8827
  async queryBundle({
8758
8828
  bundle = null,
8759
- fields = null,
8829
+ fields: _fields = null,
8760
8830
  raw = false
8761
8831
  } = {}) {
8762
8832
  this.log("info", `KnishIOClient::queryBundle() - Querying wallet bundle metadata${bundle ? ` for ${bundle}` : ""}...`);
@@ -8790,7 +8860,7 @@ var KnishIOClient = class {
8790
8860
  key = null,
8791
8861
  value = null,
8792
8862
  latest = null,
8793
- fields = null,
8863
+ fields: _fields = null,
8794
8864
  filter = null,
8795
8865
  queryArgs = null,
8796
8866
  count = null,
@@ -9096,21 +9166,22 @@ var KnishIOClient = class {
9096
9166
  amount = null,
9097
9167
  meta = null,
9098
9168
  batchId = null,
9099
- units = null
9169
+ units: _units = null
9100
9170
  }) {
9101
9171
  this.log("info", `KnishIOClient::createToken() - Creating token ${token}...`);
9102
- const mutation = this.createQuery(MutationCreateToken);
9103
- const sourceWallet = await this.getSourceWallet();
9104
- await mutation.fillMolecule({
9105
- sourceWallet,
9172
+ const mutation = await this.createMoleculeMutation({ mutationClass: MutationCreateToken });
9173
+ const recipientWallet = new Wallet({
9174
+ secret: this.getSecret(),
9175
+ bundle: this.getBundle(),
9106
9176
  token: token.toUpperCase(),
9107
- amount,
9108
- meta,
9109
- batchId,
9110
- units
9177
+ batchId
9178
+ });
9179
+ await mutation.fillMolecule({
9180
+ recipientWallet,
9181
+ amount: amount ?? 0,
9182
+ meta
9111
9183
  });
9112
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9113
- const response = await this.executeQuery(moleculeMutation);
9184
+ const response = await this.executeQuery(mutation);
9114
9185
  if (!response) {
9115
9186
  throw new CodeException("Token creation failed");
9116
9187
  }
@@ -9123,24 +9194,21 @@ var KnishIOClient = class {
9123
9194
  token,
9124
9195
  to = null,
9125
9196
  amount = null,
9126
- units = null,
9197
+ units: _units = null,
9127
9198
  meta = null,
9128
9199
  batchId = null
9129
9200
  }) {
9130
9201
  this.log("info", `KnishIOClient::requestTokens() - Requesting ${amount || "units"} of ${token}...`);
9131
- const mutation = this.createQuery(MutationRequestTokens);
9132
- const sourceWallet = await this.getSourceWallet();
9202
+ const mutation = await this.createMoleculeMutation({ mutationClass: MutationRequestTokens });
9133
9203
  await mutation.fillMolecule({
9134
- sourceWallet,
9135
9204
  token: token.toUpperCase(),
9136
- to,
9137
- amount,
9138
- units,
9205
+ amount: amount ?? 0,
9206
+ metaType: to || "",
9207
+ metaId: to || "",
9139
9208
  meta,
9140
9209
  batchId
9141
9210
  });
9142
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9143
- const response = await this.executeQuery(moleculeMutation);
9211
+ const response = await this.executeQuery(mutation);
9144
9212
  if (!response) {
9145
9213
  throw new CodeException("Token request failed");
9146
9214
  }
@@ -9152,7 +9220,7 @@ var KnishIOClient = class {
9152
9220
  async burnTokens({
9153
9221
  token,
9154
9222
  amount = null,
9155
- units = null,
9223
+ units: _units = null,
9156
9224
  sourceWallet = null
9157
9225
  }) {
9158
9226
  this.log("info", `KnishIOClient::burnTokens() - Burning ${amount || "units"} of ${token}...`);
@@ -9162,17 +9230,17 @@ var KnishIOClient = class {
9162
9230
  amount: amount || 0
9163
9231
  });
9164
9232
  }
9165
- const mutation = this.createQuery(MutationTransferTokens);
9233
+ const mutation = await this.createMoleculeMutation({ mutationClass: MutationTransferTokens });
9234
+ const recipientWallet = new Wallet({
9235
+ secret: this.getSecret(),
9236
+ bundle: "0000000000000000000000000000000000000000000000000000000000000000",
9237
+ token: token.toUpperCase()
9238
+ });
9166
9239
  await mutation.fillMolecule({
9167
- sourceWallet,
9168
- recipient: "0000000000000000000000000000000000000000000000000000000000000000",
9169
- // Burn address
9170
- token: token.toUpperCase(),
9171
- amount,
9172
- units
9240
+ recipientWallet,
9241
+ amount: amount ?? 0
9173
9242
  });
9174
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9175
- const response = await this.executeQuery(moleculeMutation);
9243
+ const response = await this.executeQuery(mutation);
9176
9244
  if (!response) {
9177
9245
  throw new CodeException("Token burn failed");
9178
9246
  }
@@ -9185,7 +9253,7 @@ var KnishIOClient = class {
9185
9253
  token,
9186
9254
  amount = null,
9187
9255
  units = null,
9188
- sourceWallet = null
9256
+ sourceWallet: _sourceWallet = null
9189
9257
  }) {
9190
9258
  this.log("info", `KnishIOClient::replenishToken() - Replenishing ${amount || "units"} of ${token}...`);
9191
9259
  return this.requestTokens({
@@ -9198,11 +9266,11 @@ var KnishIOClient = class {
9198
9266
  * Fuse token units
9199
9267
  */
9200
9268
  async fuseToken({
9201
- bundleHash,
9269
+ bundleHash: _bundleHash,
9202
9270
  tokenSlug,
9203
- newTokenUnit,
9204
- fusedTokenUnitIds,
9205
- sourceWallet = null
9271
+ newTokenUnit: _newTokenUnit,
9272
+ fusedTokenUnitIds: _fusedTokenUnitIds,
9273
+ sourceWallet: _sourceWallet = null
9206
9274
  }) {
9207
9275
  this.log("info", `KnishIOClient::fuseToken() - Fusing token units for ${tokenSlug}...`);
9208
9276
  throw new CodeException("Token fusion not yet implemented");
@@ -9217,14 +9285,14 @@ var KnishIOClient = class {
9217
9285
  token
9218
9286
  }) {
9219
9287
  this.log("info", `KnishIOClient::createWallet() - Creating wallet for token ${token}...`);
9220
- const mutation = this.createQuery(MutationCreateWallet);
9221
- const sourceWallet = await this.getSourceWallet();
9222
- await mutation.fillMolecule({
9223
- sourceWallet,
9288
+ const mutation = await this.createMoleculeMutation({ mutationClass: MutationCreateWallet });
9289
+ const newWallet = new Wallet({
9290
+ secret: this.getSecret(),
9291
+ bundle: this.getBundle(),
9224
9292
  token: token.toUpperCase()
9225
9293
  });
9226
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9227
- const response = await this.executeQuery(moleculeMutation);
9294
+ await mutation.fillMolecule(newWallet);
9295
+ const response = await this.executeQuery(mutation);
9228
9296
  if (!response) {
9229
9297
  throw new CodeException("Wallet creation failed");
9230
9298
  }
@@ -9236,7 +9304,7 @@ var KnishIOClient = class {
9236
9304
  async claimShadowWallet({
9237
9305
  token,
9238
9306
  batchId = null,
9239
- molecule = null
9307
+ molecule: _molecule = null
9240
9308
  }) {
9241
9309
  this.log("info", `KnishIOClient::claimShadowWallet() - Claiming shadow wallet for token ${token}...`);
9242
9310
  const shadowWallets = await this.queryWallets({ token });
@@ -9250,15 +9318,12 @@ var KnishIOClient = class {
9250
9318
  if (!shadowWallet.isShadow()) {
9251
9319
  throw new WalletShadowException_default("Wallet is not a shadow wallet");
9252
9320
  }
9253
- const mutation = this.createQuery(MutationClaimShadowWallet);
9254
- const sourceWallet = await this.getSourceWallet();
9321
+ const mutation = await this.createMoleculeMutation({ mutationClass: MutationClaimShadowWallet });
9255
9322
  await mutation.fillMolecule({
9256
- sourceWallet,
9257
9323
  token: token.toUpperCase(),
9258
9324
  batchId: shadowWallet.batchId
9259
9325
  });
9260
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9261
- const response = await this.executeQuery(moleculeMutation);
9326
+ const response = await this.executeQuery(mutation);
9262
9327
  if (!response) {
9263
9328
  throw new CodeException("Shadow wallet claim failed");
9264
9329
  }
@@ -9303,17 +9368,14 @@ var KnishIOClient = class {
9303
9368
  policy = null
9304
9369
  }) {
9305
9370
  this.log("info", `KnishIOClient::createMeta() - Creating metadata for ${metaType}:${metaId}...`);
9306
- const mutation = this.createQuery(MutationCreateMeta);
9307
- const sourceWallet = await this.getSourceWallet();
9371
+ const mutation = await this.createMoleculeMutation({ mutationClass: MutationCreateMeta });
9308
9372
  await mutation.fillMolecule({
9309
- sourceWallet,
9310
9373
  metaType: metaType.toUpperCase(),
9311
9374
  metaId,
9312
9375
  meta,
9313
9376
  policy
9314
9377
  });
9315
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9316
- const response = await this.executeQuery(moleculeMutation);
9378
+ const response = await this.executeQuery(mutation);
9317
9379
  if (!response) {
9318
9380
  throw new CodeException("Metadata creation failed");
9319
9381
  }
@@ -9329,17 +9391,14 @@ var KnishIOClient = class {
9329
9391
  policy = null
9330
9392
  }) {
9331
9393
  this.log("info", `KnishIOClient::createRule() - Creating rule for ${metaType}:${metaId}...`);
9332
- const mutation = this.createQuery(MutationCreateRule);
9333
- const sourceWallet = await this.getSourceWallet();
9394
+ const mutation = await this.createMoleculeMutation({ mutationClass: MutationCreateRule });
9334
9395
  await mutation.fillMolecule({
9335
- sourceWallet,
9336
9396
  metaType: metaType.toUpperCase(),
9337
9397
  metaId,
9338
9398
  rule,
9339
9399
  policy
9340
9400
  });
9341
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9342
- const response = await this.executeQuery(moleculeMutation);
9401
+ const response = await this.executeQuery(mutation);
9343
9402
  if (!response) {
9344
9403
  throw new CodeException("Rule creation failed");
9345
9404
  }
@@ -9370,16 +9429,13 @@ var KnishIOClient = class {
9370
9429
  code
9371
9430
  }) {
9372
9431
  this.log("info", `KnishIOClient::createIdentifier() - Creating identifier of type ${type}...`);
9373
- const mutation = this.createQuery(MutationCreateIdentifier);
9374
- const sourceWallet = await this.getSourceWallet();
9432
+ const mutation = await this.createMoleculeMutation({ mutationClass: MutationCreateIdentifier });
9375
9433
  await mutation.fillMolecule({
9376
- sourceWallet,
9377
9434
  type,
9378
9435
  contact,
9379
9436
  code
9380
9437
  });
9381
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9382
- const response = await this.executeQuery(moleculeMutation);
9438
+ const response = await this.executeQuery(mutation);
9383
9439
  if (!response) {
9384
9440
  throw new CodeException("Identifier creation failed");
9385
9441
  }
@@ -9394,14 +9450,11 @@ var KnishIOClient = class {
9394
9450
  }) {
9395
9451
  this.log("info", `KnishIOClient::linkIdentifier() - Linking identifier of type ${type}...`);
9396
9452
  const mutation = this.createQuery(MutationLinkIdentifier);
9397
- const sourceWallet = await this.getSourceWallet();
9398
- await mutation.fillMolecule({
9399
- sourceWallet,
9453
+ const response = await this.executeQuery(mutation, {
9454
+ bundle: this.getBundle(),
9400
9455
  type,
9401
- contact
9456
+ content: contact
9402
9457
  });
9403
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9404
- const response = await this.executeQuery(moleculeMutation);
9405
9458
  if (!response) {
9406
9459
  throw new CodeException("Identifier linking failed");
9407
9460
  }
@@ -9426,10 +9479,8 @@ var KnishIOClient = class {
9426
9479
  }) {
9427
9480
  this.log("info", `KnishIOClient::activeSession() - Declaring active session for ${metaType}:${metaId}...`);
9428
9481
  const mutation = this.createQuery(MutationActiveSession);
9429
- const sourceWallet = await this.getSourceWallet();
9430
- await mutation.fillMolecule({
9431
- sourceWallet,
9432
- bundle,
9482
+ const response = await this.executeQuery(mutation, {
9483
+ bundle: bundle || this.getBundle(),
9433
9484
  metaType: metaType.toUpperCase(),
9434
9485
  metaId,
9435
9486
  ipAddress,
@@ -9439,8 +9490,6 @@ var KnishIOClient = class {
9439
9490
  timeZone,
9440
9491
  json
9441
9492
  });
9442
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9443
- const response = await this.executeQuery(moleculeMutation);
9444
9493
  if (!response) {
9445
9494
  throw new CodeException("Active session declaration failed");
9446
9495
  }
@@ -9462,15 +9511,12 @@ var KnishIOClient = class {
9462
9511
  amount
9463
9512
  });
9464
9513
  }
9465
- const mutation = this.createQuery(MutationDepositBufferToken);
9514
+ const mutation = await this.createMoleculeMutation({ mutationClass: MutationDepositBufferToken });
9466
9515
  await mutation.fillMolecule({
9467
- sourceWallet,
9468
- tokenSlug: tokenSlug.toUpperCase(),
9469
- amount,
9516
+ amount: typeof amount === "string" ? Number(amount) : amount,
9470
9517
  tradeRates
9471
9518
  });
9472
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9473
- const response = await this.executeQuery(moleculeMutation);
9519
+ const response = await this.executeQuery(mutation);
9474
9520
  if (!response) {
9475
9521
  throw new CodeException("Buffer token deposit failed");
9476
9522
  }
@@ -9489,15 +9535,15 @@ var KnishIOClient = class {
9489
9535
  if (!sourceWallet) {
9490
9536
  sourceWallet = await this.getSourceWallet();
9491
9537
  }
9492
- const mutation = this.createQuery(MutationWithdrawBufferToken);
9493
- await mutation.fillMolecule({
9494
- sourceWallet,
9495
- tokenSlug: tokenSlug.toUpperCase(),
9496
- amount,
9497
- signingWallet
9498
- });
9499
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9500
- const response = await this.executeQuery(moleculeMutation);
9538
+ const mutation = await this.createMoleculeMutation({ mutationClass: MutationWithdrawBufferToken });
9539
+ const recipients = {};
9540
+ recipients[this.getBundle()] = amount;
9541
+ const fillMoleculeParams = { recipients };
9542
+ if (signingWallet) {
9543
+ fillMoleculeParams.signingWallet = signingWallet;
9544
+ }
9545
+ await mutation.fillMolecule(fillMoleculeParams);
9546
+ const response = await this.executeQuery(mutation);
9501
9547
  if (!response) {
9502
9548
  throw new CodeException("Buffer token withdrawal failed");
9503
9549
  }
@@ -9515,11 +9561,9 @@ var KnishIOClient = class {
9515
9561
  } = {}) {
9516
9562
  this.log("info", "KnishIOClient::requestGuestAuthToken() - Requesting guest auth token...");
9517
9563
  const mutation = this.createQuery(MutationRequestAuthorizationGuest);
9518
- await mutation.fillMolecule({
9564
+ const response = await this.executeQuery(mutation, {
9519
9565
  cellSlug: cellSlug || this.getCellSlug()
9520
9566
  });
9521
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9522
- const response = await this.executeQuery(moleculeMutation);
9523
9567
  if (!response) {
9524
9568
  throw new CodeException("Guest auth token request failed");
9525
9569
  }
@@ -9537,14 +9581,11 @@ var KnishIOClient = class {
9537
9581
  }) {
9538
9582
  this.log("info", "KnishIOClient::requestProfileAuthToken() - Requesting profile auth token...");
9539
9583
  this.setSecret(secret);
9540
- const mutation = this.createQuery(MutationRequestAuthorization);
9541
- const sourceWallet = await this.getSourceWallet();
9584
+ const mutation = await this.createMoleculeMutation({ mutationClass: MutationRequestAuthorization });
9542
9585
  await mutation.fillMolecule({
9543
- sourceWallet,
9544
- cellSlug: this.getCellSlug()
9586
+ meta: { encrypt: encrypt ? "true" : "false" }
9545
9587
  });
9546
- const moleculeMutation = await this.createMoleculeMutation({ mutationClass: mutation });
9547
- const response = await this.executeQuery(moleculeMutation);
9588
+ const response = await this.executeQuery(mutation);
9548
9589
  if (!response) {
9549
9590
  throw new CodeException("Profile auth token request failed");
9550
9591
  }