@secondlayer/stacks 5.0.0 → 5.1.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,1675 @@
1
+ var import_node_module = require("node:module");
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ function __accessProp(key) {
7
+ return this[key];
8
+ }
9
+ var __toCommonJS = (from) => {
10
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
11
+ if (entry)
12
+ return entry;
13
+ entry = __defProp({}, "__esModule", { value: true });
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (var key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(entry, key))
17
+ __defProp(entry, key, {
18
+ get: __accessProp.bind(from, key),
19
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
+ });
21
+ }
22
+ __moduleCache.set(from, entry);
23
+ return entry;
24
+ };
25
+ var __moduleCache;
26
+ var __returnValue = (v) => v;
27
+ function __exportSetter(name, newValue) {
28
+ this[name] = __returnValue.bind(null, newValue);
29
+ }
30
+ var __export = (target, all) => {
31
+ for (var name in all)
32
+ __defProp(target, name, {
33
+ get: all[name],
34
+ enumerable: true,
35
+ configurable: true,
36
+ set: __exportSetter.bind(all, name)
37
+ });
38
+ };
39
+
40
+ // src/simnet/index.ts
41
+ var exports_simnet = {};
42
+ __export(exports_simnet, {
43
+ simnetChain: () => simnetChain,
44
+ simnet: () => simnet,
45
+ SimnetUnsupportedError: () => SimnetUnsupportedError
46
+ });
47
+ module.exports = __toCommonJS(exports_simnet);
48
+
49
+ // src/errors/base.ts
50
+ function codeFromName(name) {
51
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toUpperCase();
52
+ }
53
+
54
+ class BaseError extends Error {
55
+ name = "StacksError";
56
+ #code;
57
+ shortMessage;
58
+ details;
59
+ constructor(shortMessage, options) {
60
+ const message = [
61
+ shortMessage,
62
+ options?.details ? `
63
+ ${options.details}` : ""
64
+ ].join("");
65
+ super(message, { cause: options?.cause });
66
+ if (options?.code !== undefined)
67
+ this.#code = options.code;
68
+ this.shortMessage = shortMessage;
69
+ this.details = options?.details;
70
+ }
71
+ get code() {
72
+ return this.#code ?? codeFromName(this.name);
73
+ }
74
+ set code(value) {
75
+ this.#code = value;
76
+ }
77
+ toJSON() {
78
+ return {
79
+ name: this.name,
80
+ code: this.code,
81
+ message: this.message,
82
+ shortMessage: this.shortMessage,
83
+ details: this.details,
84
+ cause: this.cause instanceof Error ? this.cause.message : undefined
85
+ };
86
+ }
87
+ }
88
+
89
+ // src/errors/http.ts
90
+ class HttpRequestError extends BaseError {
91
+ name = "HttpRequestError";
92
+ status;
93
+ url;
94
+ method;
95
+ constructor(status, options) {
96
+ const where = options?.url !== undefined ? ` (${options.method ?? "GET"} ${options.url})` : "";
97
+ super(`HTTP request failed with status ${status}${where}`, options);
98
+ this.status = status;
99
+ this.url = options?.url;
100
+ this.method = options?.method;
101
+ }
102
+ }
103
+
104
+ // src/utils/encoding.ts
105
+ var hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
106
+ function bytesToHex(bytes) {
107
+ let hex = "";
108
+ for (const b of bytes) {
109
+ hex += hexes[b];
110
+ }
111
+ return hex;
112
+ }
113
+ function hexToBytes(hex) {
114
+ let h = without0x(hex);
115
+ if (h.length % 2)
116
+ h = `0${h}`;
117
+ const array = new Uint8Array(h.length / 2);
118
+ for (let i = 0;i < array.length; i++) {
119
+ const j = i * 2;
120
+ const byte = Number.parseInt(h.slice(j, j + 2), 16);
121
+ if (Number.isNaN(byte) || byte < 0)
122
+ throw new Error("Invalid byte sequence");
123
+ array[i] = byte;
124
+ }
125
+ return array;
126
+ }
127
+ function without0x(value) {
128
+ return /^0x/i.test(value) ? value.slice(2) : value;
129
+ }
130
+ function utf8ToBytes(str) {
131
+ return new TextEncoder().encode(str);
132
+ }
133
+ function bytesToUtf8(bytes) {
134
+ return new TextDecoder().decode(bytes);
135
+ }
136
+ function asciiToBytes(str) {
137
+ const bytes = new Uint8Array(str.length);
138
+ for (let i = 0;i < str.length; i++) {
139
+ bytes[i] = str.charCodeAt(i) & 255;
140
+ }
141
+ return bytes;
142
+ }
143
+ function bytesToAscii(bytes) {
144
+ return String.fromCharCode(...bytes);
145
+ }
146
+ function concatBytes(...arrays) {
147
+ if (arrays.length === 1)
148
+ return arrays[0];
149
+ const length = arrays.reduce((a, arr) => a + arr.length, 0);
150
+ const result = new Uint8Array(length);
151
+ let pad = 0;
152
+ for (const arr of arrays) {
153
+ result.set(arr, pad);
154
+ pad += arr.length;
155
+ }
156
+ return result;
157
+ }
158
+ function intToBigInt(value) {
159
+ if (typeof value === "bigint")
160
+ return value;
161
+ if (typeof value === "string")
162
+ return BigInt(value);
163
+ if (typeof value === "number") {
164
+ if (!Number.isInteger(value))
165
+ throw new RangeError("Values of type 'number' must be an integer.");
166
+ if (value > Number.MAX_SAFE_INTEGER)
167
+ throw new RangeError(`Values of type 'number' must be <= ${Number.MAX_SAFE_INTEGER}. Use BigInt instead.`);
168
+ return BigInt(value);
169
+ }
170
+ if (value instanceof Uint8Array)
171
+ return BigInt(`0x${bytesToHex(value)}`);
172
+ throw new TypeError("Must be a number, bigint, string, or Uint8Array.");
173
+ }
174
+ function intToBytes(value, byteLength) {
175
+ return bigIntToBytes(intToBigInt(value), byteLength);
176
+ }
177
+ function bigIntToBytes(value, length = 16) {
178
+ const hex = value.toString(16).padStart(length * 2, "0");
179
+ return hexToBytes(hex);
180
+ }
181
+ function intToHex(integer, byteLength = 8) {
182
+ const value = typeof integer === "bigint" ? integer : intToBigInt(integer);
183
+ return value.toString(16).padStart(byteLength * 2, "0");
184
+ }
185
+ function toTwos(value, width) {
186
+ const limit = BigInt(1) << width - BigInt(1);
187
+ if (value < -limit || value > limit - BigInt(1)) {
188
+ throw new Error(`Unable to represent integer in width: ${width}`);
189
+ }
190
+ if (value >= BigInt(0))
191
+ return value;
192
+ return value + (BigInt(1) << width);
193
+ }
194
+ function fromTwos(value, width) {
195
+ if (value & BigInt(1) << width - BigInt(1)) {
196
+ return value - (BigInt(1) << width);
197
+ }
198
+ return value;
199
+ }
200
+ function bytesToTwosBigInt(bytes) {
201
+ if (bytes.length === 0)
202
+ return 0n;
203
+ const hex = bytesToHex(bytes);
204
+ if (hex.length === 0)
205
+ return 0n;
206
+ return fromTwos(BigInt(`0x${hex}`), BigInt(bytes.byteLength * 8));
207
+ }
208
+ function writeUInt32BE(value) {
209
+ const buf = new Uint8Array(4);
210
+ buf[0] = value >>> 24 & 255;
211
+ buf[1] = value >>> 16 & 255;
212
+ buf[2] = value >>> 8 & 255;
213
+ buf[3] = value & 255;
214
+ return buf;
215
+ }
216
+ function writeUInt16BE(value) {
217
+ const buf = new Uint8Array(2);
218
+ buf[0] = value >>> 8 & 255;
219
+ buf[1] = value & 255;
220
+ return buf;
221
+ }
222
+ function writeUInt8(value) {
223
+ return new Uint8Array([value & 255]);
224
+ }
225
+
226
+ // src/utils/hash.ts
227
+ var import_legacy = require("@noble/hashes/legacy.js");
228
+ var import_sha2 = require("@noble/hashes/sha2.js");
229
+ var import_sha22 = require("@noble/hashes/sha2.js");
230
+ function txidFromBytes(data) {
231
+ return bytesToHex(import_sha22.sha512_256(data));
232
+ }
233
+
234
+ // src/transactions/authorization.ts
235
+ var import_hmac = require("@noble/hashes/hmac.js");
236
+ var import_sha23 = require("@noble/hashes/sha2.js");
237
+ var import_secp256k1 = require("@noble/secp256k1");
238
+
239
+ // src/transactions/types.ts
240
+ var AuthType = {
241
+ Standard: 4,
242
+ Sponsored: 5
243
+ };
244
+ var PayloadType = {
245
+ TokenTransfer: 0,
246
+ SmartContract: 1,
247
+ ContractCall: 2,
248
+ PoisonMicroblock: 3,
249
+ Coinbase: 4,
250
+ CoinbaseToAltRecipient: 5,
251
+ VersionedSmartContract: 6,
252
+ TenureChange: 7,
253
+ NakamotoCoinbase: 8
254
+ };
255
+ var AddressHashMode = {
256
+ P2PKH: 0,
257
+ P2SH: 1,
258
+ P2WPKH: 2,
259
+ P2WSH: 3,
260
+ P2SH_NonSequential: 5,
261
+ P2WSH_P2SH_NonSequential: 7
262
+ };
263
+ var PostConditionPrincipalId = {
264
+ Origin: 1,
265
+ Standard: 2,
266
+ Contract: 3
267
+ };
268
+ var AssetType = {
269
+ STX: 0,
270
+ Fungible: 1,
271
+ NonFungible: 2,
272
+ Staking: 3,
273
+ Pox: 4
274
+ };
275
+ var RECOVERABLE_ECDSA_SIG_LENGTH_BYTES = 65;
276
+ var MEMO_MAX_LENGTH_BYTES = 34;
277
+ var COINBASE_BYTES_LENGTH = 32;
278
+ var VRF_PROOF_BYTES_LENGTH = 80;
279
+ var MICROBLOCK_HEADER_BYTES_LENGTH = 132;
280
+
281
+ // src/transactions/authorization.ts
282
+ import_secp256k1.etc.hmacSha256Sync = (key, ...msgs) => {
283
+ const h = import_hmac.hmac.create(import_sha23.sha256, key);
284
+ for (const msg of msgs)
285
+ h.update(msg);
286
+ return h.digest();
287
+ };
288
+ var EMPTY_SIG = bytesToHex(new Uint8Array(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES));
289
+
290
+ // src/transactions/multisig.ts
291
+ var import_secp256k12 = require("@noble/secp256k1");
292
+
293
+ // src/utils/c32.ts
294
+ var import_sha24 = require("@noble/hashes/sha2.js");
295
+ var C32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
296
+ var HEX = "0123456789abcdef";
297
+ function c32normalize(input) {
298
+ return input.toUpperCase().replace(/O/g, "0").replace(/L|I/g, "1");
299
+ }
300
+ function c32encode(inputHex) {
301
+ let hex = inputHex;
302
+ if (hex.length % 2 !== 0)
303
+ hex = `0${hex}`;
304
+ hex = hex.toLowerCase();
305
+ const res = [];
306
+ let carry = 0;
307
+ for (let i = hex.length - 1;i >= 0; i--) {
308
+ if (carry < 4) {
309
+ const currentCode = HEX.indexOf(hex[i]) >> carry;
310
+ const nextCode = i !== 0 ? HEX.indexOf(hex[i - 1]) : 0;
311
+ const nextBits = 1 + carry;
312
+ const nextLowBits = nextCode % (1 << nextBits) << 5 - nextBits;
313
+ res.unshift(C32[currentCode + nextLowBits]);
314
+ carry = nextBits;
315
+ } else {
316
+ carry = 0;
317
+ }
318
+ }
319
+ let leadingZeros = 0;
320
+ while (leadingZeros < res.length && res[leadingZeros] === "0")
321
+ leadingZeros++;
322
+ const stripped = res.slice(leadingZeros);
323
+ const bytes = hexToBytes(hex);
324
+ let zeroBytesCount = 0;
325
+ while (zeroBytesCount < bytes.length && bytes[zeroBytesCount] === 0)
326
+ zeroBytesCount++;
327
+ const prefix = Array(zeroBytesCount).fill(C32[0]);
328
+ return [...prefix, ...stripped].join("");
329
+ }
330
+ function c32decode(c32input) {
331
+ const input = c32normalize(c32input);
332
+ if (!input.match(`^[${C32}]*$`))
333
+ throw new Error("Not a c32-encoded string");
334
+ const zeroPrefix = input.match(`^${C32[0]}*`);
335
+ const numLeadingZeroBytes = zeroPrefix ? zeroPrefix[0]?.length : 0;
336
+ const res = [];
337
+ let carry = 0;
338
+ let carryBits = 0;
339
+ for (let i = input.length - 1;i >= 0; i--) {
340
+ if (carryBits === 4) {
341
+ res.unshift(HEX[carry]);
342
+ carryBits = 0;
343
+ carry = 0;
344
+ }
345
+ const currentValue = (C32.indexOf(input[i]) << carryBits) + carry;
346
+ res.unshift(HEX[currentValue % 16]);
347
+ carryBits += 1;
348
+ carry = currentValue >> 4;
349
+ if (carry > 1 << carryBits)
350
+ throw new Error("Panic error in c32 decoding");
351
+ }
352
+ res.unshift(HEX[carry]);
353
+ if (res.length % 2 === 1)
354
+ res.unshift("0");
355
+ let hexLeadingZeros = 0;
356
+ while (hexLeadingZeros < res.length && res[hexLeadingZeros] === "0")
357
+ hexLeadingZeros++;
358
+ let hexStr = res.slice(hexLeadingZeros - hexLeadingZeros % 2).join("");
359
+ for (let i = 0;i < numLeadingZeroBytes; i++)
360
+ hexStr = `00${hexStr}`;
361
+ return hexStr;
362
+ }
363
+ function c32checksum(dataHex) {
364
+ return bytesToHex(import_sha24.sha256(import_sha24.sha256(hexToBytes(dataHex))).slice(0, 4));
365
+ }
366
+ function c32checkEncode(version, data) {
367
+ if (version < 0 || version >= 32)
368
+ throw new Error("Invalid version (must be between 0 and 31)");
369
+ if (!data.match(/^[0-9a-fA-F]*$/))
370
+ throw new Error("Invalid data (not a hex string)");
371
+ let d = data.toLowerCase();
372
+ if (d.length % 2 !== 0)
373
+ d = `0${d}`;
374
+ let versionHex = version.toString(16);
375
+ if (versionHex.length === 1)
376
+ versionHex = `0${versionHex}`;
377
+ const checksumHex = c32checksum(`${versionHex}${d}`);
378
+ return `${C32[version]}${c32encode(`${d}${checksumHex}`)}`;
379
+ }
380
+ function c32checkDecode(c32data) {
381
+ const normalized = c32normalize(c32data);
382
+ const dataHex = c32decode(normalized.slice(1));
383
+ const version = C32.indexOf(normalized[0]);
384
+ const checksum = dataHex.slice(-8);
385
+ let versionHex = version.toString(16);
386
+ if (versionHex.length === 1)
387
+ versionHex = `0${versionHex}`;
388
+ if (c32checksum(`${versionHex}${dataHex.substring(0, dataHex.length - 8)}`) !== checksum) {
389
+ throw new Error("Invalid c32check string: checksum mismatch");
390
+ }
391
+ return [version, dataHex.substring(0, dataHex.length - 8)];
392
+ }
393
+ function c32address(version, hash160hex) {
394
+ if (!hash160hex.match(/^[0-9a-fA-F]{40}$/)) {
395
+ throw new Error("Invalid argument: not a hash160 hex string");
396
+ }
397
+ return `S${c32checkEncode(version, hash160hex)}`;
398
+ }
399
+ function c32addressDecode(c32addr) {
400
+ if (c32addr.length <= 5)
401
+ throw new Error("Invalid c32 address: invalid length");
402
+ if (c32addr[0] !== "S")
403
+ throw new Error('Invalid c32 address: must start with "S"');
404
+ return c32checkDecode(c32addr.slice(1));
405
+ }
406
+
407
+ // src/clarity/types.ts
408
+ var ClarityWireType = {
409
+ int: 0,
410
+ uint: 1,
411
+ buffer: 2,
412
+ true: 3,
413
+ false: 4,
414
+ address: 5,
415
+ contract: 6,
416
+ ok: 7,
417
+ err: 8,
418
+ none: 9,
419
+ some: 10,
420
+ list: 11,
421
+ tuple: 12,
422
+ ascii: 13,
423
+ utf8: 14
424
+ };
425
+ var wireTypeToClarity = Object.fromEntries(Object.entries(ClarityWireType).map(([k, v]) => [v, k]));
426
+ function clarityTypeFromByte(byte) {
427
+ const type = wireTypeToClarity[byte];
428
+ if (!type)
429
+ throw new Error(`Unknown clarity wire type: ${byte}`);
430
+ return type;
431
+ }
432
+
433
+ // src/clarity/serialize.ts
434
+ var CLARITY_INT_SIZE = 128n;
435
+ var CLARITY_INT_BYTE_SIZE = 16;
436
+ function typeIdByte(type) {
437
+ return ClarityWireType[type];
438
+ }
439
+ function withTypeId(type, bytes) {
440
+ return concatBytes(new Uint8Array([typeIdByte(type)]), bytes);
441
+ }
442
+ function serializeAddress(c32Address) {
443
+ const [version, hash160] = c32addressDecode(c32Address);
444
+ return concatBytes(new Uint8Array([version]), hexToBytes(hash160));
445
+ }
446
+ function serializeLPString(str, prefixBytes = 1) {
447
+ const content = utf8ToBytes(str);
448
+ const lengthPrefix = hexToBytes(intToHex(content.byteLength, prefixBytes));
449
+ return concatBytes(lengthPrefix, content);
450
+ }
451
+ function serializeCVBytes(value) {
452
+ switch (value.type) {
453
+ case "true":
454
+ case "false":
455
+ return new Uint8Array([typeIdByte(value.type)]);
456
+ case "int": {
457
+ const bytes = bigIntToBytes(toTwos(BigInt(value.value), CLARITY_INT_SIZE), CLARITY_INT_BYTE_SIZE);
458
+ return withTypeId(value.type, bytes);
459
+ }
460
+ case "uint": {
461
+ const bytes = bigIntToBytes(BigInt(value.value), CLARITY_INT_BYTE_SIZE);
462
+ return withTypeId(value.type, bytes);
463
+ }
464
+ case "buffer": {
465
+ const bufBytes = hexToBytes(value.value);
466
+ return withTypeId(value.type, concatBytes(writeUInt32BE(bufBytes.length), bufBytes));
467
+ }
468
+ case "none":
469
+ return new Uint8Array([typeIdByte(value.type)]);
470
+ case "some":
471
+ return withTypeId(value.type, serializeCVBytes(value.value));
472
+ case "ok":
473
+ case "err":
474
+ return withTypeId(value.type, serializeCVBytes(value.value));
475
+ case "address":
476
+ return withTypeId(value.type, serializeAddress(value.value));
477
+ case "contract": {
478
+ const [addr, name] = value.value.split(".");
479
+ if (!addr || !name)
480
+ throw new Error(`Invalid contract principal: ${value.value}`);
481
+ return withTypeId(value.type, concatBytes(serializeAddress(addr), serializeLPString(name)));
482
+ }
483
+ case "list": {
484
+ const parts = [writeUInt32BE(value.value.length)];
485
+ for (const item of value.value) {
486
+ parts.push(serializeCVBytes(item));
487
+ }
488
+ return withTypeId(value.type, concatBytes(...parts));
489
+ }
490
+ case "tuple": {
491
+ const keys = Object.keys(value.value).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
492
+ const parts = [writeUInt32BE(keys.length)];
493
+ for (const key of keys) {
494
+ parts.push(serializeLPString(key));
495
+ parts.push(serializeCVBytes(value.value[key]));
496
+ }
497
+ return withTypeId(value.type, concatBytes(...parts));
498
+ }
499
+ case "ascii": {
500
+ const strBytes = asciiToBytes(value.value);
501
+ return withTypeId(value.type, concatBytes(writeUInt32BE(strBytes.length), strBytes));
502
+ }
503
+ case "utf8": {
504
+ const strBytes = utf8ToBytes(value.value);
505
+ return withTypeId(value.type, concatBytes(writeUInt32BE(strBytes.length), strBytes));
506
+ }
507
+ default:
508
+ throw new Error("Cannot serialize unknown clarity type");
509
+ }
510
+ }
511
+ function serializeCV(value) {
512
+ return bytesToHex(serializeCVBytes(value));
513
+ }
514
+
515
+ // src/transactions/wire/serialize.ts
516
+ function serializeAddress2(c32Address) {
517
+ const [version, hash160] = c32addressDecode(c32Address);
518
+ return concatBytes(new Uint8Array([version]), hexToBytes(hash160));
519
+ }
520
+ function serializeLPString2(str, prefixBytes = 1) {
521
+ const content = utf8ToBytes(str);
522
+ const prefix = hexToBytes(intToHex(content.byteLength, prefixBytes));
523
+ return concatBytes(prefix, content);
524
+ }
525
+ function serializeLPStringLong(str) {
526
+ return serializeLPString2(str, 4);
527
+ }
528
+ function serializeMemo(memo) {
529
+ const content = asciiToBytes(memo);
530
+ const padded = new Uint8Array(MEMO_MAX_LENGTH_BYTES);
531
+ padded.set(content.slice(0, MEMO_MAX_LENGTH_BYTES));
532
+ return padded;
533
+ }
534
+ function serializeSpendingCondition(condition) {
535
+ const parts = [
536
+ writeUInt8(condition.hashMode),
537
+ hexToBytes(condition.signer),
538
+ intToBytes(condition.nonce, 8),
539
+ intToBytes(condition.fee, 8)
540
+ ];
541
+ if ("signature" in condition) {
542
+ const sc = condition;
543
+ parts.push(writeUInt8(sc.keyEncoding));
544
+ parts.push(hexToBytes(sc.signature));
545
+ } else {
546
+ const mc = condition;
547
+ parts.push(writeUInt32BE(mc.fields.length));
548
+ for (const field of mc.fields) {
549
+ parts.push(serializeAuthField(field));
550
+ }
551
+ parts.push(writeUInt16BE(mc.signaturesRequired));
552
+ }
553
+ return concatBytes(...parts);
554
+ }
555
+ function serializeAuthField(field) {
556
+ if (field.type === "publicKey") {
557
+ const typeId2 = field.pubKeyEncoding === 0 ? 0 : 1;
558
+ return concatBytes(writeUInt8(typeId2), hexToBytes(field.data));
559
+ }
560
+ const typeId = field.pubKeyEncoding === 0 ? 2 : 3;
561
+ return concatBytes(writeUInt8(typeId), hexToBytes(field.data));
562
+ }
563
+ function serializeAuthorization(auth) {
564
+ const parts = [writeUInt8(auth.authType)];
565
+ parts.push(serializeSpendingCondition(auth.spendingCondition));
566
+ if (auth.authType === AuthType.Sponsored) {
567
+ parts.push(serializeSpendingCondition(auth.sponsorSpendingCondition));
568
+ }
569
+ return concatBytes(...parts);
570
+ }
571
+ function serializePrincipal(principal) {
572
+ switch (principal.type) {
573
+ case "origin":
574
+ return writeUInt8(PostConditionPrincipalId.Origin);
575
+ case "standard":
576
+ return concatBytes(writeUInt8(PostConditionPrincipalId.Standard), serializeAddress2(principal.address));
577
+ case "contract":
578
+ return concatBytes(writeUInt8(PostConditionPrincipalId.Contract), serializeAddress2(principal.address), serializeLPString2(principal.contractName));
579
+ }
580
+ }
581
+ function serializeAssetInfo(asset) {
582
+ return concatBytes(serializeAddress2(asset.address), serializeLPString2(asset.contractName), serializeLPString2(asset.assetName));
583
+ }
584
+ function serializePostConditionWire(pc) {
585
+ const parts = [];
586
+ switch (pc.type) {
587
+ case "stx":
588
+ parts.push(writeUInt8(AssetType.STX));
589
+ parts.push(serializePrincipal(pc.principal));
590
+ parts.push(writeUInt8(pc.conditionCode));
591
+ parts.push(intToBytes(pc.amount, 8));
592
+ break;
593
+ case "ft":
594
+ parts.push(writeUInt8(AssetType.Fungible));
595
+ parts.push(serializePrincipal(pc.principal));
596
+ parts.push(serializeAssetInfo(pc.asset));
597
+ parts.push(writeUInt8(pc.conditionCode));
598
+ parts.push(intToBytes(pc.amount, 8));
599
+ break;
600
+ case "nft":
601
+ parts.push(writeUInt8(AssetType.NonFungible));
602
+ parts.push(serializePrincipal(pc.principal));
603
+ parts.push(serializeAssetInfo(pc.asset));
604
+ parts.push(serializeCVBytes(pc.assetId));
605
+ parts.push(writeUInt8(pc.conditionCode));
606
+ break;
607
+ case "staking":
608
+ parts.push(writeUInt8(AssetType.Staking));
609
+ parts.push(serializePrincipal(pc.principal));
610
+ parts.push(writeUInt8(pc.conditionCode));
611
+ parts.push(intToBytes(pc.amount, 8));
612
+ break;
613
+ case "pox":
614
+ parts.push(writeUInt8(AssetType.Pox));
615
+ parts.push(serializePrincipal(pc.principal));
616
+ parts.push(writeUInt8(pc.conditionCode));
617
+ break;
618
+ }
619
+ return concatBytes(...parts);
620
+ }
621
+ function serializePostConditions(pcs) {
622
+ const parts = [writeUInt32BE(pcs.length)];
623
+ for (const pc of pcs)
624
+ parts.push(serializePostConditionWire(pc));
625
+ return concatBytes(...parts);
626
+ }
627
+ function serializePayload(payload) {
628
+ const parts = [writeUInt8(payload.payloadType)];
629
+ switch (payload.payloadType) {
630
+ case PayloadType.TokenTransfer:
631
+ parts.push(serializeCVBytes(payload.recipient));
632
+ parts.push(intToBytes(payload.amount, 8));
633
+ parts.push(serializeMemo(payload.memo));
634
+ break;
635
+ case PayloadType.ContractCall:
636
+ parts.push(serializeAddress2(payload.contractAddress));
637
+ parts.push(serializeLPString2(payload.contractName));
638
+ parts.push(serializeLPString2(payload.functionName));
639
+ parts.push(writeUInt32BE(payload.functionArgs.length));
640
+ for (const arg of payload.functionArgs) {
641
+ parts.push(serializeCVBytes(arg));
642
+ }
643
+ break;
644
+ case PayloadType.SmartContract:
645
+ parts.push(serializeLPString2(payload.contractName));
646
+ parts.push(serializeLPStringLong(payload.codeBody));
647
+ break;
648
+ case PayloadType.VersionedSmartContract:
649
+ parts.push(writeUInt8(payload.clarityVersion ?? 2));
650
+ parts.push(serializeLPString2(payload.contractName));
651
+ parts.push(serializeLPStringLong(payload.codeBody));
652
+ break;
653
+ case PayloadType.Coinbase:
654
+ parts.push(hexToBytes(payload.coinbaseBuffer));
655
+ break;
656
+ case PayloadType.CoinbaseToAltRecipient: {
657
+ const cbAlt = payload;
658
+ parts.push(hexToBytes(cbAlt.coinbaseBuffer));
659
+ parts.push(serializeCVBytes(cbAlt.recipient));
660
+ break;
661
+ }
662
+ case PayloadType.PoisonMicroblock: {
663
+ const pm = payload;
664
+ parts.push(hexToBytes(pm.header1));
665
+ parts.push(hexToBytes(pm.header2));
666
+ break;
667
+ }
668
+ case PayloadType.TenureChange: {
669
+ const tc = payload;
670
+ parts.push(hexToBytes(tc.tenureConsensusHash));
671
+ parts.push(hexToBytes(tc.prevTenureConsensusHash));
672
+ parts.push(hexToBytes(tc.burnViewConsensusHash));
673
+ parts.push(hexToBytes(tc.previousTenureEnd));
674
+ parts.push(writeUInt32BE(tc.previousTenureBlocks));
675
+ parts.push(writeUInt8(tc.cause));
676
+ parts.push(hexToBytes(tc.pubkeyHash));
677
+ break;
678
+ }
679
+ case PayloadType.NakamotoCoinbase: {
680
+ const nc = payload;
681
+ parts.push(hexToBytes(nc.coinbaseBuffer));
682
+ if (nc.recipient) {
683
+ parts.push(serializeCVBytes({ type: "some", value: nc.recipient }));
684
+ } else {
685
+ parts.push(serializeCVBytes({ type: "none" }));
686
+ }
687
+ parts.push(hexToBytes(nc.vrfProof));
688
+ break;
689
+ }
690
+ }
691
+ return concatBytes(...parts);
692
+ }
693
+ var _txCache = new WeakMap;
694
+ function serializeTransaction(tx) {
695
+ const cached = _txCache.get(tx);
696
+ if (cached)
697
+ return cached;
698
+ const bytes = concatBytes(writeUInt8(tx.version), writeUInt32BE(tx.chainId), serializeAuthorization(tx.auth), writeUInt8(tx.anchorMode), writeUInt8(tx.postConditionMode), serializePostConditions(tx.postConditions), serializePayload(tx.payload));
699
+ _txCache.set(tx, bytes);
700
+ return bytes;
701
+ }
702
+
703
+ // src/transactions/signer.ts
704
+ function txid(tx) {
705
+ return txidFromBytes(serializeTransaction(tx));
706
+ }
707
+ function getTransactionId(tx) {
708
+ return txid(tx);
709
+ }
710
+
711
+ // src/errors/transaction.ts
712
+ class SerializationError extends BaseError {
713
+ name = "SerializationError";
714
+ }
715
+
716
+ // src/utils/bytes-reader.ts
717
+ class BytesReader {
718
+ data;
719
+ offset = 0;
720
+ constructor(data) {
721
+ this.data = data;
722
+ }
723
+ remaining() {
724
+ return this.data.length - this.offset;
725
+ }
726
+ ensure(length) {
727
+ if (this.offset + length > this.data.length) {
728
+ throw new SerializationError(`Buffer underflow: need ${length} bytes at offset ${this.offset}, have ${this.data.length}`);
729
+ }
730
+ }
731
+ readUInt8() {
732
+ this.ensure(1);
733
+ return this.data[this.offset++];
734
+ }
735
+ readUInt16BE() {
736
+ this.ensure(2);
737
+ const val = (this.data[this.offset] << 8 | this.data[this.offset + 1]) >>> 0;
738
+ this.offset += 2;
739
+ return val;
740
+ }
741
+ readUInt32BE() {
742
+ this.ensure(4);
743
+ const val = (this.data[this.offset] << 24 | this.data[this.offset + 1] << 16 | this.data[this.offset + 2] << 8 | this.data[this.offset + 3]) >>> 0;
744
+ this.offset += 4;
745
+ return val;
746
+ }
747
+ readBytes(length) {
748
+ this.ensure(length);
749
+ const slice = this.data.slice(this.offset, this.offset + length);
750
+ this.offset += length;
751
+ return slice;
752
+ }
753
+ readBigUInt64BE() {
754
+ const hex = bytesToHex(this.readBytes(8));
755
+ return hex.length > 0 ? BigInt(`0x${hex}`) : 0n;
756
+ }
757
+ }
758
+
759
+ // src/utils/constants.ts
760
+ var MAX_U128 = (1n << 128n) - 1n;
761
+ var MAX_I128 = (1n << 127n) - 1n;
762
+ var MIN_I128 = -(1n << 127n);
763
+ var AddressVersion = {
764
+ MainnetSingleSig: 22,
765
+ MainnetMultiSig: 20,
766
+ TestnetSingleSig: 26,
767
+ TestnetMultiSig: 21
768
+ };
769
+
770
+ // src/utils/address.ts
771
+ function isClarityName(name) {
772
+ const regex = /^[a-zA-Z]([a-zA-Z0-9]|[-_!?+<>=/*])*$|^[-+=/*]$|^[<>]=?$/;
773
+ return regex.test(name) && name.length < 128;
774
+ }
775
+
776
+ // src/clarity/values.ts
777
+ var MAX_U1282 = BigInt("0xffffffffffffffffffffffffffffffff");
778
+ var MIN_I1282 = BigInt("-170141183460469231731687303715884105728");
779
+ var MAX_I1282 = BigInt("0x7fffffffffffffffffffffffffffffff");
780
+ function intCV(value) {
781
+ let v = value;
782
+ if (typeof v === "string" && v.toLowerCase().startsWith("0x")) {
783
+ v = bytesToTwosBigInt(hexToBytes(v));
784
+ }
785
+ if (v instanceof Uint8Array)
786
+ v = bytesToTwosBigInt(v);
787
+ const n = intToBigInt(v);
788
+ if (n > MAX_I1282)
789
+ throw new RangeError(`Int exceeds max i128: ${MAX_I1282}`);
790
+ if (n < MIN_I1282)
791
+ throw new RangeError(`Int below min i128: ${MIN_I1282}`);
792
+ return { type: "int", value: n };
793
+ }
794
+ function uintCV(value) {
795
+ const n = intToBigInt(value);
796
+ if (n < 0n)
797
+ throw new RangeError("Cannot construct unsigned int from negative value");
798
+ if (n > MAX_U1282)
799
+ throw new RangeError(`UInt exceeds max u128: ${MAX_U1282}`);
800
+ return { type: "uint", value: n };
801
+ }
802
+ var trueCV = () => ({ type: "true" });
803
+ var falseCV = () => ({ type: "false" });
804
+ function bufferCV(buffer) {
805
+ if (buffer.byteLength > 1048576) {
806
+ throw new Error("Buffer exceeds max size of 1MB");
807
+ }
808
+ return { type: "buffer", value: bytesToHex(buffer) };
809
+ }
810
+ function standardPrincipalCV(address) {
811
+ const [version, hash1602] = c32addressDecode(address);
812
+ const normalized = c32address(version, hash1602);
813
+ return { type: "address", value: normalized };
814
+ }
815
+ function contractPrincipalCV(address, contractName) {
816
+ const [version, hash1602] = c32addressDecode(address);
817
+ const normalized = c32address(version, hash1602);
818
+ if (utf8ToBytes(contractName).byteLength >= 128) {
819
+ throw new Error("Contract name must be less than 128 bytes");
820
+ }
821
+ return { type: "contract", value: `${normalized}.${contractName}` };
822
+ }
823
+ function noneCV() {
824
+ return { type: "none" };
825
+ }
826
+ function someCV(value) {
827
+ return { type: "some", value };
828
+ }
829
+ function responseOkCV(value) {
830
+ return { type: "ok", value };
831
+ }
832
+ function responseErrorCV(value) {
833
+ return { type: "err", value };
834
+ }
835
+ function listCV(values) {
836
+ return { type: "list", value: values };
837
+ }
838
+ function tupleCV(data) {
839
+ for (const key in data) {
840
+ if (!isClarityName(key)) {
841
+ throw new Error(`"${key}" is not a valid Clarity name`);
842
+ }
843
+ }
844
+ return { type: "tuple", value: data };
845
+ }
846
+ function stringAsciiCV(value) {
847
+ return { type: "ascii", value };
848
+ }
849
+ function stringUtf8CV(value) {
850
+ return { type: "utf8", value };
851
+ }
852
+
853
+ // src/clarity/deserialize.ts
854
+ function readAddress(reader) {
855
+ const version = reader.readUInt8();
856
+ const hash1602 = bytesToHex(reader.readBytes(20));
857
+ return c32address(version, hash1602);
858
+ }
859
+ function readLPString(reader, prefixBytes = 1) {
860
+ let length = 0;
861
+ for (let i = 0;i < prefixBytes; i++) {
862
+ length = length << 8 | reader.readUInt8();
863
+ }
864
+ return bytesToUtf8(reader.readBytes(length));
865
+ }
866
+ var MAX_CV_DEPTH = 64;
867
+ var MIN_LIST_ITEM_BYTES = 1;
868
+ var MIN_TUPLE_ENTRY_BYTES = 2;
869
+ function checkCount(reader, count, minBytes) {
870
+ if (count * minBytes > reader.remaining()) {
871
+ throw new SerializationError(`Clarity value declares ${count} elements but only ${reader.remaining()} bytes remain`);
872
+ }
873
+ }
874
+ function readCV(reader, depth = 0) {
875
+ if (depth > MAX_CV_DEPTH) {
876
+ throw new SerializationError(`Clarity value nests deeper than ${MAX_CV_DEPTH} levels`);
877
+ }
878
+ const typeByte = reader.readUInt8();
879
+ const type = clarityTypeFromByte(typeByte);
880
+ switch (type) {
881
+ case "int":
882
+ return intCV(bytesToTwosBigInt(reader.readBytes(16)));
883
+ case "uint":
884
+ return uintCV(reader.readBytes(16));
885
+ case "true":
886
+ return trueCV();
887
+ case "false":
888
+ return falseCV();
889
+ case "buffer": {
890
+ const len = reader.readUInt32BE();
891
+ return bufferCV(reader.readBytes(len));
892
+ }
893
+ case "none":
894
+ return noneCV();
895
+ case "some":
896
+ return someCV(readCV(reader, depth + 1));
897
+ case "ok":
898
+ return responseOkCV(readCV(reader, depth + 1));
899
+ case "err":
900
+ return responseErrorCV(readCV(reader, depth + 1));
901
+ case "address":
902
+ return standardPrincipalCV(readAddress(reader));
903
+ case "contract": {
904
+ const addr = readAddress(reader);
905
+ const name = readLPString(reader);
906
+ return contractPrincipalCV(addr, name);
907
+ }
908
+ case "list": {
909
+ const len = reader.readUInt32BE();
910
+ checkCount(reader, len, MIN_LIST_ITEM_BYTES);
911
+ const items = [];
912
+ for (let i = 0;i < len; i++) {
913
+ items.push(readCV(reader, depth + 1));
914
+ }
915
+ return listCV(items);
916
+ }
917
+ case "tuple": {
918
+ const len = reader.readUInt32BE();
919
+ checkCount(reader, len, MIN_TUPLE_ENTRY_BYTES);
920
+ const data = {};
921
+ for (let i = 0;i < len; i++) {
922
+ const key = readLPString(reader);
923
+ data[key] = readCV(reader, depth + 1);
924
+ }
925
+ return tupleCV(data);
926
+ }
927
+ case "ascii": {
928
+ const len = reader.readUInt32BE();
929
+ return stringAsciiCV(bytesToAscii(reader.readBytes(len)));
930
+ }
931
+ case "utf8": {
932
+ const len = reader.readUInt32BE();
933
+ return stringUtf8CV(bytesToUtf8(reader.readBytes(len)));
934
+ }
935
+ default:
936
+ throw new SerializationError(`Cannot deserialize unknown clarity type: ${type}`);
937
+ }
938
+ }
939
+ function deserializeCVBytes(input) {
940
+ const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
941
+ return readCV(new BytesReader(bytes));
942
+ }
943
+ function deserializeCV(input) {
944
+ return deserializeCVBytes(input);
945
+ }
946
+
947
+ // src/transactions/wire/deserialize.ts
948
+ function readSpendingCondition(r) {
949
+ const hashMode = r.readUInt8();
950
+ const signer = bytesToHex(r.readBytes(20));
951
+ const nonce = r.readBigUInt64BE();
952
+ const fee = r.readBigUInt64BE();
953
+ if (hashMode === AddressHashMode.P2PKH || hashMode === AddressHashMode.P2WPKH) {
954
+ const keyEncoding = r.readUInt8();
955
+ const signature = bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES));
956
+ return {
957
+ hashMode,
958
+ signer,
959
+ nonce,
960
+ fee,
961
+ keyEncoding,
962
+ signature
963
+ };
964
+ }
965
+ const fieldCount = r.readUInt32BE();
966
+ const fields = [];
967
+ for (let i = 0;i < fieldCount; i++) {
968
+ const fieldType = r.readUInt8();
969
+ if (fieldType <= 1) {
970
+ const keyLen = fieldType === 0 ? 33 : 65;
971
+ fields.push({
972
+ type: "publicKey",
973
+ pubKeyEncoding: fieldType,
974
+ data: bytesToHex(r.readBytes(keyLen))
975
+ });
976
+ } else {
977
+ fields.push({
978
+ type: "signature",
979
+ pubKeyEncoding: fieldType === 2 ? 0 : 1,
980
+ data: bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES))
981
+ });
982
+ }
983
+ }
984
+ const signaturesRequired = r.readUInt16BE();
985
+ return {
986
+ hashMode,
987
+ signer,
988
+ nonce,
989
+ fee,
990
+ fields,
991
+ signaturesRequired
992
+ };
993
+ }
994
+ function readAuthorization(r) {
995
+ const authType = r.readUInt8();
996
+ const spendingCondition = readSpendingCondition(r);
997
+ if (authType === AuthType.Standard) {
998
+ return { authType: AuthType.Standard, spendingCondition };
999
+ }
1000
+ const sponsorSpendingCondition = readSpendingCondition(r);
1001
+ return {
1002
+ authType: AuthType.Sponsored,
1003
+ spendingCondition,
1004
+ sponsorSpendingCondition
1005
+ };
1006
+ }
1007
+ function readAssetInfo(r) {
1008
+ return {
1009
+ address: readAddress(r),
1010
+ contractName: readLPString(r),
1011
+ assetName: readLPString(r)
1012
+ };
1013
+ }
1014
+ function readPostConditionPrincipal(r) {
1015
+ const type = r.readUInt8();
1016
+ switch (type) {
1017
+ case PostConditionPrincipalId.Origin:
1018
+ return { type: "origin" };
1019
+ case PostConditionPrincipalId.Standard:
1020
+ return { type: "standard", address: readAddress(r) };
1021
+ case PostConditionPrincipalId.Contract:
1022
+ return {
1023
+ type: "contract",
1024
+ address: readAddress(r),
1025
+ contractName: readLPString(r)
1026
+ };
1027
+ default:
1028
+ return { type: "origin" };
1029
+ }
1030
+ }
1031
+ function readPostCondition(r) {
1032
+ const assetType = r.readUInt8();
1033
+ const principal = readPostConditionPrincipal(r);
1034
+ switch (assetType) {
1035
+ case AssetType.STX:
1036
+ return {
1037
+ type: "stx",
1038
+ principal,
1039
+ conditionCode: r.readUInt8(),
1040
+ amount: r.readBigUInt64BE()
1041
+ };
1042
+ case AssetType.Fungible:
1043
+ return {
1044
+ type: "ft",
1045
+ principal,
1046
+ asset: readAssetInfo(r),
1047
+ conditionCode: r.readUInt8(),
1048
+ amount: r.readBigUInt64BE()
1049
+ };
1050
+ case AssetType.NonFungible:
1051
+ return {
1052
+ type: "nft",
1053
+ principal,
1054
+ asset: readAssetInfo(r),
1055
+ assetId: readCV(r),
1056
+ conditionCode: r.readUInt8()
1057
+ };
1058
+ case AssetType.Staking:
1059
+ return {
1060
+ type: "staking",
1061
+ principal,
1062
+ conditionCode: r.readUInt8(),
1063
+ amount: r.readBigUInt64BE()
1064
+ };
1065
+ case AssetType.Pox:
1066
+ return {
1067
+ type: "pox",
1068
+ principal,
1069
+ conditionCode: r.readUInt8()
1070
+ };
1071
+ default:
1072
+ throw new Error(`Unknown post-condition asset type: 0x${assetType.toString(16).padStart(2, "0")}`);
1073
+ }
1074
+ }
1075
+ function readPostConditions(r) {
1076
+ const count = r.readUInt32BE();
1077
+ const pcs = [];
1078
+ for (let i = 0;i < count; i++) {
1079
+ try {
1080
+ pcs.push(readPostCondition(r));
1081
+ } catch (e) {
1082
+ if (e instanceof Error && e.message.startsWith("Unknown post-condition asset type:")) {
1083
+ throw new Error(`${e.message} (post-condition ${i + 1}/${count})`);
1084
+ }
1085
+ throw e;
1086
+ }
1087
+ }
1088
+ return pcs;
1089
+ }
1090
+ function readPayload(r) {
1091
+ const payloadType = r.readUInt8();
1092
+ switch (payloadType) {
1093
+ case PayloadType.TokenTransfer: {
1094
+ const recipient = readCV(r);
1095
+ const amount = r.readBigUInt64BE();
1096
+ const memoBytes = r.readBytes(MEMO_MAX_LENGTH_BYTES);
1097
+ const memo = bytesToAscii(memoBytes).replace(/\0+$/, "");
1098
+ return {
1099
+ payloadType: PayloadType.TokenTransfer,
1100
+ recipient,
1101
+ amount,
1102
+ memo
1103
+ };
1104
+ }
1105
+ case PayloadType.ContractCall: {
1106
+ const contractAddress = readAddress(r);
1107
+ const contractName = readLPString(r);
1108
+ const functionName = readLPString(r);
1109
+ const numArgs = r.readUInt32BE();
1110
+ const functionArgs = [];
1111
+ for (let i = 0;i < numArgs; i++)
1112
+ functionArgs.push(readCV(r));
1113
+ return {
1114
+ payloadType: PayloadType.ContractCall,
1115
+ contractAddress,
1116
+ contractName,
1117
+ functionName,
1118
+ functionArgs
1119
+ };
1120
+ }
1121
+ case PayloadType.SmartContract: {
1122
+ const contractName = readLPString(r);
1123
+ const codeBody = readLPString(r, 4);
1124
+ return { payloadType: PayloadType.SmartContract, contractName, codeBody };
1125
+ }
1126
+ case PayloadType.VersionedSmartContract: {
1127
+ const clarityVersion = r.readUInt8();
1128
+ const contractName = readLPString(r);
1129
+ const codeBody = readLPString(r, 4);
1130
+ return {
1131
+ payloadType: PayloadType.VersionedSmartContract,
1132
+ clarityVersion,
1133
+ contractName,
1134
+ codeBody
1135
+ };
1136
+ }
1137
+ case PayloadType.Coinbase: {
1138
+ const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
1139
+ return { payloadType: PayloadType.Coinbase, coinbaseBuffer };
1140
+ }
1141
+ case PayloadType.CoinbaseToAltRecipient: {
1142
+ const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
1143
+ const recipient = readCV(r);
1144
+ return {
1145
+ payloadType: PayloadType.CoinbaseToAltRecipient,
1146
+ coinbaseBuffer,
1147
+ recipient
1148
+ };
1149
+ }
1150
+ case PayloadType.PoisonMicroblock: {
1151
+ const header1 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));
1152
+ const header2 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));
1153
+ return { payloadType: PayloadType.PoisonMicroblock, header1, header2 };
1154
+ }
1155
+ case PayloadType.TenureChange: {
1156
+ const tenureConsensusHash = bytesToHex(r.readBytes(20));
1157
+ const prevTenureConsensusHash = bytesToHex(r.readBytes(20));
1158
+ const burnViewConsensusHash = bytesToHex(r.readBytes(20));
1159
+ const previousTenureEnd = bytesToHex(r.readBytes(32));
1160
+ const previousTenureBlocks = r.readUInt32BE();
1161
+ const cause = r.readUInt8();
1162
+ const pubkeyHash = bytesToHex(r.readBytes(20));
1163
+ return {
1164
+ payloadType: PayloadType.TenureChange,
1165
+ tenureConsensusHash,
1166
+ prevTenureConsensusHash,
1167
+ burnViewConsensusHash,
1168
+ previousTenureEnd,
1169
+ previousTenureBlocks,
1170
+ cause,
1171
+ pubkeyHash
1172
+ };
1173
+ }
1174
+ case PayloadType.NakamotoCoinbase: {
1175
+ const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
1176
+ const optionalCV = readCV(r);
1177
+ const recipient = optionalCV.type === "none" ? null : optionalCV.type === "some" ? optionalCV.value : optionalCV;
1178
+ const vrfProof = bytesToHex(r.readBytes(VRF_PROOF_BYTES_LENGTH));
1179
+ return {
1180
+ payloadType: PayloadType.NakamotoCoinbase,
1181
+ coinbaseBuffer,
1182
+ recipient,
1183
+ vrfProof
1184
+ };
1185
+ }
1186
+ default:
1187
+ throw new Error(`Unknown payload type: ${payloadType}`);
1188
+ }
1189
+ }
1190
+ function deserializeTransaction(input, meta) {
1191
+ const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
1192
+ const r = new BytesReader(bytes);
1193
+ const tx = {
1194
+ version: r.readUInt8(),
1195
+ chainId: r.readUInt32BE(),
1196
+ auth: readAuthorization(r),
1197
+ anchorMode: r.readUInt8(),
1198
+ postConditionMode: r.readUInt8(),
1199
+ postConditions: readPostConditions(r),
1200
+ payload: readPayload(r)
1201
+ };
1202
+ if (meta?._multisig) {
1203
+ tx._multisig = meta._multisig;
1204
+ }
1205
+ return tx;
1206
+ }
1207
+
1208
+ // src/transports/createTransport.ts
1209
+ function createTransport(type, config) {
1210
+ const { request, apiKey: _apiKey, ...exposed } = config;
1211
+ return {
1212
+ type,
1213
+ request,
1214
+ config: exposed
1215
+ };
1216
+ }
1217
+
1218
+ // src/simnet/cv.ts
1219
+ var import_transactions = require("@stacks/transactions");
1220
+ // src/clarity/structuredData.ts
1221
+ var import_sha25 = require("@noble/hashes/sha2.js");
1222
+ var SIP018_PREFIX = new Uint8Array([
1223
+ 83,
1224
+ 73,
1225
+ 80,
1226
+ 48,
1227
+ 49,
1228
+ 56
1229
+ ]);
1230
+ // src/clarity/abi/standards.ts
1231
+ var SIP010_ABI = {
1232
+ functions: [
1233
+ {
1234
+ name: "transfer",
1235
+ access: "public",
1236
+ args: [
1237
+ { name: "amount", type: "uint128" },
1238
+ { name: "sender", type: "principal" },
1239
+ { name: "recipient", type: "principal" },
1240
+ { name: "memo", type: { optional: { buff: { length: 34 } } } }
1241
+ ],
1242
+ outputs: { response: { ok: "bool", error: "uint128" } }
1243
+ },
1244
+ {
1245
+ name: "get-balance",
1246
+ access: "read-only",
1247
+ args: [{ name: "account", type: "principal" }],
1248
+ outputs: { response: { ok: "uint128", error: "uint128" } }
1249
+ },
1250
+ {
1251
+ name: "get-total-supply",
1252
+ access: "read-only",
1253
+ args: [],
1254
+ outputs: { response: { ok: "uint128", error: "uint128" } }
1255
+ },
1256
+ {
1257
+ name: "get-name",
1258
+ access: "read-only",
1259
+ args: [],
1260
+ outputs: {
1261
+ response: {
1262
+ ok: { "string-ascii": { length: 32 } },
1263
+ error: "uint128"
1264
+ }
1265
+ }
1266
+ },
1267
+ {
1268
+ name: "get-symbol",
1269
+ access: "read-only",
1270
+ args: [],
1271
+ outputs: {
1272
+ response: {
1273
+ ok: { "string-ascii": { length: 10 } },
1274
+ error: "uint128"
1275
+ }
1276
+ }
1277
+ },
1278
+ {
1279
+ name: "get-decimals",
1280
+ access: "read-only",
1281
+ args: [],
1282
+ outputs: { response: { ok: "uint128", error: "uint128" } }
1283
+ },
1284
+ {
1285
+ name: "get-token-uri",
1286
+ access: "read-only",
1287
+ args: [],
1288
+ outputs: {
1289
+ response: {
1290
+ ok: { optional: { "string-utf8": { length: 256 } } },
1291
+ error: "uint128"
1292
+ }
1293
+ }
1294
+ }
1295
+ ],
1296
+ fungible_tokens: [{ name: "token" }]
1297
+ };
1298
+ var SIP009_ABI = {
1299
+ functions: [
1300
+ {
1301
+ name: "transfer",
1302
+ access: "public",
1303
+ args: [
1304
+ { name: "id", type: "uint128" },
1305
+ { name: "sender", type: "principal" },
1306
+ { name: "recipient", type: "principal" }
1307
+ ],
1308
+ outputs: { response: { ok: "bool", error: "uint128" } }
1309
+ },
1310
+ {
1311
+ name: "get-owner",
1312
+ access: "read-only",
1313
+ args: [{ name: "id", type: "uint128" }],
1314
+ outputs: {
1315
+ response: { ok: { optional: "principal" }, error: "uint128" }
1316
+ }
1317
+ },
1318
+ {
1319
+ name: "get-last-token-id",
1320
+ access: "read-only",
1321
+ args: [],
1322
+ outputs: { response: { ok: "uint128", error: "uint128" } }
1323
+ },
1324
+ {
1325
+ name: "get-token-uri",
1326
+ access: "read-only",
1327
+ args: [{ name: "id", type: "uint128" }],
1328
+ outputs: {
1329
+ response: {
1330
+ ok: { optional: { "string-utf8": { length: 256 } } },
1331
+ error: "uint128"
1332
+ }
1333
+ }
1334
+ }
1335
+ ],
1336
+ non_fungible_tokens: [{ name: "nft", type: "uint128" }]
1337
+ };
1338
+ var SIP013_ABI = {
1339
+ functions: [
1340
+ {
1341
+ name: "transfer",
1342
+ access: "public",
1343
+ args: [
1344
+ { name: "token-id", type: "uint128" },
1345
+ { name: "amount", type: "uint128" },
1346
+ { name: "sender", type: "principal" },
1347
+ { name: "recipient", type: "principal" }
1348
+ ],
1349
+ outputs: { response: { ok: "bool", error: "uint128" } }
1350
+ },
1351
+ {
1352
+ name: "transfer-memo",
1353
+ access: "public",
1354
+ args: [
1355
+ { name: "token-id", type: "uint128" },
1356
+ { name: "amount", type: "uint128" },
1357
+ { name: "sender", type: "principal" },
1358
+ { name: "recipient", type: "principal" },
1359
+ { name: "memo", type: { buff: { length: 34 } } }
1360
+ ],
1361
+ outputs: { response: { ok: "bool", error: "uint128" } }
1362
+ },
1363
+ {
1364
+ name: "transfer-many",
1365
+ access: "public",
1366
+ args: [
1367
+ {
1368
+ name: "transfers",
1369
+ type: {
1370
+ list: {
1371
+ type: {
1372
+ tuple: [
1373
+ { name: "token-id", type: "uint128" },
1374
+ { name: "amount", type: "uint128" },
1375
+ { name: "sender", type: "principal" },
1376
+ { name: "recipient", type: "principal" }
1377
+ ]
1378
+ },
1379
+ length: 200
1380
+ }
1381
+ }
1382
+ }
1383
+ ],
1384
+ outputs: { response: { ok: "bool", error: "uint128" } }
1385
+ },
1386
+ {
1387
+ name: "transfer-many-memo",
1388
+ access: "public",
1389
+ args: [
1390
+ {
1391
+ name: "transfers",
1392
+ type: {
1393
+ list: {
1394
+ type: {
1395
+ tuple: [
1396
+ { name: "token-id", type: "uint128" },
1397
+ { name: "amount", type: "uint128" },
1398
+ { name: "sender", type: "principal" },
1399
+ { name: "recipient", type: "principal" },
1400
+ { name: "memo", type: { buff: { length: 34 } } }
1401
+ ]
1402
+ },
1403
+ length: 200
1404
+ }
1405
+ }
1406
+ }
1407
+ ],
1408
+ outputs: { response: { ok: "bool", error: "uint128" } }
1409
+ },
1410
+ {
1411
+ name: "get-balance",
1412
+ access: "read-only",
1413
+ args: [
1414
+ { name: "token-id", type: "uint128" },
1415
+ { name: "account", type: "principal" }
1416
+ ],
1417
+ outputs: { response: { ok: "uint128", error: "uint128" } }
1418
+ },
1419
+ {
1420
+ name: "get-overall-balance",
1421
+ access: "read-only",
1422
+ args: [{ name: "account", type: "principal" }],
1423
+ outputs: { response: { ok: "uint128", error: "uint128" } }
1424
+ },
1425
+ {
1426
+ name: "get-total-supply",
1427
+ access: "read-only",
1428
+ args: [{ name: "token-id", type: "uint128" }],
1429
+ outputs: { response: { ok: "uint128", error: "uint128" } }
1430
+ },
1431
+ {
1432
+ name: "get-overall-supply",
1433
+ access: "read-only",
1434
+ args: [],
1435
+ outputs: { response: { ok: "uint128", error: "uint128" } }
1436
+ },
1437
+ {
1438
+ name: "get-decimals",
1439
+ access: "read-only",
1440
+ args: [{ name: "token-id", type: "uint128" }],
1441
+ outputs: { response: { ok: "uint128", error: "uint128" } }
1442
+ },
1443
+ {
1444
+ name: "get-token-uri",
1445
+ access: "read-only",
1446
+ args: [{ name: "token-id", type: "uint128" }],
1447
+ outputs: {
1448
+ response: {
1449
+ ok: { optional: { "string-utf8": { length: 256 } } },
1450
+ error: "uint128"
1451
+ }
1452
+ }
1453
+ }
1454
+ ],
1455
+ fungible_tokens: [],
1456
+ non_fungible_tokens: []
1457
+ };
1458
+ // src/clarity/abi/classify.ts
1459
+ var STANDARDS = [
1460
+ { id: "sip-010", abi: SIP010_ABI, optional: new Set(["get-token-uri"]) },
1461
+ { id: "sip-009", abi: SIP009_ABI, optional: new Set(["get-token-uri"]) },
1462
+ {
1463
+ id: "sip-013",
1464
+ abi: SIP013_ABI,
1465
+ optional: new Set([
1466
+ "transfer-memo",
1467
+ "transfer-many",
1468
+ "transfer-many-memo",
1469
+ "get-token-uri",
1470
+ "get-overall-balance",
1471
+ "get-overall-supply"
1472
+ ])
1473
+ }
1474
+ ];
1475
+ // src/clarity/bridge.ts
1476
+ var CV_TYPE_TAGS = new Set([
1477
+ "int",
1478
+ "uint",
1479
+ "true",
1480
+ "false",
1481
+ "address",
1482
+ "contract",
1483
+ "ascii",
1484
+ "utf8",
1485
+ "buffer",
1486
+ "list",
1487
+ "tuple",
1488
+ "none",
1489
+ "some",
1490
+ "ok",
1491
+ "err"
1492
+ ]);
1493
+ // src/simnet/cv.ts
1494
+ function toChain(cv) {
1495
+ return import_transactions.Cl.deserialize(serializeCV(cv));
1496
+ }
1497
+ function fromChain(cv) {
1498
+ return deserializeCV(import_transactions.Cl.serialize(cv));
1499
+ }
1500
+ function hexCv(cv) {
1501
+ return `0x${serializeCV(cv)}`;
1502
+ }
1503
+ function cvFromHex(hex) {
1504
+ return deserializeCV(hex);
1505
+ }
1506
+ function stxBalance(session, address) {
1507
+ const holders = session.getAssetsMap().get("STX");
1508
+ return holders?.get(address) ?? 0n;
1509
+ }
1510
+
1511
+ // src/simnet/errors.ts
1512
+ class SimnetUnsupportedError extends BaseError {
1513
+ name = "SimnetUnsupportedError";
1514
+ path;
1515
+ constructor(path) {
1516
+ super(`simnet transport does not implement ${path}`);
1517
+ this.path = path;
1518
+ }
1519
+ }
1520
+
1521
+ // src/simnet/transport.ts
1522
+ function stripQuery(path) {
1523
+ const q = path.indexOf("?");
1524
+ return q === -1 ? path : path.slice(0, q);
1525
+ }
1526
+ function decodePath(path) {
1527
+ return stripQuery(path).split("/").filter(Boolean).map((s) => decodeURIComponent(s));
1528
+ }
1529
+ function contractId(address, name) {
1530
+ return `${address}.${name}`;
1531
+ }
1532
+ function originAddress(signerHash160, network) {
1533
+ const version = network === "mainnet" ? AddressVersion.MainnetSingleSig : AddressVersion.TestnetSingleSig;
1534
+ return c32address(version, signerHash160);
1535
+ }
1536
+ function normalizeTxid(txid2) {
1537
+ return txid2.startsWith("0x") ? txid2 : `0x${txid2}`;
1538
+ }
1539
+ function notFound(path) {
1540
+ throw new HttpRequestError(404, { url: path, method: "GET" });
1541
+ }
1542
+ function noEstimate(path) {
1543
+ throw new HttpRequestError(400, {
1544
+ url: path,
1545
+ method: "POST",
1546
+ details: '{"reason":"NoEstimateAvailable"}'
1547
+ });
1548
+ }
1549
+ function simnet(session) {
1550
+ const nonces = new Map;
1551
+ const receipts = new Map;
1552
+ const request = async (path, options) => {
1553
+ const method = options?.method ?? "GET";
1554
+ const parts = decodePath(path);
1555
+ if (parts[0] === "v2" && parts[1] === "info" && method === "GET") {
1556
+ return {
1557
+ stacks_tip_height: session.stacksBlockHeight ?? session.blockHeight
1558
+ };
1559
+ }
1560
+ if (parts[0] === "v2" && parts[1] === "accounts" && parts[2] && method === "GET") {
1561
+ const address = parts[2];
1562
+ return {
1563
+ nonce: nonces.get(address) ?? 0,
1564
+ balance: String(stxBalance(session, address))
1565
+ };
1566
+ }
1567
+ if (parts[0] === "v2" && parts[1] === "contracts" && parts[2] === "call-read" && parts[3] && parts[4] && parts[5] && method === "POST") {
1568
+ const body = options?.body;
1569
+ const id = contractId(parts[3], parts[4]);
1570
+ const fn = parts[5];
1571
+ const sender = body?.sender ?? parts[3];
1572
+ const args = (body?.arguments ?? []).map((hex) => toChain(cvFromHex(hex)));
1573
+ try {
1574
+ const { result } = session.callReadOnlyFn(id, fn, args, sender);
1575
+ return { okay: true, result: hexCv(fromChain(result)) };
1576
+ } catch (error) {
1577
+ const cause = error instanceof Error ? error.message : String(error);
1578
+ return { okay: false, cause };
1579
+ }
1580
+ }
1581
+ if (parts[0] === "v2" && parts[1] === "map_entry" && parts[2] && parts[3] && parts[4] && method === "POST") {
1582
+ const keyHex = typeof options?.body === "string" ? options.body : String(options?.body ?? "");
1583
+ const value = session.getMapEntry(contractId(parts[2], parts[3]), parts[4], toChain(cvFromHex(keyHex)));
1584
+ return { data: hexCv(fromChain(value)) };
1585
+ }
1586
+ if (parts[0] === "v2" && parts[1] === "data_var" && parts[2] && parts[3] && parts[4] && method === "GET") {
1587
+ const value = session.getDataVar(contractId(parts[2], parts[3]), parts[4]);
1588
+ return { data: hexCv(fromChain(value)) };
1589
+ }
1590
+ if (parts[0] === "v2" && parts[1] === "fees" && method === "POST") {
1591
+ noEstimate(path);
1592
+ }
1593
+ if (parts[0] === "v2" && parts[1] === "transactions" && method === "POST") {
1594
+ return handleBroadcast(session, options?.body, nonces, receipts);
1595
+ }
1596
+ if (parts[0] === "extended" && parts[1] === "v1" && parts[2] === "tx" && parts[3] && method === "GET") {
1597
+ const row = receipts.get(normalizeTxid(parts[3]));
1598
+ if (!row)
1599
+ notFound(path);
1600
+ return row;
1601
+ }
1602
+ throw new SimnetUnsupportedError(stripQuery(path));
1603
+ };
1604
+ return () => createTransport("simnet", { request });
1605
+ }
1606
+ function handleBroadcast(session, body, nonces, receipts) {
1607
+ const txHex = typeof body === "object" && body !== null && "tx" in body ? String(body.tx) : "";
1608
+ const tx = deserializeTransaction(hexToBytes(without0x(txHex)));
1609
+ const txid2 = normalizeTxid(getTransactionId(tx));
1610
+ const network = tx.chainId === 1 ? "mainnet" : "testnet";
1611
+ const sender = originAddress(tx.auth.spendingCondition.signer, network);
1612
+ let resultHex;
1613
+ let events = [];
1614
+ let aborted = false;
1615
+ if (tx.payload.payloadType === PayloadType.ContractCall) {
1616
+ const p = tx.payload;
1617
+ const id = contractId(p.contractAddress, p.contractName);
1618
+ const parsed = session.callPublicFn(id, p.functionName, p.functionArgs.map(toChain), sender);
1619
+ const ours = fromChain(parsed.result);
1620
+ resultHex = hexCv(ours);
1621
+ events = parsed.events;
1622
+ aborted = ours.type === "err";
1623
+ } else if (tx.payload.payloadType === PayloadType.TokenTransfer) {
1624
+ const recipient = tx.payload.recipient;
1625
+ const to = recipient.type === "address" || recipient.type === "contract" ? recipient.value : sender;
1626
+ const parsed = session.transferSTX(tx.payload.amount, to, sender);
1627
+ resultHex = hexCv(fromChain(parsed.result));
1628
+ events = parsed.events;
1629
+ } else {
1630
+ throw new SimnetUnsupportedError(`POST /v2/transactions payload ${tx.payload.payloadType}`);
1631
+ }
1632
+ nonces.set(sender, Number(tx.auth.spendingCondition.nonce) + 1);
1633
+ receipts.set(txid2, {
1634
+ tx_status: aborted ? "abort_by_response" : "success",
1635
+ block_height: session.stacksBlockHeight ?? session.blockHeight,
1636
+ tx_result: resultHex ? { hex: resultHex } : undefined,
1637
+ events
1638
+ });
1639
+ return { txid: txid2 };
1640
+ }
1641
+ // src/chains/definitions.ts
1642
+ var devnet = {
1643
+ id: 2147483648,
1644
+ name: "Stacks Devnet",
1645
+ network: "testnet",
1646
+ transactionVersion: 128,
1647
+ peerNetworkId: 4278190080,
1648
+ addressVersion: { singleSig: 26, multiSig: 21 },
1649
+ magicBytes: "id",
1650
+ bootAddress: "ST000000000000000000002AMW42H",
1651
+ nativeCurrency: { name: "Stacks", symbol: "STX", decimals: 6 },
1652
+ rpcUrls: {
1653
+ default: {
1654
+ http: ["http://localhost:3999"],
1655
+ ws: ["ws://localhost:3999/extended/v1/ws"]
1656
+ }
1657
+ }
1658
+ };
1659
+ var mocknet = {
1660
+ ...devnet,
1661
+ name: "Stacks Mocknet",
1662
+ addressVersion: { ...devnet.addressVersion }
1663
+ };
1664
+
1665
+ // src/simnet/chain.ts
1666
+ var simnetChain = {
1667
+ ...mocknet,
1668
+ name: "Clarinet Simnet",
1669
+ rpcUrls: {
1670
+ default: { http: ["simnet://clarinet"] }
1671
+ }
1672
+ };
1673
+
1674
+ //# debugId=3C6E178AD647FF0064756E2164756E21
1675
+ //# sourceMappingURL=index.cjs.map