@trufnetwork/sdk-js 0.4.2 → 0.4.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.
- package/README.md +91 -2
- package/dist/cjs/client/client.cjs +4 -0
- package/dist/cjs/client/client.cjs.map +2 -2
- package/dist/cjs/contracts-api/action.cjs +26 -0
- package/dist/cjs/contracts-api/action.cjs.map +2 -2
- package/dist/cjs/index.common.cjs.map +1 -1
- package/dist/esm/client/client.mjs +4 -0
- package/dist/esm/client/client.mjs.map +2 -2
- package/dist/esm/contracts-api/action.mjs +26 -0
- package/dist/esm/contracts-api/action.mjs.map +2 -2
- package/dist/esm/index.common.mjs.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/client/client.d.ts +2 -1
- package/dist/types/client/client.d.ts.map +1 -1
- package/dist/types/contracts-api/action.d.ts +26 -0
- package/dist/types/contracts-api/action.d.ts.map +1 -1
- package/dist/types/index.common.d.ts +1 -1
- package/dist/types/index.common.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -55,7 +55,7 @@ const client = new NodeTNClient({
|
|
|
55
55
|
address: wallet.address,
|
|
56
56
|
signer: wallet, // Any object that implements signMessage
|
|
57
57
|
},
|
|
58
|
-
chainId: "tn-v2", // or use NodeTNClient.getDefaultChainId(endpoint)
|
|
58
|
+
chainId: "tn-v2.1", // or use NodeTNClient.getDefaultChainId(endpoint)
|
|
59
59
|
});
|
|
60
60
|
```
|
|
61
61
|
|
|
@@ -162,6 +162,17 @@ await composedAction.setTaxonomy({
|
|
|
162
162
|
],
|
|
163
163
|
startDate: Math.floor(Date.now() / 1000), // When this taxonomy becomes effective
|
|
164
164
|
});
|
|
165
|
+
|
|
166
|
+
// Get taxonomy information for the composed stream
|
|
167
|
+
const taxonomies = await composedAction.getTaxonomiesForStreams({
|
|
168
|
+
streams: [client.ownStreamLocator(parentStreamId)],
|
|
169
|
+
latestOnly: true
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
console.log("Current taxonomy:");
|
|
173
|
+
taxonomies.forEach(taxonomy => {
|
|
174
|
+
console.log(`Child: ${taxonomy.childStreamId.getId()}, Weight: ${taxonomy.weight}`);
|
|
175
|
+
});
|
|
165
176
|
```
|
|
166
177
|
|
|
167
178
|
#### Stream Visibility and Permissions
|
|
@@ -189,6 +200,55 @@ await streamAction.allowReadWallet(
|
|
|
189
200
|
- Weights in composed streams must sum to 1.0.
|
|
190
201
|
- Streams can be made public or private, with fine-grained access control.
|
|
191
202
|
|
|
203
|
+
### Transaction Lifecycle and Best Practices ⚠️
|
|
204
|
+
|
|
205
|
+
**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.
|
|
206
|
+
|
|
207
|
+
> 💡 **See Complete Example**: For a comprehensive demonstration of transaction lifecycle patterns, see [`examples/transaction-lifecycle-example/index.ts`](./examples/transaction-lifecycle-example/index.ts)
|
|
208
|
+
|
|
209
|
+
#### The Race Condition Problem
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
212
|
+
// ❌ DANGEROUS - Race condition possible
|
|
213
|
+
const deployResult = await client.deployStream(streamId, StreamType.Primitive);
|
|
214
|
+
// Stream might not be ready yet!
|
|
215
|
+
await primitiveAction.insertRecord({ stream: client.ownStreamLocator(streamId), ... }); // Could fail
|
|
216
|
+
|
|
217
|
+
const destroyResult = await client.destroyStream(client.ownStreamLocator(streamId));
|
|
218
|
+
// Stream might not be destroyed yet!
|
|
219
|
+
await primitiveAction.insertRecord({ stream: client.ownStreamLocator(streamId), ... }); // Could succeed unexpectedly
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
#### Solution: Use waitForTx (Recommended for Critical Operations)
|
|
223
|
+
|
|
224
|
+
```typescript
|
|
225
|
+
// ✅ SAFE - Explicit transaction confirmation
|
|
226
|
+
const deployResult = await client.deployStream(streamId, StreamType.Primitive);
|
|
227
|
+
if (!deployResult.data) {
|
|
228
|
+
throw new Error('Deploy failed');
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Wait for deployment to complete
|
|
232
|
+
await client.waitForTx(deployResult.data.tx_hash);
|
|
233
|
+
|
|
234
|
+
// Now safe to proceed
|
|
235
|
+
await primitiveAction.insertRecord({
|
|
236
|
+
stream: client.ownStreamLocator(streamId),
|
|
237
|
+
eventTime: Math.floor(Date.now() / 1000),
|
|
238
|
+
value: "100.50"
|
|
239
|
+
});
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
#### When to Use Synchronous Patterns:
|
|
243
|
+
- ✅ **Stream deployment before data insertion**
|
|
244
|
+
- ✅ **Stream deletion before cleanup verification**
|
|
245
|
+
- ✅ **Sequential operations with dependencies**
|
|
246
|
+
- ✅ **Testing and development scenarios**
|
|
247
|
+
|
|
248
|
+
#### When Async is Acceptable:
|
|
249
|
+
- ⚡ **High-throughput data insertion** (independent records)
|
|
250
|
+
- ⚡ **Fire-and-forget operations** (with proper error handling)
|
|
251
|
+
|
|
192
252
|
### Using the SDK with Your Local Node
|
|
193
253
|
|
|
194
254
|
If you are running your own TRUF.NETWORK node, you can configure the SDK to interact with your local instance by changing the `endpoint` in the client configuration, as shown in the [Basic Client Initialization](#basic-client-initialization) section. This is useful for development, testing, or when operating within a private network.
|
|
@@ -263,6 +323,35 @@ module.exports = {
|
|
|
263
323
|
|
|
264
324
|
For other bundlers or serverless platforms, consult their documentation on module aliasing or replacement.
|
|
265
325
|
|
|
326
|
+
## Quick Reference
|
|
327
|
+
|
|
328
|
+
### Common Operations
|
|
329
|
+
|
|
330
|
+
| Operation | Method |
|
|
331
|
+
|-----------|--------|
|
|
332
|
+
| Deploy primitive stream | `client.deployStream(streamId, StreamType.Primitive)` |
|
|
333
|
+
| Deploy composed stream | `client.deployStream(streamId, StreamType.Composed)` |
|
|
334
|
+
| Insert records | `primitiveAction.insertRecord({stream, eventTime, value})` |
|
|
335
|
+
| Get stream data | `streamAction.getRecord({stream, from, to})` |
|
|
336
|
+
| Set stream taxonomy | `composedAction.setTaxonomy({stream, taxonomyItems, startDate})` |
|
|
337
|
+
| Get stream taxonomy | `composedAction.getTaxonomiesForStreams({streams, latestOnly})` |
|
|
338
|
+
| Destroy stream | `client.destroyStream(streamLocator)` |
|
|
339
|
+
|
|
340
|
+
**Safe Operation Pattern:**
|
|
341
|
+
```typescript
|
|
342
|
+
const result = await client.deployStream(streamId, StreamType.Primitive);
|
|
343
|
+
if (!result.data) throw new Error('Deploy failed');
|
|
344
|
+
await client.waitForTx(result.data.tx_hash); // Wait for confirmation
|
|
345
|
+
// Now safe to proceed with dependent operations
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
### Key Types
|
|
349
|
+
|
|
350
|
+
- `StreamType.Primitive` - Raw data streams
|
|
351
|
+
- `StreamType.Composed` - Aggregated streams with taxonomy
|
|
352
|
+
- `StreamLocator` - Stream identifier with data provider
|
|
353
|
+
- `TaxonomyQueryResult` - Taxonomy information with weights
|
|
354
|
+
|
|
266
355
|
## Further Resources & Next Steps
|
|
267
356
|
|
|
268
357
|
To continue learning and building with the TN SDK, explore the following resources:
|
|
@@ -271,7 +360,7 @@ To continue learning and building with the TN SDK, explore the following resourc
|
|
|
271
360
|
- [Getting Started Guide](./docs/getting-started.md): A detailed walkthrough for setting up and making your first interactions with the SDK.
|
|
272
361
|
- [Core Concepts Explained](./docs/core-concepts.md): Understand the fundamental building blocks of the TRUF.NETWORK and the SDK.
|
|
273
362
|
- **Detailed Documentation**:
|
|
274
|
-
- [API Reference](./docs/api-reference.md): Comprehensive details on all SDK classes, methods, types, and parameters.
|
|
363
|
+
- [API Reference](./docs/api-reference.md): Comprehensive details on all SDK classes, methods, types, and parameters including taxonomy operations.
|
|
275
364
|
- **Examples & Demos**:
|
|
276
365
|
- [Local Examples Directory](./examples)
|
|
277
366
|
- **Whitepaper**:
|
|
@@ -217,6 +217,10 @@ var BaseTNClient = class {
|
|
|
217
217
|
const composedAction = this.loadComposedAction();
|
|
218
218
|
return composedAction.listTaxonomiesByHeight(params);
|
|
219
219
|
}
|
|
220
|
+
async listMetadataByHeight(params = {}) {
|
|
221
|
+
const action = this.loadAction();
|
|
222
|
+
return action.listMetadataByHeight(params);
|
|
223
|
+
}
|
|
220
224
|
/**
|
|
221
225
|
* Gets taxonomies for specific streams in batch.
|
|
222
226
|
* High-level wrapper for ComposedAction.getTaxonomiesForStreams()
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/client/client.ts"],
|
|
4
|
-
"sourcesContent": ["import { Client, KwilSigner, NodeKwil, WebKwil } from \"@trufnetwork/kwil-js\";\nimport { KwilConfig } from \"@trufnetwork/kwil-js/dist/api_client/config\";\nimport { Kwil } from \"@trufnetwork/kwil-js/dist/client/kwil\";\nimport { EthSigner } from \"@trufnetwork/kwil-js/dist/core/signature\";\nimport { EnvironmentType } from \"@trufnetwork/kwil-js/dist/core/enums\";\nimport { GenericResponse } from \"@trufnetwork/kwil-js/dist/core/resreq\";\nimport { TxReceipt } from \"@trufnetwork/kwil-js/dist/core/tx\";\nimport { TxInfoReceipt } from \"@trufnetwork/kwil-js/dist/core/txQuery\";\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 } 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 { 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: EthSigner;\n}\n\nexport type TNClientOptions = {\n endpoint: string;\n signerInfo: SignerInfo;\n} & Omit<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: 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<TxInfoReceipt> {\n return new Promise<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(): 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<GenericResponse<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<GenericResponse<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 * 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 /**\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,qBAAsD;AAQtD,4BAAiH;AACjH,0BAA6B;AAC7B,0BAA6B;AAC7B,6BAAgC;AAChC,
|
|
4
|
+
"sourcesContent": ["import { Client, KwilSigner, NodeKwil, WebKwil } from \"@trufnetwork/kwil-js\";\nimport { KwilConfig } from \"@trufnetwork/kwil-js/dist/api_client/config\";\nimport { Kwil } from \"@trufnetwork/kwil-js/dist/client/kwil\";\nimport { EthSigner } from \"@trufnetwork/kwil-js/dist/core/signature\";\nimport { EnvironmentType } from \"@trufnetwork/kwil-js/dist/core/enums\";\nimport { GenericResponse } from \"@trufnetwork/kwil-js/dist/core/resreq\";\nimport { TxReceipt } from \"@trufnetwork/kwil-js/dist/core/tx\";\nimport { TxInfoReceipt } from \"@trufnetwork/kwil-js/dist/core/txQuery\";\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 { 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: EthSigner;\n}\n\nexport type TNClientOptions = {\n endpoint: string;\n signerInfo: SignerInfo;\n} & Omit<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: 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<TxInfoReceipt> {\n return new Promise<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(): 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<GenericResponse<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<GenericResponse<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 * 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 /**\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,qBAAsD;AAQtD,4BAAiH;AACjH,0BAA6B;AAC7B,0BAA6B;AAC7B,6BAAgC;AAChC,oBAAwE;AAGxE,6BAAgC;AAEhC,yBAA4B;AAC5B,iCAAoC;AACpC,4BAA+B;AA+BxB,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,MAA+B;AACvE,WAAO,IAAI,QAAuB,OAAO,SAAS,WAAW;AAC3D,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,gBACI,IAAI;AAAA,k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AM,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
|
}
|
|
@@ -360,6 +360,32 @@ var Action = class _Action {
|
|
|
360
360
|
}))
|
|
361
361
|
).throw();
|
|
362
362
|
}
|
|
363
|
+
async listMetadataByHeight(params = {}) {
|
|
364
|
+
const result = await this.call(
|
|
365
|
+
"list_metadata_by_height",
|
|
366
|
+
{
|
|
367
|
+
$key: params.key ?? "",
|
|
368
|
+
$ref: params.value ?? null,
|
|
369
|
+
$from_height: params.fromHeight ?? null,
|
|
370
|
+
$to_height: params.toHeight ?? null,
|
|
371
|
+
$limit: params.limit ?? null,
|
|
372
|
+
$offset: params.offset ?? null
|
|
373
|
+
}
|
|
374
|
+
);
|
|
375
|
+
return result.mapRight(
|
|
376
|
+
(records) => records.map((record) => ({
|
|
377
|
+
streamId: record.stream_id,
|
|
378
|
+
dataProvider: record.data_provider,
|
|
379
|
+
rowId: record.row_id,
|
|
380
|
+
valueInt: record.value_i,
|
|
381
|
+
valueFloat: record.value_f,
|
|
382
|
+
valueBoolean: record.value_b,
|
|
383
|
+
valueString: record.value_s,
|
|
384
|
+
valueRef: record.value_ref,
|
|
385
|
+
createdAt: record.created_at
|
|
386
|
+
}))
|
|
387
|
+
).throw();
|
|
388
|
+
}
|
|
363
389
|
/**
|
|
364
390
|
* Sets the read visibility of the stream
|
|
365
391
|
*/
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/contracts-api/action.ts"],
|
|
4
|
-
"sourcesContent": ["import {KwilSigner, NodeKwil, WebKwil} from \"@trufnetwork/kwil-js\";\nimport { ActionBody } from '@trufnetwork/kwil-js/dist/core/action';\nimport {NamedParams} from \"@trufnetwork/kwil-js/dist/core/action\";\nimport { GenericResponse } from \"@trufnetwork/kwil-js/dist/core/resreq\";\nimport { TxReceipt } from \"@trufnetwork/kwil-js/dist/core/tx\";\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\";\nimport {ValueType} from \"@trufnetwork/kwil-js/dist/utils/types\";\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 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 method on the stream\n */\n protected async executeWithNamedParams(\n method: string,\n inputs: NamedParams[],\n ): Promise<GenericResponse<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 method on the stream\n */\n protected async executeWithActionBody(\n inputs: ActionBody,\n synchronous: boolean = false,\n ): Promise<GenericResponse<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: 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<GenericResponse<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 /**\n * Sets the read visibility of the stream\n */\n public async setReadVisibility(\n stream: StreamLocator,\n visibility: VisibilityEnum,\n ): Promise<GenericResponse<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<GenericResponse<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<GenericResponse<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<GenericResponse<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<GenericResponse<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<GenericResponse<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<GenericResponse<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, ValueType | 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\", {})\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"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,uBAAuB;AAIvB,6BAAgC;AAChC,kBAAqB;AACrB,sBAAyB;AACzB,wBAAiD;AACjD,iCAAoC;AACpC,6BAAgC;AAChC,4BAMO;AA2BA,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,EAKA,MAAgB,uBACd,QACA,QACqC;AACrC,WAAO,KAAK,WAAW;AAAA,MAAQ;AAAA,QACzB,WAAW;AAAA,QACX,MAAM;AAAA,QACN;AAAA,QACA,aAAa,wCAAwC,MAAM;AAAA,MAC7D;AAAA,MACA,KAAK;AAAA,IACL;AAAA,EACN;AAAA;AAAA;AAAA;AAAA,EAKE,MAAgB,sBACZ,QACA,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AAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAa,wBACX,WACA,MACD;AACG,UAAM,SAAS,MAAM,KAAK;AAAA,MACtB;AAAA,MACA;AAAA,IACN;AACA,WAAO,OACJ;AAAA,MAAS,CAACA,YACTA,QAAO,IAAI,CAAC,SAAS;AAAA,QACnB,WAAW,IAAI;AAAA,QACf,OAAO,IAAI;AAAA,MACb,EAAE;AAAA,IACJ,EACC,MAAM;AAAA,EACX;AAAA;AAAA;AAAA;AAAA,EAKA,MAAa,kBAAmC;AAC9C,UAAM,SAAS,MAAM,KAAK,KAAkC,qBAAqB,CAAC,CAAC;AACnF,WAAO,OACJ,IAAI,CAAC,SAAS;AACb,YAAM,MAAM,KAAK,CAAC,EAAE;AACpB,YAAM,WAAW,OAAO,IAAI,SAAS,CAAC;AACtC,aAAO;AAAA,IACT,CAAC,EAAE,MAAM;AAAA,EACb;AACF;",
|
|
4
|
+
"sourcesContent": ["import {KwilSigner, NodeKwil, WebKwil} from \"@trufnetwork/kwil-js\";\nimport { ActionBody } from '@trufnetwork/kwil-js/dist/core/action';\nimport {NamedParams} from \"@trufnetwork/kwil-js/dist/core/action\";\nimport { GenericResponse } from \"@trufnetwork/kwil-js/dist/core/resreq\";\nimport { TxReceipt } from \"@trufnetwork/kwil-js/dist/core/tx\";\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\";\nimport {ValueType} from \"@trufnetwork/kwil-js/dist/utils/types\";\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 method on the stream\n */\n protected async executeWithNamedParams(\n method: string,\n inputs: NamedParams[],\n ): Promise<GenericResponse<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 method on the stream\n */\n protected async executeWithActionBody(\n inputs: ActionBody,\n synchronous: boolean = false,\n ): Promise<GenericResponse<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: 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<GenericResponse<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<GenericResponse<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<GenericResponse<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<GenericResponse<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<GenericResponse<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<GenericResponse<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<GenericResponse<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<GenericResponse<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, ValueType | 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\", {})\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"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,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,EAKA,MAAgB,uBACd,QACA,QACqC;AACrC,WAAO,KAAK,WAAW;AAAA,MAAQ;AAAA,QACzB,WAAW;AAAA,QACX,MAAM;AAAA,QACN;A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,MAAM,KAAK,CAAC,EAAE;AACpB,YAAM,WAAW,OAAO,IAAI,SAAS,CAAC;AACtC,aAAO;AAAA,IACT,CAAC,EAAE,MAAM;AAAA,EACb;AACF;",
|
|
6
6
|
"names": ["prefix", "result"]
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/index.common.ts"],
|
|
4
|
-
"sourcesContent": ["// Core client types\nexport type { TNClientOptions } from \"./client/client\";\nexport type { SignerInfo as EthProvider } from \"./client/client\";\n\n// Stream types and interfaces\nexport type { StreamLocator } from \"./types/stream\";\nexport type { StreamRecord } from \"./contracts-api/action\";\nexport type { GetRecordInput, GetFirstRecordInput } from \"./contracts-api/action\";\nexport type { InsertRecordInput } from \"./contracts-api/primitiveAction\";\nexport type { TaxonomySet, TaxonomyItem, ListTaxonomiesByHeightParams, GetTaxonomiesForStreamsParams, TaxonomyQueryResult } from \"./contracts-api/composedAction\";\n\n// Utility types and classes\nexport { StreamId } from \"./util/StreamId\";\nexport { EthereumAddress } from \"./util/EthereumAddress\";\nexport { visibility } from \"./util/visibility\";\nexport type { VisibilityEnum } from \"./util/visibility\";\n\n// Stream type constants\nexport { StreamType } from \"./contracts-api/contractValues\";\n\n// Base classes\nexport { Action } from \"./contracts-api/action\";\nexport { PrimitiveAction } from \"./contracts-api/primitiveAction\";\nexport { ComposedAction } from \"./contracts-api/composedAction\";\n\n// Role management exports\nexport { RoleManagement } from \"./contracts-api/roleManagement\";\nexport type { GrantRoleInput, RevokeRoleInput, AreMembersOfInput, WalletMembership } from \"./types/role\";\n\n"],
|
|
4
|
+
"sourcesContent": ["// Core client types\nexport type { TNClientOptions } from \"./client/client\";\nexport type { SignerInfo as EthProvider } from \"./client/client\";\n\n// Stream types and interfaces\nexport type { StreamLocator } from \"./types/stream\";\nexport type { StreamRecord, ListMetadataByHeightParams, MetadataQueryResult } from \"./contracts-api/action\";\nexport type { GetRecordInput, GetFirstRecordInput } from \"./contracts-api/action\";\nexport type { InsertRecordInput } from \"./contracts-api/primitiveAction\";\nexport type { TaxonomySet, TaxonomyItem, ListTaxonomiesByHeightParams, GetTaxonomiesForStreamsParams, TaxonomyQueryResult } from \"./contracts-api/composedAction\";\n\n// Utility types and classes\nexport { StreamId } from \"./util/StreamId\";\nexport { EthereumAddress } from \"./util/EthereumAddress\";\nexport { visibility } from \"./util/visibility\";\nexport type { VisibilityEnum } from \"./util/visibility\";\n\n// Stream type constants\nexport { StreamType } from \"./contracts-api/contractValues\";\n\n// Base classes\nexport { Action } from \"./contracts-api/action\";\nexport { PrimitiveAction } from \"./contracts-api/primitiveAction\";\nexport { ComposedAction } from \"./contracts-api/composedAction\";\n\n// Role management exports\nexport { RoleManagement } from \"./contracts-api/roleManagement\";\nexport type { GrantRoleInput, RevokeRoleInput, AreMembersOfInput, WalletMembership } from \"./types/role\";\n\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,sBAAyB;AACzB,6BAAgC;AAChC,wBAA2B;AAI3B,4BAA2B;AAG3B,oBAAuB;AACvB,6BAAgC;AAChC,4BAA+B;AAG/B,4BAA+B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -197,6 +197,10 @@ var BaseTNClient = class {
|
|
|
197
197
|
const composedAction = this.loadComposedAction();
|
|
198
198
|
return composedAction.listTaxonomiesByHeight(params);
|
|
199
199
|
}
|
|
200
|
+
async listMetadataByHeight(params = {}) {
|
|
201
|
+
const action = this.loadAction();
|
|
202
|
+
return action.listMetadataByHeight(params);
|
|
203
|
+
}
|
|
200
204
|
/**
|
|
201
205
|
* Gets taxonomies for specific streams in batch.
|
|
202
206
|
* High-level wrapper for ComposedAction.getTaxonomiesForStreams()
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/client/client.ts"],
|
|
4
|
-
"sourcesContent": ["import { Client, KwilSigner, NodeKwil, WebKwil } from \"@trufnetwork/kwil-js\";\nimport { KwilConfig } from \"@trufnetwork/kwil-js/dist/api_client/config\";\nimport { Kwil } from \"@trufnetwork/kwil-js/dist/client/kwil\";\nimport { EthSigner } from \"@trufnetwork/kwil-js/dist/core/signature\";\nimport { EnvironmentType } from \"@trufnetwork/kwil-js/dist/core/enums\";\nimport { GenericResponse } from \"@trufnetwork/kwil-js/dist/core/resreq\";\nimport { TxReceipt } from \"@trufnetwork/kwil-js/dist/core/tx\";\nimport { TxInfoReceipt } from \"@trufnetwork/kwil-js/dist/core/txQuery\";\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 } 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 { 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: EthSigner;\n}\n\nexport type TNClientOptions = {\n endpoint: string;\n signerInfo: SignerInfo;\n} & Omit<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: 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<TxInfoReceipt> {\n return new Promise<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(): 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<GenericResponse<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<GenericResponse<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 * 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 /**\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,SAAS,QAAQ,kBAAqC;AAQtD,SAAS,sBAAwG;AACjH,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB;AAChC,SAAS,
|
|
4
|
+
"sourcesContent": ["import { Client, KwilSigner, NodeKwil, WebKwil } from \"@trufnetwork/kwil-js\";\nimport { KwilConfig } from \"@trufnetwork/kwil-js/dist/api_client/config\";\nimport { Kwil } from \"@trufnetwork/kwil-js/dist/client/kwil\";\nimport { EthSigner } from \"@trufnetwork/kwil-js/dist/core/signature\";\nimport { EnvironmentType } from \"@trufnetwork/kwil-js/dist/core/enums\";\nimport { GenericResponse } from \"@trufnetwork/kwil-js/dist/core/resreq\";\nimport { TxReceipt } from \"@trufnetwork/kwil-js/dist/core/tx\";\nimport { TxInfoReceipt } from \"@trufnetwork/kwil-js/dist/core/txQuery\";\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 { 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: EthSigner;\n}\n\nexport type TNClientOptions = {\n endpoint: string;\n signerInfo: SignerInfo;\n} & Omit<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: 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<TxInfoReceipt> {\n return new Promise<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(): 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<GenericResponse<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<GenericResponse<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 * 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 /**\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,SAAS,QAAQ,kBAAqC;AAQtD,SAAS,sBAAwG;AACjH,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB;AAChC,SAAS,cAA+D;AAGxE,SAAS,uBAAuB;AAEhC,SAAS,mBAAmB;AAC5B,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;AA+BxB,IAAe,eAAf,MAAuD;AAAA,EAIlD,YAAY,SAA0B;AAHhD,wBAAU;AACV,wBAAU;AAGR,SAAK,aAAa,QAAQ;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,UAAU,QAAgB,UAAU,MAA+B;AACvE,WAAO,IAAI,QAAuB,OAAO,SAAS,WAAW;AAC3D,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,gBACI,IAAI;AAAA,kBACA,8BAA8B,QAAQ,MAAM,kBAAkB,QAAQ,MAAM,UAAU,GAAG;AAAA,gBAC7F;AAAA,cAAC;AAAA,YACP,OAAO;AACL,sBAAQ,QAAQ,IAAK;AAAA,YACvB;AACA;AAAA,UACF,KAAK;AACH;AAAA,UACF;AACE;AAAA,cACE,IAAI;AAAA,gBACF,8BAA8B,QAAQ,MAAM,kBAAkB,QAAQ,MAAM,UAAU,GAAG;AAAA,cAC3F;AAAA,YACF;AAA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ChD,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
|
}
|
|
@@ -338,6 +338,32 @@ var _Action = class _Action {
|
|
|
338
338
|
}))
|
|
339
339
|
).throw();
|
|
340
340
|
}
|
|
341
|
+
async listMetadataByHeight(params = {}) {
|
|
342
|
+
const result = await this.call(
|
|
343
|
+
"list_metadata_by_height",
|
|
344
|
+
{
|
|
345
|
+
$key: params.key ?? "",
|
|
346
|
+
$ref: params.value ?? null,
|
|
347
|
+
$from_height: params.fromHeight ?? null,
|
|
348
|
+
$to_height: params.toHeight ?? null,
|
|
349
|
+
$limit: params.limit ?? null,
|
|
350
|
+
$offset: params.offset ?? null
|
|
351
|
+
}
|
|
352
|
+
);
|
|
353
|
+
return result.mapRight(
|
|
354
|
+
(records) => records.map((record) => ({
|
|
355
|
+
streamId: record.stream_id,
|
|
356
|
+
dataProvider: record.data_provider,
|
|
357
|
+
rowId: record.row_id,
|
|
358
|
+
valueInt: record.value_i,
|
|
359
|
+
valueFloat: record.value_f,
|
|
360
|
+
valueBoolean: record.value_b,
|
|
361
|
+
valueString: record.value_s,
|
|
362
|
+
valueRef: record.value_ref,
|
|
363
|
+
createdAt: record.created_at
|
|
364
|
+
}))
|
|
365
|
+
).throw();
|
|
366
|
+
}
|
|
341
367
|
/**
|
|
342
368
|
* Sets the read visibility of the stream
|
|
343
369
|
*/
|