@wishknish/knishio-client-ts 0.7.0

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 (141) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +425 -0
  3. package/dist/index.cjs +9961 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.iife.js +32241 -0
  6. package/dist/index.iife.js.map +1 -0
  7. package/dist/index.js +9853 -0
  8. package/dist/index.js.map +1 -0
  9. package/package.json +113 -0
  10. package/src/AuthToken.ts +214 -0
  11. package/src/KnishIOClient.ts +2020 -0
  12. package/src/constants.ts +398 -0
  13. package/src/core/Atom.ts +646 -0
  14. package/src/core/AtomMeta.ts +278 -0
  15. package/src/core/Meta.ts +428 -0
  16. package/src/core/Molecule.ts +825 -0
  17. package/src/core/PolicyMeta.ts +130 -0
  18. package/src/core/TokenUnit.ts +148 -0
  19. package/src/core/Wallet.ts +467 -0
  20. package/src/exception/AtomIndexException.ts +97 -0
  21. package/src/exception/AtomsMissingException.ts +109 -0
  22. package/src/exception/AuthorizationRejectedException.ts +63 -0
  23. package/src/exception/BalanceInsufficientException.ts +58 -0
  24. package/src/exception/BaseException.ts +275 -0
  25. package/src/exception/BatchIdException.ts +58 -0
  26. package/src/exception/CodeException.ts +119 -0
  27. package/src/exception/DecryptionKeyException.ts +65 -0
  28. package/src/exception/InvalidResponseException.ts +112 -0
  29. package/src/exception/MetaMissingException.ts +58 -0
  30. package/src/exception/MolecularHashMismatchException.ts +115 -0
  31. package/src/exception/MolecularHashMissingException.ts +58 -0
  32. package/src/exception/NegativeAmountException.ts +58 -0
  33. package/src/exception/PolicyInvalidException.ts +58 -0
  34. package/src/exception/SignatureMalformedException.ts +58 -0
  35. package/src/exception/SignatureMismatchException.ts +98 -0
  36. package/src/exception/StackableUnitAmountException.ts +65 -0
  37. package/src/exception/StackableUnitDecimalsException.ts +65 -0
  38. package/src/exception/TransferBalanceException.ts +98 -0
  39. package/src/exception/TransferMalformedException.ts +58 -0
  40. package/src/exception/TransferMismatchedException.ts +58 -0
  41. package/src/exception/TransferRemainderException.ts +58 -0
  42. package/src/exception/TransferToSelfException.ts +58 -0
  43. package/src/exception/TransferUnbalancedException.ts +58 -0
  44. package/src/exception/UnauthenticatedException.ts +147 -0
  45. package/src/exception/WalletCredentialException.ts +108 -0
  46. package/src/exception/WalletShadowException.ts +65 -0
  47. package/src/exception/WrongTokenTypeException.ts +58 -0
  48. package/src/exception/index.ts +272 -0
  49. package/src/index.ts +512 -0
  50. package/src/instance/rules/Callback.ts +257 -0
  51. package/src/instance/rules/Condition.ts +96 -0
  52. package/src/instance/rules/Meta.ts +163 -0
  53. package/src/instance/rules/Rule.ts +29 -0
  54. package/src/instance/rules/exception/RuleArgumentException.ts +65 -0
  55. package/src/libraries/CheckMolecule.ts +581 -0
  56. package/src/libraries/Decimal.ts +94 -0
  57. package/src/libraries/Dot.ts +202 -0
  58. package/src/libraries/GraphQLClient.ts +276 -0
  59. package/src/libraries/Hex.ts +155 -0
  60. package/src/libraries/UrqlClientWrapper.ts +336 -0
  61. package/src/libraries/array.ts +91 -0
  62. package/src/libraries/crypto.ts +816 -0
  63. package/src/libraries/strings.ts +458 -0
  64. package/src/mutation/Mutation.ts +103 -0
  65. package/src/mutation/MutationActiveSession.ts +108 -0
  66. package/src/mutation/MutationClaimShadowWallet.ts +91 -0
  67. package/src/mutation/MutationCreateIdentifier.ts +86 -0
  68. package/src/mutation/MutationCreateMeta.ts +92 -0
  69. package/src/mutation/MutationCreateRule.ts +90 -0
  70. package/src/mutation/MutationCreateToken.ts +92 -0
  71. package/src/mutation/MutationCreateWallet.ts +78 -0
  72. package/src/mutation/MutationDepositBufferToken.ts +72 -0
  73. package/src/mutation/MutationLinkIdentifier.ts +87 -0
  74. package/src/mutation/MutationProposeMolecule.ts +147 -0
  75. package/src/mutation/MutationRequestAuthorization.ts +77 -0
  76. package/src/mutation/MutationRequestAuthorizationGuest.ts +85 -0
  77. package/src/mutation/MutationRequestTokens.ts +98 -0
  78. package/src/mutation/MutationTransferTokens.ts +87 -0
  79. package/src/mutation/MutationWithdrawBufferToken.ts +73 -0
  80. package/src/query/Query.ts +187 -0
  81. package/src/query/QueryActiveSession.ts +89 -0
  82. package/src/query/QueryAtom.ts +275 -0
  83. package/src/query/QueryBalance.ts +102 -0
  84. package/src/query/QueryBatch.ts +145 -0
  85. package/src/query/QueryBatchHistory.ts +86 -0
  86. package/src/query/QueryContinuId.ts +91 -0
  87. package/src/query/QueryMetaType.ts +177 -0
  88. package/src/query/QueryMetaTypeViaAtom.ts +199 -0
  89. package/src/query/QueryPolicy.ts +91 -0
  90. package/src/query/QueryToken.ts +90 -0
  91. package/src/query/QueryUserActivity.ts +153 -0
  92. package/src/query/QueryWalletBundle.ts +92 -0
  93. package/src/query/QueryWalletList.ts +106 -0
  94. package/src/response/EnhancedResponse.ts +345 -0
  95. package/src/response/Response.ts +254 -0
  96. package/src/response/ResponseActiveSession.ts +72 -0
  97. package/src/response/ResponseAtom.ts +132 -0
  98. package/src/response/ResponseAuthorizationGuest.ts +119 -0
  99. package/src/response/ResponseBalance.ts +153 -0
  100. package/src/response/ResponseClaimShadowWallet.ts +56 -0
  101. package/src/response/ResponseContinuId.ts +101 -0
  102. package/src/response/ResponseCreateIdentifier.ts +56 -0
  103. package/src/response/ResponseCreateMeta.ts +58 -0
  104. package/src/response/ResponseCreateRule.ts +56 -0
  105. package/src/response/ResponseCreateToken.ts +58 -0
  106. package/src/response/ResponseCreateWallet.ts +58 -0
  107. package/src/response/ResponseLinkIdentifier.ts +87 -0
  108. package/src/response/ResponseMetaBatch.ts +72 -0
  109. package/src/response/ResponseMetaType.ts +108 -0
  110. package/src/response/ResponseMetaTypeViaAtom.ts +108 -0
  111. package/src/response/ResponsePolicy.ts +90 -0
  112. package/src/response/ResponseProposeMolecule.ts +155 -0
  113. package/src/response/ResponseQueryActiveSession.ts +105 -0
  114. package/src/response/ResponseQueryUserActivity.ts +89 -0
  115. package/src/response/ResponseRequestAuthorization.ts +100 -0
  116. package/src/response/ResponseRequestAuthorizationGuest.ts +133 -0
  117. package/src/response/ResponseRequestTokens.ts +58 -0
  118. package/src/response/ResponseTransferTokens.ts +72 -0
  119. package/src/response/ResponseWalletBundle.ts +95 -0
  120. package/src/response/ResponseWalletList.ts +165 -0
  121. package/src/schemas/index.ts +457 -0
  122. package/src/subscribe/ActiveSessionSubscribe.ts +72 -0
  123. package/src/subscribe/ActiveWalletSubscribe.ts +99 -0
  124. package/src/subscribe/CreateMoleculeSubscribe.ts +106 -0
  125. package/src/subscribe/Subscribe.ts +182 -0
  126. package/src/subscribe/WalletStatusSubscribe.ts +70 -0
  127. package/src/subscribe/index.ts +59 -0
  128. package/src/types/assertions.ts +722 -0
  129. package/src/types/client.ts +567 -0
  130. package/src/types/crypto.ts +541 -0
  131. package/src/types/graphql.ts +630 -0
  132. package/src/types/guards.ts +659 -0
  133. package/src/types/index.ts +614 -0
  134. package/src/types/response.ts +133 -0
  135. package/src/types/template-literals.ts +382 -0
  136. package/src/validation/UNIVERSAL_CONFIGURATION_INTERFACES.ts +580 -0
  137. package/src/validation/ValidationService.ts +607 -0
  138. package/src/validation/schemas.ts +447 -0
  139. package/src/versions/HashAtom.ts +170 -0
  140. package/src/versions/Version4.ts +120 -0
  141. package/src/versions/index.ts +80 -0
package/README.md ADDED
@@ -0,0 +1,425 @@
1
+ <div style="text-align:center">
2
+ <img src="https://raw.githubusercontent.com/WishKnish/KnishIO-Technical-Whitepaper/master/KnishIO-Logo.png" alt="Knish.IO: Post-Blockchain Platform" />
3
+ </div>
4
+ <div style="text-align:center">info@wishknish.com | https://wishknish.com</div>
5
+
6
+ # Knish.IO TypeScript Client SDK
7
+
8
+ This is the official TypeScript implementation of the Knish.IO client SDK. Its purpose is to expose class libraries for building and signing Knish.IO Molecules, composing Atoms, generating Wallets, and much more with enhanced type safety and modern TypeScript features.
9
+
10
+ ## Installation
11
+
12
+ The SDK can be installed via either of the following:
13
+
14
+ 1. `yarn add @wishknish/knishio-client-ts`
15
+
16
+ 2. `npm install @wishknish/knishio-client-ts --save`
17
+
18
+ **Requirements:**
19
+ - Node.js 18 or higher
20
+ - TypeScript 5.6 or higher (for development)
21
+
22
+ ## Basic Usage
23
+
24
+ The purpose of the Knish.IO SDK is to expose various ledger functions to new or existing applications.
25
+
26
+ There are two ways to take advantage of these functions:
27
+
28
+ 1. The easy way: use the `KnishIOClient` wrapper class
29
+
30
+ 2. The granular way: build `Atom` and `Molecule` instances and broadcast GraphQL messages yourself
31
+
32
+ This document will explain both ways.
33
+
34
+ ## The Easy Way: KnishIOClient Wrapper
35
+
36
+ 1. Include the wrapper class in your application code:
37
+ ```typescript
38
+ import { KnishIOClient } from '@wishknish/knishio-client-ts'
39
+ ```
40
+
41
+ 2. Instantiate the class with your node URI:
42
+ ```typescript
43
+ const client = new KnishIOClient({
44
+ uri: myNodeURI,
45
+ cellSlug: myCellSlug,
46
+ serverSdkVersion: 3, // Optional, defaults to 3
47
+ logging: false // Optional, enables logging
48
+ });
49
+ ```
50
+
51
+ 3. Request authorization token from the node:
52
+ ```typescript
53
+ await client.requestAuthToken({
54
+ seed: 'myTopSecretCode',
55
+ encrypt: true // Optional, enables encryption
56
+ });
57
+ ```
58
+
59
+ (**Note:** The `seed` parameter can be a salted combination of username + password, a biometric hash, an existing user identifier from an external authentication process, for example)
60
+
61
+ 4. Begin using `client` to trigger commands described below...
62
+
63
+ ### KnishIOClient Methods
64
+
65
+ - Query metadata for a **Wallet Bundle**. Omit the `bundle` parameter to query your own Wallet Bundle:
66
+ ```typescript
67
+ const result = await client.queryBundle({
68
+ bundle: 'c47e20f99df190e418f0cc5ddfa2791e9ccc4eb297cfa21bd317dc0f98313b1d',
69
+ });
70
+
71
+ console.log(result); // Raw Metadata
72
+ ```
73
+
74
+ - Query metadata for a **Meta Asset**:
75
+
76
+ ```typescript
77
+ const result = await client.queryMeta({
78
+ metaType: 'Vehicle',
79
+ metaId: null, // Meta ID
80
+ key: 'LicensePlate',
81
+ value: '1H17P',
82
+ latest: true, // Limit meta values to latest per key
83
+ throughAtom: true // Optional, query through Atom (default: true)
84
+ });
85
+
86
+ console.log(result); // Raw Metadata
87
+ ```
88
+
89
+ - Writing new metadata for a **Meta Asset**:
90
+
91
+ ```typescript
92
+ const result = await client.createMeta({
93
+ metaType: 'Pokemon',
94
+ metaId: 'Charizard',
95
+ meta: {
96
+ type: 'fire',
97
+ weaknesses: [
98
+ 'rock',
99
+ 'water',
100
+ 'electric'
101
+ ],
102
+ immunities: [
103
+ 'ground',
104
+ ],
105
+ hp: 78,
106
+ attack: 84,
107
+ },
108
+ policy: {} // Optional policy object
109
+ });
110
+
111
+ if (result.success()) {
112
+ // Do things!
113
+ }
114
+
115
+ console.log(result.data()); // Raw response
116
+ ```
117
+
118
+ - Query Wallets associated with a Wallet Bundle:
119
+
120
+ ```typescript
121
+ const result = await client.queryWallets({
122
+ bundle: 'c47e20f99df190e418f0cc5ddfa2791e9ccc4eb297cfa21bd317dc0f98313b1d',
123
+ token: 'FOO', // Optional, filter by token
124
+ unspent: true // Optional, limit results to unspent wallets
125
+ });
126
+
127
+ console.log(result); // Raw response
128
+ ```
129
+
130
+ - Declaring new **Wallets**:
131
+
132
+ (**Note:** If Tokens are sent to undeclared Wallets, **Shadow Wallets** will be used (placeholder
133
+ Wallets that can receive, but cannot send) to store tokens until they are claimed.)
134
+
135
+ ```typescript
136
+ const result = await client.createWallet({
137
+ token: 'FOO' // Token Slug for the wallet we are declaring
138
+ });
139
+
140
+ if (result.success()) {
141
+ // Do things!
142
+ }
143
+
144
+ console.log(result.data()); // Raw response
145
+ ```
146
+
147
+ - Issuing new **Tokens**:
148
+
149
+ ```typescript
150
+ const result = await client.createToken({
151
+ token: 'CRZY', // Token slug (ticker symbol)
152
+ amount: '100000000', // Initial amount to issue
153
+ meta: {
154
+ name: 'CrazyCoin', // Public name for the token
155
+ fungibility: 'fungible', // Fungibility style (fungible / nonfungible / stackable)
156
+ supply: 'limited', // Supply style (limited / replenishable)
157
+ decimals: '2' // Decimal places
158
+ },
159
+ units: [], // Optional, for stackable tokens
160
+ batchId: null // Optional, for stackable tokens
161
+ });
162
+
163
+ if (result.success()) {
164
+ // Do things!
165
+ }
166
+
167
+ console.log(result.data()); // Raw response
168
+ ```
169
+
170
+ - Transferring **Tokens** to other users:
171
+
172
+ ```typescript
173
+ const result = await client.transferToken({
174
+ bundleHash: '7bf38257401eb3b0f20cabf5e6cf3f14c76760386473b220d95fa1c38642b61d', // Recipient's bundle hash
175
+ token: 'CRZY', // Token slug
176
+ amount: '100',
177
+ units: [], // Optional, for stackable tokens
178
+ batchId: null // Optional, for stackable tokens
179
+ });
180
+
181
+ if (result.success()) {
182
+ // Do things!
183
+ }
184
+
185
+ console.log(result.data()); // Raw response
186
+ ```
187
+
188
+ - Creating a new **Rule**:
189
+
190
+ ```typescript
191
+ const result = await client.createRule({
192
+ metaType: 'MyMetaType',
193
+ metaId: 'MyMetaId',
194
+ rule: [
195
+ // Rule definition
196
+ ],
197
+ policy: {} // Optional policy object
198
+ });
199
+
200
+ if (result.success()) {
201
+ // Do things!
202
+ }
203
+
204
+ console.log(result.data()); // Raw response
205
+ ```
206
+
207
+ - Querying **Atoms**:
208
+
209
+ ```typescript
210
+ const result = await client.queryAtom({
211
+ molecularHash: 'hash',
212
+ bundleHash: 'bundle',
213
+ isotope: 'V',
214
+ tokenSlug: 'CRZY',
215
+ latest: true,
216
+ queryArgs: {
217
+ limit: 15,
218
+ offset: 1
219
+ }
220
+ });
221
+
222
+ console.log(result.data()); // Raw response
223
+ ```
224
+
225
+ - Working with **Buffer Tokens**:
226
+
227
+ ```typescript
228
+ // Deposit to buffer
229
+ const depositResult = await client.depositBufferToken({
230
+ tokenSlug: 'CRZY',
231
+ amount: 100,
232
+ tradeRates: {
233
+ 'OTHER_TOKEN': 0.5
234
+ }
235
+ });
236
+
237
+ // Withdraw from buffer
238
+ const withdrawResult = await client.withdrawBufferToken({
239
+ tokenSlug: 'CRZY',
240
+ amount: 50
241
+ });
242
+
243
+ console.log(depositResult.data(), withdrawResult.data()); // Raw responses
244
+ ```
245
+
246
+ - Getting client fingerprint:
247
+
248
+ ```typescript
249
+ const fingerprint = await client.getFingerprint();
250
+ console.log(fingerprint);
251
+
252
+ const fingerprintData = await client.getFingerprintData();
253
+ console.log(fingerprintData);
254
+ ```
255
+
256
+ ## Advanced Usage: Working with Molecules
257
+
258
+ For more granular control, you can work directly with Molecules:
259
+
260
+ - Create a new Molecule:
261
+ ```typescript
262
+ const molecule = await client.createMolecule();
263
+ ```
264
+
265
+ - Create a custom Mutation:
266
+ ```typescript
267
+ const mutation = await client.createMoleculeMutation({
268
+ mutationClass: MyCustomMutationClass
269
+ });
270
+ ```
271
+
272
+ - Sign and check a Molecule:
273
+ ```typescript
274
+ molecule.sign();
275
+ if (!molecule.check()) {
276
+ // Handle error
277
+ }
278
+ ```
279
+
280
+ - Execute a custom Query or Mutation:
281
+ ```typescript
282
+ const result = await client.executeQuery(myQueryOrMutation, variables);
283
+ ```
284
+
285
+ ## The Hard Way: DIY Everything
286
+
287
+ This method involves individually building Atoms and Molecules, triggering the signature and validation processes, and communicating the resulting signed Molecule mutation or Query to a Knish.IO node via your favorite GraphQL client.
288
+
289
+ 1. Include the relevant classes in your application code:
290
+ ```typescript
291
+ import { Molecule, Wallet, Atom } from '@wishknish/knishio-client-ts'
292
+ ```
293
+
294
+ 2. Generate a 2048-symbol hexadecimal secret, either randomly, or via hashing login + password + salt, OAuth secret ID, biometric ID, or any other static value.
295
+
296
+ 3. (optional) Initialize a signing wallet with:
297
+ ```typescript
298
+ const wallet = new Wallet({
299
+ secret: mySecret,
300
+ token: tokenSlug,
301
+ position: myCustomPosition, // (optional) instantiate specific wallet instance vs. random
302
+ characters: myCharacterSet // (optional) override the character set used by the wallet
303
+ })
304
+ ```
305
+
306
+ **WARNING 1:** If ContinuID is enabled on the node, you will need to use a specific wallet, and therefore will first need to query the node to retrieve the `position` for that wallet.
307
+
308
+ **WARNING 2:** The Knish.IO protocol mandates that all C and M transactions be signed with a `USER` token wallet.
309
+
310
+ 4. Build your molecule with:
311
+ ```typescript
312
+ const molecule = new Molecule({
313
+ secret: mySecret,
314
+ sourceWallet: mySourceWallet, // (optional) wallet for signing
315
+ remainderWallet: myRemainderWallet, // (optional) wallet to receive remainder tokens
316
+ cellSlug: myCellSlug, // (optional) used to point a transaction to a specific branch of the ledger
317
+ version: 4 // (optional) specify the molecule version
318
+ });
319
+ ```
320
+
321
+ 5. Either use one of the shortcut methods provided by the `Molecule` class (which will build `Atom` instances for you), or create `Atom` instances yourself.
322
+
323
+ DIY example:
324
+ ```typescript
325
+ // This example records a new Wallet on the ledger
326
+
327
+ // Define metadata for our new wallet
328
+ const newWalletMeta = {
329
+ address: newWallet.address,
330
+ token: newWallet.token,
331
+ bundle: newWallet.bundle,
332
+ position: newWallet.position,
333
+ batchId: newWallet.batchId,
334
+ }
335
+
336
+ // Build the C isotope atom
337
+ const walletCreationAtom = new Atom({
338
+ position: sourceWallet.position,
339
+ walletAddress: sourceWallet.address,
340
+ isotope: 'C',
341
+ token: sourceWallet.token,
342
+ metaType: 'wallet',
343
+ metaId: newWallet.address,
344
+ meta: newWalletMeta,
345
+ index: molecule.generateIndex()
346
+ })
347
+
348
+ // Add the atom to our molecule
349
+ molecule.addAtom(walletCreationAtom)
350
+
351
+ // Adding a ContinuID / remainder atom
352
+ molecule.addContinuIdAtom();
353
+ ```
354
+
355
+ Molecule shortcut method example:
356
+ ```typescript
357
+ // This example commits metadata to some Meta Asset
358
+
359
+ // Defining our metadata
360
+ const metadata = {
361
+ foo: 'Foo',
362
+ bar: 'Bar'
363
+ }
364
+
365
+ molecule.initMeta({
366
+ meta: metadata,
367
+ metaType: 'MyMetaType',
368
+ metaId: 'MetaId123',
369
+ policy: {} // Optional policy object
370
+ });
371
+ ```
372
+
373
+ 6. Sign the molecule with the stored user secret:
374
+ ```typescript
375
+ molecule.sign()
376
+ ```
377
+
378
+ 7. Make sure everything checks out by verifying the molecule:
379
+ ```typescript
380
+ try {
381
+ molecule.check();
382
+ // If we're validating a V isotope transaction,
383
+ // add the source wallet as a parameter
384
+ molecule.check(sourceWallet);
385
+ } catch (error) {
386
+ console.error('Molecule check failed:', error);
387
+ // Handle the error
388
+ }
389
+ ```
390
+
391
+ 8. Broadcast the molecule to a Knish.IO node:
392
+ ```typescript
393
+ // Build our query object using the KnishIOClient wrapper
394
+ const mutation = await client.createMoleculeMutation({
395
+ mutationClass: MutationProposeMolecule,
396
+ molecule: molecule
397
+ });
398
+
399
+ // Send the query to the node and get a response
400
+ const response = await client.executeQuery(mutation);
401
+ ```
402
+
403
+ 9. Inspect the response...
404
+ ```typescript
405
+ // For basic queries, we look at the data property:
406
+ console.log(response.data())
407
+
408
+ // For mutations, check if the molecule was accepted by the ledger:
409
+ console.log(response.success())
410
+
411
+ // We can also check the reason for rejection
412
+ console.log(response.reason())
413
+
414
+ // Some queries may also produce a payload, with additional data:
415
+ console.log(response.payload())
416
+ ```
417
+
418
+ Payloads are provided by responses to the following queries:
419
+ 1. `QueryBalance` and `QueryContinuId` -> returns a `Wallet` instance
420
+ 2. `QueryWalletList` -> returns a list of `Wallet` instances
421
+ 3. `MutationProposeMolecule`, `MutationRequestAuthorization`, `MutationCreateIdentifier`, `MutationLinkIdentifier`, `MutationClaimShadowWallet`, `MutationCreateToken`, `MutationRequestTokens`, and `MutationTransferTokens` -> returns molecule metadata
422
+
423
+ ## Getting Help
424
+
425
+ Knish.IO is under active development, and our team is ready to assist with integration questions. The best way to seek help is to stop by our [Telegram Support Channel](https://t.me/wishknish). You can also [send us a contact request](https://knish.io/contact) via our website.