stxer 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,12 +12,43 @@ yarn add stxer
12
12
 
13
13
  ## Features
14
14
 
15
- ### 1. Batch Operations
15
+ ### 1. Transaction Simulation
16
16
 
17
- The SDK provides efficient batch reading capabilities for Stacks blockchain:
17
+ Simulate complex transaction sequences before executing them on-chain:
18
18
 
19
19
  ```typescript
20
- import { batchRead, batchReadonly } from 'stxer';
20
+ import { SimulationBuilder } from 'stxer';
21
+
22
+ const simulationId = await SimulationBuilder.new({
23
+ network: 'mainnet', // or 'testnet'
24
+ })
25
+ .withSender('ST...') // Set default sender
26
+ .addContractCall({
27
+ contract_id: 'ST...contract-name',
28
+ function_name: 'my-function',
29
+ function_args: [/* clarity values */]
30
+ })
31
+ .addSTXTransfer({
32
+ recipient: 'ST...',
33
+ amount: 1000000 // in microSTX
34
+ })
35
+ .addContractDeploy({
36
+ contract_name: 'my-contract',
37
+ source_code: '(define-public (hello) (ok "world"))'
38
+ })
39
+ .run();
40
+
41
+ // View simulation results at: https://stxer.xyz/simulations/{network}/{simulationId}
42
+ ```
43
+
44
+ ### 2. Batch Operations
45
+
46
+ The SDK provides two approaches for efficient batch reading from the Stacks blockchain:
47
+
48
+ #### Direct Batch Reading
49
+
50
+ ```typescript
51
+ import { batchRead } from 'stxer';
21
52
 
22
53
  // Batch read variables and maps
23
54
  const result = await batchRead({
@@ -29,11 +60,7 @@ const result = await batchRead({
29
60
  contract: contractPrincipalCV(...),
30
61
  mapName: 'my-map',
31
62
  mapKey: someCV
32
- }]
33
- });
34
-
35
- // Batch readonly function calls
36
- const readonlyResult = await batchReadonly({
63
+ }],
37
64
  readonly: [{
38
65
  contract: contractPrincipalCV(...),
39
66
  functionName: 'my-function',
@@ -42,35 +69,114 @@ const readonlyResult = await batchReadonly({
42
69
  });
43
70
  ```
44
71
 
45
- ### 2. Transaction Simulation
72
+ #### BatchProcessor for Queue-based Operations
46
73
 
47
- Simulate complex transaction sequences before executing them on-chain:
74
+ The BatchProcessor allows you to queue multiple read operations and automatically batch them together after a specified delay:
48
75
 
49
76
  ```typescript
50
- import { SimulationBuilder } from 'stxer';
77
+ import { BatchProcessor } from 'stxer';
51
78
 
52
- const simulationId = await SimulationBuilder.new({
53
- network: 'mainnet', // or 'testnet'
54
- })
55
- .withSender('ST...') // Set default sender
56
- .addContractCall({
57
- contract_id: 'ST...contract-name',
58
- function_name: 'my-function',
59
- function_args: [/* clarity values */]
60
- })
61
- .addSTXTransfer({
62
- recipient: 'ST...',
63
- amount: 1000000 // in microSTX
64
- })
65
- .addContractDeploy({
66
- contract_name: 'my-contract',
67
- source_code: '(define-public (hello) (ok "world"))'
79
+ const processor = new BatchProcessor({
80
+ stxerAPIEndpoint: 'https://api.stxer.xyz', // optional
81
+ batchDelayMs: 1000, // delay before processing batch
82
+ });
83
+
84
+ // Queue multiple operations that will be batched together
85
+ const [resultA, resultB] = await Promise.all([
86
+ new Promise((resolve, reject) => {
87
+ processor.enqueue({
88
+ request: {
89
+ mode: 'variable',
90
+ contractAddress: 'SP...',
91
+ contractName: 'my-contract',
92
+ variableName: 'variable-a'
93
+ },
94
+ resolve,
95
+ reject
96
+ });
97
+ }),
98
+ new Promise((resolve, reject) => {
99
+ processor.enqueue({
100
+ request: {
101
+ mode: 'variable',
102
+ contractAddress: 'SP...',
103
+ contractName: 'my-contract',
104
+ variableName: 'variable-b'
105
+ },
106
+ resolve,
107
+ reject
108
+ });
68
109
  })
69
- .run();
110
+ ]);
111
+
112
+ // You can also queue different types of operations
113
+ processor.enqueue({
114
+ request: {
115
+ mode: 'readonly',
116
+ contractAddress: 'SP...',
117
+ contractName: 'my-contract',
118
+ functionName: 'get-value',
119
+ functionArgs: []
120
+ },
121
+ resolve: (value) => console.log('Function result:', value),
122
+ reject: (error) => console.error('Error:', error)
123
+ });
70
124
 
71
- // View simulation results at: https://stxer.xyz/simulations/{network}/{simulationId}
125
+ processor.enqueue({
126
+ request: {
127
+ mode: 'mapEntry',
128
+ contractAddress: 'SP...',
129
+ contractName: 'my-contract',
130
+ mapName: 'my-map',
131
+ mapKey: someKey
132
+ },
133
+ resolve: (value) => console.log('Map entry:', value),
134
+ reject: (error) => console.error('Error:', error)
135
+ });
72
136
  ```
73
137
 
138
+ The BatchProcessor automatically:
139
+ - Queues read operations
140
+ - Batches them together after the specified delay
141
+ - Makes a single API call for all queued operations
142
+ - Distributes results back to the respective promises
143
+
144
+ This is particularly useful when you need to make multiple blockchain reads and want to optimize network calls.
145
+
146
+ ### 3. Clarity API Utilities
147
+
148
+ The SDK provides convenient utilities for reading data from Clarity contracts:
149
+
150
+ ```typescript
151
+ import { callReadonly, readVariable, readMap } from 'stxer';
152
+ import { SIP010TraitABI } from 'clarity-abi/abis';
153
+ import { unwrapResponse } from 'ts-clarity';
154
+
155
+ // Read from a contract function
156
+ const supply = await callReadonly({
157
+ abi: SIP010TraitABI.functions,
158
+ functionName: 'get-total-supply',
159
+ contract: 'SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.token-alex',
160
+ }).then(unwrapResponse);
161
+
162
+ // Read a contract variable
163
+ const paused = await readVariable({
164
+ abi: [{ name: 'paused', type: 'bool', access: 'variable' }],
165
+ variableName: 'paused',
166
+ contract: 'SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-vault-v2-01',
167
+ });
168
+
169
+ // Read from a contract map
170
+ const approved = await readMap({
171
+ abi: [{ key: 'principal', name: 'approved-tokens', value: 'bool' }],
172
+ mapName: 'approved-tokens',
173
+ key: 'SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.token-alex',
174
+ contract: 'SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-vault-v2-01',
175
+ });
176
+ ```
177
+
178
+ These utilities provide type-safe ways to interact with Clarity contracts, with built-in ABI support and response unwrapping.
179
+
74
180
  ## Configuration
75
181
 
76
182
  You can customize the API endpoints:
@@ -1,4 +1,10 @@
1
- import { type ClarityValue, type ContractPrincipalCV, type OptionalCV } from '@stacks/transactions';
1
+ /**
2
+ * WARNING:
3
+ *
4
+ * this file will be used in cross-runtime environments (browser, cloudflare workers, XLinkSDK, etc.),
5
+ * so please be careful when adding `import`s to it.
6
+ */
7
+ import { type ClarityValue, type ContractPrincipalCV } from '@stacks/transactions';
2
8
  export interface BatchReads {
3
9
  variables?: {
4
10
  contract: ContractPrincipalCV;
@@ -9,22 +15,20 @@ export interface BatchReads {
9
15
  mapName: string;
10
16
  mapKey: ClarityValue;
11
17
  }[];
18
+ readonly?: {
19
+ contract: ContractPrincipalCV;
20
+ functionName: string;
21
+ functionArgs: ClarityValue[];
22
+ }[];
12
23
  index_block_hash?: string;
13
24
  }
14
25
  export interface BatchReadsResult {
15
- variables: (ClarityValue | Error)[];
16
- maps: (OptionalCV | Error)[];
26
+ tip: string;
27
+ vars: (ClarityValue | Error)[];
28
+ maps: (ClarityValue | Error)[];
29
+ readonly: (ClarityValue | Error)[];
17
30
  }
18
31
  export interface BatchApiOptions {
19
32
  stxerApi?: string;
20
33
  }
21
34
  export declare function batchRead(reads: BatchReads, options?: BatchApiOptions): Promise<BatchReadsResult>;
22
- export interface BatchReadonlyRequest {
23
- readonly: {
24
- contract: ContractPrincipalCV;
25
- functionName: string;
26
- functionArgs: ClarityValue[];
27
- }[];
28
- index_block_hash?: string;
29
- }
30
- export declare function batchReadonly(req: BatchReadonlyRequest, options?: BatchApiOptions): Promise<(ClarityValue | Error)[]>;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * WARNING:
3
+ *
4
+ * this file will be used in cross-runtime environments (browser, cloudflare workers, XLinkSDK, etc.),
5
+ * so please be careful when adding `import`s to it.
6
+ */
7
+ import { type ClarityValue, type OptionalCV } from '@stacks/transactions';
8
+ export interface ReadOnlyRequest {
9
+ mode: 'readonly';
10
+ contractAddress: string;
11
+ contractName: string;
12
+ functionName: string;
13
+ functionArgs: ClarityValue[];
14
+ }
15
+ export interface MapEntryRequest {
16
+ mode: 'mapEntry';
17
+ contractAddress: string;
18
+ contractName: string;
19
+ mapName: string;
20
+ mapKey: ClarityValue;
21
+ }
22
+ export interface VariableRequest {
23
+ mode: 'variable';
24
+ contractAddress: string;
25
+ contractName: string;
26
+ variableName: string;
27
+ }
28
+ export type BatchRequest = MapEntryRequest | VariableRequest | ReadOnlyRequest;
29
+ export interface QueuedRequest {
30
+ request: BatchRequest;
31
+ tip?: string;
32
+ resolve: (value: ClarityValue | OptionalCV) => void;
33
+ reject: (error: Error) => void;
34
+ }
35
+ export declare class BatchProcessor {
36
+ private queues;
37
+ private timeoutIds;
38
+ private readonly stxerAPIEndpoint;
39
+ private readonly batchDelayMs;
40
+ constructor(options: {
41
+ stxerAPIEndpoint?: string;
42
+ batchDelayMs: number;
43
+ });
44
+ private getQueueKey;
45
+ enqueue(request: QueuedRequest): void;
46
+ private processBatch;
47
+ }
@@ -0,0 +1,27 @@
1
+ import type { ClarityAbiFunction, ClarityAbiMap, ClarityAbiVariable, TContractPrincipal, TPrincipal } from 'clarity-abi';
2
+ import type { InferReadonlyCallParameterType, InferReadonlyCallResultType, InferMapValueType, InferReadMapParameterType, InferReadVariableParameterType, InferVariableType } from 'ts-clarity';
3
+ import { BatchProcessor } from './BatchProcessor';
4
+ export type ReadonlyCallRuntimeOptions = {
5
+ sender?: TPrincipal;
6
+ contract: TContractPrincipal;
7
+ stacksEndpoint?: string;
8
+ indexBlockHash?: string;
9
+ batchProcessor?: BatchProcessor;
10
+ };
11
+ export type ReadMapRuntimeParameters = {
12
+ contract: TContractPrincipal;
13
+ stacksEndpoint?: string;
14
+ proof?: boolean;
15
+ indexBlockHash?: string;
16
+ batchProcessor?: BatchProcessor;
17
+ };
18
+ export type ReadVariableRuntimeParameterType = {
19
+ contract: TContractPrincipal;
20
+ stacksEndpoint?: string;
21
+ proof?: boolean;
22
+ indexBlockHash?: string;
23
+ batchProcessor?: BatchProcessor;
24
+ };
25
+ export declare function callReadonly<Functions extends readonly ClarityAbiFunction[] | readonly unknown[], FunctionName extends string>(params: InferReadonlyCallParameterType<Functions, FunctionName> & ReadonlyCallRuntimeOptions): Promise<InferReadonlyCallResultType<Functions, FunctionName>>;
26
+ export declare function readMap<Maps extends readonly ClarityAbiMap[] | readonly unknown[] = readonly ClarityAbiMap[], MapName extends string = string>(params: InferReadMapParameterType<Maps, MapName> & ReadMapRuntimeParameters): Promise<InferMapValueType<Maps, MapName> | null>;
27
+ export declare function readVariable<Variables extends readonly ClarityAbiVariable[] | readonly unknown[] = readonly ClarityAbiVariable[], VariableName extends string = string>(params: InferReadVariableParameterType<Variables, VariableName> & ReadVariableRuntimeParameterType): Promise<InferVariableType<Variables, VariableName>>;
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- export * from './batch-api';
1
+ export * from './BatchAPI';
2
2
  export * from './simulation';
3
+ export * from './clarity-api';