stxer 0.4.5 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # stxer SDK
2
2
 
3
- A powerful SDK for Stacks blockchain that provides batch operations and transaction simulation capabilities.
3
+ A powerful SDK for Stacks blockchain that provides transaction simulation, batch operations, contract AST parsing, and chain tip information.
4
4
 
5
5
  ## Installation
6
6
 
@@ -12,46 +12,296 @@ yarn add stxer
12
12
 
13
13
  ## Features
14
14
 
15
- ### 1. Transaction Simulation
15
+ ### 1. Transaction Simulation (V2 API)
16
16
 
17
- Simulate complex transaction sequences before executing them on-chain:
17
+ Simulate complex transaction sequences before executing them on-chain. The SDK supports all V2 step types:
18
+
19
+ #### Basic Simulation
18
20
 
19
21
  ```typescript
20
22
  import { SimulationBuilder } from 'stxer';
21
23
 
22
24
  const simulationId = await SimulationBuilder.new({
23
25
  network: 'mainnet', // or 'testnet'
26
+ skipTracing: false, // Set to true for faster simulations without debug info
24
27
  })
25
- .withSender('ST...') // Set default sender
28
+ .useBlockHeight(130818) // Optional: use specific block height
29
+ .withSender('SP...') // Set default sender
26
30
  .addContractCall({
27
- contract_id: 'ST...contract-name',
31
+ contract_id: 'SP...contract-name',
28
32
  function_name: 'my-function',
29
- function_args: [/* clarity values */]
33
+ function_args: [/* clarity values */],
34
+ sender: 'SP...', // Optional: overrides default sender
35
+ fee: 100, // Optional: fee in microSTX
30
36
  })
31
37
  .addSTXTransfer({
32
- recipient: 'ST...',
33
- amount: 1000000 // in microSTX
38
+ recipient: 'SP...',
39
+ amount: 1000000, // in microSTX
34
40
  })
35
41
  .addContractDeploy({
36
42
  contract_name: 'my-contract',
37
- source_code: '(define-public (hello) (ok "world"))'
43
+ source_code: '(define-public (hello) (ok "world"))',
44
+ deployer: 'SP...', // Optional: overrides default sender
45
+ clarity_version: 4, // Optional: Clarity1, Clarity2, Clarity3, or Clarity4
38
46
  })
39
47
  .run();
40
48
 
41
- // View simulation results at: https://stxer.xyz/simulations/{network}/{simulationId}
49
+ // View simulation results at: https://stxer.xyz/simulations/mainnet/{simulationId}
42
50
  ```
43
51
 
44
- ### 2. Batch Operations
52
+ #### Advanced V2 Step Types
53
+
54
+ The SDK supports all V2 simulation step types:
55
+
56
+ ```typescript
57
+ import { SimulationBuilder, ClarityVersion } from 'stxer';
58
+
59
+ const simulationId = await SimulationBuilder.new()
60
+ .withSender('SP...')
61
+
62
+ // === Transaction Steps ===
63
+ // STX Transfer
64
+ .addSTXTransfer({ recipient: 'SP...', amount: 1000 })
65
+
66
+ // Contract Call
67
+ .addContractCall({
68
+ contract_id: 'SP...contract',
69
+ function_name: 'my-function',
70
+ function_args: [boolCV(true), uintCV(123)],
71
+ })
72
+
73
+ // Contract Deploy
74
+ .addContractDeploy({
75
+ contract_name: 'my-contract',
76
+ source_code: '(define-data-var counter uint u0)',
77
+ clarity_version: ClarityVersion.Clarity4,
78
+ })
79
+
80
+ // === Eval Steps ===
81
+ // Read state
82
+ .addEvalCode('SP...contract', '(var-get counter)')
83
+
84
+ // Modify state
85
+ .addEvalCode('SP...contract', '(var-set counter u100)')
86
+
87
+ // === SetContractCode Step ===
88
+ // Directly set contract code without a transaction
89
+ .addSetContractCode({
90
+ contract_id: 'SP...contract',
91
+ source_code: '(define-data-var enabled bool false)',
92
+ clarity_version: ClarityVersion.Clarity4,
93
+ })
94
+
95
+ // === Reads Batch Step ===
96
+ // Batch multiple read operations in a single step
97
+ .addReads([
98
+ { DataVar: ['SP...contract', 'counter'] },
99
+ { DataVar: ['SP...contract', 'enabled'] },
100
+ { StxBalance: 'SP...' },
101
+ { Nonce: 'SP...' },
102
+ { EvalReadonly: ['SP...', '', 'SP...contract', '(get-counter)'] },
103
+ ])
104
+
105
+ // === TenureExtend Step ===
106
+ // Extend tenure (resets execution cost)
107
+ .addTenureExtend()
108
+
109
+ .run();
110
+ ```
111
+
112
+ #### Reads Batch Sub-Types
113
+
114
+ The `Reads` step supports multiple read operation types:
115
+
116
+ ```typescript
117
+ .addReads([
118
+ // Read a data variable
119
+ { DataVar: ['SP...contract', 'my-var'] },
120
+
121
+ // Read a map entry (key must be hex-encoded Clarity value)
122
+ { MapEntry: ['SP...contract', 'my-map', '0x0...'] },
123
+
124
+ // Call a read-only function
125
+ { EvalReadonly: ['SP...', '', 'SP...contract', '(my-function)'] },
126
+
127
+ // Read STX balance
128
+ { StxBalance: 'SP...' },
129
+
130
+ // Read fungible token balance
131
+ { FtBalance: ['SP...token-contract', 'token-name', 'SP...principal'] },
132
+
133
+ // Read fungible token supply
134
+ { FtSupply: ['SP...token-contract', 'token-name'] },
135
+
136
+ // Read account nonce
137
+ { Nonce: 'SP...' },
138
+ ])
139
+ ```
140
+
141
+ ### 2. Programmatic Simulation APIs
142
+
143
+ For advanced use cases where you need more control than `SimulationBuilder` provides, the SDK exposes low-level programmatic APIs that directly map to the stxer V2 simulation endpoints.
144
+
145
+ #### Instant Simulation
146
+
147
+ Simulate a single transaction without creating a session. Useful for apps/wallets to preview transaction results before sending:
148
+
149
+ ```typescript
150
+ import { instantSimulation } from 'stxer';
151
+
152
+ const result = await instantSimulation({
153
+ transaction: '0x...', // Hex-encoded transaction
154
+ reads: [
155
+ { DataVar: ['SP...contract', 'my-var'] },
156
+ { StxBalance: 'SP...' }
157
+ ]
158
+ });
159
+
160
+ console.log(result.receipt.result); // Transaction result
161
+ console.log(result.reads); // Optional read results
162
+ ```
163
+
164
+ #### Session-Based Simulation
165
+
166
+ For more complex scenarios with multiple steps:
167
+
168
+ ```typescript
169
+ import {
170
+ createSimulationSession,
171
+ submitSimulationSteps,
172
+ getSimulationResult,
173
+ simulationBatchReads
174
+ } from 'stxer';
175
+
176
+ // 1. Create a simulation session
177
+ const sessionId = await createSimulationSession({
178
+ skip_tracing: false // Set to true for faster simulations
179
+ });
180
+
181
+ // 2. Submit steps to the session
182
+ const stepResults = await submitSimulationSteps(sessionId, {
183
+ steps: [
184
+ { Transaction: '0x...' },
185
+ { Eval: ['SP...', '', 'SP...contract', '(var-get my-var)'] },
186
+ { SetContractCode: ['SP...contract', '(define-data-var x uint u0)', 4] },
187
+ { Reads: [
188
+ { DataVar: ['SP...contract', 'my-var'] },
189
+ { StxBalance: 'SP...' }
190
+ ]},
191
+ { TenureExtend: [] }
192
+ ]
193
+ });
194
+
195
+ console.log(`Executed ${stepResults.steps.length} steps`);
196
+
197
+ // 3. Get full simulation results
198
+ const result = await getSimulationResult(sessionId);
199
+ console.log(result.metadata);
200
+ console.log(result.steps);
201
+
202
+ // 4. Batch reads from simulation state
203
+ const reads = await simulationBatchReads(sessionId, {
204
+ vars: [['SP...contract', 'my-var']],
205
+ maps: [['SP...contract', 'my-map', '0x...']],
206
+ stx: ['SP...']
207
+ });
208
+ console.log(reads.vars);
209
+ console.log(reads.stx);
210
+ ```
211
+
212
+ #### API Options
213
+
214
+ All programmatic APIs accept an optional `stxerApi` parameter to customize the endpoint:
215
+
216
+ ```typescript
217
+ const sessionId = await createSimulationSession(
218
+ { skip_tracing: true },
219
+ { stxerApi: 'https://testnet-api.stxer.xyz' }
220
+ );
221
+ ```
222
+
223
+ #### TransactionReceipt: failure signals & events
224
+
225
+ When a step lands as `{ Transaction: { Ok: receipt } }`, the engine ran the transaction to completion — but that does **not** mean the contract logic succeeded. There are four failure signals on or around a receipt; check them in this order:
226
+
227
+ | Signal | Where | Meaning |
228
+ |---|---|---|
229
+ | Outer `Err` | `Result.Transaction = { Err: string }` | Engine refused the tx (deserialization, etc.). No receipt is produced. |
230
+ | `post_condition_aborted: true` | on the receipt | Execution ran, a post-condition tripped, state was rolled back. |
231
+ | `vm_error: string` (without PC abort) | on the receipt | Clarity VM raised a runtime error (overflow, unwrap on `none`, etc.) or static analysis failed. |
232
+ | `(err uX)` inside `result` | on the receipt | Contract returned a Clarity error response. Not signalled by any flag — decode `result` to detect (response::err prefix is `08`). |
233
+
234
+ **`post_condition_aborted` and `vm_error` are not independent.** When a post-condition trips, the upstream sets `post_condition_aborted: true` *and* writes the PC abort reason into `vm_error` as a side effect — so `vm_error` is also non-null in that case. The reverse is not true: `vm_error` alone (with `post_condition_aborted: false`) means a VM/runtime/analysis failure that is *not* a PC abort. A clean way to narrow:
235
+
236
+ ```typescript
237
+ if (receipt.post_condition_aborted) {
238
+ // PC abort. receipt.vm_error holds the abort reason.
239
+ } else if (receipt.vm_error != null) {
240
+ // Runtime / analysis failure (not a PC abort).
241
+ } else if (receipt.result.startsWith('08')) {
242
+ // Contract returned (err uX). Decode receipt.result for the value.
243
+ } else {
244
+ // Clean success.
245
+ }
246
+ ```
247
+
248
+ **Events are JSON-encoded strings, not objects.** `receipt.events` is `string[]`; each entry is a JSON-encoded event payload. Call `JSON.parse(receipt.events[i])` to inspect — iterating without parsing yields opaque strings.
249
+
250
+ ```typescript
251
+ for (const ev of receipt.events) {
252
+ const event = JSON.parse(ev) as { type: string; contract_event?: { ... } };
253
+ if (event.type === 'contract_event') { /* handle print/log */ }
254
+ }
255
+ ```
256
+
257
+ ### 3. Get Chain Tip
258
+
259
+ Fetch the current chain tip information:
260
+
261
+ ```typescript
262
+ import { getTip, type SidecarTip } from 'stxer';
263
+
264
+ const tip: SidecarTip = await getTip();
265
+ console.log(`Current block: ${tip.block_height}`);
266
+ console.log(`Block hash: ${tip.block_hash}`);
267
+ console.log(`Bitcoin height: ${tip.bitcoin_height}`);
268
+ console.log(`Tenure cost: ${tip.tenure_cost}`);
269
+ ```
270
+
271
+ ### 4. Contract AST Operations
272
+
273
+ Fetch or parse contract Abstract Syntax Trees:
274
+
275
+ ```typescript
276
+ import { getContractAST, parseContract } from 'stxer';
277
+
278
+ // Fetch on-chain contract AST
279
+ const ast = await getContractAST({
280
+ contractId: 'SP102V8P0F7JX67ARQ77WEA3D3CFB5XW39REDT0AM.amm-pool-v2-01'
281
+ });
282
+ console.log(ast.source_code);
283
+ console.log(ast.abi);
284
+
285
+ // Parse local source code
286
+ const parsed = await parseContract({
287
+ contractId: 'SP...contract-name',
288
+ sourceCode: '(define-public (hello) (ok "world"))',
289
+ clarityVersion: '4', // Optional: '1' | '2' | '3' | '4'
290
+ epoch: 'Epoch33' // Optional
291
+ });
292
+ ```
293
+
294
+ ### 5. Batch Operations
45
295
 
46
296
  The SDK provides two approaches for efficient batch reading from the Stacks blockchain:
47
297
 
48
298
  #### Direct Batch Reading
49
299
 
50
300
  ```typescript
51
- import { batchRead } from 'stxer';
301
+ import { batchRead, type BatchReadsResult } from 'stxer';
52
302
 
53
303
  // Batch read variables and maps
54
- const result = await batchRead({
304
+ const result: BatchReadsResult = await batchRead({
55
305
  variables: [{
56
306
  contract: contractPrincipalCV(...),
57
307
  variableName: 'my-var'
@@ -67,6 +317,14 @@ const result = await batchRead({
67
317
  functionArgs: [/* clarity values */]
68
318
  }]
69
319
  });
320
+
321
+ // Result shape — `index_block_hash` matches the upstream wire field
322
+ // (the SDK previously aliased this as `tip`; renamed to remove the
323
+ // indirection).
324
+ result.index_block_hash; // string — the block the batch ran against
325
+ result.vars; // (ClarityValue | Error)[]
326
+ result.maps; // (ClarityValue | Error)[]
327
+ result.readonly; // (ClarityValue | Error)[]
70
328
  ```
71
329
 
72
330
  #### BatchProcessor for Queue-based Operations
@@ -123,7 +381,7 @@ The BatchProcessor automatically:
123
381
 
124
382
  This is particularly useful when you need to make multiple blockchain reads and want to optimize network calls.
125
383
 
126
- ### 3. Clarity API Utilities
384
+ ### 6. Clarity API Utilities
127
385
 
128
386
  The SDK provides convenient utilities for reading data from Clarity contracts:
129
387
 
@@ -159,16 +417,128 @@ These utilities provide type-safe ways to interact with Clarity contracts, with
159
417
 
160
418
  ## Configuration
161
419
 
162
- You can customize the API endpoints:
420
+ ### API Endpoint Constants
421
+
422
+ The SDK exports constants for stxer API endpoints:
423
+
424
+ ```typescript
425
+ import { STXER_API_MAINNET, STXER_API_TESTNET } from 'stxer';
426
+
427
+ console.log(STXER_API_MAINNET); // https://api.stxer.xyz
428
+ console.log(STXER_API_TESTNET); // https://testnet-api.stxer.xyz
429
+ ```
430
+
431
+ ### Customizing API Endpoints
432
+
433
+ You can customize the API endpoints for all operations:
163
434
 
164
435
  ```typescript
436
+ import { SimulationBuilder, STXER_API_TESTNET } from 'stxer';
437
+
165
438
  const builder = SimulationBuilder.new({
166
- apiEndpoint: 'https://api.stxer.xyz', // Default stxer API endpoint
167
- stacksNodeAPI: 'https://api.hiro.so', // Default Stacks API endpoint
168
- network: 'mainnet' // or 'testnet'
439
+ apiEndpoint: STXER_API_TESTNET, // Use testnet
440
+ stacksNodeAPI: 'https://api.testnet.hiro.so', // Testnet Stacks API
441
+ network: 'testnet',
442
+ skipTracing: false, // Set to true for faster simulations (no debug UI support)
443
+ });
444
+ ```
445
+
446
+ For `getTip` and AST operations:
447
+
448
+ ```typescript
449
+ import { getTip, getContractAST, parseContract, STXER_API_MAINNET } from 'stxer';
450
+
451
+ const tip = await getTip({
452
+ stxerApi: STXER_API_MAINNET // Optional, defaults to mainnet
169
453
  });
454
+
455
+ const ast = await getContractAST({
456
+ contractId: 'SP...contract',
457
+ stxerApi: STXER_API_MAINNET // Optional
458
+ });
459
+ ```
460
+
461
+ ## Samples
462
+
463
+ Runnable end-to-end examples live in [`src/sample/`](https://github.com/stxer/stxer-sdk/tree/master/src/sample) on GitHub. Samples track `master` and may evolve faster than published SDK versions; if you pin a specific SDK version, browse the matching git tag.
464
+
465
+ | Sample | What it demonstrates |
466
+ |---|---|
467
+ | [`counter.ts`](https://github.com/stxer/stxer-sdk/blob/master/src/sample/counter.ts) | Full Simulation v2 lifecycle without `SimulationBuilder` — every `SimulationStepInput` variant (Transaction / Eval / SetContractCode / Reads / TenureExtend), narrowing on `SimulationStepResult`, and `SimulationStepSummary`. |
468
+ | [`instant.ts`](https://github.com/stxer/stxer-sdk/blob/master/src/sample/instant.ts) | `instantSimulation` with all 7 `ReadStep` variants. |
469
+ | [`failure-modes.ts`](https://github.com/stxer/stxer-sdk/blob/master/src/sample/failure-modes.ts) | The four failure signals on a `TransactionReceipt`, with bug-zoo triggers for each. |
470
+ | [`batch-categories.ts`](https://github.com/stxer/stxer-sdk/blob/master/src/sample/batch-categories.ts) | Every `simulationBatchReads` category and the sidecar `batchRead`. |
471
+ | [`contract-vitest.test.ts`](https://github.com/stxer/stxer-sdk/blob/master/src/sample/contract-vitest.test.ts) | Vitest suite that drives a Clarity contract through Simulation v2 — copy-pasteable CI test template. Pinned fork point so assertions stay deterministic. |
472
+ | [`verify-types.ts`](https://github.com/stxer/stxer-sdk/blob/master/src/sample/verify-types.ts) | Runtime type-drift detector. Hits every endpoint, dereferences every documented field, asserts each value's runtime type matches the declared SDK type. Run it before publishing your client after upstream changes. |
473
+ | [`read.ts`](https://github.com/stxer/stxer-sdk/blob/master/src/sample/read.ts) | `batchRead`, `BatchProcessor`, and the high-level `clarity-api` helpers (`callReadonly`, `readVariable`, `readMap`). |
474
+
475
+ Run any of them locally by cloning the SDK repo and:
476
+
477
+ ```bash
478
+ pnpm install
479
+ pnpm sample:counter # or sample:instant / failure-modes / batch-categories / verify-types
480
+ pnpm sample:vitest # run the Vitest contract-test sample
170
481
  ```
171
482
 
483
+ ## API Reference
484
+
485
+ ### Constants
486
+
487
+ - `STXER_API_MAINNET` - Mainnet API endpoint (https://api.stxer.xyz)
488
+ - `STXER_API_TESTNET` - Testnet API endpoint (https://testnet-api.stxer.xyz)
489
+ - `DEFAULT_STXER_API` - Default API endpoint (same as STXER_API_MAINNET)
490
+
491
+ ### Simulation Builder (High-Level)
492
+
493
+ - `SimulationBuilder.new(options)` - Create a new simulation builder
494
+ - `builder.useBlockHeight(height)` - Set block height for simulation
495
+ - `builder.withSender(address)` - Set default sender address
496
+
497
+ **Transaction Steps:**
498
+ - `builder.addContractCall(params)` - Add a contract call step
499
+ - `builder.addSTXTransfer(params)` - Add an STX transfer step
500
+ - `builder.addContractDeploy(params)` - Add a contract deployment step
501
+
502
+ **V2 Step Types:**
503
+ - `builder.addEvalCode(contractId, code)` - Add arbitrary code evaluation (with state modification)
504
+ - `builder.addSetContractCode(params)` - Directly set contract code without transaction
505
+ - `builder.addReads(reads[])` - Batch read operations in a single step
506
+ - `builder.addTenureExtend()` - Extend tenure (resets execution cost)
507
+
508
+ **Execution:**
509
+ - `builder.run()` - Execute the simulation and return simulation ID
510
+
511
+ ### Programmatic Simulation APIs (Low-Level)
512
+
513
+ **Instant Simulation:**
514
+ - `instantSimulation(request, options?)` - Simulate a single transaction without session
515
+
516
+ **Session Management:**
517
+ - `createSimulationSession(options?, apiOptions?)` - Create a new simulation session
518
+ - `submitSimulationSteps(sessionId, request, options?)` - Submit steps to a session
519
+ - `getSimulationResult(sessionId, options?)` - Get full simulation results
520
+ - `simulationBatchReads(sessionId, request, options?)` - Batch reads from simulation state
521
+
522
+ ### Chain Tip
523
+
524
+ - `getTip(options?)` - Fetch current chain tip information
525
+
526
+ ### Contract AST
527
+
528
+ - `getContractAST({ contractId, stxerApi? })` - Fetch on-chain contract AST
529
+ - `parseContract({ sourceCode, contractId, clarityVersion?, epoch?, stxerApi? })` - Parse source code to AST
530
+
531
+ ### Batch Operations
532
+
533
+ - `batchRead(reads, options?)` - Execute batch read operations
534
+ - `new BatchProcessor({ stxerAPIEndpoint?, batchDelayMs })` - Create a batch processor
535
+
536
+ ### Clarity API
537
+
538
+ - `callReadonly(params)` - Call a read-only contract function
539
+ - `readVariable(params)` - Read a contract variable
540
+ - `readMap(params)` - Read from a contract map
541
+
172
542
  ## Support
173
543
 
174
544
  This product is made possible through community support. Consider supporting the development:
package/dist/ast.d.ts ADDED
@@ -0,0 +1,32 @@
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 { ClarityEpoch, ContractAST } from './types';
8
+ export interface AstOptions {
9
+ stxerApi?: string;
10
+ }
11
+ export interface GetContractAstOptions extends AstOptions {
12
+ contractId: string;
13
+ }
14
+ /**
15
+ * Fetch the AST for an on-chain contract.
16
+ * @param options - Contract ID and optional API endpoint
17
+ * @returns The contract AST with metadata
18
+ */
19
+ export declare function getContractAST(options: GetContractAstOptions): Promise<ContractAST>;
20
+ export interface ParseContractOptions extends AstOptions {
21
+ sourceCode: string;
22
+ contractId: string;
23
+ clarityVersion?: '1' | '2' | '3' | '4';
24
+ epoch?: ClarityEpoch;
25
+ }
26
+ /**
27
+ * Parse contract source code into an AST.
28
+ * @param options - Source code, contract ID, and optional configuration
29
+ * @returns The parsed contract AST
30
+ */
31
+ export declare function parseContract(options: ParseContractOptions): Promise<ContractAST>;
32
+ export type { ClarityAbi, ClarityAbiFunction, ClarityAbiFungibleToken, ClarityAbiMap, ClarityAbiNonFungibleToken, ClarityAbiType, ClarityAbiVariable, ClarityEpoch, ClarityVersion, ContractAST, SymbolicExpression, } from './types';
@@ -23,7 +23,8 @@ export interface BatchReads {
23
23
  index_block_hash?: string;
24
24
  }
25
25
  export interface BatchReadsResult {
26
- tip: string;
26
+ /** Index block hash the batch ran against. Matches the wire field name. */
27
+ index_block_hash: string;
27
28
  vars: (ClarityValue | Error)[];
28
29
  maps: (ClarityValue | Error)[];
29
30
  readonly: (ClarityValue | Error)[];
@@ -1,6 +1,6 @@
1
1
  import type { ClarityAbiFunction, ClarityAbiMap, ClarityAbiVariable, TContractPrincipal, TPrincipal } from 'clarity-abi';
2
2
  import type { InferMapValueType, InferReadMapParameterType, InferReadonlyCallParameterType, InferReadonlyCallResultType, InferReadVariableParameterType, InferVariableType } from 'ts-clarity';
3
- import { BatchProcessor } from './BatchProcessor';
3
+ import { BatchProcessor } from './batch-processor';
4
4
  export type ReadonlyCallRuntimeOptions = {
5
5
  sender?: TPrincipal;
6
6
  contract: TContractPrincipal;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * API endpoint constants
3
+ */
4
+ /** Default stxer API endpoint for mainnet */
5
+ export declare const STXER_API_MAINNET = "https://api.stxer.xyz";
6
+ /** stxer API endpoint for testnet */
7
+ export declare const STXER_API_TESTNET = "https://testnet-api.stxer.xyz";
8
+ /** Default stxer API endpoint (mainnet) */
9
+ export declare const DEFAULT_STXER_API = "https://api.stxer.xyz";
package/dist/index.d.ts CHANGED
@@ -1,3 +1,8 @@
1
- export * from './BatchAPI';
1
+ export * from './ast';
2
+ export * from './batch-api';
2
3
  export * from './clarity-api';
4
+ export * from './constants';
3
5
  export * from './simulation';
6
+ export * from './simulation-api';
7
+ export * from './tip';
8
+ export * from './types';
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Low-level programmatic simulation APIs
3
+ *
4
+ * These functions provide direct access to the stxer V2 simulation endpoints
5
+ * for programmatic use cases where you need more control than SimulationBuilder provides.
6
+ */
7
+ import type { InstantSimulationRequest, InstantSimulationResponse, SimulationBatchReadsRequest, SimulationBatchReadsResponse, SimulationResult, SubmitSimulationStepsRequest, SubmitSimulationStepsResponse } from './types';
8
+ /**
9
+ * Options for API calls
10
+ */
11
+ export interface SimulationApiOptions {
12
+ /** stxer API endpoint (default: https://api.stxer.xyz) */
13
+ stxerApi?: string;
14
+ }
15
+ /**
16
+ * Create simulation session options
17
+ */
18
+ export interface CreateSessionOptions {
19
+ /** Block height for simulation (optional, uses tip if not provided) */
20
+ block_height?: number;
21
+ /** Block hash corresponding to block_height */
22
+ block_hash?: string;
23
+ /** Skip debug tracing for faster simulations */
24
+ skip_tracing?: boolean;
25
+ }
26
+ /**
27
+ * Instantly simulate a transaction
28
+ *
29
+ * This is useful for apps/wallets to get the result of a transaction before sending it.
30
+ * Lightweight - no debug tracing information.
31
+ *
32
+ * @param request - Instant simulation request
33
+ * @param options - API options
34
+ * @returns Instant simulation response with receipt and optional reads
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * import { instantSimulation } from 'stxer';
39
+ *
40
+ * const result = await instantSimulation({
41
+ * transaction: '0x...',
42
+ * block_height: 130818,
43
+ * block_hash: '0x...',
44
+ * reads: [
45
+ * { DataVar: ['SP...contract', 'my-var'] },
46
+ * { StxBalance: 'SP...' }
47
+ * ]
48
+ * });
49
+ * console.log(result.receipt.result);
50
+ * ```
51
+ */
52
+ export declare function instantSimulation(request: InstantSimulationRequest, options?: SimulationApiOptions): Promise<InstantSimulationResponse>;
53
+ /**
54
+ * Create a new simulation session
55
+ *
56
+ * A session allows you to run multiple steps in a forked chain state.
57
+ *
58
+ * @param options - Create session options
59
+ * @param apiOptions - API options
60
+ * @returns Session ID
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * import { createSimulationSession } from 'stxer';
65
+ *
66
+ * const sessionId = await createSimulationSession({
67
+ * block_height: 130818,
68
+ * skip_tracing: false
69
+ * });
70
+ * ```
71
+ */
72
+ export declare function createSimulationSession(options?: CreateSessionOptions, apiOptions?: SimulationApiOptions): Promise<string>;
73
+ /**
74
+ * Submit steps to a simulation session
75
+ *
76
+ * Steps are executed sequentially in the session's forked chain state.
77
+ *
78
+ * @param sessionId - Simulation session ID
79
+ * @param request - Steps to submit
80
+ * @param options - API options
81
+ * @returns Array of step results
82
+ *
83
+ * @example
84
+ * ```typescript
85
+ * import { submitSimulationSteps } from 'stxer';
86
+ *
87
+ * const results = await submitSimulationSteps(sessionId, {
88
+ * steps: [
89
+ * { Transaction: '0x...' },
90
+ * { Eval: ['SP...', '', 'SP...contract', '(var-get my-var)'] },
91
+ * { Reads: [{ DataVar: ['SP...contract', 'my-var'] }] }
92
+ * ]
93
+ * });
94
+ * ```
95
+ */
96
+ export declare function submitSimulationSteps(sessionId: string, request: SubmitSimulationStepsRequest, options?: SimulationApiOptions): Promise<SubmitSimulationStepsResponse>;
97
+ /**
98
+ * Get simulation session results
99
+ *
100
+ * Returns the full simulation result including metadata and all step results.
101
+ *
102
+ * @param sessionId - Simulation session ID
103
+ * @param options - API options
104
+ * @returns Complete simulation result
105
+ *
106
+ * @example
107
+ * ```typescript
108
+ * import { getSimulationResult } from 'stxer';
109
+ *
110
+ * const result = await getSimulationResult(sessionId);
111
+ * console.log(result.metadata);
112
+ * console.log(result.steps);
113
+ * ```
114
+ */
115
+ export declare function getSimulationResult(sessionId: string, options?: SimulationApiOptions): Promise<SimulationResult>;
116
+ /**
117
+ * Batch reads from a simulation session
118
+ *
119
+ * Similar to sidecar batch reads, but reads from the simulation's forked state.
120
+ *
121
+ * @param sessionId - Simulation session ID
122
+ * @param request - Batch reads request
123
+ * @param options - API options
124
+ * @returns Batch read results
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * import { simulationBatchReads } from 'stxer';
129
+ *
130
+ * const results = await simulationBatchReads(sessionId, {
131
+ * vars: [['SP...contract', 'my-var']],
132
+ * maps: [['SP...contract', 'my-map', '0x...']],
133
+ * stx: ['SP...']
134
+ * });
135
+ * console.log(results.vars);
136
+ * ```
137
+ */
138
+ export declare function simulationBatchReads(sessionId: string, request: SimulationBatchReadsRequest, options?: SimulationApiOptions): Promise<SimulationBatchReadsResponse>;