stxer 0.2.6 → 0.3.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.
@@ -0,0 +1,387 @@
1
+ import { type AccountDataResponse, getNodeInfo, richFetch } from 'ts-clarity';
2
+ import type { Block } from '@stacks/stacks-blockchain-api-types';
3
+ import {
4
+ STACKS_MAINNET,
5
+ STACKS_TESTNET,
6
+ type StacksNetworkName,
7
+ } from '@stacks/network';
8
+ import {
9
+ type ClarityValue,
10
+ ClarityVersion,
11
+ PostConditionMode,
12
+ type StacksTransactionWire,
13
+ bufferCV,
14
+ contractPrincipalCV,
15
+ makeUnsignedContractCall,
16
+ makeUnsignedContractDeploy,
17
+ makeUnsignedSTXTokenTransfer,
18
+ serializeCVBytes,
19
+ stringAsciiCV,
20
+ tupleCV,
21
+ uintCV,
22
+ } from '@stacks/transactions';
23
+ import { c32addressDecode } from 'c32check';
24
+
25
+ function runTx(tx: StacksTransactionWire) {
26
+ // type 0: run transaction
27
+ return tupleCV({ type: uintCV(0), data: bufferCV(tx.serializeBytes()) });
28
+ }
29
+
30
+ export interface SimulationEval {
31
+ contract_id: string;
32
+ code: string;
33
+ }
34
+
35
+ export function runEval({ contract_id, code }: SimulationEval) {
36
+ const [contract_address, contract_name] = contract_id.split('.');
37
+ // type 1: eval arbitrary code inside a contract
38
+ return tupleCV({
39
+ type: uintCV(1),
40
+ data: bufferCV(
41
+ serializeCVBytes(
42
+ tupleCV({
43
+ contract: contractPrincipalCV(contract_address, contract_name),
44
+ code: stringAsciiCV(code),
45
+ })
46
+ )
47
+ ),
48
+ });
49
+ }
50
+
51
+ export async function runSimulation(
52
+ apiEndpoint: string,
53
+ block_hash: string,
54
+ block_height: number,
55
+ txs: (StacksTransactionWire | SimulationEval)[]
56
+ ) {
57
+ // Convert 'sim-v1' to Uint8Array
58
+ const header = new TextEncoder().encode('sim-v1');
59
+ // Create 8 bytes for block height
60
+ const heightBytes = new Uint8Array(8);
61
+ // Convert block height to bytes
62
+ const view = new DataView(heightBytes.buffer);
63
+ view.setBigUint64(0, BigInt(block_height), false); // false for big-endian
64
+
65
+ // Convert block hash to bytes
66
+ const hashHex = block_hash.startsWith('0x')
67
+ ? block_hash.substring(2)
68
+ : block_hash;
69
+ // Replace non-null assertion with null check
70
+ const matches = hashHex.match(/.{1,2}/g);
71
+ if (!matches) {
72
+ throw new Error('Invalid block hash format');
73
+ }
74
+ const hashBytes = new Uint8Array(
75
+ matches.map((byte) => Number.parseInt(byte, 16))
76
+ );
77
+
78
+ // Convert transactions to bytes
79
+ const txBytes = txs
80
+ .map((t) => ('contract_id' in t && 'code' in t ? runEval(t) : runTx(t)))
81
+ .map((t) => serializeCVBytes(t));
82
+
83
+ // Combine all byte arrays
84
+ const totalLength =
85
+ header.length +
86
+ heightBytes.length +
87
+ hashBytes.length +
88
+ txBytes.reduce((acc, curr) => acc + curr.length, 0);
89
+ const body = new Uint8Array(totalLength);
90
+
91
+ let offset = 0;
92
+ body.set(header, offset);
93
+ offset += header.length;
94
+ body.set(heightBytes, offset);
95
+ offset += heightBytes.length;
96
+ body.set(hashBytes, offset);
97
+ offset += hashBytes.length;
98
+ for (const tx of txBytes) {
99
+ body.set(tx, offset);
100
+ offset += tx.length;
101
+ }
102
+
103
+ const rs = await fetch(apiEndpoint, {
104
+ method: 'POST',
105
+ body,
106
+ }).then(async (rs) => {
107
+ const response = await rs.text();
108
+ if (!response.startsWith('{')) {
109
+ throw new Error(`failed to submit simulation: ${response}`);
110
+ }
111
+ return JSON.parse(response) as { id: string };
112
+ });
113
+ return rs.id;
114
+ }
115
+
116
+ interface SimulationBuilderOptions {
117
+ apiEndpoint?: string;
118
+ stacksNodeAPI?: string;
119
+ network?: StacksNetworkName | string;
120
+ }
121
+
122
+ export class SimulationBuilder {
123
+ private apiEndpoint: string;
124
+ private stacksNodeAPI: string;
125
+ private network: StacksNetworkName | string;
126
+
127
+ private constructor(options: SimulationBuilderOptions = {}) {
128
+ this.apiEndpoint = options.apiEndpoint ?? 'https://api.stxer.xyz';
129
+ this.stacksNodeAPI = options.stacksNodeAPI ?? 'https://api.hiro.so';
130
+ this.network = options.network ?? 'mainnet';
131
+ }
132
+
133
+ public static new(options?: SimulationBuilderOptions) {
134
+ return new SimulationBuilder(options);
135
+ }
136
+
137
+ // biome-ignore lint/style/useNumberNamespace: <explanation>
138
+ private block = NaN;
139
+ private sender = '';
140
+ private steps: (
141
+ | {
142
+ // contract call
143
+ contract_id: string;
144
+ function_name: string;
145
+ function_args?: ClarityValue[];
146
+ sender: string;
147
+ fee: number;
148
+ }
149
+ | {
150
+ // contract deploy
151
+ contract_name: string;
152
+ source_code: string;
153
+ deployer: string;
154
+ fee: number;
155
+ clarity_version: ClarityVersion;
156
+ }
157
+ | {
158
+ // STX transfer
159
+ recipient: string;
160
+ amount: number;
161
+ sender: string;
162
+ fee: number;
163
+ }
164
+ | SimulationEval
165
+ )[] = [];
166
+
167
+ public useBlockHeight(block: number) {
168
+ this.block = block;
169
+ return this;
170
+ }
171
+ public withSender(address: string) {
172
+ this.sender = address;
173
+ return this;
174
+ }
175
+ public addSTXTransfer(params: {
176
+ recipient: string;
177
+ amount: number;
178
+ sender?: string;
179
+ fee?: number;
180
+ }) {
181
+ if (params.sender == null && this.sender === '') {
182
+ throw new Error(
183
+ 'Please specify a sender with useSender or adding a sender paramenter'
184
+ );
185
+ }
186
+ this.steps.push({
187
+ ...params,
188
+ sender: params.sender ?? this.sender,
189
+ fee: params.fee ?? 0,
190
+ });
191
+ return this;
192
+ }
193
+ public addContractCall(params: {
194
+ contract_id: string;
195
+ function_name: string;
196
+ function_args?: ClarityValue[];
197
+ sender?: string;
198
+ fee?: number;
199
+ }) {
200
+ if (params.sender == null && this.sender === '') {
201
+ throw new Error(
202
+ 'Please specify a sender with useSender or adding a sender paramenter'
203
+ );
204
+ }
205
+ this.steps.push({
206
+ ...params,
207
+ sender: params.sender ?? this.sender,
208
+ fee: params.fee ?? 0,
209
+ });
210
+ return this;
211
+ }
212
+ public addContractDeploy(params: {
213
+ contract_name: string;
214
+ source_code: string;
215
+ deployer?: string;
216
+ fee?: number;
217
+ clarity_version?: ClarityVersion;
218
+ }) {
219
+ if (params.deployer == null && this.sender === '') {
220
+ throw new Error(
221
+ 'Please specify a deployer with useSender or adding a deployer paramenter'
222
+ );
223
+ }
224
+ this.steps.push({
225
+ ...params,
226
+ deployer: params.deployer ?? this.sender,
227
+ fee: params.fee ?? 0,
228
+ clarity_version: params.clarity_version ?? ClarityVersion.Clarity3,
229
+ });
230
+ return this;
231
+ }
232
+ public addEvalCode(inside_contract_id: string, code: string) {
233
+ this.steps.push({
234
+ contract_id: inside_contract_id,
235
+ code,
236
+ });
237
+ return this;
238
+ }
239
+ public addMapRead(contract_id: string, map: string, key: string) {
240
+ this.steps.push({
241
+ contract_id,
242
+ code: `(map-get ${map} ${key})`,
243
+ });
244
+ return this;
245
+ }
246
+ public addVarRead(contract_id: string, variable: string) {
247
+ this.steps.push({
248
+ contract_id,
249
+ code: `(var-get ${variable})`,
250
+ });
251
+ return this;
252
+ }
253
+
254
+ private async getBlockInfo() {
255
+ if (Number.isNaN(this.block)) {
256
+ const { stacks_tip_height } = await getNodeInfo({
257
+ stacksEndpoint: this.stacksNodeAPI,
258
+ });
259
+ this.block = stacks_tip_height;
260
+ }
261
+ const info: Block = await richFetch(
262
+ `${this.stacksNodeAPI}/extended/v1/block/by_height/${this.block}?unanchored=true`
263
+ ).then((r) => r.json());
264
+ if (
265
+ info.height !== this.block ||
266
+ typeof info.hash !== 'string' ||
267
+ !info.hash.startsWith('0x')
268
+ ) {
269
+ throw new Error(
270
+ `failed to get block info for block height ${this.block}`
271
+ );
272
+ }
273
+ return {
274
+ block_height: this.block,
275
+ block_hash: info.hash.substring(2),
276
+ index_block_hash: info.index_block_hash.substring(2),
277
+ };
278
+ }
279
+
280
+ public async run() {
281
+ console.log(
282
+ `--------------------------------
283
+ This product can never exist without your support!
284
+
285
+ We receive sponsorship funds with:
286
+ SP212Y5JKN59YP3GYG07K3S8W5SSGE4KH6B5STXER
287
+
288
+ Feedbacks and feature requests are welcome.
289
+ To get in touch: contact@stxer.xyz
290
+ --------------------------------`
291
+ );
292
+ const block = await this.getBlockInfo();
293
+ console.log(
294
+ `Using block height ${block.block_height} hash 0x${block.block_hash} to run simulation.`
295
+ );
296
+ const txs: (StacksTransactionWire | SimulationEval)[] = [];
297
+ const nonce_by_address = new Map<string, number>();
298
+ const nextNonce = async (sender: string) => {
299
+ const nonce = nonce_by_address.get(sender);
300
+ if (nonce == null) {
301
+ const url = `${
302
+ this.stacksNodeAPI
303
+ }/v2/accounts/${sender}?proof=${false}&tip=${block.index_block_hash}`;
304
+ const account: AccountDataResponse = await richFetch(url).then((r) =>
305
+ r.json()
306
+ );
307
+ nonce_by_address.set(sender, account.nonce + 1);
308
+ return account.nonce;
309
+ }
310
+ nonce_by_address.set(sender, nonce + 1);
311
+ return nonce;
312
+ };
313
+ for (const step of this.steps) {
314
+ let network = this.network === 'mainnet' ? STACKS_MAINNET : STACKS_TESTNET;
315
+ if (this.stacksNodeAPI) {
316
+ network = {
317
+ ...network,
318
+ client: {
319
+ ...network.client,
320
+ baseUrl: this.stacksNodeAPI,
321
+ },
322
+ };
323
+ }
324
+ if ('sender' in step && 'function_name' in step) {
325
+ const nonce = await nextNonce(step.sender);
326
+ const [contractAddress, contractName] = step.contract_id.split('.');
327
+ const tx = await makeUnsignedContractCall({
328
+ contractAddress,
329
+ contractName,
330
+ functionName: step.function_name,
331
+ functionArgs: step.function_args ?? [],
332
+ nonce,
333
+ network,
334
+ publicKey: '',
335
+ postConditionMode: PostConditionMode.Allow,
336
+ fee: step.fee,
337
+ });
338
+ tx.auth.spendingCondition.signer = c32addressDecode(step.sender)[1];
339
+ txs.push(tx);
340
+ } else if ('sender' in step && 'recipient' in step) {
341
+ const nonce = await nextNonce(step.sender);
342
+ const tx = await makeUnsignedSTXTokenTransfer({
343
+ recipient: step.recipient,
344
+ amount: step.amount,
345
+ nonce,
346
+ network,
347
+ publicKey: '',
348
+ fee: step.fee,
349
+ });
350
+ tx.auth.spendingCondition.signer = c32addressDecode(step.sender)[1];
351
+ txs.push(tx);
352
+ } else if ('deployer' in step) {
353
+ const nonce = await nextNonce(step.deployer);
354
+ const tx = await makeUnsignedContractDeploy({
355
+ contractName: step.contract_name,
356
+ codeBody: step.source_code,
357
+ nonce,
358
+ network,
359
+ publicKey: '',
360
+ postConditionMode: PostConditionMode.Allow,
361
+ fee: step.fee,
362
+ });
363
+ tx.auth.spendingCondition.signer = c32addressDecode(step.deployer)[1];
364
+ txs.push(tx);
365
+ } else if ('code' in step) {
366
+ txs.push(step);
367
+ } else {
368
+ // biome-ignore lint/style/noUnusedTemplateLiteral: <explanation>
369
+ console.log(`Invalid simulation step:`, step);
370
+ }
371
+ }
372
+ const id = await runSimulation(
373
+ `${this.apiEndpoint}/simulations`,
374
+ block.block_hash,
375
+ block.block_height,
376
+ txs
377
+ );
378
+ console.log(
379
+ `Simulation will be available at: https://stxer.xyz/simulations/${this.network}/${id}`
380
+ );
381
+ return id;
382
+ }
383
+
384
+ public pipe(transform: (builder: SimulationBuilder) => SimulationBuilder): SimulationBuilder {
385
+ return transform(this);
386
+ }
387
+ }