@trufnetwork/sdk-js 0.5.2 → 0.5.4

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/README.md +59 -1
  2. package/dist/cjs/client/client.cjs +11 -0
  3. package/dist/cjs/client/client.cjs.map +2 -2
  4. package/dist/cjs/contracts-api/action.cjs +3 -1
  5. package/dist/cjs/contracts-api/action.cjs.map +2 -2
  6. package/dist/cjs/contracts-api/attestationAction.cjs +9 -4
  7. package/dist/cjs/contracts-api/attestationAction.cjs.map +2 -2
  8. package/dist/cjs/contracts-api/transactionAction.cjs +139 -0
  9. package/dist/cjs/contracts-api/transactionAction.cjs.map +7 -0
  10. package/dist/cjs/internal.cjs +2 -0
  11. package/dist/cjs/internal.cjs.map +2 -2
  12. package/dist/cjs/types/attestation.cjs +2 -1
  13. package/dist/cjs/types/attestation.cjs.map +2 -2
  14. package/dist/cjs/types/transaction.cjs.map +1 -1
  15. package/dist/cjs/util/AttestationEncoding.cjs +341 -0
  16. package/dist/cjs/util/AttestationEncoding.cjs.map +2 -2
  17. package/dist/esm/client/client.mjs +11 -0
  18. package/dist/esm/client/client.mjs.map +2 -2
  19. package/dist/esm/contracts-api/action.mjs +3 -1
  20. package/dist/esm/contracts-api/action.mjs.map +2 -2
  21. package/dist/esm/contracts-api/attestationAction.mjs +9 -4
  22. package/dist/esm/contracts-api/attestationAction.mjs.map +2 -2
  23. package/dist/esm/contracts-api/transactionAction.mjs +122 -0
  24. package/dist/esm/contracts-api/transactionAction.mjs.map +7 -0
  25. package/dist/esm/internal.mjs +4 -0
  26. package/dist/esm/internal.mjs.map +2 -2
  27. package/dist/esm/types/attestation.mjs +2 -1
  28. package/dist/esm/types/attestation.mjs.map +2 -2
  29. package/dist/esm/util/AttestationEncoding.mjs +341 -0
  30. package/dist/esm/util/AttestationEncoding.mjs.map +2 -2
  31. package/dist/tsconfig.build.tsbuildinfo +1 -1
  32. package/dist/types/client/client.d.ts +6 -0
  33. package/dist/types/client/client.d.ts.map +1 -1
  34. package/dist/types/contracts-api/action.d.ts +2 -1
  35. package/dist/types/contracts-api/action.d.ts.map +1 -1
  36. package/dist/types/contracts-api/attestationAction.d.ts.map +1 -1
  37. package/dist/types/contracts-api/transactionAction.d.ts +36 -0
  38. package/dist/types/contracts-api/transactionAction.d.ts.map +1 -0
  39. package/dist/types/internal.d.ts +2 -0
  40. package/dist/types/internal.d.ts.map +1 -1
  41. package/dist/types/types/attestation.d.ts +4 -2
  42. package/dist/types/types/attestation.d.ts.map +1 -1
  43. package/dist/types/types/transaction.d.ts +59 -0
  44. package/dist/types/types/transaction.d.ts.map +1 -1
  45. package/dist/types/util/AttestationEncoding.d.ts +118 -1
  46. package/dist/types/util/AttestationEncoding.d.ts.map +1 -1
  47. package/package.json +2 -2
package/README.md CHANGED
@@ -274,6 +274,39 @@ attestations.forEach(att => {
274
274
  });
275
275
  ```
276
276
 
277
+ #### Parsing Attestation Payloads
278
+
279
+ The SDK provides utilities to parse and verify signed attestation payloads:
280
+
281
+ ```typescript
282
+ import { parseAttestationPayload } from "@trufnetwork/sdk-js";
283
+ import { sha256, recoverAddress } from "ethers";
284
+
285
+ // Get signed attestation
286
+ const signed = await attestationAction.getSignedAttestation({
287
+ requestTxId: result.requestTxId,
288
+ });
289
+
290
+ // Extract canonical payload and signature
291
+ const canonicalPayload = signed.payload.slice(0, -65);
292
+ const signature = signed.payload.slice(-65);
293
+
294
+ // Verify signature
295
+ const digest = sha256(canonicalPayload);
296
+ const validatorAddress = recoverAddress(digest, {
297
+ r: "0x" + Buffer.from(signature.slice(0, 32)).toString("hex"),
298
+ s: "0x" + Buffer.from(signature.slice(32, 64)).toString("hex"),
299
+ v: signature[64]
300
+ });
301
+
302
+ // Parse and decode the payload
303
+ const parsed = parseAttestationPayload(canonicalPayload);
304
+ console.log(`Validator: ${validatorAddress}`);
305
+ console.log(`Query Results: ${parsed.result.length} rows`);
306
+ ```
307
+
308
+ **📖 For complete documentation including signature verification, payload structure, result decoding, and EVM integration examples, see the [Attestation Payload Parsing](./docs/api-reference.md#attestation-payload-parsing) section in the API Reference.**
309
+
277
310
  #### Attestation Payload Structure
278
311
 
279
312
  The signed attestation payload is a binary blob containing:
@@ -284,13 +317,35 @@ The signed attestation payload is a binary blob containing:
284
317
  5. Stream ID (32 bytes, length-prefixed)
285
318
  6. Action ID (2 bytes)
286
319
  7. Arguments (variable, length-prefixed)
287
- 8. Result (variable, length-prefixed)
320
+ 8. Result (variable, ABI-encoded, length-prefixed)
288
321
  9. Signature (65 bytes, secp256k1)
289
322
 
290
323
  This payload can be passed to EVM smart contracts for on-chain verification using `ecrecover`.
291
324
 
292
325
  For a complete example, see [examples/attestation](./examples/attestation).
293
326
 
327
+ ### Transaction Ledger Queries
328
+
329
+ Query transaction history, fees, and distributions for auditing and analytics.
330
+
331
+ ```typescript
332
+ // Get transaction details
333
+ const transactionAction = client.loadTransactionAction();
334
+ const txEvent = await transactionAction.getTransactionEvent({
335
+ txId: '0xabcdef...'
336
+ });
337
+ console.log(`Method: ${txEvent.method}, Fee: ${txEvent.feeAmount} wei`);
338
+
339
+ // List fees paid by wallet
340
+ const entries = await transactionAction.listTransactionFees({
341
+ wallet: address,
342
+ mode: 'paid', // 'paid', 'received', or 'both'
343
+ limit: 10
344
+ });
345
+ ```
346
+
347
+ **📖 For complete documentation including parameters, return types, pagination, filtering modes, and real-world examples, see the [Transaction Ledger Queries](./docs/api-reference.md#transaction-ledger-queries) section in the API Reference.**
348
+
294
349
  ### Transaction Lifecycle and Best Practices ⚠️
295
350
 
296
351
  **Critical Understanding**: TN operations return success when transactions enter the mempool, NOT when they're executed on-chain. For operations where order matters, you must wait for transactions to be mined before proceeding.
@@ -428,7 +483,10 @@ For other bundlers or serverless platforms, consult their documentation on modul
428
483
  | Get stream taxonomy | `composedAction.getTaxonomiesForStreams({streams, latestOnly})` |
429
484
  | Request attestation | `attestationAction.requestAttestation({dataProvider, streamId, actionName, args, encryptSig, maxFee})` |
430
485
  | Get signed attestation | `attestationAction.getSignedAttestation({requestTxId})` |
486
+ | Parse attestation payload | `parseAttestationPayload(canonicalPayload)` |
431
487
  | List attestations | `attestationAction.listAttestations({requester, limit, offset, orderBy})` |
488
+ | Get transaction event | `transactionAction.getTransactionEvent({txId})` |
489
+ | List transaction fees | `transactionAction.listTransactionFees({wallet, mode, limit, offset})` |
432
490
  | Destroy stream | `client.destroyStream(streamLocator)` |
433
491
 
434
492
  **Safe Operation Pattern:**
@@ -34,6 +34,7 @@ var import_listStreams = require("./listStreams.cjs");
34
34
  var import_getLastTransactions = require("./getLastTransactions.cjs");
35
35
  var import_roleManagement = require("../contracts-api/roleManagement.cjs");
36
36
  var import_attestationAction = require("../contracts-api/attestationAction.cjs");
37
+ var import_transactionAction = require("../contracts-api/transactionAction.cjs");
37
38
  var BaseTNClient = class {
38
39
  kwilClient;
39
40
  signerInfo;
@@ -173,6 +174,16 @@ var BaseTNClient = class {
173
174
  this.getKwilSigner()
174
175
  );
175
176
  }
177
+ /**
178
+ * Loads the transaction action API, permitting transaction ledger queries.
179
+ * @returns An instance of TransactionAction.
180
+ */
181
+ loadTransactionAction() {
182
+ return new import_transactionAction.TransactionAction(
183
+ this.getKwilClient(),
184
+ this.getKwilSigner()
185
+ );
186
+ }
176
187
  /**
177
188
  * Creates a new stream locator.
178
189
  * @param streamId - The ID of the stream.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/client/client.ts"],
4
- "sourcesContent": ["import { Client, KwilSigner, NodeKwil, WebKwil, Types, EnvironmentType } from \"@trufnetwork/kwil-js\";\nimport { ComposedAction, ListTaxonomiesByHeightParams, GetTaxonomiesForStreamsParams, TaxonomyQueryResult } from \"../contracts-api/composedAction\";\nimport { deployStream } from \"../contracts-api/deployStream\";\nimport { deleteStream } from \"../contracts-api/deleteStream\";\nimport { PrimitiveAction } from \"../contracts-api/primitiveAction\";\nimport { Action, ListMetadataByHeightParams, MetadataQueryResult } from \"../contracts-api/action\";\nimport { StreamType } from \"../contracts-api/contractValues\";\nimport { StreamLocator, TNStream } from \"../types/stream\";\nimport { EthereumAddress } from \"../util/EthereumAddress\";\nimport { StreamId } from \"../util/StreamId\";\nimport { listStreams } from \"./listStreams\";\nimport { getLastTransactions } from \"./getLastTransactions\";\nimport { RoleManagement } from \"../contracts-api/roleManagement\";\nimport { AttestationAction } from \"../contracts-api/attestationAction\";\nimport { OwnerIdentifier } from \"../types/role\";\n\nexport interface SignerInfo {\n // we need to have the address upfront to create the KwilSigner, instead of relying on the signer to return it asynchronously\n address: string;\n signer: Types.EthSigner;\n}\n\nexport type TNClientOptions = {\n endpoint: string;\n signerInfo: SignerInfo;\n} & Omit<Types.KwilConfig, \"kwilProvider\">;\n\nexport interface ListStreamsInput {\n dataProvider?: string;\n limit?: number;\n offset?: number;\n orderBy?: string;\n blockHeight?: number;\n}\n\n/**\n * @param dataProvider optional address; when omitted or null, returns for all providers\n * @param limitSize max rows to return (default 6, max 100)\n */\nexport interface GetLastTransactionsInput {\n dataProvider?: string;\n limitSize?: number;\n}\n\nexport abstract class BaseTNClient<T extends EnvironmentType> {\n protected kwilClient: Types.Kwil<T> | undefined;\n protected signerInfo: SignerInfo;\n\n protected constructor(options: TNClientOptions) {\n this.signerInfo = options.signerInfo;\n }\n\n /**\n * Waits for a transaction to be mined by TN.\n * @param txHash - The transaction hash to wait for.\n * @param timeout - The timeout in milliseconds.\n * @returns A promise that resolves to the transaction info receipt.\n */\n async waitForTx(txHash: string, timeout = 12000): Promise<Types.TxInfoReceipt> {\n return new Promise<Types.TxInfoReceipt>(async (resolve, reject) => {\n const interval = setInterval(async () => {\n const receipt = await this.getKwilClient()\n [\"txInfoClient\"](txHash)\n .catch(() => ({ data: undefined, status: undefined }));\n switch (receipt.status) {\n case 200:\n if (receipt.data?.tx_result?.log !== undefined && receipt.data?.tx_result?.log.includes(\"ERROR\")) {\n reject(\n new Error(\n `Transaction failed: status ${receipt.status} : log message ${receipt.data?.tx_result.log}`,\n ))\n } else {\n resolve(receipt.data!);\n }\n break;\n case undefined:\n break;\n default:\n reject(\n new Error(\n `Transaction failed: status ${receipt.status} : log message ${receipt.data?.tx_result.log}`,\n ),\n );\n }\n }, 1000);\n setTimeout(() => {\n clearInterval(interval);\n reject(new Error(\"Transaction failed: Timeout\"));\n }, timeout);\n });\n }\n\n /**\n * Returns the Kwil signer used by the client.\n * @returns An instance of KwilSigner.\n */\n getKwilSigner(): KwilSigner {\n return new KwilSigner(\n this.signerInfo.signer,\n this.address().getAddress(),\n );\n }\n\n /**\n * Returns the Kwil client used by the client.\n * @returns An instance of Kwil.\n * @throws If the Kwil client is not initialized.\n */\n getKwilClient(): Types.Kwil<EnvironmentType> {\n if (!this.kwilClient) {\n throw new Error(\"Kwil client not initialized\");\n }\n return this.kwilClient;\n }\n\n /**\n * Deploys a new stream.\n * @param streamId - The ID of the stream to deploy.\n * @param streamType - The type of the stream.\n * @param synchronous - Whether the deployment should be synchronous.\n * @param contractVersion\n * @returns A promise that resolves to a generic response containing the transaction receipt.\n */\n async deployStream(\n streamId: StreamId,\n streamType: StreamType,\n synchronous?: boolean,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await deployStream({\n streamId,\n streamType,\n synchronous,\n kwilClient: this.getKwilClient(),\n kwilSigner: this.getKwilSigner(),\n });\n }\n\n /**\n * Destroys a stream.\n * @param stream - The StreamLocator of the stream to destroy.\n * @param synchronous - Whether the destruction should be synchronous.\n * @returns A promise that resolves to a generic response containing the transaction receipt.\n */\n async destroyStream(\n stream: StreamLocator,\n synchronous?: boolean,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await deleteStream({\n stream,\n synchronous,\n kwilClient: this.getKwilClient(),\n kwilSigner: this.getKwilSigner(),\n });\n }\n\n /**\n * Loads an already deployed stream, permitting its API usage.\n * @returns An instance of IStream.\n */\n loadAction(): Action {\n return new Action(\n this.getKwilClient() as WebKwil | NodeKwil,\n this.getKwilSigner(),\n );\n }\n\n /**\n * Loads a primitive stream.\n * @returns An instance of IPrimitiveStream.\n */\n loadPrimitiveAction(): PrimitiveAction {\n return PrimitiveAction.fromStream(this.loadAction());\n }\n\n /**\n * Loads a composed stream.\n * @returns An instance of IComposedStream.\n */\n loadComposedAction(): ComposedAction {\n return ComposedAction.fromStream(this.loadAction());\n }\n\n /**\n * Loads the role management contract API, permitting its RBAC usage.\n */\n loadRoleManagementAction(): RoleManagement {\n return RoleManagement.fromClient(\n this.getKwilClient() as WebKwil | NodeKwil,\n this.getKwilSigner(),\n );\n }\n\n /**\n * Loads the attestation action API, permitting attestation operations.\n * @returns An instance of AttestationAction.\n */\n loadAttestationAction(): AttestationAction {\n return new AttestationAction(\n this.getKwilClient() as WebKwil | NodeKwil,\n this.getKwilSigner(),\n );\n }\n\n /**\n * Creates a new stream locator.\n * @param streamId - The ID of the stream.\n * @returns A StreamLocator object.\n */\n ownStreamLocator(streamId: StreamId): StreamLocator {\n return {\n streamId,\n dataProvider: this.address(),\n };\n }\n\n /**\n * Returns the address of the signer used by the client.\n * @returns An instance of EthereumAddress.\n */\n address(): EthereumAddress {\n return new EthereumAddress(this.signerInfo.address);\n }\n\n /**\n * Returns all streams from the TN network.\n * @param input - The input parameters for listing streams.\n * @returns A promise that resolves to a list of stream locators.\n */\n async getListStreams(input: ListStreamsInput): Promise<TNStream[]> {\n return listStreams(this.getKwilClient() as WebKwil | NodeKwil,this.getKwilSigner(),input);\n }\n\n /**\n * Returns the last write activity across streams.\n * @param input - The input parameters for getting last transactions.\n * @returns A promise that resolves to a list of last transactions.\n */\n async getLastTransactions(input: GetLastTransactionsInput): Promise<any[]> {\n return getLastTransactions(this.getKwilClient() as WebKwil | NodeKwil,this.getKwilSigner(),input);\n }\n\n /**\n * Lists taxonomies by height range for incremental synchronization.\n * High-level wrapper for ComposedAction.listTaxonomiesByHeight()\n * \n * @param params Height range and pagination parameters \n * @returns Promise resolving to taxonomy query results\n * \n * @example\n * ```typescript\n * const taxonomies = await client.listTaxonomiesByHeight({\n * fromHeight: 1000,\n * toHeight: 2000,\n * limit: 100,\n * latestOnly: true\n * });\n * ```\n */\n async listTaxonomiesByHeight(params: ListTaxonomiesByHeightParams = {}): Promise<TaxonomyQueryResult[]> {\n const composedAction = this.loadComposedAction();\n return composedAction.listTaxonomiesByHeight(params);\n }\n\n async listMetadataByHeight(params: ListMetadataByHeightParams = {}): Promise<MetadataQueryResult[]> {\n const action = this.loadAction();\n return action.listMetadataByHeight(params);\n }\n\n async getWalletBalance(chain: string, walletAddress: string) {\n const action = this.loadAction();\n return action.getWalletBalance(chain, walletAddress);\n }\n\n /**\n * Performs a withdrawal operation by bridging tokens\n * @param chain The chain identifier (e.g., \"sepolia\", \"mainnet\", \"polygon\", etc.)\n * @param amount The amount to withdraw\n * @returns Promise that resolves to the transaction hash, or throws on error\n */\n async withdraw(chain: string, amount: string, recipient: string): Promise<string> {\n const action = this.loadAction();\n \n // Bridge tokens in a single operation\n const bridgeResult = await action.bridgeTokens(chain, amount, recipient);\n if (!bridgeResult.data?.tx_hash) {\n throw new Error(\"Bridge tokens operation failed: no transaction hash returned\");\n }\n \n // Wait for bridge transaction to be mined - let waitForTx errors bubble up\n try {\n await this.waitForTx(bridgeResult.data.tx_hash);\n } catch (error) {\n throw new Error(`Bridge tokens transaction failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n \n // Return the transaction hash\n return bridgeResult.data.tx_hash;\n }\n\n /**\n * Lists wallet rewards for a specific wallet address on a blockchain network\n * @param chain The chain identifier (e.g., \"sepolia\", \"mainnet\", \"polygon\", etc.)\n * @param wallet The wallet address to list rewards for\n * @param withPending Whether to include pending rewards\n * @returns Promise that resolves to an array of rewards data\n */\n async listWalletRewards(chain: string, wallet: string, withPending: boolean): Promise<any[]> {\n const action = this.loadAction();\n return action.listWalletRewards(chain, wallet, withPending);\n }\n\n /**\n * Gets taxonomies for specific streams in batch.\n * High-level wrapper for ComposedAction.getTaxonomiesForStreams()\n * \n * @param params Stream locators and options\n * @returns Promise resolving to taxonomy query results\n * \n * @example\n * ```typescript\n * const streams = [\n * { dataProvider: provider1, streamId: streamId1 },\n * { dataProvider: provider2, streamId: streamId2 }\n * ];\n * const taxonomies = await client.getTaxonomiesForStreams({\n * streams,\n * latestOnly: true\n * });\n * ```\n */\n async getTaxonomiesForStreams(params: GetTaxonomiesForStreamsParams): Promise<TaxonomyQueryResult[]> {\n const composedAction = this.loadComposedAction();\n return composedAction.getTaxonomiesForStreams(params);\n }\n\n /**\n * Get the default chain id for a provider. Use with caution, as this decreases the security of the TN.\n * @param provider - The provider URL.\n * @returns A promise that resolves to the chain ID.\n */\n public static async getDefaultChainId(provider: string) {\n const kwilClient = new Client({\n kwilProvider: provider,\n });\n const chainInfo = await kwilClient[\"chainInfoClient\"]();\n return chainInfo.data?.chain_id;\n }\n\n /*\n * High-level role-management helpers. These wrap the lower-level\n * RoleManagement contract calls and expose a simpler API on the\n * TN client.\n */\n\n /** Grants a role to one or more wallets. */\n async grantRole(input: {\n owner: OwnerIdentifier;\n roleName: string;\n wallets: EthereumAddress | EthereumAddress[];\n synchronous?: boolean;\n }): Promise<string> {\n const rm = this.loadRoleManagementAction();\n const walletsArr: EthereumAddress[] = Array.isArray(input.wallets)\n ? input.wallets\n : [input.wallets];\n const tx = await rm.grantRole(\n {\n owner: input.owner,\n roleName: input.roleName,\n wallets: walletsArr,\n },\n input.synchronous,\n );\n return tx.data?.tx_hash as unknown as string;\n }\n\n /** Revokes a role from one or more wallets. */\n async revokeRole(input: {\n owner: OwnerIdentifier;\n roleName: string;\n wallets: EthereumAddress | EthereumAddress[];\n synchronous?: boolean;\n }): Promise<string> {\n const rm = this.loadRoleManagementAction();\n const walletsArr: EthereumAddress[] = Array.isArray(input.wallets)\n ? input.wallets\n : [input.wallets];\n const tx = await rm.revokeRole(\n {\n owner: input.owner,\n roleName: input.roleName,\n wallets: walletsArr,\n },\n input.synchronous,\n );\n return tx.data?.tx_hash as unknown as string;\n }\n\n /**\n * Checks if a wallet is member of a role.\n * Returns true if the wallet is a member.\n */\n async isMemberOf(input: {\n owner: OwnerIdentifier;\n roleName: string;\n wallet: EthereumAddress;\n }): Promise<boolean> {\n const rm = this.loadRoleManagementAction();\n const res = await rm.areMembersOf({\n owner: input.owner,\n roleName: input.roleName,\n wallets: [input.wallet],\n });\n return res.length > 0 && res[0].isMember;\n }\n\n /**\n * Lists role members \u2013 currently unsupported in the\n * smart-contract layer.\n */\n async listRoleMembers(input: {\n owner: OwnerIdentifier;\n roleName: string;\n limit?: number;\n offset?: number;\n }): Promise<import(\"../types/role\").RoleMember[]> {\n const rm = this.loadRoleManagementAction();\n return rm.listRoleMembers({\n owner: input.owner,\n roleName: input.roleName,\n limit: input.limit,\n offset: input.offset,\n });\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAA8E;AAC9E,4BAAiH;AACjH,0BAA6B;AAC7B,0BAA6B;AAC7B,6BAAgC;AAChC,oBAAwE;AAGxE,6BAAgC;AAEhC,yBAA4B;AAC5B,iCAAoC;AACpC,4BAA+B;AAC/B,+BAAkC;AA+B3B,IAAe,eAAf,MAAuD;AAAA,EAClD;AAAA,EACA;AAAA,EAEA,YAAY,SAA0B;AAC9C,SAAK,aAAa,QAAQ;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,UAAU,QAAgB,UAAU,MAAqC;AAC7E,WAAO,IAAI,QAA6B,OAAO,SAAS,WAAW;AACjE,YAAM,WAAW,YAAY,YAAY;AACvC,cAAM,UAAU,MAAM,KAAK,cAAc,EACtC,cAAc,EAAE,MAAM,EACtB,MAAM,OAAO,EAAE,MAAM,QAAW,QAAQ,OAAU,EAAE;AACvD,gBAAQ,QAAQ,QAAQ;AAAA,UACtB,KAAK;AACH,gBAAI,QAAQ,MAAM,WAAW,QAAQ,UAAa,QAAQ,MAAM,WAAW,IAAI,SAAS,OAAO,GAAG;AAChG;AAAA,gB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AAK,yBAAyB;AACzC,WAAO,GAAG,gBAAgB;AAAA,MACxB,OAAO,MAAM;AAAA,MACb,UAAU,MAAM;AAAA,MAChB,OAAO,MAAM;AAAA,MACb,QAAQ,MAAM;AAAA,IAChB,CAAC;AAAA,EACH;AACF;",
4
+ "sourcesContent": ["import { Client, KwilSigner, NodeKwil, WebKwil, Types, EnvironmentType } from \"@trufnetwork/kwil-js\";\nimport { ComposedAction, ListTaxonomiesByHeightParams, GetTaxonomiesForStreamsParams, TaxonomyQueryResult } from \"../contracts-api/composedAction\";\nimport { deployStream } from \"../contracts-api/deployStream\";\nimport { deleteStream } from \"../contracts-api/deleteStream\";\nimport { PrimitiveAction } from \"../contracts-api/primitiveAction\";\nimport { Action, ListMetadataByHeightParams, MetadataQueryResult } from \"../contracts-api/action\";\nimport { StreamType } from \"../contracts-api/contractValues\";\nimport { StreamLocator, TNStream } from \"../types/stream\";\nimport { EthereumAddress } from \"../util/EthereumAddress\";\nimport { StreamId } from \"../util/StreamId\";\nimport { listStreams } from \"./listStreams\";\nimport { getLastTransactions } from \"./getLastTransactions\";\nimport { RoleManagement } from \"../contracts-api/roleManagement\";\nimport { AttestationAction } from \"../contracts-api/attestationAction\";\nimport { TransactionAction } from \"../contracts-api/transactionAction\";\nimport { OwnerIdentifier } from \"../types/role\";\n\nexport interface SignerInfo {\n // we need to have the address upfront to create the KwilSigner, instead of relying on the signer to return it asynchronously\n address: string;\n signer: Types.EthSigner;\n}\n\nexport type TNClientOptions = {\n endpoint: string;\n signerInfo: SignerInfo;\n} & Omit<Types.KwilConfig, \"kwilProvider\">;\n\nexport interface ListStreamsInput {\n dataProvider?: string;\n limit?: number;\n offset?: number;\n orderBy?: string;\n blockHeight?: number;\n}\n\n/**\n * @param dataProvider optional address; when omitted or null, returns for all providers\n * @param limitSize max rows to return (default 6, max 100)\n */\nexport interface GetLastTransactionsInput {\n dataProvider?: string;\n limitSize?: number;\n}\n\nexport abstract class BaseTNClient<T extends EnvironmentType> {\n protected kwilClient: Types.Kwil<T> | undefined;\n protected signerInfo: SignerInfo;\n\n protected constructor(options: TNClientOptions) {\n this.signerInfo = options.signerInfo;\n }\n\n /**\n * Waits for a transaction to be mined by TN.\n * @param txHash - The transaction hash to wait for.\n * @param timeout - The timeout in milliseconds.\n * @returns A promise that resolves to the transaction info receipt.\n */\n async waitForTx(txHash: string, timeout = 12000): Promise<Types.TxInfoReceipt> {\n return new Promise<Types.TxInfoReceipt>(async (resolve, reject) => {\n const interval = setInterval(async () => {\n const receipt = await this.getKwilClient()\n [\"txInfoClient\"](txHash)\n .catch(() => ({ data: undefined, status: undefined }));\n switch (receipt.status) {\n case 200:\n if (receipt.data?.tx_result?.log !== undefined && receipt.data?.tx_result?.log.includes(\"ERROR\")) {\n reject(\n new Error(\n `Transaction failed: status ${receipt.status} : log message ${receipt.data?.tx_result.log}`,\n ))\n } else {\n resolve(receipt.data!);\n }\n break;\n case undefined:\n break;\n default:\n reject(\n new Error(\n `Transaction failed: status ${receipt.status} : log message ${receipt.data?.tx_result.log}`,\n ),\n );\n }\n }, 1000);\n setTimeout(() => {\n clearInterval(interval);\n reject(new Error(\"Transaction failed: Timeout\"));\n }, timeout);\n });\n }\n\n /**\n * Returns the Kwil signer used by the client.\n * @returns An instance of KwilSigner.\n */\n getKwilSigner(): KwilSigner {\n return new KwilSigner(\n this.signerInfo.signer,\n this.address().getAddress(),\n );\n }\n\n /**\n * Returns the Kwil client used by the client.\n * @returns An instance of Kwil.\n * @throws If the Kwil client is not initialized.\n */\n getKwilClient(): Types.Kwil<EnvironmentType> {\n if (!this.kwilClient) {\n throw new Error(\"Kwil client not initialized\");\n }\n return this.kwilClient;\n }\n\n /**\n * Deploys a new stream.\n * @param streamId - The ID of the stream to deploy.\n * @param streamType - The type of the stream.\n * @param synchronous - Whether the deployment should be synchronous.\n * @param contractVersion\n * @returns A promise that resolves to a generic response containing the transaction receipt.\n */\n async deployStream(\n streamId: StreamId,\n streamType: StreamType,\n synchronous?: boolean,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await deployStream({\n streamId,\n streamType,\n synchronous,\n kwilClient: this.getKwilClient(),\n kwilSigner: this.getKwilSigner(),\n });\n }\n\n /**\n * Destroys a stream.\n * @param stream - The StreamLocator of the stream to destroy.\n * @param synchronous - Whether the destruction should be synchronous.\n * @returns A promise that resolves to a generic response containing the transaction receipt.\n */\n async destroyStream(\n stream: StreamLocator,\n synchronous?: boolean,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await deleteStream({\n stream,\n synchronous,\n kwilClient: this.getKwilClient(),\n kwilSigner: this.getKwilSigner(),\n });\n }\n\n /**\n * Loads an already deployed stream, permitting its API usage.\n * @returns An instance of IStream.\n */\n loadAction(): Action {\n return new Action(\n this.getKwilClient() as WebKwil | NodeKwil,\n this.getKwilSigner(),\n );\n }\n\n /**\n * Loads a primitive stream.\n * @returns An instance of IPrimitiveStream.\n */\n loadPrimitiveAction(): PrimitiveAction {\n return PrimitiveAction.fromStream(this.loadAction());\n }\n\n /**\n * Loads a composed stream.\n * @returns An instance of IComposedStream.\n */\n loadComposedAction(): ComposedAction {\n return ComposedAction.fromStream(this.loadAction());\n }\n\n /**\n * Loads the role management contract API, permitting its RBAC usage.\n */\n loadRoleManagementAction(): RoleManagement {\n return RoleManagement.fromClient(\n this.getKwilClient() as WebKwil | NodeKwil,\n this.getKwilSigner(),\n );\n }\n\n /**\n * Loads the attestation action API, permitting attestation operations.\n * @returns An instance of AttestationAction.\n */\n loadAttestationAction(): AttestationAction {\n return new AttestationAction(\n this.getKwilClient() as WebKwil | NodeKwil,\n this.getKwilSigner(),\n );\n }\n\n /**\n * Loads the transaction action API, permitting transaction ledger queries.\n * @returns An instance of TransactionAction.\n */\n loadTransactionAction(): TransactionAction {\n return new TransactionAction(\n this.getKwilClient() as WebKwil | NodeKwil,\n this.getKwilSigner(),\n );\n }\n\n /**\n * Creates a new stream locator.\n * @param streamId - The ID of the stream.\n * @returns A StreamLocator object.\n */\n ownStreamLocator(streamId: StreamId): StreamLocator {\n return {\n streamId,\n dataProvider: this.address(),\n };\n }\n\n /**\n * Returns the address of the signer used by the client.\n * @returns An instance of EthereumAddress.\n */\n address(): EthereumAddress {\n return new EthereumAddress(this.signerInfo.address);\n }\n\n /**\n * Returns all streams from the TN network.\n * @param input - The input parameters for listing streams.\n * @returns A promise that resolves to a list of stream locators.\n */\n async getListStreams(input: ListStreamsInput): Promise<TNStream[]> {\n return listStreams(this.getKwilClient() as WebKwil | NodeKwil,this.getKwilSigner(),input);\n }\n\n /**\n * Returns the last write activity across streams.\n * @param input - The input parameters for getting last transactions.\n * @returns A promise that resolves to a list of last transactions.\n */\n async getLastTransactions(input: GetLastTransactionsInput): Promise<any[]> {\n return getLastTransactions(this.getKwilClient() as WebKwil | NodeKwil,this.getKwilSigner(),input);\n }\n\n /**\n * Lists taxonomies by height range for incremental synchronization.\n * High-level wrapper for ComposedAction.listTaxonomiesByHeight()\n * \n * @param params Height range and pagination parameters \n * @returns Promise resolving to taxonomy query results\n * \n * @example\n * ```typescript\n * const taxonomies = await client.listTaxonomiesByHeight({\n * fromHeight: 1000,\n * toHeight: 2000,\n * limit: 100,\n * latestOnly: true\n * });\n * ```\n */\n async listTaxonomiesByHeight(params: ListTaxonomiesByHeightParams = {}): Promise<TaxonomyQueryResult[]> {\n const composedAction = this.loadComposedAction();\n return composedAction.listTaxonomiesByHeight(params);\n }\n\n async listMetadataByHeight(params: ListMetadataByHeightParams = {}): Promise<MetadataQueryResult[]> {\n const action = this.loadAction();\n return action.listMetadataByHeight(params);\n }\n\n async getWalletBalance(chain: string, walletAddress: string) {\n const action = this.loadAction();\n return action.getWalletBalance(chain, walletAddress);\n }\n\n /**\n * Performs a withdrawal operation by bridging tokens\n * @param chain The chain identifier (e.g., \"sepolia\", \"mainnet\", \"polygon\", etc.)\n * @param amount The amount to withdraw\n * @returns Promise that resolves to the transaction hash, or throws on error\n */\n async withdraw(chain: string, amount: string, recipient: string): Promise<string> {\n const action = this.loadAction();\n \n // Bridge tokens in a single operation\n const bridgeResult = await action.bridgeTokens(chain, amount, recipient);\n if (!bridgeResult.data?.tx_hash) {\n throw new Error(\"Bridge tokens operation failed: no transaction hash returned\");\n }\n \n // Wait for bridge transaction to be mined - let waitForTx errors bubble up\n try {\n await this.waitForTx(bridgeResult.data.tx_hash);\n } catch (error) {\n throw new Error(`Bridge tokens transaction failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n \n // Return the transaction hash\n return bridgeResult.data.tx_hash;\n }\n\n /**\n * Lists wallet rewards for a specific wallet address on a blockchain network\n * @param chain The chain identifier (e.g., \"sepolia\", \"mainnet\", \"polygon\", etc.)\n * @param wallet The wallet address to list rewards for\n * @param withPending Whether to include pending rewards\n * @returns Promise that resolves to an array of rewards data\n */\n async listWalletRewards(chain: string, wallet: string, withPending: boolean): Promise<any[]> {\n const action = this.loadAction();\n return action.listWalletRewards(chain, wallet, withPending);\n }\n\n /**\n * Gets taxonomies for specific streams in batch.\n * High-level wrapper for ComposedAction.getTaxonomiesForStreams()\n * \n * @param params Stream locators and options\n * @returns Promise resolving to taxonomy query results\n * \n * @example\n * ```typescript\n * const streams = [\n * { dataProvider: provider1, streamId: streamId1 },\n * { dataProvider: provider2, streamId: streamId2 }\n * ];\n * const taxonomies = await client.getTaxonomiesForStreams({\n * streams,\n * latestOnly: true\n * });\n * ```\n */\n async getTaxonomiesForStreams(params: GetTaxonomiesForStreamsParams): Promise<TaxonomyQueryResult[]> {\n const composedAction = this.loadComposedAction();\n return composedAction.getTaxonomiesForStreams(params);\n }\n\n /**\n * Get the default chain id for a provider. Use with caution, as this decreases the security of the TN.\n * @param provider - The provider URL.\n * @returns A promise that resolves to the chain ID.\n */\n public static async getDefaultChainId(provider: string) {\n const kwilClient = new Client({\n kwilProvider: provider,\n });\n const chainInfo = await kwilClient[\"chainInfoClient\"]();\n return chainInfo.data?.chain_id;\n }\n\n /*\n * High-level role-management helpers. These wrap the lower-level\n * RoleManagement contract calls and expose a simpler API on the\n * TN client.\n */\n\n /** Grants a role to one or more wallets. */\n async grantRole(input: {\n owner: OwnerIdentifier;\n roleName: string;\n wallets: EthereumAddress | EthereumAddress[];\n synchronous?: boolean;\n }): Promise<string> {\n const rm = this.loadRoleManagementAction();\n const walletsArr: EthereumAddress[] = Array.isArray(input.wallets)\n ? input.wallets\n : [input.wallets];\n const tx = await rm.grantRole(\n {\n owner: input.owner,\n roleName: input.roleName,\n wallets: walletsArr,\n },\n input.synchronous,\n );\n return tx.data?.tx_hash as unknown as string;\n }\n\n /** Revokes a role from one or more wallets. */\n async revokeRole(input: {\n owner: OwnerIdentifier;\n roleName: string;\n wallets: EthereumAddress | EthereumAddress[];\n synchronous?: boolean;\n }): Promise<string> {\n const rm = this.loadRoleManagementAction();\n const walletsArr: EthereumAddress[] = Array.isArray(input.wallets)\n ? input.wallets\n : [input.wallets];\n const tx = await rm.revokeRole(\n {\n owner: input.owner,\n roleName: input.roleName,\n wallets: walletsArr,\n },\n input.synchronous,\n );\n return tx.data?.tx_hash as unknown as string;\n }\n\n /**\n * Checks if a wallet is member of a role.\n * Returns true if the wallet is a member.\n */\n async isMemberOf(input: {\n owner: OwnerIdentifier;\n roleName: string;\n wallet: EthereumAddress;\n }): Promise<boolean> {\n const rm = this.loadRoleManagementAction();\n const res = await rm.areMembersOf({\n owner: input.owner,\n roleName: input.roleName,\n wallets: [input.wallet],\n });\n return res.length > 0 && res[0].isMember;\n }\n\n /**\n * Lists role members \u2013 currently unsupported in the\n * smart-contract layer.\n */\n async listRoleMembers(input: {\n owner: OwnerIdentifier;\n roleName: string;\n limit?: number;\n offset?: number;\n }): Promise<import(\"../types/role\").RoleMember[]> {\n const rm = this.loadRoleManagementAction();\n return rm.listRoleMembers({\n owner: input.owner,\n roleName: input.roleName,\n limit: input.limit,\n offset: input.offset,\n });\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAA8E;AAC9E,4BAAiH;AACjH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,OAAO,MAAM;AAAA,QACb,UAAU,MAAM;AAAA,QAChB,SAAS;AAAA,MACX;AAAA,MACA,MAAM;AAAA,IACR;AACA,WAAO,GAAG,MAAM;AAAA,EAClB;AAAA;AAAA,EAGA,MAAM,WAAW,OAKG;AAClB,UAAM,KAAK,KAAK,yBAAyB;AACzC,UAAM,aAAgC,MAAM,QAAQ,MAAM,OAAO,IAC7D,MAAM,UACN,CAAC,MAAM,OAAO;AAClB,UAAM,KAAK,MAAM,GAAG;AAAA,MAClB;AAAA,QACE,OAAO,MAAM;AAAA,QACb,UAAU,MAAM;AAAA,QAChB,SAAS;AAAA,MACX;AAAA,MACA,MAAM;AAAA,IACR;AACA,WAAO,GAAG,MAAM;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,WAAW,OAII;AACnB,UAAM,KAAK,KAAK,yBAAyB;AACzC,UAAM,MAAM,MAAM,GAAG,aAAa;AAAA,MAChC,OAAO,MAAM;AAAA,MACb,UAAU,MAAM;AAAA,MAChB,SAAS,CAAC,MAAM,MAAM;AAAA,IACxB,CAAC;AACD,WAAO,IAAI,SAAS,KAAK,IAAI,CAAC,EAAE;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,gBAAgB,OAK4B;AAChD,UAAM,KAAK,KAAK,yBAAyB;AACzC,WAAO,GAAG,gBAAgB;AAAA,MACxB,OAAO,MAAM;AAAA,MACb,UAAU,MAAM;AAAA,MAChB,OAAO,MAAM;AAAA,MACb,QAAQ,MAAM;AAAA,IAChB,CAAC;AAAA,EACH;AACF;",
6
6
  "names": []
7
7
  }
@@ -49,14 +49,16 @@ var Action = class _Action {
49
49
  * Executes a stream method with named parameters
50
50
  * @param method - The action name to execute
51
51
  * @param inputs - Named parameters for the action
52
+ * @param types - Optional type specifications for parameters (e.g., NUMERIC)
52
53
  * @returns Transaction receipt
53
54
  */
54
- async executeWithNamedParams(method, inputs) {
55
+ async executeWithNamedParams(method, inputs, types) {
55
56
  return this.kwilClient.execute(
56
57
  {
57
58
  namespace: "main",
58
59
  name: method,
59
60
  inputs,
61
+ types,
60
62
  description: `TN SDK - Executing method on stream: ${method}`
61
63
  },
62
64
  this.kwilSigner
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/contracts-api/action.ts"],
4
- "sourcesContent": ["import {KwilSigner, NodeKwil, WebKwil, Types} from \"@trufnetwork/kwil-js\";\nimport { Either } from \"monads-io\";\nimport { DateString } from \"../types/other\";\nimport { StreamLocator } from \"../types/stream\";\nimport { CacheAwareResponse, GetRecordOptions, GetIndexOptions, GetIndexChangeOptions, GetFirstRecordOptions } from \"../types/cache\";\nimport { EthereumAddress } from \"../util/EthereumAddress\";\nimport { head } from \"../util/head\";\nimport { StreamId } from \"../util/StreamId\";\nimport { toVisibilityEnum, VisibilityEnum } from \"../util/visibility\";\nimport { CacheMetadataParser } from \"../util/cacheMetadataParser\";\nimport { CacheValidation } from \"../util/cacheValidation\";\nimport {\n MetadataKey,\n MetadataKeyValueMap,\n MetadataTableKey,\n MetadataValueTypeForKey,\n StreamType,\n} from \"./contractValues\";\n// ValueType is available as Types.ValueType\n\nexport interface GetRecordInput {\n stream: StreamLocator;\n from?: number;\n to?: number;\n frozenAt?: number;\n baseTime?: DateString | number;\n prefix?: string;\n}\n\nexport interface GetFirstRecordInput {\n stream: StreamLocator;\n after?: number;\n frozenAt?: number;\n}\n\nexport interface StreamRecord {\n eventTime: number;\n value: string;\n}\n\nexport interface GetIndexChangeInput extends GetRecordInput {\n timeInterval: number;\n}\n\nexport interface ListMetadataByHeightParams {\n /** Key reference filter. Default: empty string */\n key?: string;\n /** Value reference filter. Default: null */\n value?: string;\n /** Start height (inclusive). If null, uses earliest available. */\n fromHeight?: number;\n /** End height (inclusive). If null, uses current height. */\n toHeight?: number;\n /** Maximum number of results to return. Default: 1000 */\n limit?: number;\n /** Number of results to skip for pagination. Default: 0 */\n offset?: number;\n}\n\nexport interface MetadataQueryResult {\n streamId: string;\n dataProvider: string;\n rowId: string;\n valueInt: number | null;\n valueFloat: string | null;\n valueBoolean: boolean | null;\n valueString: string | null;\n valueRef: string | null;\n createdAt: number;\n}\n\nexport class Action {\n protected kwilClient: WebKwil | NodeKwil;\n protected kwilSigner: KwilSigner;\n /** Track if deprecation warnings were already emitted */\n private static _legacyWarnEmitted: Record<string, boolean> = {\n getRecord: false,\n getIndex: false,\n getFirstRecord: false,\n getIndexChange: false,\n };\n constructor(\n kwilClient: WebKwil | NodeKwil,\n kwilSigner: KwilSigner,\n ) {\n this.kwilClient = kwilClient;\n this.kwilSigner = kwilSigner;\n }\n\n /**\n * Executes a stream method with named parameters\n * @param method - The action name to execute\n * @param inputs - Named parameters for the action\n * @returns Transaction receipt\n */\n protected async executeWithNamedParams(\n method: string,\n inputs: Types.NamedParams[],\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return this.kwilClient.execute({\n namespace: \"main\",\n name: method,\n inputs,\n description: `TN SDK - Executing method on stream: ${method}`,\n },\n this.kwilSigner,\n );\n }\n\n /**\n * Executes a stream action with a complete ActionBody\n * @param inputs - Complete action body with all execution parameters\n * @param synchronous - Whether to wait for transaction to be mined\n * @returns Transaction receipt\n */\n protected async executeWithActionBody(\n inputs: Types.ActionBody,\n synchronous: boolean = false,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return this.kwilClient.execute(inputs, this.kwilSigner, synchronous);\n }\n\n /**\n * Calls a method on the stream\n */\n protected async call<T>(\n method: string,\n inputs: Types.NamedParams,\n ): Promise<Either<number, T>> {\n const result = await this.kwilClient.call(\n {\n namespace: \"main\",\n name: method,\n inputs: inputs,\n },\n this.kwilSigner,\n );\n\n if (result.status !== 200) {\n return Either.left(result.status);\n }\n\n return Either.right(result.data?.result as T);\n }\n\n /**\n * @deprecated Use getRecord(stream, options?) to leverage cache support and future-proof parameter handling.\n */\n public async getRecord(input: GetRecordInput): Promise<StreamRecord[]>;\n public async getRecord(stream: StreamLocator, options?: GetRecordOptions): Promise<CacheAwareResponse<StreamRecord[]>>;\n public async getRecord(\n inputOrStream: GetRecordInput | StreamLocator,\n options?: GetRecordOptions\n ): Promise<StreamRecord[] | CacheAwareResponse<StreamRecord[]>> {\n // Handle backward compatibility\n if ('stream' in inputOrStream) {\n // Legacy call format\n const input = inputOrStream as GetRecordInput;\n // emit deprecation warning once\n if (!Action._legacyWarnEmitted.getRecord) {\n Action._legacyWarnEmitted.getRecord = true;\n if (typeof console !== 'undefined' && console.warn) {\n console.warn('[TN SDK] Deprecated signature: getRecord(input). Use getRecord(stream, options?) instead.');\n }\n }\n const prefix = input.prefix ? input.prefix : \"\"\n const result = await this.call<{ event_time: number; value: string }[]>(\n prefix + \"get_record\",\n {\n $data_provider: input.stream.dataProvider.getAddress(),\n $stream_id: input.stream.streamId.getId(),\n $from: input.from,\n $to: input.to,\n $frozen_at: input.frozenAt,\n }\n );\n return result\n .mapRight((result) =>\n result.map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n })),\n )\n .throw();\n }\n \n // New cache-aware call format\n const stream = inputOrStream as StreamLocator;\n \n // Validate options if provided\n if (options) {\n CacheValidation.validateGetRecordOptions(options);\n CacheValidation.validateTimeRange(options.from, options.to);\n }\n \n const prefix = options?.prefix ? options.prefix : \"\"\n const params: any = {\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $from: options?.from,\n $to: options?.to,\n $frozen_at: options?.frozenAt,\n };\n \n if (options?.useCache !== undefined) {\n params.$use_cache = options.useCache;\n }\n \n const result = await this.kwilClient.call(\n {\n namespace: \"main\",\n name: prefix + \"get_record\",\n inputs: params,\n },\n this.kwilSigner,\n );\n \n if (result.status !== 200) {\n throw new Error(`Failed to get record: ${result.status}`);\n }\n \n const data = (result.data?.result as { event_time: number; value: string }[]).map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n }));\n \n let cache = CacheMetadataParser.extractFromResponse(result);\n \n // Enhance cache metadata with SDK-provided context\n if (cache) {\n cache = {\n ...cache,\n streamId: stream.streamId.getId(),\n dataProvider: stream.dataProvider.getAddress(),\n from: options?.from,\n to: options?.to,\n frozenAt: options?.frozenAt,\n rowsServed: data.length\n };\n }\n \n return {\n data,\n cache: cache || undefined,\n logs: result.data?.logs ? CacheMetadataParser.parseLogsForMetadata(result.data.logs) : undefined,\n };\n }\n\n /**\n * Returns the index of the stream within the given date range\n * @deprecated Use getIndex(stream, options?) to leverage cache support and future-proof parameter handling.\n */\n public async getIndex(input: GetRecordInput): Promise<StreamRecord[]>;\n public async getIndex(stream: StreamLocator, options?: GetIndexOptions): Promise<CacheAwareResponse<StreamRecord[]>>;\n public async getIndex(\n inputOrStream: GetRecordInput | StreamLocator,\n options?: GetIndexOptions\n ): Promise<StreamRecord[] | CacheAwareResponse<StreamRecord[]>> {\n // Handle backward compatibility\n if ('stream' in inputOrStream) {\n // Legacy call format\n const input = inputOrStream as GetRecordInput;\n if (!Action._legacyWarnEmitted.getIndex) {\n Action._legacyWarnEmitted.getIndex = true;\n if (typeof console !== 'undefined' && console.warn) {\n console.warn('[TN SDK] Deprecated signature: getIndex(input). Use getIndex(stream, options?) instead.');\n }\n }\n const prefix = input.prefix ? input.prefix : \"\"\n const result = await this.call<{ event_time: number; value: string }[]>(\n prefix + \"get_index\",\n {\n $data_provider: input.stream.dataProvider.getAddress(),\n $stream_id: input.stream.streamId.getId(),\n $from: input.from,\n $to: input.to,\n $frozen_at: input.frozenAt,\n $base_time: input.baseTime,\n }\n );\n return result\n .mapRight((result) =>\n result.map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n })),\n )\n .throw();\n }\n \n // New cache-aware call format\n const stream = inputOrStream as StreamLocator;\n \n // Validate options if provided\n if (options) {\n CacheValidation.validateGetIndexOptions(options);\n CacheValidation.validateTimeRange(options.from, options.to);\n }\n \n const prefix = options?.prefix ? options.prefix : \"\"\n const params: any = {\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $from: options?.from,\n $to: options?.to,\n $frozen_at: options?.frozenAt,\n $base_time: options?.baseTime,\n };\n \n if (options?.useCache !== undefined) {\n params.$use_cache = options.useCache;\n }\n \n const result = await this.kwilClient.call(\n {\n namespace: \"main\",\n name: prefix + \"get_index\",\n inputs: params,\n },\n this.kwilSigner,\n );\n \n if (result.status !== 200) {\n throw new Error(`Failed to get index: ${result.status}`);\n }\n \n const data = (result.data?.result as { event_time: number; value: string }[]).map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n }));\n \n let cache = CacheMetadataParser.extractFromResponse(result);\n \n // Enhance cache metadata with SDK-provided context\n if (cache) {\n cache = {\n ...cache,\n streamId: stream.streamId.getId(),\n dataProvider: stream.dataProvider.getAddress(),\n from: options?.from,\n to: options?.to,\n frozenAt: options?.frozenAt,\n rowsServed: data.length\n };\n }\n \n return {\n data,\n cache: cache || undefined,\n logs: result.data?.logs ? CacheMetadataParser.parseLogsForMetadata(result.data.logs) : undefined\n };\n }\n\n /**\n * Returns the type of the stream\n */\n public async getType(\n stream: StreamLocator,\n ): Promise<StreamType> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.TypeKey);\n\n if (!result) {\n throw new Error(\"Failed to get stream type\");\n }\n\n const type = head(result).unwrapOrElse(() => {\n throw new Error(\n \"Failed to get stream type. Check if the stream is initialized.\",\n );\n });\n\n const validTypes = [StreamType.Primitive, StreamType.Composed];\n\n if (!validTypes.includes(type.value as StreamType)) {\n throw new Error(`Invalid stream type: ${type.value}`);\n }\n\n return type.value as StreamType;\n }\n\n /**\n * Returns the first record of the stream\n * @deprecated Use getFirstRecord(stream, options?) to leverage cache support and future-proof parameter handling.\n */\n public async getFirstRecord(\n input: GetFirstRecordInput,\n ): Promise<StreamRecord | null>;\n public async getFirstRecord(\n stream: StreamLocator,\n options?: GetFirstRecordOptions\n ): Promise<CacheAwareResponse<StreamRecord | null>>;\n public async getFirstRecord(\n inputOrStream: GetFirstRecordInput | StreamLocator,\n options?: GetFirstRecordOptions\n ): Promise<StreamRecord | null | CacheAwareResponse<StreamRecord | null>> {\n // Handle backward compatibility\n if ('stream' in inputOrStream) {\n // Legacy call format\n const input = inputOrStream as GetFirstRecordInput;\n if (!Action._legacyWarnEmitted.getFirstRecord) {\n Action._legacyWarnEmitted.getFirstRecord = true;\n if (typeof console !== 'undefined' && console.warn) {\n console.warn('[TN SDK] Deprecated signature: getFirstRecord(input). Use getFirstRecord(stream, options?) instead.');\n }\n }\n const result = await this.call<{ event_time: number; value: string }[]>(\n \"get_first_record\",\n {\n $data_provider: input.stream.dataProvider.getAddress(),\n $stream_id: input.stream.streamId.getId(),\n $after: input.after,\n $frozen_at: input.frozenAt,\n }\n );\n\n return result\n .mapRight(head)\n .mapRight((result) =>\n result\n .map((result) => ({\n eventTime: result.event_time,\n value: result.value,\n }))\n .unwrapOr(null),\n )\n .throw();\n }\n \n // New cache-aware call format\n const stream = inputOrStream as StreamLocator;\n \n // Validate options if provided\n if (options) {\n CacheValidation.validateGetFirstRecordOptions(options);\n }\n \n const params: any = {\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $after: options?.after,\n $frozen_at: options?.frozenAt,\n };\n \n if (options?.useCache !== undefined) {\n params.$use_cache = options.useCache;\n }\n \n const result = await this.kwilClient.call(\n {\n namespace: \"main\",\n name: \"get_first_record\",\n inputs: params,\n },\n this.kwilSigner,\n );\n \n if (result.status !== 200) {\n throw new Error(`Failed to get first record: ${result.status}`);\n }\n \n const rawData = result.data?.result as { event_time: number; value: string }[];\n const data = rawData && rawData.length > 0 ? {\n eventTime: rawData[0].event_time,\n value: rawData[0].value,\n } : null;\n \n let cache = CacheMetadataParser.extractFromResponse(result);\n \n // Enhance cache metadata with SDK-provided context\n if (cache) {\n cache = {\n ...cache,\n streamId: stream.streamId.getId(),\n dataProvider: stream.dataProvider.getAddress(),\n frozenAt: options?.frozenAt,\n rowsServed: data ? 1 : 0\n };\n }\n \n return {\n data,\n cache: cache || undefined,\n logs: result.data?.logs ? CacheMetadataParser.parseLogsForMetadata(result.data.logs) : undefined\n };\n }\n\n protected async setMetadata<K extends MetadataKey>(\n stream: StreamLocator,\n key: K,\n value: MetadataValueTypeForKey<K>,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await this.executeWithNamedParams(\"insert_metadata\", [{\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $key: key,\n $value: value,\n $val_type: MetadataKeyValueMap[key],\n },\n ]);\n }\n\n protected async getMetadata<K extends MetadataKey>(\n stream: StreamLocator,\n key: K,\n // onlyLatest: boolean = true,\n filteredRef?: string,\n limit?: number,\n offset?: number,\n orderBy?: string,\n ): Promise<\n { rowId: string; value: MetadataValueTypeForKey<K>; createdAt: number }[]\n > {\n const result = await this.call<\n {\n row_id: string;\n value_i: number;\n value_f: string;\n value_b: boolean;\n value_s: string;\n value_ref: string;\n created_at: number;\n }[]\n >(\"get_metadata\", {\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $key: key,\n $ref: filteredRef,\n $limit: limit,\n $offset: offset,\n $order_by: orderBy,\n },\n );\n return result\n .mapRight((result) =>\n result.map((row) => ({\n rowId: row.row_id,\n value: row[\n MetadataTableKey[MetadataKeyValueMap[key as MetadataKey]]\n ] as MetadataValueTypeForKey<K>,\n createdAt: row.created_at,\n })),\n )\n .throw();\n }\n\n public async listMetadataByHeight<K extends MetadataKey>(\n params: ListMetadataByHeightParams = {},\n ): Promise<MetadataQueryResult[]> {\n type MetadataRawResult = {\n stream_id: string;\n data_provider: string;\n row_id: string;\n value_i: number | null;\n value_f: string | null;\n value_b: boolean | null;\n value_s: string | null;\n value_ref: string | null;\n created_at: number;\n }[];\n const result = await this.call<MetadataRawResult>(\n \"list_metadata_by_height\",\n {\n $key: params.key ?? \"\",\n $ref: params.value ?? null,\n $from_height: params.fromHeight ?? null,\n $to_height: params.toHeight ?? null,\n $limit: params.limit ?? null,\n $offset: params.offset ?? null,\n },\n );\n\n return result\n .mapRight((records) => \n records.map(record => ({\n streamId: record.stream_id,\n dataProvider: record.data_provider,\n rowId: record.row_id,\n valueInt: record.value_i,\n valueFloat: record.value_f,\n valueBoolean: record.value_b,\n valueString: record.value_s,\n valueRef: record.value_ref,\n createdAt: record.created_at,\n }))\n )\n .throw();\n }\n\n /**\n * Sets the read visibility of the stream\n */\n public async setReadVisibility(\n stream: StreamLocator,\n visibility: VisibilityEnum,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await this.setMetadata(\n stream,\n MetadataKey.ReadVisibilityKey,\n visibility.toString(),\n );\n }\n\n /**\n * Returns the read visibility of the stream\n */\n public async getReadVisibility(\n stream: StreamLocator,\n ): Promise<VisibilityEnum | null> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.ReadVisibilityKey);\n\n return head(result)\n .map((row) => toVisibilityEnum(row.value))\n .unwrapOr(null);\n }\n\n /**\n * Sets the compose visibility of the stream\n */\n public async setComposeVisibility(\n stream: StreamLocator,\n visibility: VisibilityEnum,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await this.setMetadata(\n stream,\n MetadataKey.ComposeVisibilityKey,\n visibility.toString(),\n );\n }\n\n /**\n * Returns the compose visibility of the stream\n */\n public async getComposeVisibility(\n stream: StreamLocator,\n ): Promise<VisibilityEnum | null> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.ComposeVisibilityKey);\n\n return head(result)\n .map((row) => toVisibilityEnum(row.value))\n .unwrapOr(null);\n }\n\n /**\n * Allows a wallet to read the stream\n */\n public async allowReadWallet(\n stream: StreamLocator,\n wallet: EthereumAddress,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await this.setMetadata(\n stream,\n MetadataKey.AllowReadWalletKey,\n wallet.getAddress(),\n );\n }\n\n /**\n * Disables a wallet from reading the stream\n */\n public async disableReadWallet(\n stream: StreamLocator,\n wallet: EthereumAddress,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.AllowReadWalletKey,\n wallet.getAddress(),\n );\n\n const row_id = head(result)\n .map((row) => row.rowId)\n .unwrapOr(null);\n\n if (!row_id) {\n throw new Error(\"Wallet not found in allowed list\");\n }\n\n return await this.disableMetadata(stream, row_id);\n }\n\n /**\n * Allows a stream to use this stream as child\n */\n public async allowComposeStream(\n stream: StreamLocator,\n wallet: StreamLocator,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await this.setMetadata(\n stream,\n MetadataKey.AllowComposeStreamKey,\n wallet.streamId.getId(),\n );\n }\n\n /**\n * Disables a stream from using this stream as child\n */\n public async disableComposeStream(\n stream: StreamLocator,\n wallet: StreamLocator,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.AllowComposeStreamKey,\n wallet.toString(),\n );\n\n const row_id = head(result)\n .map((row) => row.rowId)\n .unwrapOr(null);\n\n if (!row_id) {\n throw new Error(\"Stream not found in allowed list\");\n }\n\n return await this.disableMetadata(stream, row_id);\n }\n\n protected async disableMetadata(\n stream: StreamLocator,\n rowId: string,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await this.executeWithNamedParams(\"disable_metadata\", [{\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $row_id: rowId,\n }]);\n }\n\n /**\n * Returns the wallets allowed to read the stream\n */\n public async getAllowedReadWallets(\n stream: StreamLocator,\n ): Promise<EthereumAddress[]> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.AllowReadWalletKey);\n\n return result\n .filter((row) => row.value)\n .map((row) => new EthereumAddress(row.value));\n }\n\n /**\n * Returns the streams allowed to compose the stream\n */\n public async getAllowedComposeStreams(\n stream: StreamLocator,\n ): Promise<StreamLocator[]> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.AllowComposeStreamKey);\n\n return result\n .filter((row) => row.value)\n .map((row) => {\n const [streamId, dataProvider] = row.value.split(\":\");\n return {\n streamId: StreamId.fromString(streamId).throw(),\n dataProvider: new EthereumAddress(dataProvider),\n };\n });\n }\n\n /**\n * Returns the index change of the stream within the given date range\n * @deprecated Use getIndexChange(stream, options) to leverage cache support and future-proof parameter handling.\n */\n public async getIndexChange(\n input: GetIndexChangeInput,\n ): Promise<StreamRecord[]>;\n public async getIndexChange(\n stream: StreamLocator,\n options: GetIndexChangeOptions\n ): Promise<CacheAwareResponse<StreamRecord[]>>;\n public async getIndexChange(\n inputOrStream: GetIndexChangeInput | StreamLocator,\n options?: GetIndexChangeOptions\n ): Promise<StreamRecord[] | CacheAwareResponse<StreamRecord[]>> {\n // Handle backward compatibility\n if ('stream' in inputOrStream) {\n // Legacy call format\n const input = inputOrStream as GetIndexChangeInput;\n if (!Action._legacyWarnEmitted.getIndexChange) {\n Action._legacyWarnEmitted.getIndexChange = true;\n if (typeof console !== 'undefined' && console.warn) {\n console.warn('[TN SDK] Deprecated signature: getIndexChange(input). Use getIndexChange(stream, options?) instead.');\n }\n }\n const result = await this.call<{ event_time: number; value: string }[]>(\n \"get_index_change\", \n {\n $data_provider: input.stream.dataProvider.getAddress(),\n $stream_id: input.stream.streamId.getId(),\n $from: input.from,\n $to: input.to,\n $frozen_at: input.frozenAt,\n $base_time: input.baseTime,\n $time_interval: input.timeInterval,\n }\n );\n\n return result\n .mapRight((result) =>\n result.map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n })),\n )\n .throw();\n }\n \n // New cache-aware call format\n const stream = inputOrStream as StreamLocator;\n if (!options) {\n throw new Error('Options parameter is required for cache-aware getIndexChange');\n }\n \n // Validate options\n CacheValidation.validateGetIndexChangeOptions(options);\n CacheValidation.validateTimeRange(options.from, options.to);\n \n const params: any = {\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $from: options.from,\n $to: options.to,\n $frozen_at: options.frozenAt,\n $base_time: options.baseTime,\n $time_interval: options.timeInterval,\n };\n \n if (options.useCache !== undefined) {\n params.$use_cache = options.useCache;\n }\n \n const result = await this.kwilClient.call(\n {\n namespace: \"main\",\n name: \"get_index_change\",\n inputs: params,\n },\n this.kwilSigner,\n );\n \n if (result.status !== 200) {\n throw new Error(`Failed to get index change: ${result.status}`);\n }\n \n const data = (result.data?.result as { event_time: number; value: string }[]).map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n }));\n \n let cache = CacheMetadataParser.extractFromResponse(result);\n \n // Enhance cache metadata with SDK-provided context\n if (cache) {\n cache = {\n ...cache,\n streamId: stream.streamId.getId(),\n dataProvider: stream.dataProvider.getAddress(),\n from: options.from,\n to: options.to,\n frozenAt: options.frozenAt,\n rowsServed: data.length\n };\n }\n \n return {\n data,\n cache: cache || undefined,\n logs: result.data?.logs ? CacheMetadataParser.parseLogsForMetadata(result.data.logs) : undefined\n };\n }\n\n /**\n * A custom method that accepts the procedure name and the input of GetRecordInput\n * Returns the result of the procedure in the same format as StreamRecord\n * I.e. a custom procedure named \"get_price\" that returns a list of date_value and value\n * can be called with customGetProcedure(\"get_price\", { dateFrom: \"2021-01-01\", dateTo: \"2021-01-31\" })\n */\n public async customGetProcedure(\n procedure: string,\n input: GetRecordInput,\n ): Promise<StreamRecord[]> {\n const result = await this.call<{ event_time: number; value: string }[]>(\n procedure,\n {\n $data_provider: input.stream.dataProvider.getAddress(),\n $stream_id: input.stream.streamId.getId(),\n $from: input.from,\n $to: input.to,\n $frozen_at: input.frozenAt\n }\n );\n return result\n .mapRight((result) =>\n result.map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n })),\n )\n .throw();\n }\n\n\n /**\n * A custom method that accepts the procedure name and custom input of type Record<string, any>\n * Returns the result of the procedure in the same format as StreamRecord\n * I.e. a custom procedure named \"get_custom_index\" that returns a list of date_value and value\n * can be called with customProcedureWithArgs(\"get_custom_index\", { $customArg1: \"value1\", $customArg2: \"value2\" })\n * where $customArg1 and $customArg2 are the arguments of the procedure\n * @param procedure\n * @param args\n */\n public async customProcedureWithArgs(\n procedure: string,\n args: Record<string, Types.ValueType | Types.ValueType[]>,\n ){\n const result = await this.call<{ event_time: number; value: string }[]>(\n procedure,\n args\n );\n return result\n .mapRight((result) =>\n result.map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n })),\n )\n .throw();\n }\n\n /**\n * Returns the size of database\n */\n public async getDatabaseSize(): Promise<BigInt> {\n const result = await this.call<{ database_size: BigInt }[]>(\"get_database_size_v2\", {})\n return result\n .map((rows) => {\n const raw = rows[0].database_size;\n const asBigInt = BigInt(raw.toString());\n return asBigInt;\n }).throw();\n }\n\n /**\n * Returns the size of database in human-readable format (e.g., \"22 GB\", \"1.5 TB\")\n */\n public async getDatabaseSizePretty(): Promise<string> {\n const result = await this.call<{ database_size_pretty: string }[]>(\"get_database_size_v2_pretty\", {})\n return result\n .map((rows) => rows[0].database_size_pretty)\n .throw();\n }\n\n /**\n * Gets the wallet balance on any supported blockchain network\n * @param chain The chain identifier (e.g., \"sepolia\", \"mainnet\", \"polygon\", etc.)\n * @param walletAddress The wallet address to check balance for\n * @returns Promise that resolves to the balance as a string, or throws on error\n */\n public async getWalletBalance(\n chain: string,\n walletAddress: string\n ): Promise<string> {\n const result = await this.call<{ balance?: string; }[]>(\n `${chain}_wallet_balance`,\n {\n $wallet_address: walletAddress,\n }\n );\n\n return result\n .mapRight((rows) => {\n if (rows.length === 0) {\n throw new Error(\"You don't have necessary permissions to execute this query\");\n }\n \n const row = rows[0];\n \n if (row.balance === undefined) {\n throw new Error(\"No balance returned from wallet balance query\");\n }\n \n return row.balance;\n })\n .throw();\n }\n\n /**\n * Calls the whoami action to get the caller's wallet address\n * This is useful for verifying wallet authentication with TN\n * @returns Promise that resolves to the caller's wallet address\n */\n public async whoami(): Promise<string> {\n const result = await this.call<{ caller: string }[]>(\n \"whoami\",\n {}\n );\n\n return result\n .mapRight((rows) => {\n if (rows.length === 0) {\n throw new Error(\"No response from whoami action\");\n }\n \n const row = rows[0];\n \n if (!row.caller) {\n throw new Error(\"No caller address returned from whoami\");\n }\n \n return row.caller;\n })\n .throw();\n }\n\n /**\n * Bridges tokens on a blockchain network\n * @param chain The chain identifier (e.g., \"sepolia\", \"mainnet\", \"polygon\", etc.)\n * @param amount The amount to bridge\n * @returns Promise that resolves to GenericResponse<TxReceipt>\n */\n public async bridgeTokens(\n chain: string,\n amount: string,\n recipient: string\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n // Validate amount is greater than 0\n const numAmount = parseFloat(amount);\n if (isNaN(numAmount) || numAmount <= 0) {\n throw new Error(`Invalid amount: ${amount}. Amount must be greater than 0.`);\n }\n\n return await this.executeWithNamedParams(`${chain}_bridge_tokens`, [{\n $recipient: recipient,\n $amount: amount\n }]);\n }\n\n /**\n * Lists wallet rewards on a blockchain network\n * @param chain The chain identifier (e.g., \"sepolia\", \"mainnet\", \"polygon\", etc.)\n * @param wallet The wallet address to list rewards for\n * @param withPending Whether to include pending rewards\n * @returns Promise that resolves to the rewards data\n */\n public async listWalletRewards(\n chain: string,\n wallet: string,\n withPending: boolean\n ): Promise<any[]> {\n const result = await this.kwilClient.call(\n {\n namespace: `${chain}_bridge`,\n name: \"list_wallet_rewards\",\n inputs: {\n $param_1: wallet,\n $param_2: withPending,\n },\n },\n this.kwilSigner,\n );\n\n if (result.status !== 200) {\n throw new Error(`Failed to list wallet rewards: ${result.status}`);\n }\n\n return result.data?.result || [];\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAAuB;AAIvB,6BAAgC;AAChC,kBAAqB;AACrB,sBAAyB;AACzB,wBAAiD;AACjD,iCAAoC;AACpC,6BAAgC;AAChC,4BAMO;AAsDA,IAAM,SAAN,MAAM,QAAO;AAAA,EACR;AAAA,EACA;AAAA;AAAA,EAEV,OAAe,qBAA8C;AAAA,IAC3D,WAAW;AAAA,IACX,UAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,EAClB;AAAA,EACA,YACE,YACA,YACA;AACA,SAAK,aAAa;AAClB,SAAK,aAAa;AAAA,EACpB;AAAA;AAA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M,IAAI,MAAM,wCAAwC;AAAA,MAC1D;AAEA,aAAO,IAAI;AAAA,IACb,CAAC,EACA,MAAM;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAa,aACX,OACA,QACA,WACiD;AAEjD,UAAM,YAAY,WAAW,MAAM;AACnC,QAAI,MAAM,SAAS,KAAK,aAAa,GAAG;AACtC,YAAM,IAAI,MAAM,mBAAmB,MAAM,kCAAkC;AAAA,IAC7E;AAEA,WAAO,MAAM,KAAK,uBAAuB,GAAG,KAAK,kBAAkB,CAAC;AAAA,MAClE,YAAY;AAAA,MACZ,SAAS;AAAA,IACX,CAAC,CAAC;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAa,kBACX,OACA,QACA,aACgB;AAChB,UAAM,SAAS,MAAM,KAAK,WAAW;AAAA,MACnC;AAAA,QACE,WAAW,GAAG,KAAK;AAAA,QACnB,MAAM;AAAA,QACN,QAAQ;AAAA,UACN,UAAU;AAAA,UACV,UAAU;AAAA,QACZ;AAAA,MACF;AAAA,MACA,KAAK;AAAA,IACP;AAEA,QAAI,OAAO,WAAW,KAAK;AACzB,YAAM,IAAI,MAAM,kCAAkC,OAAO,MAAM,EAAE;AAAA,IACnE;AAEA,WAAO,OAAO,MAAM,UAAU,CAAC;AAAA,EACjC;AACF;",
4
+ "sourcesContent": ["import {KwilSigner, NodeKwil, WebKwil, Types} from \"@trufnetwork/kwil-js\";\nimport { Either } from \"monads-io\";\nimport { DateString } from \"../types/other\";\nimport { StreamLocator } from \"../types/stream\";\nimport { CacheAwareResponse, GetRecordOptions, GetIndexOptions, GetIndexChangeOptions, GetFirstRecordOptions } from \"../types/cache\";\nimport { EthereumAddress } from \"../util/EthereumAddress\";\nimport { head } from \"../util/head\";\nimport { StreamId } from \"../util/StreamId\";\nimport { toVisibilityEnum, VisibilityEnum } from \"../util/visibility\";\nimport { CacheMetadataParser } from \"../util/cacheMetadataParser\";\nimport { CacheValidation } from \"../util/cacheValidation\";\nimport {\n MetadataKey,\n MetadataKeyValueMap,\n MetadataTableKey,\n MetadataValueTypeForKey,\n StreamType,\n} from \"./contractValues\";\n// ValueType is available as Types.ValueType\n\nexport interface GetRecordInput {\n stream: StreamLocator;\n from?: number;\n to?: number;\n frozenAt?: number;\n baseTime?: DateString | number;\n prefix?: string;\n}\n\nexport interface GetFirstRecordInput {\n stream: StreamLocator;\n after?: number;\n frozenAt?: number;\n}\n\nexport interface StreamRecord {\n eventTime: number;\n value: string;\n}\n\nexport interface GetIndexChangeInput extends GetRecordInput {\n timeInterval: number;\n}\n\nexport interface ListMetadataByHeightParams {\n /** Key reference filter. Default: empty string */\n key?: string;\n /** Value reference filter. Default: null */\n value?: string;\n /** Start height (inclusive). If null, uses earliest available. */\n fromHeight?: number;\n /** End height (inclusive). If null, uses current height. */\n toHeight?: number;\n /** Maximum number of results to return. Default: 1000 */\n limit?: number;\n /** Number of results to skip for pagination. Default: 0 */\n offset?: number;\n}\n\nexport interface MetadataQueryResult {\n streamId: string;\n dataProvider: string;\n rowId: string;\n valueInt: number | null;\n valueFloat: string | null;\n valueBoolean: boolean | null;\n valueString: string | null;\n valueRef: string | null;\n createdAt: number;\n}\n\nexport class Action {\n protected kwilClient: WebKwil | NodeKwil;\n protected kwilSigner: KwilSigner;\n /** Track if deprecation warnings were already emitted */\n private static _legacyWarnEmitted: Record<string, boolean> = {\n getRecord: false,\n getIndex: false,\n getFirstRecord: false,\n getIndexChange: false,\n };\n constructor(\n kwilClient: WebKwil | NodeKwil,\n kwilSigner: KwilSigner,\n ) {\n this.kwilClient = kwilClient;\n this.kwilSigner = kwilSigner;\n }\n\n /**\n * Executes a stream method with named parameters\n * @param method - The action name to execute\n * @param inputs - Named parameters for the action\n * @param types - Optional type specifications for parameters (e.g., NUMERIC)\n * @returns Transaction receipt\n */\n protected async executeWithNamedParams(\n method: string,\n inputs: Types.NamedParams[],\n types?: Record<string, any>,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return this.kwilClient.execute({\n namespace: \"main\",\n name: method,\n inputs,\n types,\n description: `TN SDK - Executing method on stream: ${method}`,\n },\n this.kwilSigner,\n );\n }\n\n /**\n * Executes a stream action with a complete ActionBody\n * @param inputs - Complete action body with all execution parameters\n * @param synchronous - Whether to wait for transaction to be mined\n * @returns Transaction receipt\n */\n protected async executeWithActionBody(\n inputs: Types.ActionBody,\n synchronous: boolean = false,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return this.kwilClient.execute(inputs, this.kwilSigner, synchronous);\n }\n\n /**\n * Calls a method on the stream\n */\n protected async call<T>(\n method: string,\n inputs: Types.NamedParams,\n ): Promise<Either<number, T>> {\n const result = await this.kwilClient.call(\n {\n namespace: \"main\",\n name: method,\n inputs: inputs,\n },\n this.kwilSigner,\n );\n\n if (result.status !== 200) {\n return Either.left(result.status);\n }\n\n return Either.right(result.data?.result as T);\n }\n\n /**\n * @deprecated Use getRecord(stream, options?) to leverage cache support and future-proof parameter handling.\n */\n public async getRecord(input: GetRecordInput): Promise<StreamRecord[]>;\n public async getRecord(stream: StreamLocator, options?: GetRecordOptions): Promise<CacheAwareResponse<StreamRecord[]>>;\n public async getRecord(\n inputOrStream: GetRecordInput | StreamLocator,\n options?: GetRecordOptions\n ): Promise<StreamRecord[] | CacheAwareResponse<StreamRecord[]>> {\n // Handle backward compatibility\n if ('stream' in inputOrStream) {\n // Legacy call format\n const input = inputOrStream as GetRecordInput;\n // emit deprecation warning once\n if (!Action._legacyWarnEmitted.getRecord) {\n Action._legacyWarnEmitted.getRecord = true;\n if (typeof console !== 'undefined' && console.warn) {\n console.warn('[TN SDK] Deprecated signature: getRecord(input). Use getRecord(stream, options?) instead.');\n }\n }\n const prefix = input.prefix ? input.prefix : \"\"\n const result = await this.call<{ event_time: number; value: string }[]>(\n prefix + \"get_record\",\n {\n $data_provider: input.stream.dataProvider.getAddress(),\n $stream_id: input.stream.streamId.getId(),\n $from: input.from,\n $to: input.to,\n $frozen_at: input.frozenAt,\n }\n );\n return result\n .mapRight((result) =>\n result.map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n })),\n )\n .throw();\n }\n \n // New cache-aware call format\n const stream = inputOrStream as StreamLocator;\n \n // Validate options if provided\n if (options) {\n CacheValidation.validateGetRecordOptions(options);\n CacheValidation.validateTimeRange(options.from, options.to);\n }\n \n const prefix = options?.prefix ? options.prefix : \"\"\n const params: any = {\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $from: options?.from,\n $to: options?.to,\n $frozen_at: options?.frozenAt,\n };\n \n if (options?.useCache !== undefined) {\n params.$use_cache = options.useCache;\n }\n \n const result = await this.kwilClient.call(\n {\n namespace: \"main\",\n name: prefix + \"get_record\",\n inputs: params,\n },\n this.kwilSigner,\n );\n \n if (result.status !== 200) {\n throw new Error(`Failed to get record: ${result.status}`);\n }\n \n const data = (result.data?.result as { event_time: number; value: string }[]).map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n }));\n \n let cache = CacheMetadataParser.extractFromResponse(result);\n \n // Enhance cache metadata with SDK-provided context\n if (cache) {\n cache = {\n ...cache,\n streamId: stream.streamId.getId(),\n dataProvider: stream.dataProvider.getAddress(),\n from: options?.from,\n to: options?.to,\n frozenAt: options?.frozenAt,\n rowsServed: data.length\n };\n }\n \n return {\n data,\n cache: cache || undefined,\n logs: result.data?.logs ? CacheMetadataParser.parseLogsForMetadata(result.data.logs) : undefined,\n };\n }\n\n /**\n * Returns the index of the stream within the given date range\n * @deprecated Use getIndex(stream, options?) to leverage cache support and future-proof parameter handling.\n */\n public async getIndex(input: GetRecordInput): Promise<StreamRecord[]>;\n public async getIndex(stream: StreamLocator, options?: GetIndexOptions): Promise<CacheAwareResponse<StreamRecord[]>>;\n public async getIndex(\n inputOrStream: GetRecordInput | StreamLocator,\n options?: GetIndexOptions\n ): Promise<StreamRecord[] | CacheAwareResponse<StreamRecord[]>> {\n // Handle backward compatibility\n if ('stream' in inputOrStream) {\n // Legacy call format\n const input = inputOrStream as GetRecordInput;\n if (!Action._legacyWarnEmitted.getIndex) {\n Action._legacyWarnEmitted.getIndex = true;\n if (typeof console !== 'undefined' && console.warn) {\n console.warn('[TN SDK] Deprecated signature: getIndex(input). Use getIndex(stream, options?) instead.');\n }\n }\n const prefix = input.prefix ? input.prefix : \"\"\n const result = await this.call<{ event_time: number; value: string }[]>(\n prefix + \"get_index\",\n {\n $data_provider: input.stream.dataProvider.getAddress(),\n $stream_id: input.stream.streamId.getId(),\n $from: input.from,\n $to: input.to,\n $frozen_at: input.frozenAt,\n $base_time: input.baseTime,\n }\n );\n return result\n .mapRight((result) =>\n result.map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n })),\n )\n .throw();\n }\n \n // New cache-aware call format\n const stream = inputOrStream as StreamLocator;\n \n // Validate options if provided\n if (options) {\n CacheValidation.validateGetIndexOptions(options);\n CacheValidation.validateTimeRange(options.from, options.to);\n }\n \n const prefix = options?.prefix ? options.prefix : \"\"\n const params: any = {\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $from: options?.from,\n $to: options?.to,\n $frozen_at: options?.frozenAt,\n $base_time: options?.baseTime,\n };\n \n if (options?.useCache !== undefined) {\n params.$use_cache = options.useCache;\n }\n \n const result = await this.kwilClient.call(\n {\n namespace: \"main\",\n name: prefix + \"get_index\",\n inputs: params,\n },\n this.kwilSigner,\n );\n \n if (result.status !== 200) {\n throw new Error(`Failed to get index: ${result.status}`);\n }\n \n const data = (result.data?.result as { event_time: number; value: string }[]).map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n }));\n \n let cache = CacheMetadataParser.extractFromResponse(result);\n \n // Enhance cache metadata with SDK-provided context\n if (cache) {\n cache = {\n ...cache,\n streamId: stream.streamId.getId(),\n dataProvider: stream.dataProvider.getAddress(),\n from: options?.from,\n to: options?.to,\n frozenAt: options?.frozenAt,\n rowsServed: data.length\n };\n }\n \n return {\n data,\n cache: cache || undefined,\n logs: result.data?.logs ? CacheMetadataParser.parseLogsForMetadata(result.data.logs) : undefined\n };\n }\n\n /**\n * Returns the type of the stream\n */\n public async getType(\n stream: StreamLocator,\n ): Promise<StreamType> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.TypeKey);\n\n if (!result) {\n throw new Error(\"Failed to get stream type\");\n }\n\n const type = head(result).unwrapOrElse(() => {\n throw new Error(\n \"Failed to get stream type. Check if the stream is initialized.\",\n );\n });\n\n const validTypes = [StreamType.Primitive, StreamType.Composed];\n\n if (!validTypes.includes(type.value as StreamType)) {\n throw new Error(`Invalid stream type: ${type.value}`);\n }\n\n return type.value as StreamType;\n }\n\n /**\n * Returns the first record of the stream\n * @deprecated Use getFirstRecord(stream, options?) to leverage cache support and future-proof parameter handling.\n */\n public async getFirstRecord(\n input: GetFirstRecordInput,\n ): Promise<StreamRecord | null>;\n public async getFirstRecord(\n stream: StreamLocator,\n options?: GetFirstRecordOptions\n ): Promise<CacheAwareResponse<StreamRecord | null>>;\n public async getFirstRecord(\n inputOrStream: GetFirstRecordInput | StreamLocator,\n options?: GetFirstRecordOptions\n ): Promise<StreamRecord | null | CacheAwareResponse<StreamRecord | null>> {\n // Handle backward compatibility\n if ('stream' in inputOrStream) {\n // Legacy call format\n const input = inputOrStream as GetFirstRecordInput;\n if (!Action._legacyWarnEmitted.getFirstRecord) {\n Action._legacyWarnEmitted.getFirstRecord = true;\n if (typeof console !== 'undefined' && console.warn) {\n console.warn('[TN SDK] Deprecated signature: getFirstRecord(input). Use getFirstRecord(stream, options?) instead.');\n }\n }\n const result = await this.call<{ event_time: number; value: string }[]>(\n \"get_first_record\",\n {\n $data_provider: input.stream.dataProvider.getAddress(),\n $stream_id: input.stream.streamId.getId(),\n $after: input.after,\n $frozen_at: input.frozenAt,\n }\n );\n\n return result\n .mapRight(head)\n .mapRight((result) =>\n result\n .map((result) => ({\n eventTime: result.event_time,\n value: result.value,\n }))\n .unwrapOr(null),\n )\n .throw();\n }\n \n // New cache-aware call format\n const stream = inputOrStream as StreamLocator;\n \n // Validate options if provided\n if (options) {\n CacheValidation.validateGetFirstRecordOptions(options);\n }\n \n const params: any = {\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $after: options?.after,\n $frozen_at: options?.frozenAt,\n };\n \n if (options?.useCache !== undefined) {\n params.$use_cache = options.useCache;\n }\n \n const result = await this.kwilClient.call(\n {\n namespace: \"main\",\n name: \"get_first_record\",\n inputs: params,\n },\n this.kwilSigner,\n );\n \n if (result.status !== 200) {\n throw new Error(`Failed to get first record: ${result.status}`);\n }\n \n const rawData = result.data?.result as { event_time: number; value: string }[];\n const data = rawData && rawData.length > 0 ? {\n eventTime: rawData[0].event_time,\n value: rawData[0].value,\n } : null;\n \n let cache = CacheMetadataParser.extractFromResponse(result);\n \n // Enhance cache metadata with SDK-provided context\n if (cache) {\n cache = {\n ...cache,\n streamId: stream.streamId.getId(),\n dataProvider: stream.dataProvider.getAddress(),\n frozenAt: options?.frozenAt,\n rowsServed: data ? 1 : 0\n };\n }\n \n return {\n data,\n cache: cache || undefined,\n logs: result.data?.logs ? CacheMetadataParser.parseLogsForMetadata(result.data.logs) : undefined\n };\n }\n\n protected async setMetadata<K extends MetadataKey>(\n stream: StreamLocator,\n key: K,\n value: MetadataValueTypeForKey<K>,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await this.executeWithNamedParams(\"insert_metadata\", [{\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $key: key,\n $value: value,\n $val_type: MetadataKeyValueMap[key],\n },\n ]);\n }\n\n protected async getMetadata<K extends MetadataKey>(\n stream: StreamLocator,\n key: K,\n // onlyLatest: boolean = true,\n filteredRef?: string,\n limit?: number,\n offset?: number,\n orderBy?: string,\n ): Promise<\n { rowId: string; value: MetadataValueTypeForKey<K>; createdAt: number }[]\n > {\n const result = await this.call<\n {\n row_id: string;\n value_i: number;\n value_f: string;\n value_b: boolean;\n value_s: string;\n value_ref: string;\n created_at: number;\n }[]\n >(\"get_metadata\", {\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $key: key,\n $ref: filteredRef,\n $limit: limit,\n $offset: offset,\n $order_by: orderBy,\n },\n );\n return result\n .mapRight((result) =>\n result.map((row) => ({\n rowId: row.row_id,\n value: row[\n MetadataTableKey[MetadataKeyValueMap[key as MetadataKey]]\n ] as MetadataValueTypeForKey<K>,\n createdAt: row.created_at,\n })),\n )\n .throw();\n }\n\n public async listMetadataByHeight<K extends MetadataKey>(\n params: ListMetadataByHeightParams = {},\n ): Promise<MetadataQueryResult[]> {\n type MetadataRawResult = {\n stream_id: string;\n data_provider: string;\n row_id: string;\n value_i: number | null;\n value_f: string | null;\n value_b: boolean | null;\n value_s: string | null;\n value_ref: string | null;\n created_at: number;\n }[];\n const result = await this.call<MetadataRawResult>(\n \"list_metadata_by_height\",\n {\n $key: params.key ?? \"\",\n $ref: params.value ?? null,\n $from_height: params.fromHeight ?? null,\n $to_height: params.toHeight ?? null,\n $limit: params.limit ?? null,\n $offset: params.offset ?? null,\n },\n );\n\n return result\n .mapRight((records) => \n records.map(record => ({\n streamId: record.stream_id,\n dataProvider: record.data_provider,\n rowId: record.row_id,\n valueInt: record.value_i,\n valueFloat: record.value_f,\n valueBoolean: record.value_b,\n valueString: record.value_s,\n valueRef: record.value_ref,\n createdAt: record.created_at,\n }))\n )\n .throw();\n }\n\n /**\n * Sets the read visibility of the stream\n */\n public async setReadVisibility(\n stream: StreamLocator,\n visibility: VisibilityEnum,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await this.setMetadata(\n stream,\n MetadataKey.ReadVisibilityKey,\n visibility.toString(),\n );\n }\n\n /**\n * Returns the read visibility of the stream\n */\n public async getReadVisibility(\n stream: StreamLocator,\n ): Promise<VisibilityEnum | null> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.ReadVisibilityKey);\n\n return head(result)\n .map((row) => toVisibilityEnum(row.value))\n .unwrapOr(null);\n }\n\n /**\n * Sets the compose visibility of the stream\n */\n public async setComposeVisibility(\n stream: StreamLocator,\n visibility: VisibilityEnum,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await this.setMetadata(\n stream,\n MetadataKey.ComposeVisibilityKey,\n visibility.toString(),\n );\n }\n\n /**\n * Returns the compose visibility of the stream\n */\n public async getComposeVisibility(\n stream: StreamLocator,\n ): Promise<VisibilityEnum | null> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.ComposeVisibilityKey);\n\n return head(result)\n .map((row) => toVisibilityEnum(row.value))\n .unwrapOr(null);\n }\n\n /**\n * Allows a wallet to read the stream\n */\n public async allowReadWallet(\n stream: StreamLocator,\n wallet: EthereumAddress,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await this.setMetadata(\n stream,\n MetadataKey.AllowReadWalletKey,\n wallet.getAddress(),\n );\n }\n\n /**\n * Disables a wallet from reading the stream\n */\n public async disableReadWallet(\n stream: StreamLocator,\n wallet: EthereumAddress,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.AllowReadWalletKey,\n wallet.getAddress(),\n );\n\n const row_id = head(result)\n .map((row) => row.rowId)\n .unwrapOr(null);\n\n if (!row_id) {\n throw new Error(\"Wallet not found in allowed list\");\n }\n\n return await this.disableMetadata(stream, row_id);\n }\n\n /**\n * Allows a stream to use this stream as child\n */\n public async allowComposeStream(\n stream: StreamLocator,\n wallet: StreamLocator,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await this.setMetadata(\n stream,\n MetadataKey.AllowComposeStreamKey,\n wallet.streamId.getId(),\n );\n }\n\n /**\n * Disables a stream from using this stream as child\n */\n public async disableComposeStream(\n stream: StreamLocator,\n wallet: StreamLocator,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.AllowComposeStreamKey,\n wallet.toString(),\n );\n\n const row_id = head(result)\n .map((row) => row.rowId)\n .unwrapOr(null);\n\n if (!row_id) {\n throw new Error(\"Stream not found in allowed list\");\n }\n\n return await this.disableMetadata(stream, row_id);\n }\n\n protected async disableMetadata(\n stream: StreamLocator,\n rowId: string,\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n return await this.executeWithNamedParams(\"disable_metadata\", [{\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $row_id: rowId,\n }]);\n }\n\n /**\n * Returns the wallets allowed to read the stream\n */\n public async getAllowedReadWallets(\n stream: StreamLocator,\n ): Promise<EthereumAddress[]> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.AllowReadWalletKey);\n\n return result\n .filter((row) => row.value)\n .map((row) => new EthereumAddress(row.value));\n }\n\n /**\n * Returns the streams allowed to compose the stream\n */\n public async getAllowedComposeStreams(\n stream: StreamLocator,\n ): Promise<StreamLocator[]> {\n const result = await this.getMetadata(\n stream,\n MetadataKey.AllowComposeStreamKey);\n\n return result\n .filter((row) => row.value)\n .map((row) => {\n const [streamId, dataProvider] = row.value.split(\":\");\n return {\n streamId: StreamId.fromString(streamId).throw(),\n dataProvider: new EthereumAddress(dataProvider),\n };\n });\n }\n\n /**\n * Returns the index change of the stream within the given date range\n * @deprecated Use getIndexChange(stream, options) to leverage cache support and future-proof parameter handling.\n */\n public async getIndexChange(\n input: GetIndexChangeInput,\n ): Promise<StreamRecord[]>;\n public async getIndexChange(\n stream: StreamLocator,\n options: GetIndexChangeOptions\n ): Promise<CacheAwareResponse<StreamRecord[]>>;\n public async getIndexChange(\n inputOrStream: GetIndexChangeInput | StreamLocator,\n options?: GetIndexChangeOptions\n ): Promise<StreamRecord[] | CacheAwareResponse<StreamRecord[]>> {\n // Handle backward compatibility\n if ('stream' in inputOrStream) {\n // Legacy call format\n const input = inputOrStream as GetIndexChangeInput;\n if (!Action._legacyWarnEmitted.getIndexChange) {\n Action._legacyWarnEmitted.getIndexChange = true;\n if (typeof console !== 'undefined' && console.warn) {\n console.warn('[TN SDK] Deprecated signature: getIndexChange(input). Use getIndexChange(stream, options?) instead.');\n }\n }\n const result = await this.call<{ event_time: number; value: string }[]>(\n \"get_index_change\", \n {\n $data_provider: input.stream.dataProvider.getAddress(),\n $stream_id: input.stream.streamId.getId(),\n $from: input.from,\n $to: input.to,\n $frozen_at: input.frozenAt,\n $base_time: input.baseTime,\n $time_interval: input.timeInterval,\n }\n );\n\n return result\n .mapRight((result) =>\n result.map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n })),\n )\n .throw();\n }\n \n // New cache-aware call format\n const stream = inputOrStream as StreamLocator;\n if (!options) {\n throw new Error('Options parameter is required for cache-aware getIndexChange');\n }\n \n // Validate options\n CacheValidation.validateGetIndexChangeOptions(options);\n CacheValidation.validateTimeRange(options.from, options.to);\n \n const params: any = {\n $data_provider: stream.dataProvider.getAddress(),\n $stream_id: stream.streamId.getId(),\n $from: options.from,\n $to: options.to,\n $frozen_at: options.frozenAt,\n $base_time: options.baseTime,\n $time_interval: options.timeInterval,\n };\n \n if (options.useCache !== undefined) {\n params.$use_cache = options.useCache;\n }\n \n const result = await this.kwilClient.call(\n {\n namespace: \"main\",\n name: \"get_index_change\",\n inputs: params,\n },\n this.kwilSigner,\n );\n \n if (result.status !== 200) {\n throw new Error(`Failed to get index change: ${result.status}`);\n }\n \n const data = (result.data?.result as { event_time: number; value: string }[]).map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n }));\n \n let cache = CacheMetadataParser.extractFromResponse(result);\n \n // Enhance cache metadata with SDK-provided context\n if (cache) {\n cache = {\n ...cache,\n streamId: stream.streamId.getId(),\n dataProvider: stream.dataProvider.getAddress(),\n from: options.from,\n to: options.to,\n frozenAt: options.frozenAt,\n rowsServed: data.length\n };\n }\n \n return {\n data,\n cache: cache || undefined,\n logs: result.data?.logs ? CacheMetadataParser.parseLogsForMetadata(result.data.logs) : undefined\n };\n }\n\n /**\n * A custom method that accepts the procedure name and the input of GetRecordInput\n * Returns the result of the procedure in the same format as StreamRecord\n * I.e. a custom procedure named \"get_price\" that returns a list of date_value and value\n * can be called with customGetProcedure(\"get_price\", { dateFrom: \"2021-01-01\", dateTo: \"2021-01-31\" })\n */\n public async customGetProcedure(\n procedure: string,\n input: GetRecordInput,\n ): Promise<StreamRecord[]> {\n const result = await this.call<{ event_time: number; value: string }[]>(\n procedure,\n {\n $data_provider: input.stream.dataProvider.getAddress(),\n $stream_id: input.stream.streamId.getId(),\n $from: input.from,\n $to: input.to,\n $frozen_at: input.frozenAt\n }\n );\n return result\n .mapRight((result) =>\n result.map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n })),\n )\n .throw();\n }\n\n\n /**\n * A custom method that accepts the procedure name and custom input of type Record<string, any>\n * Returns the result of the procedure in the same format as StreamRecord\n * I.e. a custom procedure named \"get_custom_index\" that returns a list of date_value and value\n * can be called with customProcedureWithArgs(\"get_custom_index\", { $customArg1: \"value1\", $customArg2: \"value2\" })\n * where $customArg1 and $customArg2 are the arguments of the procedure\n * @param procedure\n * @param args\n */\n public async customProcedureWithArgs(\n procedure: string,\n args: Record<string, Types.ValueType | Types.ValueType[]>,\n ){\n const result = await this.call<{ event_time: number; value: string }[]>(\n procedure,\n args\n );\n return result\n .mapRight((result) =>\n result.map((row) => ({\n eventTime: row.event_time,\n value: row.value,\n })),\n )\n .throw();\n }\n\n /**\n * Returns the size of database\n */\n public async getDatabaseSize(): Promise<BigInt> {\n const result = await this.call<{ database_size: BigInt }[]>(\"get_database_size_v2\", {})\n return result\n .map((rows) => {\n const raw = rows[0].database_size;\n const asBigInt = BigInt(raw.toString());\n return asBigInt;\n }).throw();\n }\n\n /**\n * Returns the size of database in human-readable format (e.g., \"22 GB\", \"1.5 TB\")\n */\n public async getDatabaseSizePretty(): Promise<string> {\n const result = await this.call<{ database_size_pretty: string }[]>(\"get_database_size_v2_pretty\", {})\n return result\n .map((rows) => rows[0].database_size_pretty)\n .throw();\n }\n\n /**\n * Gets the wallet balance on any supported blockchain network\n * @param chain The chain identifier (e.g., \"sepolia\", \"mainnet\", \"polygon\", etc.)\n * @param walletAddress The wallet address to check balance for\n * @returns Promise that resolves to the balance as a string, or throws on error\n */\n public async getWalletBalance(\n chain: string,\n walletAddress: string\n ): Promise<string> {\n const result = await this.call<{ balance?: string; }[]>(\n `${chain}_wallet_balance`,\n {\n $wallet_address: walletAddress,\n }\n );\n\n return result\n .mapRight((rows) => {\n if (rows.length === 0) {\n throw new Error(\"You don't have necessary permissions to execute this query\");\n }\n \n const row = rows[0];\n \n if (row.balance === undefined) {\n throw new Error(\"No balance returned from wallet balance query\");\n }\n \n return row.balance;\n })\n .throw();\n }\n\n /**\n * Calls the whoami action to get the caller's wallet address\n * This is useful for verifying wallet authentication with TN\n * @returns Promise that resolves to the caller's wallet address\n */\n public async whoami(): Promise<string> {\n const result = await this.call<{ caller: string }[]>(\n \"whoami\",\n {}\n );\n\n return result\n .mapRight((rows) => {\n if (rows.length === 0) {\n throw new Error(\"No response from whoami action\");\n }\n \n const row = rows[0];\n \n if (!row.caller) {\n throw new Error(\"No caller address returned from whoami\");\n }\n \n return row.caller;\n })\n .throw();\n }\n\n /**\n * Bridges tokens on a blockchain network\n * @param chain The chain identifier (e.g., \"sepolia\", \"mainnet\", \"polygon\", etc.)\n * @param amount The amount to bridge\n * @returns Promise that resolves to GenericResponse<TxReceipt>\n */\n public async bridgeTokens(\n chain: string,\n amount: string,\n recipient: string\n ): Promise<Types.GenericResponse<Types.TxReceipt>> {\n // Validate amount is greater than 0\n const numAmount = parseFloat(amount);\n if (isNaN(numAmount) || numAmount <= 0) {\n throw new Error(`Invalid amount: ${amount}. Amount must be greater than 0.`);\n }\n\n return await this.executeWithNamedParams(`${chain}_bridge_tokens`, [{\n $recipient: recipient,\n $amount: amount\n }]);\n }\n\n /**\n * Lists wallet rewards on a blockchain network\n * @param chain The chain identifier (e.g., \"sepolia\", \"mainnet\", \"polygon\", etc.)\n * @param wallet The wallet address to list rewards for\n * @param withPending Whether to include pending rewards\n * @returns Promise that resolves to the rewards data\n */\n public async listWalletRewards(\n chain: string,\n wallet: string,\n withPending: boolean\n ): Promise<any[]> {\n const result = await this.kwilClient.call(\n {\n namespace: `${chain}_bridge`,\n name: \"list_wallet_rewards\",\n inputs: {\n $param_1: wallet,\n $param_2: withPending,\n },\n },\n this.kwilSigner,\n );\n\n if (result.status !== 200) {\n throw new Error(`Failed to list wallet rewards: ${result.status}`);\n }\n\n return result.data?.result || [];\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAAuB;AAIvB,6BAAgC;AAChC,kBAAqB;AACrB,sBAAyB;AACzB,wBAAiD;AACjD,iCAAoC;AACpC,6BAAgC;AAChC,4BAMO;AAsDA,IAAM,SAAN,MAAM,QAAO;AAAA,EACR;AAAA,EACA;AAAA;AAAA,EAEV,OAAe,qBAA8C;AAAA,IAC3D,WAAW;AAAA,IACX,UAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,gBAAgB;AAAA,EAClB;AAAA,EACA,YACE,YACA,YACA;AACA,SAAK,aAAa;AAClB,SAAK,aAAa;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAgB,uBACd,QACA,QACA,OACiD;AACjD,WAAO,KAAK,WAAW;AAAA,MAAQ;AAAA,QACzB,WAAW;AAAA,QACX,MAAM;AAAA,QACN;AAAA,QACA;AAAA,QACA,aAAa,wCAAwC,MAAM;AAAA,MAC7D;AAAA,MACA,KAAK;AAAA,IACL;AAAA,EACN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAgB,sBACd,QACA,cAAuB,OAC0B;AACjD,WAAO,KAAK,WAAW,QAAQ,QAAQ,KAAK,YAAY,WAAW;AAAA,EACrE;AAAA;AAAA;AAAA;AAAA,EAKA,MAAgB,KACd,QACA,QAC4B;AAC5B,UAAM,SAAS,MAAM,KAAK,WAAW;AAAA,MACnC;AAAA,QACE,WAAW;AAAA,QACX,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B;AAChB,UAAM,SAAS,MAAM,KAAK,WAAW;AAAA,MACnC;AAAA,QACE,WAAW,GAAG,KAAK;AAAA,QACnB,MAAM;AAAA,QACN,QAAQ;AAAA,UACN,UAAU;AAAA,UACV,UAAU;AAAA,QACZ;AAAA,MACF;AAAA,MACA,KAAK;AAAA,IACP;AAEA,QAAI,OAAO,WAAW,KAAK;AACzB,YAAM,IAAI,MAAM,kCAAkC,OAAO,MAAM,EAAE;AAAA,IACnE;AAEA,WAAO,OAAO,MAAM,UAAU,CAAC;AAAA,EACjC;AACF;",
6
6
  "names": ["prefix", "result"]
7
7
  }
@@ -23,6 +23,7 @@ __export(attestationAction_exports, {
23
23
  AttestationAction: () => AttestationAction
24
24
  });
25
25
  module.exports = __toCommonJS(attestationAction_exports);
26
+ var import_kwil_js = require("@trufnetwork/kwil-js");
26
27
  var import_action = require("./action.cjs");
27
28
  var import_attestation = require("../types/attestation.cjs");
28
29
  var import_AttestationEncoding = require("../util/AttestationEncoding.cjs");
@@ -68,9 +69,12 @@ var AttestationAction = class extends import_action.Action {
68
69
  $action_name: input.actionName,
69
70
  $args_bytes: argsBytes,
70
71
  $encrypt_sig: input.encryptSig,
71
- $max_fee: input.maxFee
72
+ $max_fee: input.maxFee.toString()
72
73
  }];
73
- const result = await this.executeWithNamedParams("request_attestation", params);
74
+ const types = {
75
+ $max_fee: import_kwil_js.Utils.DataType.Numeric(78, 0)
76
+ };
77
+ const result = await this.executeWithNamedParams("request_attestation", params, types);
74
78
  if (!result.data?.tx_hash) {
75
79
  throw new Error(
76
80
  "Failed to request attestation: no transaction hash returned"
@@ -179,7 +183,7 @@ var AttestationAction = class extends import_action.Action {
179
183
  const limit = input.limit ?? 5e3;
180
184
  const offset = input.offset ?? 0;
181
185
  const params = {
182
- $requester: input.requester ?? null,
186
+ $requester: input.requester ?? new Uint8Array(0),
183
187
  $limit: limit,
184
188
  $offset: offset,
185
189
  $order_by: input.orderBy ?? null
@@ -190,7 +194,8 @@ var AttestationAction = class extends import_action.Action {
190
194
  `Failed to list attestations: HTTP status ${result.value}`
191
195
  );
192
196
  }
193
- const rows = result.value;
197
+ const rightValue = typeof result.value === "function" ? result.value() : result.value;
198
+ const rows = Array.isArray(rightValue) ? rightValue : [];
194
199
  if (!rows || rows.length === 0) {
195
200
  return [];
196
201
  }