stxer 0.2.6 → 0.3.1

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