@secondlayer/stacks 5.1.3 → 6.0.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 +1 -8
- package/package.json +3 -23
- package/dist/src/tools/btc/index.cjs +0 -131
- package/dist/src/tools/btc/index.cjs.map +0 -10
- package/dist/src/tools/btc/index.d.cts +0 -10
- package/dist/src/tools/btc/index.d.ts +0 -10
- package/dist/src/tools/btc/index.js +0 -90
- package/dist/src/tools/btc/index.js.map +0 -10
- package/dist/src/tools/index.cjs +0 -3865
- package/dist/src/tools/index.cjs.map +0 -80
- package/dist/src/tools/index.d.cts +0 -206
- package/dist/src/tools/index.d.ts +0 -206
- package/dist/src/tools/index.js +0 -3827
- package/dist/src/tools/index.js.map +0 -80
package/dist/src/tools/index.js
DELETED
|
@@ -1,3827 +0,0 @@
|
|
|
1
|
-
// src/tools/index.ts
|
|
2
|
-
import { tool } from "ai";
|
|
3
|
-
import { z } from "zod";
|
|
4
|
-
|
|
5
|
-
// src/errors/base.ts
|
|
6
|
-
function codeFromName(name) {
|
|
7
|
-
return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toUpperCase();
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
class BaseError extends Error {
|
|
11
|
-
name = "StacksError";
|
|
12
|
-
#code;
|
|
13
|
-
shortMessage;
|
|
14
|
-
details;
|
|
15
|
-
constructor(shortMessage, options) {
|
|
16
|
-
const message = [
|
|
17
|
-
shortMessage,
|
|
18
|
-
options?.details ? `
|
|
19
|
-
${options.details}` : ""
|
|
20
|
-
].join("");
|
|
21
|
-
super(message, { cause: options?.cause });
|
|
22
|
-
if (options?.code !== undefined)
|
|
23
|
-
this.#code = options.code;
|
|
24
|
-
this.shortMessage = shortMessage;
|
|
25
|
-
this.details = options?.details;
|
|
26
|
-
}
|
|
27
|
-
get code() {
|
|
28
|
-
return this.#code ?? codeFromName(this.name);
|
|
29
|
-
}
|
|
30
|
-
set code(value) {
|
|
31
|
-
this.#code = value;
|
|
32
|
-
}
|
|
33
|
-
toJSON() {
|
|
34
|
-
return {
|
|
35
|
-
name: this.name,
|
|
36
|
-
code: this.code,
|
|
37
|
-
message: this.message,
|
|
38
|
-
shortMessage: this.shortMessage,
|
|
39
|
-
details: this.details,
|
|
40
|
-
cause: this.cause instanceof Error ? this.cause.message : undefined
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
// src/errors/response.ts
|
|
46
|
-
class MalformedResponseError extends BaseError {
|
|
47
|
-
name = "MalformedResponseError";
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
class ReadContractError extends BaseError {
|
|
51
|
-
name = "ReadContractError";
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// src/utils/c32.ts
|
|
55
|
-
import { sha256 } from "@noble/hashes/sha2.js";
|
|
56
|
-
|
|
57
|
-
// src/utils/encoding.ts
|
|
58
|
-
var hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
59
|
-
function bytesToHex(bytes) {
|
|
60
|
-
let hex = "";
|
|
61
|
-
for (const b of bytes) {
|
|
62
|
-
hex += hexes[b];
|
|
63
|
-
}
|
|
64
|
-
return hex;
|
|
65
|
-
}
|
|
66
|
-
function hexToBytes(hex) {
|
|
67
|
-
let h = without0x(hex);
|
|
68
|
-
if (h.length % 2)
|
|
69
|
-
h = `0${h}`;
|
|
70
|
-
const array = new Uint8Array(h.length / 2);
|
|
71
|
-
for (let i = 0;i < array.length; i++) {
|
|
72
|
-
const j = i * 2;
|
|
73
|
-
const byte = Number.parseInt(h.slice(j, j + 2), 16);
|
|
74
|
-
if (Number.isNaN(byte) || byte < 0)
|
|
75
|
-
throw new Error("Invalid byte sequence");
|
|
76
|
-
array[i] = byte;
|
|
77
|
-
}
|
|
78
|
-
return array;
|
|
79
|
-
}
|
|
80
|
-
function with0x(value) {
|
|
81
|
-
return /^0x/i.test(value) ? value : `0x${value}`;
|
|
82
|
-
}
|
|
83
|
-
function without0x(value) {
|
|
84
|
-
return /^0x/i.test(value) ? value.slice(2) : value;
|
|
85
|
-
}
|
|
86
|
-
function utf8ToBytes(str) {
|
|
87
|
-
return new TextEncoder().encode(str);
|
|
88
|
-
}
|
|
89
|
-
function bytesToUtf8(bytes) {
|
|
90
|
-
return new TextDecoder().decode(bytes);
|
|
91
|
-
}
|
|
92
|
-
function asciiToBytes(str) {
|
|
93
|
-
const bytes = new Uint8Array(str.length);
|
|
94
|
-
for (let i = 0;i < str.length; i++) {
|
|
95
|
-
bytes[i] = str.charCodeAt(i) & 255;
|
|
96
|
-
}
|
|
97
|
-
return bytes;
|
|
98
|
-
}
|
|
99
|
-
function bytesToAscii(bytes) {
|
|
100
|
-
return String.fromCharCode(...bytes);
|
|
101
|
-
}
|
|
102
|
-
function concatBytes(...arrays) {
|
|
103
|
-
if (arrays.length === 1)
|
|
104
|
-
return arrays[0];
|
|
105
|
-
const length = arrays.reduce((a, arr) => a + arr.length, 0);
|
|
106
|
-
const result = new Uint8Array(length);
|
|
107
|
-
let pad = 0;
|
|
108
|
-
for (const arr of arrays) {
|
|
109
|
-
result.set(arr, pad);
|
|
110
|
-
pad += arr.length;
|
|
111
|
-
}
|
|
112
|
-
return result;
|
|
113
|
-
}
|
|
114
|
-
function intToBigInt(value) {
|
|
115
|
-
if (typeof value === "bigint")
|
|
116
|
-
return value;
|
|
117
|
-
if (typeof value === "string")
|
|
118
|
-
return BigInt(value);
|
|
119
|
-
if (typeof value === "number") {
|
|
120
|
-
if (!Number.isInteger(value))
|
|
121
|
-
throw new RangeError("Values of type 'number' must be an integer.");
|
|
122
|
-
if (value > Number.MAX_SAFE_INTEGER)
|
|
123
|
-
throw new RangeError(`Values of type 'number' must be <= ${Number.MAX_SAFE_INTEGER}. Use BigInt instead.`);
|
|
124
|
-
return BigInt(value);
|
|
125
|
-
}
|
|
126
|
-
if (value instanceof Uint8Array)
|
|
127
|
-
return BigInt(`0x${bytesToHex(value)}`);
|
|
128
|
-
throw new TypeError("Must be a number, bigint, string, or Uint8Array.");
|
|
129
|
-
}
|
|
130
|
-
function intToBytes(value, byteLength) {
|
|
131
|
-
return bigIntToBytes(intToBigInt(value), byteLength);
|
|
132
|
-
}
|
|
133
|
-
function bigIntToBytes(value, length = 16) {
|
|
134
|
-
const hex = value.toString(16).padStart(length * 2, "0");
|
|
135
|
-
return hexToBytes(hex);
|
|
136
|
-
}
|
|
137
|
-
function intToHex(integer, byteLength = 8) {
|
|
138
|
-
const value = typeof integer === "bigint" ? integer : intToBigInt(integer);
|
|
139
|
-
return value.toString(16).padStart(byteLength * 2, "0");
|
|
140
|
-
}
|
|
141
|
-
function toTwos(value, width) {
|
|
142
|
-
const limit = BigInt(1) << width - BigInt(1);
|
|
143
|
-
if (value < -limit || value > limit - BigInt(1)) {
|
|
144
|
-
throw new Error(`Unable to represent integer in width: ${width}`);
|
|
145
|
-
}
|
|
146
|
-
if (value >= BigInt(0))
|
|
147
|
-
return value;
|
|
148
|
-
return value + (BigInt(1) << width);
|
|
149
|
-
}
|
|
150
|
-
function fromTwos(value, width) {
|
|
151
|
-
if (value & BigInt(1) << width - BigInt(1)) {
|
|
152
|
-
return value - (BigInt(1) << width);
|
|
153
|
-
}
|
|
154
|
-
return value;
|
|
155
|
-
}
|
|
156
|
-
function bytesToTwosBigInt(bytes) {
|
|
157
|
-
if (bytes.length === 0)
|
|
158
|
-
return 0n;
|
|
159
|
-
const hex = bytesToHex(bytes);
|
|
160
|
-
if (hex.length === 0)
|
|
161
|
-
return 0n;
|
|
162
|
-
return fromTwos(BigInt(`0x${hex}`), BigInt(bytes.byteLength * 8));
|
|
163
|
-
}
|
|
164
|
-
function writeUInt32BE(value) {
|
|
165
|
-
const buf = new Uint8Array(4);
|
|
166
|
-
buf[0] = value >>> 24 & 255;
|
|
167
|
-
buf[1] = value >>> 16 & 255;
|
|
168
|
-
buf[2] = value >>> 8 & 255;
|
|
169
|
-
buf[3] = value & 255;
|
|
170
|
-
return buf;
|
|
171
|
-
}
|
|
172
|
-
function writeUInt16BE(value) {
|
|
173
|
-
const buf = new Uint8Array(2);
|
|
174
|
-
buf[0] = value >>> 8 & 255;
|
|
175
|
-
buf[1] = value & 255;
|
|
176
|
-
return buf;
|
|
177
|
-
}
|
|
178
|
-
function writeUInt8(value) {
|
|
179
|
-
return new Uint8Array([value & 255]);
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
// src/utils/c32.ts
|
|
183
|
-
var C32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
184
|
-
var HEX = "0123456789abcdef";
|
|
185
|
-
function c32normalize(input) {
|
|
186
|
-
return input.toUpperCase().replace(/O/g, "0").replace(/L|I/g, "1");
|
|
187
|
-
}
|
|
188
|
-
function c32encode(inputHex) {
|
|
189
|
-
let hex = inputHex;
|
|
190
|
-
if (hex.length % 2 !== 0)
|
|
191
|
-
hex = `0${hex}`;
|
|
192
|
-
hex = hex.toLowerCase();
|
|
193
|
-
const res = [];
|
|
194
|
-
let carry = 0;
|
|
195
|
-
for (let i = hex.length - 1;i >= 0; i--) {
|
|
196
|
-
if (carry < 4) {
|
|
197
|
-
const currentCode = HEX.indexOf(hex[i]) >> carry;
|
|
198
|
-
const nextCode = i !== 0 ? HEX.indexOf(hex[i - 1]) : 0;
|
|
199
|
-
const nextBits = 1 + carry;
|
|
200
|
-
const nextLowBits = nextCode % (1 << nextBits) << 5 - nextBits;
|
|
201
|
-
res.unshift(C32[currentCode + nextLowBits]);
|
|
202
|
-
carry = nextBits;
|
|
203
|
-
} else {
|
|
204
|
-
carry = 0;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
let leadingZeros = 0;
|
|
208
|
-
while (leadingZeros < res.length && res[leadingZeros] === "0")
|
|
209
|
-
leadingZeros++;
|
|
210
|
-
const stripped = res.slice(leadingZeros);
|
|
211
|
-
const bytes = hexToBytes(hex);
|
|
212
|
-
let zeroBytesCount = 0;
|
|
213
|
-
while (zeroBytesCount < bytes.length && bytes[zeroBytesCount] === 0)
|
|
214
|
-
zeroBytesCount++;
|
|
215
|
-
const prefix = Array(zeroBytesCount).fill(C32[0]);
|
|
216
|
-
return [...prefix, ...stripped].join("");
|
|
217
|
-
}
|
|
218
|
-
function c32decode(c32input) {
|
|
219
|
-
const input = c32normalize(c32input);
|
|
220
|
-
if (!input.match(`^[${C32}]*$`))
|
|
221
|
-
throw new Error("Not a c32-encoded string");
|
|
222
|
-
const zeroPrefix = input.match(`^${C32[0]}*`);
|
|
223
|
-
const numLeadingZeroBytes = zeroPrefix ? zeroPrefix[0]?.length : 0;
|
|
224
|
-
const res = [];
|
|
225
|
-
let carry = 0;
|
|
226
|
-
let carryBits = 0;
|
|
227
|
-
for (let i = input.length - 1;i >= 0; i--) {
|
|
228
|
-
if (carryBits === 4) {
|
|
229
|
-
res.unshift(HEX[carry]);
|
|
230
|
-
carryBits = 0;
|
|
231
|
-
carry = 0;
|
|
232
|
-
}
|
|
233
|
-
const currentValue = (C32.indexOf(input[i]) << carryBits) + carry;
|
|
234
|
-
res.unshift(HEX[currentValue % 16]);
|
|
235
|
-
carryBits += 1;
|
|
236
|
-
carry = currentValue >> 4;
|
|
237
|
-
if (carry > 1 << carryBits)
|
|
238
|
-
throw new Error("Panic error in c32 decoding");
|
|
239
|
-
}
|
|
240
|
-
res.unshift(HEX[carry]);
|
|
241
|
-
if (res.length % 2 === 1)
|
|
242
|
-
res.unshift("0");
|
|
243
|
-
let hexLeadingZeros = 0;
|
|
244
|
-
while (hexLeadingZeros < res.length && res[hexLeadingZeros] === "0")
|
|
245
|
-
hexLeadingZeros++;
|
|
246
|
-
let hexStr = res.slice(hexLeadingZeros - hexLeadingZeros % 2).join("");
|
|
247
|
-
for (let i = 0;i < numLeadingZeroBytes; i++)
|
|
248
|
-
hexStr = `00${hexStr}`;
|
|
249
|
-
return hexStr;
|
|
250
|
-
}
|
|
251
|
-
function c32checksum(dataHex) {
|
|
252
|
-
return bytesToHex(sha256(sha256(hexToBytes(dataHex))).slice(0, 4));
|
|
253
|
-
}
|
|
254
|
-
function c32checkEncode(version, data) {
|
|
255
|
-
if (version < 0 || version >= 32)
|
|
256
|
-
throw new Error("Invalid version (must be between 0 and 31)");
|
|
257
|
-
if (!data.match(/^[0-9a-fA-F]*$/))
|
|
258
|
-
throw new Error("Invalid data (not a hex string)");
|
|
259
|
-
let d = data.toLowerCase();
|
|
260
|
-
if (d.length % 2 !== 0)
|
|
261
|
-
d = `0${d}`;
|
|
262
|
-
let versionHex = version.toString(16);
|
|
263
|
-
if (versionHex.length === 1)
|
|
264
|
-
versionHex = `0${versionHex}`;
|
|
265
|
-
const checksumHex = c32checksum(`${versionHex}${d}`);
|
|
266
|
-
return `${C32[version]}${c32encode(`${d}${checksumHex}`)}`;
|
|
267
|
-
}
|
|
268
|
-
function c32checkDecode(c32data) {
|
|
269
|
-
const normalized = c32normalize(c32data);
|
|
270
|
-
const dataHex = c32decode(normalized.slice(1));
|
|
271
|
-
const version = C32.indexOf(normalized[0]);
|
|
272
|
-
const checksum = dataHex.slice(-8);
|
|
273
|
-
let versionHex = version.toString(16);
|
|
274
|
-
if (versionHex.length === 1)
|
|
275
|
-
versionHex = `0${versionHex}`;
|
|
276
|
-
if (c32checksum(`${versionHex}${dataHex.substring(0, dataHex.length - 8)}`) !== checksum) {
|
|
277
|
-
throw new Error("Invalid c32check string: checksum mismatch");
|
|
278
|
-
}
|
|
279
|
-
return [version, dataHex.substring(0, dataHex.length - 8)];
|
|
280
|
-
}
|
|
281
|
-
function c32address(version, hash160hex) {
|
|
282
|
-
if (!hash160hex.match(/^[0-9a-fA-F]{40}$/)) {
|
|
283
|
-
throw new Error("Invalid argument: not a hash160 hex string");
|
|
284
|
-
}
|
|
285
|
-
return `S${c32checkEncode(version, hash160hex)}`;
|
|
286
|
-
}
|
|
287
|
-
function c32addressDecode(c32addr) {
|
|
288
|
-
if (c32addr.length <= 5)
|
|
289
|
-
throw new Error("Invalid c32 address: invalid length");
|
|
290
|
-
if (c32addr[0] !== "S")
|
|
291
|
-
throw new Error('Invalid c32 address: must start with "S"');
|
|
292
|
-
return c32checkDecode(c32addr.slice(1));
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
// src/clarity/types.ts
|
|
296
|
-
var ClarityWireType = {
|
|
297
|
-
int: 0,
|
|
298
|
-
uint: 1,
|
|
299
|
-
buffer: 2,
|
|
300
|
-
true: 3,
|
|
301
|
-
false: 4,
|
|
302
|
-
address: 5,
|
|
303
|
-
contract: 6,
|
|
304
|
-
ok: 7,
|
|
305
|
-
err: 8,
|
|
306
|
-
none: 9,
|
|
307
|
-
some: 10,
|
|
308
|
-
list: 11,
|
|
309
|
-
tuple: 12,
|
|
310
|
-
ascii: 13,
|
|
311
|
-
utf8: 14
|
|
312
|
-
};
|
|
313
|
-
var wireTypeToClarity = Object.fromEntries(Object.entries(ClarityWireType).map(([k, v]) => [v, k]));
|
|
314
|
-
function clarityTypeFromByte(byte) {
|
|
315
|
-
const type = wireTypeToClarity[byte];
|
|
316
|
-
if (!type)
|
|
317
|
-
throw new Error(`Unknown clarity wire type: ${byte}`);
|
|
318
|
-
return type;
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
// src/clarity/serialize.ts
|
|
322
|
-
var CLARITY_INT_SIZE = 128n;
|
|
323
|
-
var CLARITY_INT_BYTE_SIZE = 16;
|
|
324
|
-
function typeIdByte(type) {
|
|
325
|
-
return ClarityWireType[type];
|
|
326
|
-
}
|
|
327
|
-
function withTypeId(type, bytes) {
|
|
328
|
-
return concatBytes(new Uint8Array([typeIdByte(type)]), bytes);
|
|
329
|
-
}
|
|
330
|
-
function serializeAddress(c32Address) {
|
|
331
|
-
const [version, hash160] = c32addressDecode(c32Address);
|
|
332
|
-
return concatBytes(new Uint8Array([version]), hexToBytes(hash160));
|
|
333
|
-
}
|
|
334
|
-
function serializeLPString(str, prefixBytes = 1) {
|
|
335
|
-
const content = utf8ToBytes(str);
|
|
336
|
-
const lengthPrefix = hexToBytes(intToHex(content.byteLength, prefixBytes));
|
|
337
|
-
return concatBytes(lengthPrefix, content);
|
|
338
|
-
}
|
|
339
|
-
function serializeCVBytes(value) {
|
|
340
|
-
switch (value.type) {
|
|
341
|
-
case "true":
|
|
342
|
-
case "false":
|
|
343
|
-
return new Uint8Array([typeIdByte(value.type)]);
|
|
344
|
-
case "int": {
|
|
345
|
-
const bytes = bigIntToBytes(toTwos(BigInt(value.value), CLARITY_INT_SIZE), CLARITY_INT_BYTE_SIZE);
|
|
346
|
-
return withTypeId(value.type, bytes);
|
|
347
|
-
}
|
|
348
|
-
case "uint": {
|
|
349
|
-
const bytes = bigIntToBytes(BigInt(value.value), CLARITY_INT_BYTE_SIZE);
|
|
350
|
-
return withTypeId(value.type, bytes);
|
|
351
|
-
}
|
|
352
|
-
case "buffer": {
|
|
353
|
-
const bufBytes = hexToBytes(value.value);
|
|
354
|
-
return withTypeId(value.type, concatBytes(writeUInt32BE(bufBytes.length), bufBytes));
|
|
355
|
-
}
|
|
356
|
-
case "none":
|
|
357
|
-
return new Uint8Array([typeIdByte(value.type)]);
|
|
358
|
-
case "some":
|
|
359
|
-
return withTypeId(value.type, serializeCVBytes(value.value));
|
|
360
|
-
case "ok":
|
|
361
|
-
case "err":
|
|
362
|
-
return withTypeId(value.type, serializeCVBytes(value.value));
|
|
363
|
-
case "address":
|
|
364
|
-
return withTypeId(value.type, serializeAddress(value.value));
|
|
365
|
-
case "contract": {
|
|
366
|
-
const [addr, name] = value.value.split(".");
|
|
367
|
-
if (!addr || !name)
|
|
368
|
-
throw new Error(`Invalid contract principal: ${value.value}`);
|
|
369
|
-
return withTypeId(value.type, concatBytes(serializeAddress(addr), serializeLPString(name)));
|
|
370
|
-
}
|
|
371
|
-
case "list": {
|
|
372
|
-
const parts = [writeUInt32BE(value.value.length)];
|
|
373
|
-
for (const item of value.value) {
|
|
374
|
-
parts.push(serializeCVBytes(item));
|
|
375
|
-
}
|
|
376
|
-
return withTypeId(value.type, concatBytes(...parts));
|
|
377
|
-
}
|
|
378
|
-
case "tuple": {
|
|
379
|
-
const keys = Object.keys(value.value).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
380
|
-
const parts = [writeUInt32BE(keys.length)];
|
|
381
|
-
for (const key of keys) {
|
|
382
|
-
parts.push(serializeLPString(key));
|
|
383
|
-
parts.push(serializeCVBytes(value.value[key]));
|
|
384
|
-
}
|
|
385
|
-
return withTypeId(value.type, concatBytes(...parts));
|
|
386
|
-
}
|
|
387
|
-
case "ascii": {
|
|
388
|
-
const strBytes = asciiToBytes(value.value);
|
|
389
|
-
return withTypeId(value.type, concatBytes(writeUInt32BE(strBytes.length), strBytes));
|
|
390
|
-
}
|
|
391
|
-
case "utf8": {
|
|
392
|
-
const strBytes = utf8ToBytes(value.value);
|
|
393
|
-
return withTypeId(value.type, concatBytes(writeUInt32BE(strBytes.length), strBytes));
|
|
394
|
-
}
|
|
395
|
-
default:
|
|
396
|
-
throw new Error("Cannot serialize unknown clarity type");
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
// src/transactions/types.ts
|
|
401
|
-
var AuthType = {
|
|
402
|
-
Standard: 4,
|
|
403
|
-
Sponsored: 5
|
|
404
|
-
};
|
|
405
|
-
var PayloadType = {
|
|
406
|
-
TokenTransfer: 0,
|
|
407
|
-
SmartContract: 1,
|
|
408
|
-
ContractCall: 2,
|
|
409
|
-
PoisonMicroblock: 3,
|
|
410
|
-
Coinbase: 4,
|
|
411
|
-
CoinbaseToAltRecipient: 5,
|
|
412
|
-
VersionedSmartContract: 6,
|
|
413
|
-
TenureChange: 7,
|
|
414
|
-
NakamotoCoinbase: 8
|
|
415
|
-
};
|
|
416
|
-
var AnchorMode = {
|
|
417
|
-
OnChainOnly: 1,
|
|
418
|
-
OffChainOnly: 2,
|
|
419
|
-
Any: 3
|
|
420
|
-
};
|
|
421
|
-
var PostConditionModeWire = {
|
|
422
|
-
Allow: 1,
|
|
423
|
-
Deny: 2,
|
|
424
|
-
Originator: 3
|
|
425
|
-
};
|
|
426
|
-
var AddressHashMode = {
|
|
427
|
-
P2PKH: 0,
|
|
428
|
-
P2SH: 1,
|
|
429
|
-
P2WPKH: 2,
|
|
430
|
-
P2WSH: 3,
|
|
431
|
-
P2SH_NonSequential: 5,
|
|
432
|
-
P2WSH_P2SH_NonSequential: 7
|
|
433
|
-
};
|
|
434
|
-
var PubKeyEncoding = {
|
|
435
|
-
Compressed: 0,
|
|
436
|
-
Uncompressed: 1
|
|
437
|
-
};
|
|
438
|
-
var FungibleConditionCode = {
|
|
439
|
-
Equal: 1,
|
|
440
|
-
Greater: 2,
|
|
441
|
-
GreaterEqual: 3,
|
|
442
|
-
Less: 4,
|
|
443
|
-
LessEqual: 5
|
|
444
|
-
};
|
|
445
|
-
var NonFungibleConditionCode = {
|
|
446
|
-
Sends: 16,
|
|
447
|
-
DoesNotSend: 17,
|
|
448
|
-
MaybeSent: 18
|
|
449
|
-
};
|
|
450
|
-
var PoxConditionCode = {
|
|
451
|
-
WillNotPerform: 48,
|
|
452
|
-
MayPerform: 49,
|
|
453
|
-
WillPerform: 50
|
|
454
|
-
};
|
|
455
|
-
var PostConditionPrincipalId = {
|
|
456
|
-
Origin: 1,
|
|
457
|
-
Standard: 2,
|
|
458
|
-
Contract: 3
|
|
459
|
-
};
|
|
460
|
-
var AssetType = {
|
|
461
|
-
STX: 0,
|
|
462
|
-
Fungible: 1,
|
|
463
|
-
NonFungible: 2,
|
|
464
|
-
Staking: 3,
|
|
465
|
-
Pox: 4
|
|
466
|
-
};
|
|
467
|
-
var RECOVERABLE_ECDSA_SIG_LENGTH_BYTES = 65;
|
|
468
|
-
var MEMO_MAX_LENGTH_BYTES = 34;
|
|
469
|
-
var COINBASE_BYTES_LENGTH = 32;
|
|
470
|
-
var VRF_PROOF_BYTES_LENGTH = 80;
|
|
471
|
-
var MICROBLOCK_HEADER_BYTES_LENGTH = 132;
|
|
472
|
-
|
|
473
|
-
// src/transactions/wire/serialize.ts
|
|
474
|
-
function serializeAddress2(c32Address) {
|
|
475
|
-
const [version, hash160] = c32addressDecode(c32Address);
|
|
476
|
-
return concatBytes(new Uint8Array([version]), hexToBytes(hash160));
|
|
477
|
-
}
|
|
478
|
-
function serializeLPString2(str, prefixBytes = 1) {
|
|
479
|
-
const content = utf8ToBytes(str);
|
|
480
|
-
const prefix = hexToBytes(intToHex(content.byteLength, prefixBytes));
|
|
481
|
-
return concatBytes(prefix, content);
|
|
482
|
-
}
|
|
483
|
-
function serializeLPStringLong(str) {
|
|
484
|
-
return serializeLPString2(str, 4);
|
|
485
|
-
}
|
|
486
|
-
function serializeMemo(memo) {
|
|
487
|
-
const content = asciiToBytes(memo);
|
|
488
|
-
const padded = new Uint8Array(MEMO_MAX_LENGTH_BYTES);
|
|
489
|
-
padded.set(content.slice(0, MEMO_MAX_LENGTH_BYTES));
|
|
490
|
-
return padded;
|
|
491
|
-
}
|
|
492
|
-
function serializeSpendingCondition(condition) {
|
|
493
|
-
const parts = [
|
|
494
|
-
writeUInt8(condition.hashMode),
|
|
495
|
-
hexToBytes(condition.signer),
|
|
496
|
-
intToBytes(condition.nonce, 8),
|
|
497
|
-
intToBytes(condition.fee, 8)
|
|
498
|
-
];
|
|
499
|
-
if ("signature" in condition) {
|
|
500
|
-
const sc = condition;
|
|
501
|
-
parts.push(writeUInt8(sc.keyEncoding));
|
|
502
|
-
parts.push(hexToBytes(sc.signature));
|
|
503
|
-
} else {
|
|
504
|
-
const mc = condition;
|
|
505
|
-
parts.push(writeUInt32BE(mc.fields.length));
|
|
506
|
-
for (const field of mc.fields) {
|
|
507
|
-
parts.push(serializeAuthField(field));
|
|
508
|
-
}
|
|
509
|
-
parts.push(writeUInt16BE(mc.signaturesRequired));
|
|
510
|
-
}
|
|
511
|
-
return concatBytes(...parts);
|
|
512
|
-
}
|
|
513
|
-
function serializeAuthField(field) {
|
|
514
|
-
if (field.type === "publicKey") {
|
|
515
|
-
const typeId2 = field.pubKeyEncoding === 0 ? 0 : 1;
|
|
516
|
-
return concatBytes(writeUInt8(typeId2), hexToBytes(field.data));
|
|
517
|
-
}
|
|
518
|
-
const typeId = field.pubKeyEncoding === 0 ? 2 : 3;
|
|
519
|
-
return concatBytes(writeUInt8(typeId), hexToBytes(field.data));
|
|
520
|
-
}
|
|
521
|
-
function serializeAuthorization(auth) {
|
|
522
|
-
const parts = [writeUInt8(auth.authType)];
|
|
523
|
-
parts.push(serializeSpendingCondition(auth.spendingCondition));
|
|
524
|
-
if (auth.authType === AuthType.Sponsored) {
|
|
525
|
-
parts.push(serializeSpendingCondition(auth.sponsorSpendingCondition));
|
|
526
|
-
}
|
|
527
|
-
return concatBytes(...parts);
|
|
528
|
-
}
|
|
529
|
-
function serializePrincipal(principal) {
|
|
530
|
-
switch (principal.type) {
|
|
531
|
-
case "origin":
|
|
532
|
-
return writeUInt8(PostConditionPrincipalId.Origin);
|
|
533
|
-
case "standard":
|
|
534
|
-
return concatBytes(writeUInt8(PostConditionPrincipalId.Standard), serializeAddress2(principal.address));
|
|
535
|
-
case "contract":
|
|
536
|
-
return concatBytes(writeUInt8(PostConditionPrincipalId.Contract), serializeAddress2(principal.address), serializeLPString2(principal.contractName));
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
function serializeAssetInfo(asset) {
|
|
540
|
-
return concatBytes(serializeAddress2(asset.address), serializeLPString2(asset.contractName), serializeLPString2(asset.assetName));
|
|
541
|
-
}
|
|
542
|
-
function serializePostConditionWire(pc) {
|
|
543
|
-
const parts = [];
|
|
544
|
-
switch (pc.type) {
|
|
545
|
-
case "stx":
|
|
546
|
-
parts.push(writeUInt8(AssetType.STX));
|
|
547
|
-
parts.push(serializePrincipal(pc.principal));
|
|
548
|
-
parts.push(writeUInt8(pc.conditionCode));
|
|
549
|
-
parts.push(intToBytes(pc.amount, 8));
|
|
550
|
-
break;
|
|
551
|
-
case "ft":
|
|
552
|
-
parts.push(writeUInt8(AssetType.Fungible));
|
|
553
|
-
parts.push(serializePrincipal(pc.principal));
|
|
554
|
-
parts.push(serializeAssetInfo(pc.asset));
|
|
555
|
-
parts.push(writeUInt8(pc.conditionCode));
|
|
556
|
-
parts.push(intToBytes(pc.amount, 8));
|
|
557
|
-
break;
|
|
558
|
-
case "nft":
|
|
559
|
-
parts.push(writeUInt8(AssetType.NonFungible));
|
|
560
|
-
parts.push(serializePrincipal(pc.principal));
|
|
561
|
-
parts.push(serializeAssetInfo(pc.asset));
|
|
562
|
-
parts.push(serializeCVBytes(pc.assetId));
|
|
563
|
-
parts.push(writeUInt8(pc.conditionCode));
|
|
564
|
-
break;
|
|
565
|
-
case "staking":
|
|
566
|
-
parts.push(writeUInt8(AssetType.Staking));
|
|
567
|
-
parts.push(serializePrincipal(pc.principal));
|
|
568
|
-
parts.push(writeUInt8(pc.conditionCode));
|
|
569
|
-
parts.push(intToBytes(pc.amount, 8));
|
|
570
|
-
break;
|
|
571
|
-
case "pox":
|
|
572
|
-
parts.push(writeUInt8(AssetType.Pox));
|
|
573
|
-
parts.push(serializePrincipal(pc.principal));
|
|
574
|
-
parts.push(writeUInt8(pc.conditionCode));
|
|
575
|
-
break;
|
|
576
|
-
}
|
|
577
|
-
return concatBytes(...parts);
|
|
578
|
-
}
|
|
579
|
-
function serializePostConditions(pcs) {
|
|
580
|
-
const parts = [writeUInt32BE(pcs.length)];
|
|
581
|
-
for (const pc of pcs)
|
|
582
|
-
parts.push(serializePostConditionWire(pc));
|
|
583
|
-
return concatBytes(...parts);
|
|
584
|
-
}
|
|
585
|
-
function serializePayload(payload) {
|
|
586
|
-
const parts = [writeUInt8(payload.payloadType)];
|
|
587
|
-
switch (payload.payloadType) {
|
|
588
|
-
case PayloadType.TokenTransfer:
|
|
589
|
-
parts.push(serializeCVBytes(payload.recipient));
|
|
590
|
-
parts.push(intToBytes(payload.amount, 8));
|
|
591
|
-
parts.push(serializeMemo(payload.memo));
|
|
592
|
-
break;
|
|
593
|
-
case PayloadType.ContractCall:
|
|
594
|
-
parts.push(serializeAddress2(payload.contractAddress));
|
|
595
|
-
parts.push(serializeLPString2(payload.contractName));
|
|
596
|
-
parts.push(serializeLPString2(payload.functionName));
|
|
597
|
-
parts.push(writeUInt32BE(payload.functionArgs.length));
|
|
598
|
-
for (const arg of payload.functionArgs) {
|
|
599
|
-
parts.push(serializeCVBytes(arg));
|
|
600
|
-
}
|
|
601
|
-
break;
|
|
602
|
-
case PayloadType.SmartContract:
|
|
603
|
-
parts.push(serializeLPString2(payload.contractName));
|
|
604
|
-
parts.push(serializeLPStringLong(payload.codeBody));
|
|
605
|
-
break;
|
|
606
|
-
case PayloadType.VersionedSmartContract:
|
|
607
|
-
parts.push(writeUInt8(payload.clarityVersion ?? 2));
|
|
608
|
-
parts.push(serializeLPString2(payload.contractName));
|
|
609
|
-
parts.push(serializeLPStringLong(payload.codeBody));
|
|
610
|
-
break;
|
|
611
|
-
case PayloadType.Coinbase:
|
|
612
|
-
parts.push(hexToBytes(payload.coinbaseBuffer));
|
|
613
|
-
break;
|
|
614
|
-
case PayloadType.CoinbaseToAltRecipient: {
|
|
615
|
-
const cbAlt = payload;
|
|
616
|
-
parts.push(hexToBytes(cbAlt.coinbaseBuffer));
|
|
617
|
-
parts.push(serializeCVBytes(cbAlt.recipient));
|
|
618
|
-
break;
|
|
619
|
-
}
|
|
620
|
-
case PayloadType.PoisonMicroblock: {
|
|
621
|
-
const pm = payload;
|
|
622
|
-
parts.push(hexToBytes(pm.header1));
|
|
623
|
-
parts.push(hexToBytes(pm.header2));
|
|
624
|
-
break;
|
|
625
|
-
}
|
|
626
|
-
case PayloadType.TenureChange: {
|
|
627
|
-
const tc = payload;
|
|
628
|
-
parts.push(hexToBytes(tc.tenureConsensusHash));
|
|
629
|
-
parts.push(hexToBytes(tc.prevTenureConsensusHash));
|
|
630
|
-
parts.push(hexToBytes(tc.burnViewConsensusHash));
|
|
631
|
-
parts.push(hexToBytes(tc.previousTenureEnd));
|
|
632
|
-
parts.push(writeUInt32BE(tc.previousTenureBlocks));
|
|
633
|
-
parts.push(writeUInt8(tc.cause));
|
|
634
|
-
parts.push(hexToBytes(tc.pubkeyHash));
|
|
635
|
-
break;
|
|
636
|
-
}
|
|
637
|
-
case PayloadType.NakamotoCoinbase: {
|
|
638
|
-
const nc = payload;
|
|
639
|
-
parts.push(hexToBytes(nc.coinbaseBuffer));
|
|
640
|
-
if (nc.recipient) {
|
|
641
|
-
parts.push(serializeCVBytes({ type: "some", value: nc.recipient }));
|
|
642
|
-
} else {
|
|
643
|
-
parts.push(serializeCVBytes({ type: "none" }));
|
|
644
|
-
}
|
|
645
|
-
parts.push(hexToBytes(nc.vrfProof));
|
|
646
|
-
break;
|
|
647
|
-
}
|
|
648
|
-
}
|
|
649
|
-
return concatBytes(...parts);
|
|
650
|
-
}
|
|
651
|
-
var _txCache = new WeakMap;
|
|
652
|
-
function clearTxCache(tx) {
|
|
653
|
-
_txCache.delete(tx);
|
|
654
|
-
}
|
|
655
|
-
function serializeTransaction(tx) {
|
|
656
|
-
const cached = _txCache.get(tx);
|
|
657
|
-
if (cached)
|
|
658
|
-
return cached;
|
|
659
|
-
const bytes = concatBytes(writeUInt8(tx.version), writeUInt32BE(tx.chainId), serializeAuthorization(tx.auth), writeUInt8(tx.anchorMode), writeUInt8(tx.postConditionMode), serializePostConditions(tx.postConditions), serializePayload(tx.payload));
|
|
660
|
-
_txCache.set(tx, bytes);
|
|
661
|
-
return bytes;
|
|
662
|
-
}
|
|
663
|
-
|
|
664
|
-
// src/actions/public/estimateFee.ts
|
|
665
|
-
function isValidEstimation(e) {
|
|
666
|
-
return typeof e === "object" && e !== null && "fee_rate" in e && "fee" in e && (typeof e.fee_rate === "number" || typeof e.fee_rate === "string") && (typeof e.fee === "number" || typeof e.fee === "string");
|
|
667
|
-
}
|
|
668
|
-
async function estimateFee(client, params) {
|
|
669
|
-
const payloadHex = bytesToHex(serializePayload(params.transaction.payload));
|
|
670
|
-
const txHex = bytesToHex(serializeTransaction(params.transaction));
|
|
671
|
-
const data = await client.request("/v2/fees/transaction", {
|
|
672
|
-
method: "POST",
|
|
673
|
-
body: {
|
|
674
|
-
estimated_len: Math.ceil(txHex.length / 2),
|
|
675
|
-
transaction_payload: `0x${payloadHex}`
|
|
676
|
-
}
|
|
677
|
-
});
|
|
678
|
-
const raw = data?.estimations ?? [];
|
|
679
|
-
return raw.map((e) => {
|
|
680
|
-
if (!isValidEstimation(e)) {
|
|
681
|
-
throw new MalformedResponseError("estimateFee: node response contains invalid fee estimation entry");
|
|
682
|
-
}
|
|
683
|
-
return {
|
|
684
|
-
feeRate: Number(e.fee_rate),
|
|
685
|
-
fee: Number(e.fee)
|
|
686
|
-
};
|
|
687
|
-
});
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
// src/actions/public/getAccountHistory.ts
|
|
691
|
-
async function getAccountHistory(client, params) {
|
|
692
|
-
const limit = Math.min(params.limit ?? 20, 50);
|
|
693
|
-
return client.request(`/extended/v2/addresses/${encodeURIComponent(params.address)}/transactions?limit=${limit}`, { method: "GET" });
|
|
694
|
-
}
|
|
695
|
-
|
|
696
|
-
// src/actions/public/getAccountInfo.ts
|
|
697
|
-
async function getAccountInfo(client, params) {
|
|
698
|
-
const data = await client.request(`/v2/accounts/${encodeURIComponent(params.address)}?proof=1`, { method: "GET" });
|
|
699
|
-
const balance = data?.balance;
|
|
700
|
-
const nonce = data?.nonce;
|
|
701
|
-
if (typeof balance !== "string" && typeof balance !== "number" || typeof nonce !== "string" && typeof nonce !== "number") {
|
|
702
|
-
throw new MalformedResponseError(`getAccountInfo: /v2/accounts/${params.address} response is missing "balance" or "nonce"`);
|
|
703
|
-
}
|
|
704
|
-
return {
|
|
705
|
-
balance: BigInt(balance),
|
|
706
|
-
nonce: BigInt(nonce),
|
|
707
|
-
balanceProof: data.balance_proof ?? "",
|
|
708
|
-
nonceProof: data.nonce_proof ?? ""
|
|
709
|
-
};
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
// src/actions/public/getBalance.ts
|
|
713
|
-
async function getBalance(client, params) {
|
|
714
|
-
const data = await client.request(`/v2/accounts/${encodeURIComponent(params.address)}`, {
|
|
715
|
-
method: "GET"
|
|
716
|
-
});
|
|
717
|
-
const balance = data?.balance;
|
|
718
|
-
if (typeof balance !== "string" && typeof balance !== "number") {
|
|
719
|
-
throw new MalformedResponseError(`getBalance: /v2/accounts/${params.address} response is missing "balance"`);
|
|
720
|
-
}
|
|
721
|
-
return BigInt(balance);
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
// src/actions/public/getBlock.ts
|
|
725
|
-
async function getBlock(client, params) {
|
|
726
|
-
if (params?.hash) {
|
|
727
|
-
return client.request(`/extended/v2/blocks/${encodeURIComponent(params.hash)}`, { method: "GET" });
|
|
728
|
-
}
|
|
729
|
-
if (params?.height !== undefined) {
|
|
730
|
-
return client.request(`/extended/v2/blocks/${encodeURIComponent(String(params.height))}`, { method: "GET" });
|
|
731
|
-
}
|
|
732
|
-
const data = await client.request("/extended/v2/blocks?limit=1", {
|
|
733
|
-
method: "GET"
|
|
734
|
-
});
|
|
735
|
-
const results = data?.results;
|
|
736
|
-
return Array.isArray(results) ? results[0] ?? null : data;
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
// src/actions/public/getBlockHeight.ts
|
|
740
|
-
async function getBlockHeight(client) {
|
|
741
|
-
const data = await client.request("/v2/info", { method: "GET" });
|
|
742
|
-
if (typeof data?.stacks_tip_height !== "number") {
|
|
743
|
-
throw new MalformedResponseError('getBlockHeight: /v2/info response is missing "stacks_tip_height"');
|
|
744
|
-
}
|
|
745
|
-
return data.stacks_tip_height;
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
// src/actions/public/getMempoolStats.ts
|
|
749
|
-
async function getMempoolStats(client) {
|
|
750
|
-
return client.request("/extended/v1/tx/mempool/stats", { method: "GET" });
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
// src/actions/public/getNftHoldings.ts
|
|
754
|
-
async function getNftHoldings(client, params) {
|
|
755
|
-
const limit = Math.min(params.limit ?? 20, 50);
|
|
756
|
-
return client.request(`/extended/v1/tokens/nft/holdings?principal=${encodeURIComponent(params.address)}&limit=${limit}`, { method: "GET" });
|
|
757
|
-
}
|
|
758
|
-
|
|
759
|
-
// src/errors/transaction.ts
|
|
760
|
-
class BroadcastError extends BaseError {
|
|
761
|
-
name = "BroadcastError";
|
|
762
|
-
txid;
|
|
763
|
-
reason;
|
|
764
|
-
reasonData;
|
|
765
|
-
constructor(message, options) {
|
|
766
|
-
super(message, options);
|
|
767
|
-
this.txid = options?.txid;
|
|
768
|
-
this.reason = options?.reason;
|
|
769
|
-
this.reasonData = options?.reasonData;
|
|
770
|
-
}
|
|
771
|
-
}
|
|
772
|
-
|
|
773
|
-
class TransactionAbortedError extends BaseError {
|
|
774
|
-
name = "TransactionAbortedError";
|
|
775
|
-
receipt;
|
|
776
|
-
constructor(message, options) {
|
|
777
|
-
super(message, options);
|
|
778
|
-
this.receipt = options.receipt;
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
class TransactionDroppedError extends BaseError {
|
|
783
|
-
name = "TransactionDroppedError";
|
|
784
|
-
txid;
|
|
785
|
-
constructor(message, options) {
|
|
786
|
-
super(message, options);
|
|
787
|
-
this.txid = options.txid;
|
|
788
|
-
}
|
|
789
|
-
}
|
|
790
|
-
|
|
791
|
-
class WaitForTransactionTimeoutError extends BaseError {
|
|
792
|
-
name = "WaitForTransactionTimeoutError";
|
|
793
|
-
txid;
|
|
794
|
-
constructor(message, options) {
|
|
795
|
-
super(message, options);
|
|
796
|
-
this.txid = options.txid;
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
|
|
800
|
-
class SerializationError extends BaseError {
|
|
801
|
-
name = "SerializationError";
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
// src/utils/bytes-reader.ts
|
|
805
|
-
class BytesReader {
|
|
806
|
-
data;
|
|
807
|
-
offset = 0;
|
|
808
|
-
constructor(data) {
|
|
809
|
-
this.data = data;
|
|
810
|
-
}
|
|
811
|
-
remaining() {
|
|
812
|
-
return this.data.length - this.offset;
|
|
813
|
-
}
|
|
814
|
-
ensure(length) {
|
|
815
|
-
if (this.offset + length > this.data.length) {
|
|
816
|
-
throw new SerializationError(`Buffer underflow: need ${length} bytes at offset ${this.offset}, have ${this.data.length}`);
|
|
817
|
-
}
|
|
818
|
-
}
|
|
819
|
-
readUInt8() {
|
|
820
|
-
this.ensure(1);
|
|
821
|
-
return this.data[this.offset++];
|
|
822
|
-
}
|
|
823
|
-
readUInt16BE() {
|
|
824
|
-
this.ensure(2);
|
|
825
|
-
const val = (this.data[this.offset] << 8 | this.data[this.offset + 1]) >>> 0;
|
|
826
|
-
this.offset += 2;
|
|
827
|
-
return val;
|
|
828
|
-
}
|
|
829
|
-
readUInt32BE() {
|
|
830
|
-
this.ensure(4);
|
|
831
|
-
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;
|
|
832
|
-
this.offset += 4;
|
|
833
|
-
return val;
|
|
834
|
-
}
|
|
835
|
-
readBytes(length) {
|
|
836
|
-
this.ensure(length);
|
|
837
|
-
const slice = this.data.slice(this.offset, this.offset + length);
|
|
838
|
-
this.offset += length;
|
|
839
|
-
return slice;
|
|
840
|
-
}
|
|
841
|
-
readBigUInt64BE() {
|
|
842
|
-
const hex = bytesToHex(this.readBytes(8));
|
|
843
|
-
return hex.length > 0 ? BigInt(`0x${hex}`) : 0n;
|
|
844
|
-
}
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
// src/utils/constants.ts
|
|
848
|
-
var MAX_U128 = (1n << 128n) - 1n;
|
|
849
|
-
var MAX_I128 = (1n << 127n) - 1n;
|
|
850
|
-
var MIN_I128 = -(1n << 127n);
|
|
851
|
-
var AddressVersion = {
|
|
852
|
-
MainnetSingleSig: 22,
|
|
853
|
-
MainnetMultiSig: 20,
|
|
854
|
-
TestnetSingleSig: 26,
|
|
855
|
-
TestnetMultiSig: 21
|
|
856
|
-
};
|
|
857
|
-
|
|
858
|
-
// src/utils/hash.ts
|
|
859
|
-
import { ripemd160 } from "@noble/hashes/legacy.js";
|
|
860
|
-
import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
|
|
861
|
-
import { sha512_256 } from "@noble/hashes/sha2.js";
|
|
862
|
-
function hash160(input) {
|
|
863
|
-
return ripemd160(sha2562(input));
|
|
864
|
-
}
|
|
865
|
-
function txidFromBytes(data) {
|
|
866
|
-
return bytesToHex(sha512_256(data));
|
|
867
|
-
}
|
|
868
|
-
function hashP2PKH(input) {
|
|
869
|
-
return bytesToHex(hash160(input));
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
// src/utils/address.ts
|
|
873
|
-
function publicKeyToAddress(publicKey, network = "mainnet") {
|
|
874
|
-
const bytes = typeof publicKey === "string" ? hexToBytes(without0x(publicKey)) : publicKey;
|
|
875
|
-
const version = network === "mainnet" ? AddressVersion.MainnetSingleSig : AddressVersion.TestnetSingleSig;
|
|
876
|
-
return c32address(version, bytesToHex(hash160(bytes)));
|
|
877
|
-
}
|
|
878
|
-
var CONTRACT_NAME_REGEX = /^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/;
|
|
879
|
-
function validateStacksAddress(address) {
|
|
880
|
-
try {
|
|
881
|
-
c32addressDecode(address);
|
|
882
|
-
return true;
|
|
883
|
-
} catch {
|
|
884
|
-
return false;
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
|
-
function parsePrincipal(value) {
|
|
888
|
-
const parts = value.split(".");
|
|
889
|
-
if (parts.length > 2)
|
|
890
|
-
return null;
|
|
891
|
-
const [address, contractName] = parts;
|
|
892
|
-
if (!validateStacksAddress(address))
|
|
893
|
-
return null;
|
|
894
|
-
if (contractName === undefined)
|
|
895
|
-
return { address };
|
|
896
|
-
if (!CONTRACT_NAME_REGEX.test(contractName))
|
|
897
|
-
return null;
|
|
898
|
-
return { address, contractName };
|
|
899
|
-
}
|
|
900
|
-
function parseContractId(contractId) {
|
|
901
|
-
const parsed = parsePrincipal(contractId);
|
|
902
|
-
if (!parsed?.contractName)
|
|
903
|
-
throw new Error(`Invalid contract identifier: ${contractId}`);
|
|
904
|
-
return [parsed.address, parsed.contractName];
|
|
905
|
-
}
|
|
906
|
-
function isClarityName(name) {
|
|
907
|
-
const regex = /^[a-zA-Z]([a-zA-Z0-9]|[-_!?+<>=/*])*$|^[-+=/*]$|^[<>]=?$/;
|
|
908
|
-
return regex.test(name) && name.length < 128;
|
|
909
|
-
}
|
|
910
|
-
|
|
911
|
-
// src/clarity/values.ts
|
|
912
|
-
var MAX_U1282 = BigInt("0xffffffffffffffffffffffffffffffff");
|
|
913
|
-
var MIN_I1282 = BigInt("-170141183460469231731687303715884105728");
|
|
914
|
-
var MAX_I1282 = BigInt("0x7fffffffffffffffffffffffffffffff");
|
|
915
|
-
function intCV(value) {
|
|
916
|
-
let v = value;
|
|
917
|
-
if (typeof v === "string" && v.toLowerCase().startsWith("0x")) {
|
|
918
|
-
v = bytesToTwosBigInt(hexToBytes(v));
|
|
919
|
-
}
|
|
920
|
-
if (v instanceof Uint8Array)
|
|
921
|
-
v = bytesToTwosBigInt(v);
|
|
922
|
-
const n = intToBigInt(v);
|
|
923
|
-
if (n > MAX_I1282)
|
|
924
|
-
throw new RangeError(`Int exceeds max i128: ${MAX_I1282}`);
|
|
925
|
-
if (n < MIN_I1282)
|
|
926
|
-
throw new RangeError(`Int below min i128: ${MIN_I1282}`);
|
|
927
|
-
return { type: "int", value: n };
|
|
928
|
-
}
|
|
929
|
-
function uintCV(value) {
|
|
930
|
-
const n = intToBigInt(value);
|
|
931
|
-
if (n < 0n)
|
|
932
|
-
throw new RangeError("Cannot construct unsigned int from negative value");
|
|
933
|
-
if (n > MAX_U1282)
|
|
934
|
-
throw new RangeError(`UInt exceeds max u128: ${MAX_U1282}`);
|
|
935
|
-
return { type: "uint", value: n };
|
|
936
|
-
}
|
|
937
|
-
var trueCV = () => ({ type: "true" });
|
|
938
|
-
var falseCV = () => ({ type: "false" });
|
|
939
|
-
var boolCV = (v) => v ? trueCV() : falseCV();
|
|
940
|
-
function bufferCV(buffer) {
|
|
941
|
-
if (buffer.byteLength > 1048576) {
|
|
942
|
-
throw new Error("Buffer exceeds max size of 1MB");
|
|
943
|
-
}
|
|
944
|
-
return { type: "buffer", value: bytesToHex(buffer) };
|
|
945
|
-
}
|
|
946
|
-
function standardPrincipalCV(address) {
|
|
947
|
-
const [version, hash1602] = c32addressDecode(address);
|
|
948
|
-
const normalized = c32address(version, hash1602);
|
|
949
|
-
return { type: "address", value: normalized };
|
|
950
|
-
}
|
|
951
|
-
function contractPrincipalCV(address, contractName) {
|
|
952
|
-
const [version, hash1602] = c32addressDecode(address);
|
|
953
|
-
const normalized = c32address(version, hash1602);
|
|
954
|
-
if (utf8ToBytes(contractName).byteLength >= 128) {
|
|
955
|
-
throw new Error("Contract name must be less than 128 bytes");
|
|
956
|
-
}
|
|
957
|
-
return { type: "contract", value: `${normalized}.${contractName}` };
|
|
958
|
-
}
|
|
959
|
-
function noneCV() {
|
|
960
|
-
return { type: "none" };
|
|
961
|
-
}
|
|
962
|
-
function someCV(value) {
|
|
963
|
-
return { type: "some", value };
|
|
964
|
-
}
|
|
965
|
-
function responseOkCV(value) {
|
|
966
|
-
return { type: "ok", value };
|
|
967
|
-
}
|
|
968
|
-
function responseErrorCV(value) {
|
|
969
|
-
return { type: "err", value };
|
|
970
|
-
}
|
|
971
|
-
function listCV(values) {
|
|
972
|
-
return { type: "list", value: values };
|
|
973
|
-
}
|
|
974
|
-
function tupleCV(data) {
|
|
975
|
-
for (const key in data) {
|
|
976
|
-
if (!isClarityName(key)) {
|
|
977
|
-
throw new Error(`"${key}" is not a valid Clarity name`);
|
|
978
|
-
}
|
|
979
|
-
}
|
|
980
|
-
return { type: "tuple", value: data };
|
|
981
|
-
}
|
|
982
|
-
function stringAsciiCV(value) {
|
|
983
|
-
return { type: "ascii", value };
|
|
984
|
-
}
|
|
985
|
-
function stringUtf8CV(value) {
|
|
986
|
-
return { type: "utf8", value };
|
|
987
|
-
}
|
|
988
|
-
var Cl = {
|
|
989
|
-
int: intCV,
|
|
990
|
-
uint: uintCV,
|
|
991
|
-
bool: boolCV,
|
|
992
|
-
principal(address) {
|
|
993
|
-
const parsed = parsePrincipal(address);
|
|
994
|
-
if (!parsed)
|
|
995
|
-
throw new Error(`Invalid principal: ${address}`);
|
|
996
|
-
return parsed.contractName ? contractPrincipalCV(parsed.address, parsed.contractName) : standardPrincipalCV(parsed.address);
|
|
997
|
-
},
|
|
998
|
-
address(address) {
|
|
999
|
-
return Cl.principal(address);
|
|
1000
|
-
},
|
|
1001
|
-
contractPrincipal: contractPrincipalCV,
|
|
1002
|
-
standardPrincipal: standardPrincipalCV,
|
|
1003
|
-
buffer: bufferCV,
|
|
1004
|
-
bufferFromHex: (hex) => bufferCV(hexToBytes(hex)),
|
|
1005
|
-
bufferFromAscii: (ascii) => bufferCV(asciiToBytes(ascii)),
|
|
1006
|
-
bufferFromUtf8: (utf8) => bufferCV(utf8ToBytes(utf8)),
|
|
1007
|
-
none: noneCV,
|
|
1008
|
-
some: someCV,
|
|
1009
|
-
ok: responseOkCV,
|
|
1010
|
-
error: responseErrorCV,
|
|
1011
|
-
list: listCV,
|
|
1012
|
-
tuple: tupleCV,
|
|
1013
|
-
stringAscii: stringAsciiCV,
|
|
1014
|
-
stringUtf8: stringUtf8CV,
|
|
1015
|
-
serialize(value) {
|
|
1016
|
-
return bytesToHex(serializeCVBytes(value));
|
|
1017
|
-
},
|
|
1018
|
-
deserialize: deserializeCVBytes
|
|
1019
|
-
};
|
|
1020
|
-
|
|
1021
|
-
// src/clarity/deserialize.ts
|
|
1022
|
-
function readAddress(reader) {
|
|
1023
|
-
const version = reader.readUInt8();
|
|
1024
|
-
const hash1602 = bytesToHex(reader.readBytes(20));
|
|
1025
|
-
return c32address(version, hash1602);
|
|
1026
|
-
}
|
|
1027
|
-
function readLPString(reader, prefixBytes = 1) {
|
|
1028
|
-
let length = 0;
|
|
1029
|
-
for (let i = 0;i < prefixBytes; i++) {
|
|
1030
|
-
length = length << 8 | reader.readUInt8();
|
|
1031
|
-
}
|
|
1032
|
-
return bytesToUtf8(reader.readBytes(length));
|
|
1033
|
-
}
|
|
1034
|
-
var MAX_CV_DEPTH = 64;
|
|
1035
|
-
var MIN_LIST_ITEM_BYTES = 1;
|
|
1036
|
-
var MIN_TUPLE_ENTRY_BYTES = 2;
|
|
1037
|
-
function checkCount(reader, count, minBytes) {
|
|
1038
|
-
if (count * minBytes > reader.remaining()) {
|
|
1039
|
-
throw new SerializationError(`Clarity value declares ${count} elements but only ${reader.remaining()} bytes remain`);
|
|
1040
|
-
}
|
|
1041
|
-
}
|
|
1042
|
-
function readCV(reader, depth = 0) {
|
|
1043
|
-
if (depth > MAX_CV_DEPTH) {
|
|
1044
|
-
throw new SerializationError(`Clarity value nests deeper than ${MAX_CV_DEPTH} levels`);
|
|
1045
|
-
}
|
|
1046
|
-
const typeByte = reader.readUInt8();
|
|
1047
|
-
const type = clarityTypeFromByte(typeByte);
|
|
1048
|
-
switch (type) {
|
|
1049
|
-
case "int":
|
|
1050
|
-
return intCV(bytesToTwosBigInt(reader.readBytes(16)));
|
|
1051
|
-
case "uint":
|
|
1052
|
-
return uintCV(reader.readBytes(16));
|
|
1053
|
-
case "true":
|
|
1054
|
-
return trueCV();
|
|
1055
|
-
case "false":
|
|
1056
|
-
return falseCV();
|
|
1057
|
-
case "buffer": {
|
|
1058
|
-
const len = reader.readUInt32BE();
|
|
1059
|
-
return bufferCV(reader.readBytes(len));
|
|
1060
|
-
}
|
|
1061
|
-
case "none":
|
|
1062
|
-
return noneCV();
|
|
1063
|
-
case "some":
|
|
1064
|
-
return someCV(readCV(reader, depth + 1));
|
|
1065
|
-
case "ok":
|
|
1066
|
-
return responseOkCV(readCV(reader, depth + 1));
|
|
1067
|
-
case "err":
|
|
1068
|
-
return responseErrorCV(readCV(reader, depth + 1));
|
|
1069
|
-
case "address":
|
|
1070
|
-
return standardPrincipalCV(readAddress(reader));
|
|
1071
|
-
case "contract": {
|
|
1072
|
-
const addr = readAddress(reader);
|
|
1073
|
-
const name = readLPString(reader);
|
|
1074
|
-
return contractPrincipalCV(addr, name);
|
|
1075
|
-
}
|
|
1076
|
-
case "list": {
|
|
1077
|
-
const len = reader.readUInt32BE();
|
|
1078
|
-
checkCount(reader, len, MIN_LIST_ITEM_BYTES);
|
|
1079
|
-
const items = [];
|
|
1080
|
-
for (let i = 0;i < len; i++) {
|
|
1081
|
-
items.push(readCV(reader, depth + 1));
|
|
1082
|
-
}
|
|
1083
|
-
return listCV(items);
|
|
1084
|
-
}
|
|
1085
|
-
case "tuple": {
|
|
1086
|
-
const len = reader.readUInt32BE();
|
|
1087
|
-
checkCount(reader, len, MIN_TUPLE_ENTRY_BYTES);
|
|
1088
|
-
const data = {};
|
|
1089
|
-
for (let i = 0;i < len; i++) {
|
|
1090
|
-
const key = readLPString(reader);
|
|
1091
|
-
data[key] = readCV(reader, depth + 1);
|
|
1092
|
-
}
|
|
1093
|
-
return tupleCV(data);
|
|
1094
|
-
}
|
|
1095
|
-
case "ascii": {
|
|
1096
|
-
const len = reader.readUInt32BE();
|
|
1097
|
-
return stringAsciiCV(bytesToAscii(reader.readBytes(len)));
|
|
1098
|
-
}
|
|
1099
|
-
case "utf8": {
|
|
1100
|
-
const len = reader.readUInt32BE();
|
|
1101
|
-
return stringUtf8CV(bytesToUtf8(reader.readBytes(len)));
|
|
1102
|
-
}
|
|
1103
|
-
default:
|
|
1104
|
-
throw new SerializationError(`Cannot deserialize unknown clarity type: ${type}`);
|
|
1105
|
-
}
|
|
1106
|
-
}
|
|
1107
|
-
function deserializeCVBytes(input) {
|
|
1108
|
-
const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
|
|
1109
|
-
return readCV(new BytesReader(bytes));
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
|
-
// src/errors/http.ts
|
|
1113
|
-
class HttpRequestError extends BaseError {
|
|
1114
|
-
name = "HttpRequestError";
|
|
1115
|
-
status;
|
|
1116
|
-
url;
|
|
1117
|
-
method;
|
|
1118
|
-
constructor(status, options) {
|
|
1119
|
-
const where = options?.url !== undefined ? ` (${options.method ?? "GET"} ${options.url})` : "";
|
|
1120
|
-
super(`HTTP request failed with status ${status}${where}`, options);
|
|
1121
|
-
this.status = status;
|
|
1122
|
-
this.url = options?.url;
|
|
1123
|
-
this.method = options?.method;
|
|
1124
|
-
}
|
|
1125
|
-
}
|
|
1126
|
-
|
|
1127
|
-
// src/errors/transport.ts
|
|
1128
|
-
class TimeoutError extends BaseError {
|
|
1129
|
-
name = "TimeoutError";
|
|
1130
|
-
method;
|
|
1131
|
-
url;
|
|
1132
|
-
timeout;
|
|
1133
|
-
attempt;
|
|
1134
|
-
constructor(params) {
|
|
1135
|
-
super(`${params.method} ${params.url} did not complete within ${params.timeout}ms (attempt ${params.attempt + 1})`);
|
|
1136
|
-
this.method = params.method;
|
|
1137
|
-
this.url = params.url;
|
|
1138
|
-
this.timeout = params.timeout;
|
|
1139
|
-
this.attempt = params.attempt;
|
|
1140
|
-
}
|
|
1141
|
-
}
|
|
1142
|
-
|
|
1143
|
-
// src/transports/createTransport.ts
|
|
1144
|
-
function createTransport(type, config) {
|
|
1145
|
-
const { request, apiKey: _apiKey, ...exposed } = config;
|
|
1146
|
-
return {
|
|
1147
|
-
type,
|
|
1148
|
-
request,
|
|
1149
|
-
config: exposed
|
|
1150
|
-
};
|
|
1151
|
-
}
|
|
1152
|
-
var MAX_ERROR_DETAILS_BYTES = 4096;
|
|
1153
|
-
function capDetails(body) {
|
|
1154
|
-
if (body === undefined)
|
|
1155
|
-
return;
|
|
1156
|
-
const bytes = new TextEncoder().encode(body);
|
|
1157
|
-
if (bytes.length <= MAX_ERROR_DETAILS_BYTES)
|
|
1158
|
-
return body;
|
|
1159
|
-
const head = new TextDecoder().decode(bytes.subarray(0, MAX_ERROR_DETAILS_BYTES));
|
|
1160
|
-
return `${head}... [truncated ${bytes.length - MAX_ERROR_DETAILS_BYTES} bytes]`;
|
|
1161
|
-
}
|
|
1162
|
-
function isRetryableStatus(status) {
|
|
1163
|
-
return status === 429 || status >= 500;
|
|
1164
|
-
}
|
|
1165
|
-
var MAX_RETRY_AFTER_MS = 60000;
|
|
1166
|
-
function retryAfterMs(response) {
|
|
1167
|
-
const value = response.headers.get("Retry-After");
|
|
1168
|
-
if (!value)
|
|
1169
|
-
return;
|
|
1170
|
-
const seconds = Number(value);
|
|
1171
|
-
const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - Date.now();
|
|
1172
|
-
if (!Number.isFinite(ms) || ms < 0 || ms > MAX_RETRY_AFTER_MS)
|
|
1173
|
-
return;
|
|
1174
|
-
return ms;
|
|
1175
|
-
}
|
|
1176
|
-
function abortReason(signal) {
|
|
1177
|
-
const reason = signal.reason;
|
|
1178
|
-
if (reason instanceof Error)
|
|
1179
|
-
return reason;
|
|
1180
|
-
return new DOMException(typeof reason === "string" ? reason : "The operation was aborted", "AbortError");
|
|
1181
|
-
}
|
|
1182
|
-
function sleep(ms, signal) {
|
|
1183
|
-
return new Promise((resolve, reject) => {
|
|
1184
|
-
if (signal?.aborted)
|
|
1185
|
-
return reject(abortReason(signal));
|
|
1186
|
-
const onAbort = () => {
|
|
1187
|
-
clearTimeout(id);
|
|
1188
|
-
reject(abortReason(signal));
|
|
1189
|
-
};
|
|
1190
|
-
const id = setTimeout(() => {
|
|
1191
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1192
|
-
resolve();
|
|
1193
|
-
}, ms);
|
|
1194
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1195
|
-
});
|
|
1196
|
-
}
|
|
1197
|
-
async function fetchWithRetry(url, options, retryCount, retryDelay, timeout, extra = {}) {
|
|
1198
|
-
const { signal } = extra;
|
|
1199
|
-
const read = extra.read ?? (async (response) => response);
|
|
1200
|
-
const method = options.method ?? "GET";
|
|
1201
|
-
let lastError;
|
|
1202
|
-
for (let attempt = 0;attempt <= retryCount; attempt++) {
|
|
1203
|
-
if (signal?.aborted)
|
|
1204
|
-
throw abortReason(signal);
|
|
1205
|
-
const controller = new AbortController;
|
|
1206
|
-
let timedOut = false;
|
|
1207
|
-
const timeoutId = setTimeout(() => {
|
|
1208
|
-
timedOut = true;
|
|
1209
|
-
controller.abort(new TimeoutError({ method, url, timeout, attempt }));
|
|
1210
|
-
}, timeout);
|
|
1211
|
-
const onCallerAbort = () => controller.abort(abortReason(signal));
|
|
1212
|
-
signal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
1213
|
-
const aborted = new Promise((_, reject) => {
|
|
1214
|
-
if (controller.signal.aborted)
|
|
1215
|
-
return reject(controller.signal.reason);
|
|
1216
|
-
controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
|
|
1217
|
-
});
|
|
1218
|
-
let response;
|
|
1219
|
-
try {
|
|
1220
|
-
try {
|
|
1221
|
-
response = await Promise.race([
|
|
1222
|
-
fetch(url, { ...options, signal: controller.signal }),
|
|
1223
|
-
aborted
|
|
1224
|
-
]);
|
|
1225
|
-
} catch (error) {
|
|
1226
|
-
if (signal?.aborted)
|
|
1227
|
-
throw abortReason(signal);
|
|
1228
|
-
lastError = timedOut ? new TimeoutError({ method, url, timeout, attempt }) : error instanceof Error ? error : new Error(String(error));
|
|
1229
|
-
if (attempt < retryCount) {
|
|
1230
|
-
clearTimeout(timeoutId);
|
|
1231
|
-
await sleep(retryDelay * (attempt + 1), signal);
|
|
1232
|
-
continue;
|
|
1233
|
-
}
|
|
1234
|
-
throw lastError;
|
|
1235
|
-
}
|
|
1236
|
-
if (response.ok) {
|
|
1237
|
-
try {
|
|
1238
|
-
return await Promise.race([read(response), aborted]);
|
|
1239
|
-
} catch (error) {
|
|
1240
|
-
response.body?.cancel().catch(() => {});
|
|
1241
|
-
if (signal?.aborted)
|
|
1242
|
-
throw abortReason(signal);
|
|
1243
|
-
if (!timedOut)
|
|
1244
|
-
throw error;
|
|
1245
|
-
lastError = new TimeoutError({ method, url, timeout, attempt });
|
|
1246
|
-
if (attempt < retryCount) {
|
|
1247
|
-
clearTimeout(timeoutId);
|
|
1248
|
-
await sleep(retryDelay * (attempt + 1), signal);
|
|
1249
|
-
continue;
|
|
1250
|
-
}
|
|
1251
|
-
throw lastError;
|
|
1252
|
-
}
|
|
1253
|
-
}
|
|
1254
|
-
const retryable = isRetryableStatus(response.status);
|
|
1255
|
-
if (!retryable || attempt === retryCount) {
|
|
1256
|
-
const body = await Promise.race([
|
|
1257
|
-
response.text().catch(() => {
|
|
1258
|
-
return;
|
|
1259
|
-
}),
|
|
1260
|
-
aborted.catch(() => {
|
|
1261
|
-
return;
|
|
1262
|
-
})
|
|
1263
|
-
]);
|
|
1264
|
-
throw new HttpRequestError(response.status, {
|
|
1265
|
-
details: capDetails(body),
|
|
1266
|
-
url,
|
|
1267
|
-
method
|
|
1268
|
-
});
|
|
1269
|
-
}
|
|
1270
|
-
lastError = new HttpRequestError(response.status, { url, method });
|
|
1271
|
-
const delay = retryAfterMs(response) ?? retryDelay * (attempt + 1);
|
|
1272
|
-
response.body?.cancel().catch(() => {});
|
|
1273
|
-
clearTimeout(timeoutId);
|
|
1274
|
-
await sleep(delay, signal);
|
|
1275
|
-
} finally {
|
|
1276
|
-
clearTimeout(timeoutId);
|
|
1277
|
-
signal?.removeEventListener("abort", onCallerAbort);
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
throw lastError ?? new Error("Request failed");
|
|
1281
|
-
}
|
|
1282
|
-
async function readBody(response) {
|
|
1283
|
-
const contentType = response.headers.get("content-type") ?? "";
|
|
1284
|
-
if (contentType.includes("application/json")) {
|
|
1285
|
-
return response.json();
|
|
1286
|
-
}
|
|
1287
|
-
return response.text();
|
|
1288
|
-
}
|
|
1289
|
-
function buildRequestFn(baseUrl, config) {
|
|
1290
|
-
const {
|
|
1291
|
-
timeout = 30000,
|
|
1292
|
-
retryCount = 3,
|
|
1293
|
-
retryDelay = 150,
|
|
1294
|
-
fetchOptions = {},
|
|
1295
|
-
apiKey
|
|
1296
|
-
} = config;
|
|
1297
|
-
return async (path, options) => {
|
|
1298
|
-
const url = `${baseUrl.replace(/\/$/, "")}${path}`;
|
|
1299
|
-
const headers = {
|
|
1300
|
-
"Content-Type": "application/json",
|
|
1301
|
-
...fetchOptions.headers,
|
|
1302
|
-
...options?.headers
|
|
1303
|
-
};
|
|
1304
|
-
if (apiKey) {
|
|
1305
|
-
headers["x-api-key"] = apiKey;
|
|
1306
|
-
}
|
|
1307
|
-
const init = {
|
|
1308
|
-
...fetchOptions,
|
|
1309
|
-
method: options?.method ?? "GET",
|
|
1310
|
-
headers
|
|
1311
|
-
};
|
|
1312
|
-
if (options?.body !== undefined) {
|
|
1313
|
-
init.body = JSON.stringify(options.body);
|
|
1314
|
-
}
|
|
1315
|
-
return fetchWithRetry(url, init, options?.retryCount ?? retryCount, retryDelay, timeout, { signal: options?.signal, read: readBody });
|
|
1316
|
-
};
|
|
1317
|
-
}
|
|
1318
|
-
|
|
1319
|
-
// src/actions/public/txSources.ts
|
|
1320
|
-
function normalizeTxid(txid) {
|
|
1321
|
-
return txid.startsWith("0x") ? txid : `0x${txid}`;
|
|
1322
|
-
}
|
|
1323
|
-
function decodeResultHex(hex) {
|
|
1324
|
-
if (!hex)
|
|
1325
|
-
return {};
|
|
1326
|
-
try {
|
|
1327
|
-
return { result: deserializeCVBytes(hex), resultHex: hex };
|
|
1328
|
-
} catch {
|
|
1329
|
-
return { resultHex: hex };
|
|
1330
|
-
}
|
|
1331
|
-
}
|
|
1332
|
-
function normalizeStatus(txStatus) {
|
|
1333
|
-
switch (txStatus) {
|
|
1334
|
-
case "pending":
|
|
1335
|
-
case "success":
|
|
1336
|
-
case "abort_by_response":
|
|
1337
|
-
case "abort_by_post_condition":
|
|
1338
|
-
return txStatus;
|
|
1339
|
-
default:
|
|
1340
|
-
return txStatus.startsWith("dropped") ? "dropped" : undefined;
|
|
1341
|
-
}
|
|
1342
|
-
}
|
|
1343
|
-
function extendedApiSource() {
|
|
1344
|
-
return {
|
|
1345
|
-
async get({ client, txid }) {
|
|
1346
|
-
let data;
|
|
1347
|
-
try {
|
|
1348
|
-
data = await client.request(`/extended/v1/tx/${encodeURIComponent(normalizeTxid(txid))}`, { method: "GET" });
|
|
1349
|
-
} catch (error) {
|
|
1350
|
-
if (error instanceof HttpRequestError && error.status === 404) {
|
|
1351
|
-
return { receipt: null };
|
|
1352
|
-
}
|
|
1353
|
-
throw error;
|
|
1354
|
-
}
|
|
1355
|
-
const txStatus = typeof data?.tx_status === "string" ? data.tx_status : undefined;
|
|
1356
|
-
if (!txStatus)
|
|
1357
|
-
return { receipt: null };
|
|
1358
|
-
const status = normalizeStatus(txStatus);
|
|
1359
|
-
if (!status)
|
|
1360
|
-
return { receipt: null };
|
|
1361
|
-
return {
|
|
1362
|
-
receipt: {
|
|
1363
|
-
txid: normalizeTxid(txid),
|
|
1364
|
-
status,
|
|
1365
|
-
blockHeight: typeof data.block_height === "number" && data.block_height > 0 ? data.block_height : undefined,
|
|
1366
|
-
blockHash: data.block_hash ?? undefined,
|
|
1367
|
-
...decodeResultHex(data.tx_result?.hex),
|
|
1368
|
-
events: Array.isArray(data.events) ? data.events : [],
|
|
1369
|
-
raw: data
|
|
1370
|
-
}
|
|
1371
|
-
};
|
|
1372
|
-
}
|
|
1373
|
-
};
|
|
1374
|
-
}
|
|
1375
|
-
|
|
1376
|
-
// src/actions/public/getTransaction.ts
|
|
1377
|
-
async function getTransaction(client, params) {
|
|
1378
|
-
const source = params.source ?? extendedApiSource();
|
|
1379
|
-
const { receipt } = await source.get({ client, txid: params.txid });
|
|
1380
|
-
return receipt;
|
|
1381
|
-
}
|
|
1382
|
-
|
|
1383
|
-
// src/actions/public/readContract.ts
|
|
1384
|
-
async function readContract(client, params) {
|
|
1385
|
-
const [address, name] = parseContractId(params.contract);
|
|
1386
|
-
const sender = params.sender ?? address;
|
|
1387
|
-
const serializedArgs = (params.args ?? []).map((arg) => with0x(bytesToHex(serializeCVBytes(arg))));
|
|
1388
|
-
const path = `/v2/contracts/call-read/${encodeURIComponent(address)}/${encodeURIComponent(name)}/${encodeURIComponent(params.functionName)}`;
|
|
1389
|
-
const data = await client.request(params.tip ? `${path}?tip=${encodeURIComponent(params.tip)}` : path, {
|
|
1390
|
-
method: "POST",
|
|
1391
|
-
body: {
|
|
1392
|
-
sender,
|
|
1393
|
-
arguments: serializedArgs
|
|
1394
|
-
}
|
|
1395
|
-
});
|
|
1396
|
-
if (data.okay) {
|
|
1397
|
-
if (typeof data.result !== "string") {
|
|
1398
|
-
throw new MalformedResponseError(`readContract: /v2/contracts/call-read response is missing "result"`);
|
|
1399
|
-
}
|
|
1400
|
-
return deserializeCVBytes(data.result);
|
|
1401
|
-
}
|
|
1402
|
-
throw new ReadContractError(data.cause ?? "Read-only call failed");
|
|
1403
|
-
}
|
|
1404
|
-
|
|
1405
|
-
// src/actions/wallet/utils.ts
|
|
1406
|
-
function isProviderAccount(account) {
|
|
1407
|
-
return account.type === "provider";
|
|
1408
|
-
}
|
|
1409
|
-
var FEE_TIERS = ["min", "low", "mid", "high"];
|
|
1410
|
-
var TIER_INDEX = { low: 0, mid: 1, high: 2 };
|
|
1411
|
-
function isFeeTier(fee) {
|
|
1412
|
-
return typeof fee === "string" && FEE_TIERS.includes(fee);
|
|
1413
|
-
}
|
|
1414
|
-
function minimumFee(transaction) {
|
|
1415
|
-
return BigInt(serializeTransaction(transaction).length);
|
|
1416
|
-
}
|
|
1417
|
-
function isNoEstimateAvailable(error) {
|
|
1418
|
-
return error instanceof HttpRequestError && error.status === 400 && (error.details?.includes("NoEstimateAvailable") ?? false);
|
|
1419
|
-
}
|
|
1420
|
-
async function resolveFee(client, transaction, fee) {
|
|
1421
|
-
if (fee !== undefined && !isFeeTier(fee))
|
|
1422
|
-
return { fee: intToBigInt(fee) };
|
|
1423
|
-
const tier = fee ?? "mid";
|
|
1424
|
-
if (tier === "min")
|
|
1425
|
-
return { fee: minimumFee(transaction), tier };
|
|
1426
|
-
let estimates;
|
|
1427
|
-
try {
|
|
1428
|
-
estimates = await estimateFee(client, { transaction });
|
|
1429
|
-
} catch (error) {
|
|
1430
|
-
if (!isNoEstimateAvailable(error))
|
|
1431
|
-
throw error;
|
|
1432
|
-
return { fee: minimumFee(transaction), tier: "min" };
|
|
1433
|
-
}
|
|
1434
|
-
const pick = estimates[TIER_INDEX[tier]] ?? estimates[estimates.length - 1];
|
|
1435
|
-
if (pick)
|
|
1436
|
-
return { fee: BigInt(pick.fee), tier };
|
|
1437
|
-
return { fee: minimumFee(transaction), tier: "min" };
|
|
1438
|
-
}
|
|
1439
|
-
function setUnsignedFee(transaction, fee) {
|
|
1440
|
-
transaction.auth.spendingCondition.fee = fee;
|
|
1441
|
-
clearTxCache(transaction);
|
|
1442
|
-
}
|
|
1443
|
-
function assertNoFeeTierForProvider(fee) {
|
|
1444
|
-
if (isFeeTier(fee)) {
|
|
1445
|
-
throw new Error(`Fee tier '${fee}' requires local signing; provider (wallet) accounts set their own fee`);
|
|
1446
|
-
}
|
|
1447
|
-
}
|
|
1448
|
-
|
|
1449
|
-
// src/clarity/abi/utils.ts
|
|
1450
|
-
function toCamelCase(str) {
|
|
1451
|
-
return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/-([A-Z])/g, (_, letter) => letter).replace(/-(\d)/g, (_, digit) => digit).replace(/-/g, "").replace(/^\d/, "_$&");
|
|
1452
|
-
}
|
|
1453
|
-
// src/clarity/abi/guards.ts
|
|
1454
|
-
function isAbiList(type) {
|
|
1455
|
-
return typeof type === "object" && type !== null && "list" in type;
|
|
1456
|
-
}
|
|
1457
|
-
function isAbiTuple(type) {
|
|
1458
|
-
return typeof type === "object" && type !== null && "tuple" in type;
|
|
1459
|
-
}
|
|
1460
|
-
function isAbiOptional(type) {
|
|
1461
|
-
return typeof type === "object" && type !== null && "optional" in type;
|
|
1462
|
-
}
|
|
1463
|
-
function isAbiResponse(type) {
|
|
1464
|
-
return typeof type === "object" && type !== null && "response" in type;
|
|
1465
|
-
}
|
|
1466
|
-
function isAbiBuffer(type) {
|
|
1467
|
-
return typeof type === "object" && type !== null && "buff" in type;
|
|
1468
|
-
}
|
|
1469
|
-
function isAbiStringAscii(type) {
|
|
1470
|
-
return typeof type === "object" && type !== null && "string-ascii" in type;
|
|
1471
|
-
}
|
|
1472
|
-
function isAbiStringUtf8(type) {
|
|
1473
|
-
return typeof type === "object" && type !== null && "string-utf8" in type;
|
|
1474
|
-
}
|
|
1475
|
-
|
|
1476
|
-
// src/clarity/bridge.ts
|
|
1477
|
-
var CV_TYPE_TAGS = new Set([
|
|
1478
|
-
"int",
|
|
1479
|
-
"uint",
|
|
1480
|
-
"true",
|
|
1481
|
-
"false",
|
|
1482
|
-
"address",
|
|
1483
|
-
"contract",
|
|
1484
|
-
"ascii",
|
|
1485
|
-
"utf8",
|
|
1486
|
-
"buffer",
|
|
1487
|
-
"list",
|
|
1488
|
-
"tuple",
|
|
1489
|
-
"none",
|
|
1490
|
-
"some",
|
|
1491
|
-
"ok",
|
|
1492
|
-
"err"
|
|
1493
|
-
]);
|
|
1494
|
-
function isClarityValue(value) {
|
|
1495
|
-
if (typeof value !== "object" || value === null)
|
|
1496
|
-
return false;
|
|
1497
|
-
const type = value.type;
|
|
1498
|
-
if (typeof type !== "string" || !CV_TYPE_TAGS.has(type))
|
|
1499
|
-
return false;
|
|
1500
|
-
if (type === "true" || type === "false" || type === "none")
|
|
1501
|
-
return true;
|
|
1502
|
-
return "value" in value;
|
|
1503
|
-
}
|
|
1504
|
-
var HEX_PAIRS_REGEX = /^(?:[0-9a-fA-F]{2})+$/;
|
|
1505
|
-
function coerceBuffer(value) {
|
|
1506
|
-
if (value instanceof Uint8Array)
|
|
1507
|
-
return bufferCV(value);
|
|
1508
|
-
if (typeof value === "object" && value !== null && "type" in value) {
|
|
1509
|
-
const tagged = value;
|
|
1510
|
-
if (tagged.type === "buffer" && isClarityValue(value))
|
|
1511
|
-
return value;
|
|
1512
|
-
if (typeof tagged.value === "string") {
|
|
1513
|
-
if (tagged.type === "ascii")
|
|
1514
|
-
return Cl.bufferFromAscii(tagged.value);
|
|
1515
|
-
if (tagged.type === "utf8")
|
|
1516
|
-
return Cl.bufferFromUtf8(tagged.value);
|
|
1517
|
-
if (tagged.type === "hex")
|
|
1518
|
-
return Cl.bufferFromHex(tagged.value);
|
|
1519
|
-
}
|
|
1520
|
-
throw new Error(`Unsupported buffer input: ${JSON.stringify(value)}`);
|
|
1521
|
-
}
|
|
1522
|
-
if (typeof value === "string") {
|
|
1523
|
-
const hex = value.startsWith("0x") ? value.slice(2) : value;
|
|
1524
|
-
if (HEX_PAIRS_REGEX.test(hex))
|
|
1525
|
-
return Cl.bufferFromHex(hex);
|
|
1526
|
-
return Cl.bufferFromUtf8(value);
|
|
1527
|
-
}
|
|
1528
|
-
throw new Error("buffer arg expects Uint8Array, hex string, { type, value }, or BufferCV");
|
|
1529
|
-
}
|
|
1530
|
-
function jsToClarityValue(abiType, value) {
|
|
1531
|
-
if (isAbiBuffer(abiType))
|
|
1532
|
-
return coerceBuffer(value);
|
|
1533
|
-
if (isClarityValue(value))
|
|
1534
|
-
return value;
|
|
1535
|
-
if (abiType === "uint128")
|
|
1536
|
-
return uintCV(value);
|
|
1537
|
-
if (abiType === "int128")
|
|
1538
|
-
return intCV(value);
|
|
1539
|
-
if (abiType === "bool")
|
|
1540
|
-
return boolCV(value);
|
|
1541
|
-
if (abiType === "principal" || abiType === "trait_reference")
|
|
1542
|
-
return Cl.principal(value);
|
|
1543
|
-
if (isAbiStringAscii(abiType))
|
|
1544
|
-
return stringAsciiCV(value);
|
|
1545
|
-
if (isAbiStringUtf8(abiType))
|
|
1546
|
-
return stringUtf8CV(value);
|
|
1547
|
-
if (isAbiList(abiType)) {
|
|
1548
|
-
const arr = value;
|
|
1549
|
-
return listCV(arr.map((item) => jsToClarityValue(abiType.list.type, item)));
|
|
1550
|
-
}
|
|
1551
|
-
if (isAbiTuple(abiType)) {
|
|
1552
|
-
const obj = value;
|
|
1553
|
-
const data = {};
|
|
1554
|
-
for (const field of abiType.tuple) {
|
|
1555
|
-
const camelKey = toCamelCase(field.name);
|
|
1556
|
-
const hasOriginal = field.name in obj;
|
|
1557
|
-
const hasCamel = camelKey in obj;
|
|
1558
|
-
const fieldValue = hasOriginal ? obj[field.name] : hasCamel ? obj[camelKey] : undefined;
|
|
1559
|
-
if (fieldValue === undefined && !isAbiOptional(field.type)) {
|
|
1560
|
-
throw new Error(`Missing tuple field: ${field.name}`);
|
|
1561
|
-
}
|
|
1562
|
-
data[field.name] = jsToClarityValue(field.type, fieldValue);
|
|
1563
|
-
}
|
|
1564
|
-
return tupleCV(data);
|
|
1565
|
-
}
|
|
1566
|
-
if (isAbiOptional(abiType)) {
|
|
1567
|
-
if (value === null || value === undefined)
|
|
1568
|
-
return noneCV();
|
|
1569
|
-
return someCV(jsToClarityValue(abiType.optional, value));
|
|
1570
|
-
}
|
|
1571
|
-
if (isAbiResponse(abiType)) {
|
|
1572
|
-
const obj = value;
|
|
1573
|
-
if ("ok" in obj && !("err" in obj))
|
|
1574
|
-
return responseOkCV(jsToClarityValue(abiType.response.ok, obj.ok));
|
|
1575
|
-
if ("err" in obj && !("ok" in obj))
|
|
1576
|
-
return responseErrorCV(jsToClarityValue(abiType.response.error, obj.err));
|
|
1577
|
-
throw new Error("Response must have exactly 'ok' or 'err' property");
|
|
1578
|
-
}
|
|
1579
|
-
throw new Error(`Unknown ABI type: ${JSON.stringify(abiType)}`);
|
|
1580
|
-
}
|
|
1581
|
-
function clarityValueToJSUntyped(abiType, cv) {
|
|
1582
|
-
return clarityValueToJSInner(abiType, cv);
|
|
1583
|
-
}
|
|
1584
|
-
function clarityValueToJSInner(abiType, cv) {
|
|
1585
|
-
if (abiType === "uint128" || abiType === "int128") {
|
|
1586
|
-
if (cv.type !== "int" && cv.type !== "uint")
|
|
1587
|
-
throw new Error(`Expected int/uint CV, got ${cv.type}`);
|
|
1588
|
-
return cv.value;
|
|
1589
|
-
}
|
|
1590
|
-
if (abiType === "bool") {
|
|
1591
|
-
if (cv.type === "true")
|
|
1592
|
-
return true;
|
|
1593
|
-
if (cv.type === "false")
|
|
1594
|
-
return false;
|
|
1595
|
-
throw new Error(`Expected bool CV, got ${cv.type}`);
|
|
1596
|
-
}
|
|
1597
|
-
if (abiType === "principal" || abiType === "trait_reference") {
|
|
1598
|
-
if (cv.type !== "address" && cv.type !== "contract")
|
|
1599
|
-
throw new Error(`Expected principal CV, got ${cv.type}`);
|
|
1600
|
-
return cv.value;
|
|
1601
|
-
}
|
|
1602
|
-
if (isAbiStringAscii(abiType) || isAbiStringUtf8(abiType)) {
|
|
1603
|
-
if (cv.type !== "ascii" && cv.type !== "utf8")
|
|
1604
|
-
throw new Error(`Expected string CV, got ${cv.type}`);
|
|
1605
|
-
return cv.value;
|
|
1606
|
-
}
|
|
1607
|
-
if (isAbiBuffer(abiType)) {
|
|
1608
|
-
if (cv.type !== "buffer")
|
|
1609
|
-
throw new Error(`Expected buffer CV, got ${cv.type}`);
|
|
1610
|
-
const hex = cv.value;
|
|
1611
|
-
const bytes = new Uint8Array(hex.length / 2);
|
|
1612
|
-
for (let i = 0;i < bytes.length; i++) {
|
|
1613
|
-
bytes[i] = Number.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
|
1614
|
-
}
|
|
1615
|
-
return bytes;
|
|
1616
|
-
}
|
|
1617
|
-
if (isAbiList(abiType)) {
|
|
1618
|
-
if (cv.type !== "list")
|
|
1619
|
-
throw new Error(`Expected list CV, got ${cv.type}`);
|
|
1620
|
-
return cv.value.map((item) => clarityValueToJSInner(abiType.list.type, item));
|
|
1621
|
-
}
|
|
1622
|
-
if (isAbiTuple(abiType)) {
|
|
1623
|
-
if (cv.type !== "tuple")
|
|
1624
|
-
throw new Error(`Expected tuple CV, got ${cv.type}`);
|
|
1625
|
-
const result = {};
|
|
1626
|
-
for (const field of abiType.tuple) {
|
|
1627
|
-
const fieldCV = cv.value[field.name];
|
|
1628
|
-
if (!fieldCV)
|
|
1629
|
-
throw new Error(`Missing tuple field in CV: ${field.name}`);
|
|
1630
|
-
const camelKey = toCamelCase(field.name);
|
|
1631
|
-
result[camelKey] = clarityValueToJSInner(field.type, fieldCV);
|
|
1632
|
-
}
|
|
1633
|
-
return result;
|
|
1634
|
-
}
|
|
1635
|
-
if (isAbiOptional(abiType)) {
|
|
1636
|
-
if (cv.type === "none")
|
|
1637
|
-
return null;
|
|
1638
|
-
if (cv.type === "some")
|
|
1639
|
-
return clarityValueToJSInner(abiType.optional, cv.value);
|
|
1640
|
-
throw new Error(`Expected optional CV, got ${cv.type}`);
|
|
1641
|
-
}
|
|
1642
|
-
if (isAbiResponse(abiType)) {
|
|
1643
|
-
if (cv.type === "ok")
|
|
1644
|
-
return { ok: clarityValueToJSInner(abiType.response.ok, cv.value) };
|
|
1645
|
-
if (cv.type === "err")
|
|
1646
|
-
return { err: clarityValueToJSInner(abiType.response.error, cv.value) };
|
|
1647
|
-
throw new Error(`Expected response CV, got ${cv.type}`);
|
|
1648
|
-
}
|
|
1649
|
-
throw new Error(`Unknown ABI type: ${JSON.stringify(abiType)}`);
|
|
1650
|
-
}
|
|
1651
|
-
|
|
1652
|
-
// src/transactions/wire/deserialize.ts
|
|
1653
|
-
function readSpendingCondition(r) {
|
|
1654
|
-
const hashMode = r.readUInt8();
|
|
1655
|
-
const signer = bytesToHex(r.readBytes(20));
|
|
1656
|
-
const nonce = r.readBigUInt64BE();
|
|
1657
|
-
const fee = r.readBigUInt64BE();
|
|
1658
|
-
if (hashMode === AddressHashMode.P2PKH || hashMode === AddressHashMode.P2WPKH) {
|
|
1659
|
-
const keyEncoding = r.readUInt8();
|
|
1660
|
-
const signature = bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES));
|
|
1661
|
-
return {
|
|
1662
|
-
hashMode,
|
|
1663
|
-
signer,
|
|
1664
|
-
nonce,
|
|
1665
|
-
fee,
|
|
1666
|
-
keyEncoding,
|
|
1667
|
-
signature
|
|
1668
|
-
};
|
|
1669
|
-
}
|
|
1670
|
-
const fieldCount = r.readUInt32BE();
|
|
1671
|
-
const fields = [];
|
|
1672
|
-
for (let i = 0;i < fieldCount; i++) {
|
|
1673
|
-
const fieldType = r.readUInt8();
|
|
1674
|
-
if (fieldType <= 1) {
|
|
1675
|
-
const keyLen = fieldType === 0 ? 33 : 65;
|
|
1676
|
-
fields.push({
|
|
1677
|
-
type: "publicKey",
|
|
1678
|
-
pubKeyEncoding: fieldType,
|
|
1679
|
-
data: bytesToHex(r.readBytes(keyLen))
|
|
1680
|
-
});
|
|
1681
|
-
} else {
|
|
1682
|
-
fields.push({
|
|
1683
|
-
type: "signature",
|
|
1684
|
-
pubKeyEncoding: fieldType === 2 ? 0 : 1,
|
|
1685
|
-
data: bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES))
|
|
1686
|
-
});
|
|
1687
|
-
}
|
|
1688
|
-
}
|
|
1689
|
-
const signaturesRequired = r.readUInt16BE();
|
|
1690
|
-
return {
|
|
1691
|
-
hashMode,
|
|
1692
|
-
signer,
|
|
1693
|
-
nonce,
|
|
1694
|
-
fee,
|
|
1695
|
-
fields,
|
|
1696
|
-
signaturesRequired
|
|
1697
|
-
};
|
|
1698
|
-
}
|
|
1699
|
-
function readAuthorization(r) {
|
|
1700
|
-
const authType = r.readUInt8();
|
|
1701
|
-
const spendingCondition = readSpendingCondition(r);
|
|
1702
|
-
if (authType === AuthType.Standard) {
|
|
1703
|
-
return { authType: AuthType.Standard, spendingCondition };
|
|
1704
|
-
}
|
|
1705
|
-
const sponsorSpendingCondition = readSpendingCondition(r);
|
|
1706
|
-
return {
|
|
1707
|
-
authType: AuthType.Sponsored,
|
|
1708
|
-
spendingCondition,
|
|
1709
|
-
sponsorSpendingCondition
|
|
1710
|
-
};
|
|
1711
|
-
}
|
|
1712
|
-
function readAssetInfo(r) {
|
|
1713
|
-
return {
|
|
1714
|
-
address: readAddress(r),
|
|
1715
|
-
contractName: readLPString(r),
|
|
1716
|
-
assetName: readLPString(r)
|
|
1717
|
-
};
|
|
1718
|
-
}
|
|
1719
|
-
function readPostConditionPrincipal(r) {
|
|
1720
|
-
const type = r.readUInt8();
|
|
1721
|
-
switch (type) {
|
|
1722
|
-
case PostConditionPrincipalId.Origin:
|
|
1723
|
-
return { type: "origin" };
|
|
1724
|
-
case PostConditionPrincipalId.Standard:
|
|
1725
|
-
return { type: "standard", address: readAddress(r) };
|
|
1726
|
-
case PostConditionPrincipalId.Contract:
|
|
1727
|
-
return {
|
|
1728
|
-
type: "contract",
|
|
1729
|
-
address: readAddress(r),
|
|
1730
|
-
contractName: readLPString(r)
|
|
1731
|
-
};
|
|
1732
|
-
default:
|
|
1733
|
-
return { type: "origin" };
|
|
1734
|
-
}
|
|
1735
|
-
}
|
|
1736
|
-
function readPostCondition(r) {
|
|
1737
|
-
const assetType = r.readUInt8();
|
|
1738
|
-
const principal = readPostConditionPrincipal(r);
|
|
1739
|
-
switch (assetType) {
|
|
1740
|
-
case AssetType.STX:
|
|
1741
|
-
return {
|
|
1742
|
-
type: "stx",
|
|
1743
|
-
principal,
|
|
1744
|
-
conditionCode: r.readUInt8(),
|
|
1745
|
-
amount: r.readBigUInt64BE()
|
|
1746
|
-
};
|
|
1747
|
-
case AssetType.Fungible:
|
|
1748
|
-
return {
|
|
1749
|
-
type: "ft",
|
|
1750
|
-
principal,
|
|
1751
|
-
asset: readAssetInfo(r),
|
|
1752
|
-
conditionCode: r.readUInt8(),
|
|
1753
|
-
amount: r.readBigUInt64BE()
|
|
1754
|
-
};
|
|
1755
|
-
case AssetType.NonFungible:
|
|
1756
|
-
return {
|
|
1757
|
-
type: "nft",
|
|
1758
|
-
principal,
|
|
1759
|
-
asset: readAssetInfo(r),
|
|
1760
|
-
assetId: readCV(r),
|
|
1761
|
-
conditionCode: r.readUInt8()
|
|
1762
|
-
};
|
|
1763
|
-
case AssetType.Staking:
|
|
1764
|
-
return {
|
|
1765
|
-
type: "staking",
|
|
1766
|
-
principal,
|
|
1767
|
-
conditionCode: r.readUInt8(),
|
|
1768
|
-
amount: r.readBigUInt64BE()
|
|
1769
|
-
};
|
|
1770
|
-
case AssetType.Pox:
|
|
1771
|
-
return {
|
|
1772
|
-
type: "pox",
|
|
1773
|
-
principal,
|
|
1774
|
-
conditionCode: r.readUInt8()
|
|
1775
|
-
};
|
|
1776
|
-
default:
|
|
1777
|
-
throw new Error(`Unknown post-condition asset type: 0x${assetType.toString(16).padStart(2, "0")}`);
|
|
1778
|
-
}
|
|
1779
|
-
}
|
|
1780
|
-
function readPostConditions(r) {
|
|
1781
|
-
const count = r.readUInt32BE();
|
|
1782
|
-
const pcs = [];
|
|
1783
|
-
for (let i = 0;i < count; i++) {
|
|
1784
|
-
try {
|
|
1785
|
-
pcs.push(readPostCondition(r));
|
|
1786
|
-
} catch (e) {
|
|
1787
|
-
if (e instanceof Error && e.message.startsWith("Unknown post-condition asset type:")) {
|
|
1788
|
-
throw new Error(`${e.message} (post-condition ${i + 1}/${count})`);
|
|
1789
|
-
}
|
|
1790
|
-
throw e;
|
|
1791
|
-
}
|
|
1792
|
-
}
|
|
1793
|
-
return pcs;
|
|
1794
|
-
}
|
|
1795
|
-
function readPayload(r) {
|
|
1796
|
-
const payloadType = r.readUInt8();
|
|
1797
|
-
switch (payloadType) {
|
|
1798
|
-
case PayloadType.TokenTransfer: {
|
|
1799
|
-
const recipient = readCV(r);
|
|
1800
|
-
const amount = r.readBigUInt64BE();
|
|
1801
|
-
const memoBytes = r.readBytes(MEMO_MAX_LENGTH_BYTES);
|
|
1802
|
-
const memo = bytesToAscii(memoBytes).replace(/\0+$/, "");
|
|
1803
|
-
return {
|
|
1804
|
-
payloadType: PayloadType.TokenTransfer,
|
|
1805
|
-
recipient,
|
|
1806
|
-
amount,
|
|
1807
|
-
memo
|
|
1808
|
-
};
|
|
1809
|
-
}
|
|
1810
|
-
case PayloadType.ContractCall: {
|
|
1811
|
-
const contractAddress = readAddress(r);
|
|
1812
|
-
const contractName = readLPString(r);
|
|
1813
|
-
const functionName = readLPString(r);
|
|
1814
|
-
const numArgs = r.readUInt32BE();
|
|
1815
|
-
const functionArgs = [];
|
|
1816
|
-
for (let i = 0;i < numArgs; i++)
|
|
1817
|
-
functionArgs.push(readCV(r));
|
|
1818
|
-
return {
|
|
1819
|
-
payloadType: PayloadType.ContractCall,
|
|
1820
|
-
contractAddress,
|
|
1821
|
-
contractName,
|
|
1822
|
-
functionName,
|
|
1823
|
-
functionArgs
|
|
1824
|
-
};
|
|
1825
|
-
}
|
|
1826
|
-
case PayloadType.SmartContract: {
|
|
1827
|
-
const contractName = readLPString(r);
|
|
1828
|
-
const codeBody = readLPString(r, 4);
|
|
1829
|
-
return { payloadType: PayloadType.SmartContract, contractName, codeBody };
|
|
1830
|
-
}
|
|
1831
|
-
case PayloadType.VersionedSmartContract: {
|
|
1832
|
-
const clarityVersion = r.readUInt8();
|
|
1833
|
-
const contractName = readLPString(r);
|
|
1834
|
-
const codeBody = readLPString(r, 4);
|
|
1835
|
-
return {
|
|
1836
|
-
payloadType: PayloadType.VersionedSmartContract,
|
|
1837
|
-
clarityVersion,
|
|
1838
|
-
contractName,
|
|
1839
|
-
codeBody
|
|
1840
|
-
};
|
|
1841
|
-
}
|
|
1842
|
-
case PayloadType.Coinbase: {
|
|
1843
|
-
const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
|
|
1844
|
-
return { payloadType: PayloadType.Coinbase, coinbaseBuffer };
|
|
1845
|
-
}
|
|
1846
|
-
case PayloadType.CoinbaseToAltRecipient: {
|
|
1847
|
-
const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
|
|
1848
|
-
const recipient = readCV(r);
|
|
1849
|
-
return {
|
|
1850
|
-
payloadType: PayloadType.CoinbaseToAltRecipient,
|
|
1851
|
-
coinbaseBuffer,
|
|
1852
|
-
recipient
|
|
1853
|
-
};
|
|
1854
|
-
}
|
|
1855
|
-
case PayloadType.PoisonMicroblock: {
|
|
1856
|
-
const header1 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));
|
|
1857
|
-
const header2 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));
|
|
1858
|
-
return { payloadType: PayloadType.PoisonMicroblock, header1, header2 };
|
|
1859
|
-
}
|
|
1860
|
-
case PayloadType.TenureChange: {
|
|
1861
|
-
const tenureConsensusHash = bytesToHex(r.readBytes(20));
|
|
1862
|
-
const prevTenureConsensusHash = bytesToHex(r.readBytes(20));
|
|
1863
|
-
const burnViewConsensusHash = bytesToHex(r.readBytes(20));
|
|
1864
|
-
const previousTenureEnd = bytesToHex(r.readBytes(32));
|
|
1865
|
-
const previousTenureBlocks = r.readUInt32BE();
|
|
1866
|
-
const cause = r.readUInt8();
|
|
1867
|
-
const pubkeyHash = bytesToHex(r.readBytes(20));
|
|
1868
|
-
return {
|
|
1869
|
-
payloadType: PayloadType.TenureChange,
|
|
1870
|
-
tenureConsensusHash,
|
|
1871
|
-
prevTenureConsensusHash,
|
|
1872
|
-
burnViewConsensusHash,
|
|
1873
|
-
previousTenureEnd,
|
|
1874
|
-
previousTenureBlocks,
|
|
1875
|
-
cause,
|
|
1876
|
-
pubkeyHash
|
|
1877
|
-
};
|
|
1878
|
-
}
|
|
1879
|
-
case PayloadType.NakamotoCoinbase: {
|
|
1880
|
-
const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
|
|
1881
|
-
const optionalCV = readCV(r);
|
|
1882
|
-
const recipient = optionalCV.type === "none" ? null : optionalCV.type === "some" ? optionalCV.value : optionalCV;
|
|
1883
|
-
const vrfProof = bytesToHex(r.readBytes(VRF_PROOF_BYTES_LENGTH));
|
|
1884
|
-
return {
|
|
1885
|
-
payloadType: PayloadType.NakamotoCoinbase,
|
|
1886
|
-
coinbaseBuffer,
|
|
1887
|
-
recipient,
|
|
1888
|
-
vrfProof
|
|
1889
|
-
};
|
|
1890
|
-
}
|
|
1891
|
-
default:
|
|
1892
|
-
throw new Error(`Unknown payload type: ${payloadType}`);
|
|
1893
|
-
}
|
|
1894
|
-
}
|
|
1895
|
-
function deserializePostConditionWire(input) {
|
|
1896
|
-
const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
|
|
1897
|
-
return readPostCondition(new BytesReader(bytes));
|
|
1898
|
-
}
|
|
1899
|
-
function deserializeTransaction(input, meta) {
|
|
1900
|
-
const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
|
|
1901
|
-
const r = new BytesReader(bytes);
|
|
1902
|
-
const tx = {
|
|
1903
|
-
version: r.readUInt8(),
|
|
1904
|
-
chainId: r.readUInt32BE(),
|
|
1905
|
-
auth: readAuthorization(r),
|
|
1906
|
-
anchorMode: r.readUInt8(),
|
|
1907
|
-
postConditionMode: r.readUInt8(),
|
|
1908
|
-
postConditions: readPostConditions(r),
|
|
1909
|
-
payload: readPayload(r)
|
|
1910
|
-
};
|
|
1911
|
-
if (meta?._multisig) {
|
|
1912
|
-
tx._multisig = meta._multisig;
|
|
1913
|
-
}
|
|
1914
|
-
return tx;
|
|
1915
|
-
}
|
|
1916
|
-
|
|
1917
|
-
// src/postconditions/convert.ts
|
|
1918
|
-
var MAX_U64 = 18446744073709551615n;
|
|
1919
|
-
function parsePostConditionAmount(amount) {
|
|
1920
|
-
const value = intToBigInt(amount);
|
|
1921
|
-
if (value < 0n || value > MAX_U64) {
|
|
1922
|
-
throw new RangeError(`Post-condition amount must be between 0 and ${MAX_U64} (u64 max), received: ${value}`);
|
|
1923
|
-
}
|
|
1924
|
-
return value;
|
|
1925
|
-
}
|
|
1926
|
-
var FUNGIBLE_CODE_MAP = {
|
|
1927
|
-
eq: FungibleConditionCode.Equal,
|
|
1928
|
-
gt: FungibleConditionCode.Greater,
|
|
1929
|
-
gte: FungibleConditionCode.GreaterEqual,
|
|
1930
|
-
lt: FungibleConditionCode.Less,
|
|
1931
|
-
lte: FungibleConditionCode.LessEqual
|
|
1932
|
-
};
|
|
1933
|
-
var FUNGIBLE_CODE_REVERSE = {
|
|
1934
|
-
[FungibleConditionCode.Equal]: "eq",
|
|
1935
|
-
[FungibleConditionCode.Greater]: "gt",
|
|
1936
|
-
[FungibleConditionCode.GreaterEqual]: "gte",
|
|
1937
|
-
[FungibleConditionCode.Less]: "lt",
|
|
1938
|
-
[FungibleConditionCode.LessEqual]: "lte"
|
|
1939
|
-
};
|
|
1940
|
-
var NFT_CODE_MAP = {
|
|
1941
|
-
sent: NonFungibleConditionCode.Sends,
|
|
1942
|
-
"not-sent": NonFungibleConditionCode.DoesNotSend,
|
|
1943
|
-
"maybe-sent": NonFungibleConditionCode.MaybeSent
|
|
1944
|
-
};
|
|
1945
|
-
var NFT_CODE_REVERSE = {
|
|
1946
|
-
[NonFungibleConditionCode.Sends]: "sent",
|
|
1947
|
-
[NonFungibleConditionCode.DoesNotSend]: "not-sent",
|
|
1948
|
-
[NonFungibleConditionCode.MaybeSent]: "maybe-sent"
|
|
1949
|
-
};
|
|
1950
|
-
var POX_CODE_MAP = {
|
|
1951
|
-
"will-not-perform": PoxConditionCode.WillNotPerform,
|
|
1952
|
-
"may-perform": PoxConditionCode.MayPerform,
|
|
1953
|
-
"will-perform": PoxConditionCode.WillPerform
|
|
1954
|
-
};
|
|
1955
|
-
var POX_CODE_REVERSE = {
|
|
1956
|
-
[PoxConditionCode.WillNotPerform]: "will-not-perform",
|
|
1957
|
-
[PoxConditionCode.MayPerform]: "may-perform",
|
|
1958
|
-
[PoxConditionCode.WillPerform]: "will-perform"
|
|
1959
|
-
};
|
|
1960
|
-
function resolvePrincipal(address) {
|
|
1961
|
-
if (address === "origin")
|
|
1962
|
-
return { type: "origin" };
|
|
1963
|
-
const [addr, name] = address.split(".");
|
|
1964
|
-
if (name) {
|
|
1965
|
-
return { type: "contract", address: addr, contractName: name };
|
|
1966
|
-
}
|
|
1967
|
-
return { type: "standard", address: addr };
|
|
1968
|
-
}
|
|
1969
|
-
function principalToString(principal) {
|
|
1970
|
-
if (principal.type === "origin")
|
|
1971
|
-
return "origin";
|
|
1972
|
-
if (principal.type === "contract") {
|
|
1973
|
-
return `${principal.address}.${principal.contractName}`;
|
|
1974
|
-
}
|
|
1975
|
-
return principal.address;
|
|
1976
|
-
}
|
|
1977
|
-
function assetToString(asset) {
|
|
1978
|
-
return `${asset.address}.${asset.contractName}::${asset.assetName}`;
|
|
1979
|
-
}
|
|
1980
|
-
function parseAsset(asset) {
|
|
1981
|
-
const [contractId, tokenName] = asset.split("::");
|
|
1982
|
-
const [addr, name] = parseContractId(contractId);
|
|
1983
|
-
return { address: addr, contractName: name, assetName: tokenName };
|
|
1984
|
-
}
|
|
1985
|
-
function convertPostCondition(pc) {
|
|
1986
|
-
switch (pc.type) {
|
|
1987
|
-
case "stx-postcondition":
|
|
1988
|
-
return {
|
|
1989
|
-
type: "stx",
|
|
1990
|
-
principal: resolvePrincipal(pc.address),
|
|
1991
|
-
conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
|
|
1992
|
-
amount: parsePostConditionAmount(pc.amount)
|
|
1993
|
-
};
|
|
1994
|
-
case "ft-postcondition":
|
|
1995
|
-
return {
|
|
1996
|
-
type: "ft",
|
|
1997
|
-
principal: resolvePrincipal(pc.address),
|
|
1998
|
-
asset: parseAsset(pc.asset),
|
|
1999
|
-
conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
|
|
2000
|
-
amount: parsePostConditionAmount(pc.amount)
|
|
2001
|
-
};
|
|
2002
|
-
case "nft-postcondition":
|
|
2003
|
-
return {
|
|
2004
|
-
type: "nft",
|
|
2005
|
-
principal: resolvePrincipal(pc.address),
|
|
2006
|
-
asset: parseAsset(pc.asset),
|
|
2007
|
-
conditionCode: NFT_CODE_MAP[pc.condition],
|
|
2008
|
-
assetId: pc.assetId
|
|
2009
|
-
};
|
|
2010
|
-
case "staking-postcondition":
|
|
2011
|
-
return {
|
|
2012
|
-
type: "staking",
|
|
2013
|
-
principal: resolvePrincipal(pc.address),
|
|
2014
|
-
conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
|
|
2015
|
-
amount: parsePostConditionAmount(pc.amount)
|
|
2016
|
-
};
|
|
2017
|
-
case "pox-postcondition":
|
|
2018
|
-
return {
|
|
2019
|
-
type: "pox",
|
|
2020
|
-
principal: resolvePrincipal(pc.address),
|
|
2021
|
-
conditionCode: POX_CODE_MAP[pc.condition]
|
|
2022
|
-
};
|
|
2023
|
-
}
|
|
2024
|
-
}
|
|
2025
|
-
function wireToPostCondition(wire) {
|
|
2026
|
-
switch (wire.type) {
|
|
2027
|
-
case "stx":
|
|
2028
|
-
return {
|
|
2029
|
-
type: "stx-postcondition",
|
|
2030
|
-
address: principalToString(wire.principal),
|
|
2031
|
-
condition: fungibleName(wire.conditionCode),
|
|
2032
|
-
amount: wire.amount.toString()
|
|
2033
|
-
};
|
|
2034
|
-
case "ft":
|
|
2035
|
-
return {
|
|
2036
|
-
type: "ft-postcondition",
|
|
2037
|
-
address: principalToString(wire.principal),
|
|
2038
|
-
condition: fungibleName(wire.conditionCode),
|
|
2039
|
-
amount: wire.amount.toString(),
|
|
2040
|
-
asset: assetToString(wire.asset)
|
|
2041
|
-
};
|
|
2042
|
-
case "nft":
|
|
2043
|
-
return {
|
|
2044
|
-
type: "nft-postcondition",
|
|
2045
|
-
address: principalToString(wire.principal),
|
|
2046
|
-
condition: nftName(wire.conditionCode),
|
|
2047
|
-
asset: assetToString(wire.asset),
|
|
2048
|
-
assetId: wire.assetId
|
|
2049
|
-
};
|
|
2050
|
-
case "staking":
|
|
2051
|
-
return {
|
|
2052
|
-
type: "staking-postcondition",
|
|
2053
|
-
address: principalToString(wire.principal),
|
|
2054
|
-
condition: fungibleName(wire.conditionCode),
|
|
2055
|
-
amount: wire.amount.toString()
|
|
2056
|
-
};
|
|
2057
|
-
case "pox":
|
|
2058
|
-
return {
|
|
2059
|
-
type: "pox-postcondition",
|
|
2060
|
-
address: principalToString(wire.principal),
|
|
2061
|
-
condition: poxName(wire.conditionCode)
|
|
2062
|
-
};
|
|
2063
|
-
}
|
|
2064
|
-
}
|
|
2065
|
-
function fungibleName(code) {
|
|
2066
|
-
const name = FUNGIBLE_CODE_REVERSE[code];
|
|
2067
|
-
if (!name)
|
|
2068
|
-
throw new Error(`Unknown fungible post-condition code: ${code}`);
|
|
2069
|
-
return name;
|
|
2070
|
-
}
|
|
2071
|
-
function nftName(code) {
|
|
2072
|
-
const name = NFT_CODE_REVERSE[code];
|
|
2073
|
-
if (!name)
|
|
2074
|
-
throw new Error(`Unknown nft post-condition code: ${code}`);
|
|
2075
|
-
return name;
|
|
2076
|
-
}
|
|
2077
|
-
function poxName(code) {
|
|
2078
|
-
const name = POX_CODE_REVERSE[code];
|
|
2079
|
-
if (!name)
|
|
2080
|
-
throw new Error(`Unknown pox post-condition code: ${code}`);
|
|
2081
|
-
return name;
|
|
2082
|
-
}
|
|
2083
|
-
function fromHex(hex) {
|
|
2084
|
-
return wireToPostCondition(deserializePostConditionWire(hex));
|
|
2085
|
-
}
|
|
2086
|
-
|
|
2087
|
-
// src/transactions/authorization.ts
|
|
2088
|
-
import { hmac } from "@noble/hashes/hmac.js";
|
|
2089
|
-
import { sha256 as sha2563 } from "@noble/hashes/sha2.js";
|
|
2090
|
-
import { etc, getPublicKey as nobleGetPublicKey, sign } from "@noble/secp256k1";
|
|
2091
|
-
etc.hmacSha256Sync = (key, ...msgs) => {
|
|
2092
|
-
const h = hmac.create(sha2563, key);
|
|
2093
|
-
for (const msg of msgs)
|
|
2094
|
-
h.update(msg);
|
|
2095
|
-
return h.digest();
|
|
2096
|
-
};
|
|
2097
|
-
var EMPTY_SIG = bytesToHex(new Uint8Array(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES));
|
|
2098
|
-
function createSingleSigSpendingCondition(publicKey, nonce, fee) {
|
|
2099
|
-
const pubKeyBytes = hexToBytes(publicKey);
|
|
2100
|
-
const signer = hashP2PKH(pubKeyBytes);
|
|
2101
|
-
const isCompressed = pubKeyBytes.length === 33;
|
|
2102
|
-
return {
|
|
2103
|
-
hashMode: AddressHashMode.P2PKH,
|
|
2104
|
-
signer,
|
|
2105
|
-
nonce,
|
|
2106
|
-
fee,
|
|
2107
|
-
keyEncoding: isCompressed ? PubKeyEncoding.Compressed : PubKeyEncoding.Uncompressed,
|
|
2108
|
-
signature: EMPTY_SIG
|
|
2109
|
-
};
|
|
2110
|
-
}
|
|
2111
|
-
function createStandardAuth(spendingCondition) {
|
|
2112
|
-
return { authType: AuthType.Standard, spendingCondition };
|
|
2113
|
-
}
|
|
2114
|
-
function createSponsoredAuth(spendingCondition, sponsorSpendingCondition) {
|
|
2115
|
-
return {
|
|
2116
|
-
authType: AuthType.Sponsored,
|
|
2117
|
-
spendingCondition,
|
|
2118
|
-
sponsorSpendingCondition: sponsorSpendingCondition ?? createSingleSigSpendingCondition("0".repeat(66), 0n, 0n)
|
|
2119
|
-
};
|
|
2120
|
-
}
|
|
2121
|
-
function clearCondition(condition) {
|
|
2122
|
-
if ("signature" in condition) {
|
|
2123
|
-
return {
|
|
2124
|
-
...condition,
|
|
2125
|
-
nonce: 0n,
|
|
2126
|
-
fee: 0n,
|
|
2127
|
-
signature: EMPTY_SIG
|
|
2128
|
-
};
|
|
2129
|
-
}
|
|
2130
|
-
return {
|
|
2131
|
-
...condition,
|
|
2132
|
-
nonce: 0n,
|
|
2133
|
-
fee: 0n,
|
|
2134
|
-
fields: []
|
|
2135
|
-
};
|
|
2136
|
-
}
|
|
2137
|
-
function sponsorSigningSentinel() {
|
|
2138
|
-
return {
|
|
2139
|
-
hashMode: AddressHashMode.P2PKH,
|
|
2140
|
-
signer: "00".repeat(20),
|
|
2141
|
-
nonce: 0n,
|
|
2142
|
-
fee: 0n,
|
|
2143
|
-
keyEncoding: PubKeyEncoding.Compressed,
|
|
2144
|
-
signature: EMPTY_SIG
|
|
2145
|
-
};
|
|
2146
|
-
}
|
|
2147
|
-
function intoInitialSighashAuth(auth) {
|
|
2148
|
-
if (auth.authType === AuthType.Standard) {
|
|
2149
|
-
return createStandardAuth(clearCondition(auth.spendingCondition));
|
|
2150
|
-
}
|
|
2151
|
-
return createSponsoredAuth(clearCondition(auth.spendingCondition), sponsorSigningSentinel());
|
|
2152
|
-
}
|
|
2153
|
-
function sigHashPreSign(curSigHash, authType, fee, nonce) {
|
|
2154
|
-
const data = concatBytes(hexToBytes(curSigHash), new Uint8Array([authType]), intToBytes(fee, 8), intToBytes(nonce, 8));
|
|
2155
|
-
return txidFromBytes(data);
|
|
2156
|
-
}
|
|
2157
|
-
|
|
2158
|
-
// src/transactions/multisig.ts
|
|
2159
|
-
import {
|
|
2160
|
-
getPublicKey as nobleGetPublicKey2,
|
|
2161
|
-
sign as nobleSign
|
|
2162
|
-
} from "@noble/secp256k1";
|
|
2163
|
-
var OP_CHECKMULTISIG = 174;
|
|
2164
|
-
function makeRedeemScript(publicKeys, signaturesRequired) {
|
|
2165
|
-
const parts = [];
|
|
2166
|
-
parts.push(new Uint8Array([80 + signaturesRequired]));
|
|
2167
|
-
for (const pk of publicKeys) {
|
|
2168
|
-
const pkBytes = hexToBytes(pk);
|
|
2169
|
-
parts.push(new Uint8Array([pkBytes.length]));
|
|
2170
|
-
parts.push(pkBytes);
|
|
2171
|
-
}
|
|
2172
|
-
parts.push(new Uint8Array([80 + publicKeys.length]));
|
|
2173
|
-
parts.push(new Uint8Array([OP_CHECKMULTISIG]));
|
|
2174
|
-
return concatBytes(...parts);
|
|
2175
|
-
}
|
|
2176
|
-
function createMultiSigSpendingCondition(publicKeys, signaturesRequired, nonce, fee, hashMode = AddressHashMode.P2SH) {
|
|
2177
|
-
const redeemScript = makeRedeemScript(publicKeys, signaturesRequired);
|
|
2178
|
-
const signer = bytesToHex(hash160(redeemScript));
|
|
2179
|
-
return {
|
|
2180
|
-
hashMode,
|
|
2181
|
-
signer,
|
|
2182
|
-
nonce,
|
|
2183
|
-
fee,
|
|
2184
|
-
fields: [],
|
|
2185
|
-
signaturesRequired
|
|
2186
|
-
};
|
|
2187
|
-
}
|
|
2188
|
-
|
|
2189
|
-
// src/transactions/build.ts
|
|
2190
|
-
function resolvePcMode(mode) {
|
|
2191
|
-
if (mode === "allow")
|
|
2192
|
-
return PostConditionModeWire.Allow;
|
|
2193
|
-
if (mode === "originator")
|
|
2194
|
-
return PostConditionModeWire.Originator;
|
|
2195
|
-
return PostConditionModeWire.Deny;
|
|
2196
|
-
}
|
|
2197
|
-
function convertPostConditions(pcs) {
|
|
2198
|
-
if (!pcs || pcs.length === 0)
|
|
2199
|
-
return [];
|
|
2200
|
-
return pcs.map((pc) => convertPostCondition(typeof pc === "string" ? fromHex(pc) : pc));
|
|
2201
|
-
}
|
|
2202
|
-
function resolveSpendingCondition(opts, nonce, fee) {
|
|
2203
|
-
if (opts.publicKeys) {
|
|
2204
|
-
return createMultiSigSpendingCondition(opts.publicKeys, opts.signaturesRequired, nonce, fee, opts.hashMode);
|
|
2205
|
-
}
|
|
2206
|
-
return createSingleSigSpendingCondition(opts.publicKey, nonce, fee);
|
|
2207
|
-
}
|
|
2208
|
-
function resolveAuth(spendingCondition, sponsored) {
|
|
2209
|
-
return sponsored ? createSponsoredAuth(spendingCondition) : createStandardAuth(spendingCondition);
|
|
2210
|
-
}
|
|
2211
|
-
function resolveVersionAndChainId(chain) {
|
|
2212
|
-
if (!chain)
|
|
2213
|
-
return { version: 0, chainId: 1 };
|
|
2214
|
-
return { version: chain.transactionVersion, chainId: chain.id };
|
|
2215
|
-
}
|
|
2216
|
-
function buildContractCall(options) {
|
|
2217
|
-
const { version, chainId } = resolveVersionAndChainId(options.chain);
|
|
2218
|
-
const fee = intToBigInt(options.fee);
|
|
2219
|
-
const nonce = intToBigInt(options.nonce);
|
|
2220
|
-
const spendingCondition = resolveSpendingCondition(options, nonce, fee);
|
|
2221
|
-
const tx = {
|
|
2222
|
-
version,
|
|
2223
|
-
chainId,
|
|
2224
|
-
auth: resolveAuth(spendingCondition, options.sponsored),
|
|
2225
|
-
anchorMode: AnchorMode.Any,
|
|
2226
|
-
postConditionMode: resolvePcMode(options.postConditionMode),
|
|
2227
|
-
postConditions: convertPostConditions(options.postConditions),
|
|
2228
|
-
payload: {
|
|
2229
|
-
payloadType: PayloadType.ContractCall,
|
|
2230
|
-
contractAddress: options.contractAddress,
|
|
2231
|
-
contractName: options.contractName,
|
|
2232
|
-
functionName: options.functionName,
|
|
2233
|
-
functionArgs: options.functionArgs
|
|
2234
|
-
}
|
|
2235
|
-
};
|
|
2236
|
-
if (options.publicKeys) {
|
|
2237
|
-
tx._multisig = { publicKeys: options.publicKeys };
|
|
2238
|
-
}
|
|
2239
|
-
return tx;
|
|
2240
|
-
}
|
|
2241
|
-
|
|
2242
|
-
// src/actions/public/getMapEntry.ts
|
|
2243
|
-
async function getMapEntry(client, params) {
|
|
2244
|
-
const [address, name] = parseContractId(params.contract);
|
|
2245
|
-
const serializedKey = with0x(bytesToHex(serializeCVBytes(params.key)));
|
|
2246
|
-
const data = await client.request(`/v2/map_entry/${address}/${name}/${params.mapName}`, {
|
|
2247
|
-
method: "POST",
|
|
2248
|
-
body: serializedKey
|
|
2249
|
-
});
|
|
2250
|
-
if (typeof data?.data !== "string") {
|
|
2251
|
-
throw new MalformedResponseError(`getMapEntry: /v2/map_entry/${address}/${name}/${params.mapName} response is missing "data"`);
|
|
2252
|
-
}
|
|
2253
|
-
return deserializeCVBytes(data.data);
|
|
2254
|
-
}
|
|
2255
|
-
|
|
2256
|
-
// src/actions/public/getNonce.ts
|
|
2257
|
-
async function getNonce(client, params) {
|
|
2258
|
-
const data = await client.request(`/v2/accounts/${encodeURIComponent(params.address)}`, { method: "GET" });
|
|
2259
|
-
const nonce = data?.nonce;
|
|
2260
|
-
if (typeof nonce !== "number" && typeof nonce !== "string") {
|
|
2261
|
-
throw new MalformedResponseError(`getNonce: /v2/accounts/${params.address} response is missing "nonce"`);
|
|
2262
|
-
}
|
|
2263
|
-
return BigInt(nonce);
|
|
2264
|
-
}
|
|
2265
|
-
|
|
2266
|
-
// src/transactions/signer.ts
|
|
2267
|
-
function txid(tx) {
|
|
2268
|
-
return txidFromBytes(serializeTransaction(tx));
|
|
2269
|
-
}
|
|
2270
|
-
function signBegin(tx) {
|
|
2271
|
-
const cleared = {
|
|
2272
|
-
...tx,
|
|
2273
|
-
auth: intoInitialSighashAuth(tx.auth)
|
|
2274
|
-
};
|
|
2275
|
-
return txid(cleared);
|
|
2276
|
-
}
|
|
2277
|
-
async function signTransactionWithAccount(tx, account) {
|
|
2278
|
-
const sigHash = signBegin(tx);
|
|
2279
|
-
const condition = tx.auth.spendingCondition;
|
|
2280
|
-
const sigHashPre = sigHashPreSign(sigHash, AuthType.Standard, condition.fee, condition.nonce);
|
|
2281
|
-
const sigBytes = await account.sign(hexToBytes(sigHashPre));
|
|
2282
|
-
const nextSig = bytesToHex(sigBytes);
|
|
2283
|
-
return {
|
|
2284
|
-
...tx,
|
|
2285
|
-
auth: {
|
|
2286
|
-
...tx.auth,
|
|
2287
|
-
spendingCondition: {
|
|
2288
|
-
...condition,
|
|
2289
|
-
signature: nextSig
|
|
2290
|
-
}
|
|
2291
|
-
}
|
|
2292
|
-
};
|
|
2293
|
-
}
|
|
2294
|
-
function getTransactionId(tx) {
|
|
2295
|
-
return txid(tx);
|
|
2296
|
-
}
|
|
2297
|
-
|
|
2298
|
-
// src/actions/public/waitForTransactionReceipt.ts
|
|
2299
|
-
var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2300
|
-
async function waitForTransactionReceipt(client, params) {
|
|
2301
|
-
const {
|
|
2302
|
-
txid: txid2,
|
|
2303
|
-
confirmations = 1,
|
|
2304
|
-
timeout = 180000,
|
|
2305
|
-
pollingInterval = 3000
|
|
2306
|
-
} = params;
|
|
2307
|
-
const source = params.source ?? extendedApiSource();
|
|
2308
|
-
const droppedGracePeriod = params.droppedGracePeriod ?? (source.canonicalOnly ? timeout : 30000);
|
|
2309
|
-
const startedAt = Date.now();
|
|
2310
|
-
let unknownSince = null;
|
|
2311
|
-
let everPending = false;
|
|
2312
|
-
while (true) {
|
|
2313
|
-
const snapshot = await source.get({ client, txid: txid2 });
|
|
2314
|
-
const receipt = snapshot.receipt;
|
|
2315
|
-
if (receipt === null) {
|
|
2316
|
-
unknownSince ??= Date.now();
|
|
2317
|
-
if (Date.now() - unknownSince >= droppedGracePeriod) {
|
|
2318
|
-
throw new TransactionDroppedError(everPending ? `Transaction ${txid2} left the mempool without being mined` : `Transaction ${txid2} was never observed by the status source`, { txid: txid2 });
|
|
2319
|
-
}
|
|
2320
|
-
} else {
|
|
2321
|
-
unknownSince = null;
|
|
2322
|
-
switch (receipt.status) {
|
|
2323
|
-
case "dropped":
|
|
2324
|
-
throw new TransactionDroppedError(`Transaction ${txid2} was dropped from the mempool`, { txid: txid2 });
|
|
2325
|
-
case "abort_by_response":
|
|
2326
|
-
case "abort_by_post_condition":
|
|
2327
|
-
throw new TransactionAbortedError(`Transaction ${txid2} aborted (${receipt.status})`, { receipt });
|
|
2328
|
-
case "pending":
|
|
2329
|
-
everPending = true;
|
|
2330
|
-
break;
|
|
2331
|
-
case "success": {
|
|
2332
|
-
if (confirmations <= 1)
|
|
2333
|
-
return receipt;
|
|
2334
|
-
if (receipt.blockHeight !== undefined) {
|
|
2335
|
-
const tip = snapshot.tip ?? await getBlockHeight(client);
|
|
2336
|
-
if (tip - receipt.blockHeight + 1 >= confirmations)
|
|
2337
|
-
return receipt;
|
|
2338
|
-
}
|
|
2339
|
-
break;
|
|
2340
|
-
}
|
|
2341
|
-
}
|
|
2342
|
-
}
|
|
2343
|
-
if (Date.now() - startedAt >= timeout) {
|
|
2344
|
-
throw new WaitForTransactionTimeoutError(`Timed out after ${timeout}ms waiting for transaction ${txid2}`, { txid: txid2 });
|
|
2345
|
-
}
|
|
2346
|
-
await sleep2(pollingInterval);
|
|
2347
|
-
}
|
|
2348
|
-
}
|
|
2349
|
-
|
|
2350
|
-
// src/actions/wallet/sendTransaction.ts
|
|
2351
|
-
async function sendTransaction(client, params) {
|
|
2352
|
-
const hex = bytesToHex(serializeTransaction(params.transaction));
|
|
2353
|
-
const body = { tx: hex };
|
|
2354
|
-
if (params.attachment) {
|
|
2355
|
-
body.attachment = typeof params.attachment === "string" ? params.attachment : bytesToHex(params.attachment);
|
|
2356
|
-
}
|
|
2357
|
-
let data;
|
|
2358
|
-
try {
|
|
2359
|
-
data = await client.request("/v2/transactions", {
|
|
2360
|
-
method: "POST",
|
|
2361
|
-
body,
|
|
2362
|
-
retryCount: 0
|
|
2363
|
-
});
|
|
2364
|
-
} catch (error) {
|
|
2365
|
-
if (error instanceof HttpRequestError && error.details) {
|
|
2366
|
-
try {
|
|
2367
|
-
data = JSON.parse(error.details);
|
|
2368
|
-
} catch {
|
|
2369
|
-
throw error;
|
|
2370
|
-
}
|
|
2371
|
-
} else if (error instanceof TimeoutError) {
|
|
2372
|
-
const txid3 = getTransactionId(params.transaction);
|
|
2373
|
-
const receipt = await getTransaction(client, { txid: txid3 }).catch(() => null);
|
|
2374
|
-
if (receipt === null)
|
|
2375
|
-
throw error;
|
|
2376
|
-
data = { txid: txid3 };
|
|
2377
|
-
} else {
|
|
2378
|
-
throw error;
|
|
2379
|
-
}
|
|
2380
|
-
}
|
|
2381
|
-
if (data.error) {
|
|
2382
|
-
throw new BroadcastError(data.reason ?? data.error, {
|
|
2383
|
-
reason: data.reason,
|
|
2384
|
-
reasonData: data.reason_data,
|
|
2385
|
-
txid: data.txid ?? getTransactionId(params.transaction)
|
|
2386
|
-
});
|
|
2387
|
-
}
|
|
2388
|
-
const txid2 = typeof data === "string" ? data.replace(/"/g, "") : data.txid ?? getTransactionId(params.transaction);
|
|
2389
|
-
if (params.wait) {
|
|
2390
|
-
const confirmations = params.wait === true ? 1 : params.wait;
|
|
2391
|
-
const receipt = await waitForTransactionReceipt(client, {
|
|
2392
|
-
txid: txid2,
|
|
2393
|
-
confirmations
|
|
2394
|
-
});
|
|
2395
|
-
return { txid: txid2, receipt };
|
|
2396
|
-
}
|
|
2397
|
-
return { txid: txid2 };
|
|
2398
|
-
}
|
|
2399
|
-
|
|
2400
|
-
// src/actions/wallet/nonceManager.ts
|
|
2401
|
-
async function resolveNonce(client, address) {
|
|
2402
|
-
if (client.nonceManager)
|
|
2403
|
-
return client.nonceManager.consume({ client, address });
|
|
2404
|
-
return getNonce(client, { address });
|
|
2405
|
-
}
|
|
2406
|
-
async function releaseNonce(client, address, nonce) {
|
|
2407
|
-
if (!client.nonceManager)
|
|
2408
|
-
return;
|
|
2409
|
-
try {
|
|
2410
|
-
await client.nonceManager.release({ client, address, nonce });
|
|
2411
|
-
} catch {}
|
|
2412
|
-
}
|
|
2413
|
-
function isNonceConflictError(error) {
|
|
2414
|
-
if (!(error instanceof BroadcastError))
|
|
2415
|
-
return false;
|
|
2416
|
-
if (error.reason === "ConflictingNonceInMempool" || error.reason === "BadNonce") {
|
|
2417
|
-
return true;
|
|
2418
|
-
}
|
|
2419
|
-
if (error.reason !== undefined)
|
|
2420
|
-
return false;
|
|
2421
|
-
return error.message.toLowerCase().includes("nonce");
|
|
2422
|
-
}
|
|
2423
|
-
async function broadcastWithNonceReset(client, params) {
|
|
2424
|
-
try {
|
|
2425
|
-
const result = await sendTransaction(client, {
|
|
2426
|
-
transaction: params.transaction
|
|
2427
|
-
});
|
|
2428
|
-
return result.txid;
|
|
2429
|
-
} catch (error) {
|
|
2430
|
-
if (client.nonceManager && isNonceConflictError(error)) {
|
|
2431
|
-
await client.nonceManager.reset({ client, address: params.address });
|
|
2432
|
-
}
|
|
2433
|
-
throw error;
|
|
2434
|
-
}
|
|
2435
|
-
}
|
|
2436
|
-
|
|
2437
|
-
// src/actions/wallet/callContract.ts
|
|
2438
|
-
async function callContract(client, params) {
|
|
2439
|
-
const account = client.account;
|
|
2440
|
-
if (!account)
|
|
2441
|
-
throw new Error("Account required");
|
|
2442
|
-
const [contractAddress, contractName] = parseContractId(params.contract);
|
|
2443
|
-
if (isProviderAccount(account)) {
|
|
2444
|
-
assertNoFeeTierForProvider(params.fee);
|
|
2445
|
-
const result = await account.provider.request("stx_callContract", {
|
|
2446
|
-
contract: params.contract,
|
|
2447
|
-
functionName: params.functionName,
|
|
2448
|
-
functionArgs: params.functionArgs ?? []
|
|
2449
|
-
});
|
|
2450
|
-
return result.txid;
|
|
2451
|
-
}
|
|
2452
|
-
const managed = params.nonce === undefined && client.nonceManager !== undefined;
|
|
2453
|
-
const nonce = params.nonce ?? await resolveNonce(client, account.address);
|
|
2454
|
-
try {
|
|
2455
|
-
const needsFeeResolution = params.fee === undefined || isFeeTier(params.fee);
|
|
2456
|
-
const unsigned = buildContractCall({
|
|
2457
|
-
contractAddress,
|
|
2458
|
-
contractName,
|
|
2459
|
-
functionName: params.functionName,
|
|
2460
|
-
functionArgs: params.functionArgs ?? [],
|
|
2461
|
-
fee: needsFeeResolution ? 0n : params.fee,
|
|
2462
|
-
nonce,
|
|
2463
|
-
publicKey: account.publicKey,
|
|
2464
|
-
chain: client.chain,
|
|
2465
|
-
postConditionMode: params.postConditionMode,
|
|
2466
|
-
postConditions: params.postConditions
|
|
2467
|
-
});
|
|
2468
|
-
if (needsFeeResolution) {
|
|
2469
|
-
const { fee } = await resolveFee(client, unsigned, params.fee);
|
|
2470
|
-
setUnsignedFee(unsigned, fee);
|
|
2471
|
-
}
|
|
2472
|
-
const signed = await signTransactionWithAccount(unsigned, account);
|
|
2473
|
-
return await broadcastWithNonceReset(client, {
|
|
2474
|
-
transaction: signed,
|
|
2475
|
-
address: account.address
|
|
2476
|
-
});
|
|
2477
|
-
} catch (error) {
|
|
2478
|
-
if (managed)
|
|
2479
|
-
await releaseNonce(client, account.address, nonce);
|
|
2480
|
-
throw error;
|
|
2481
|
-
}
|
|
2482
|
-
}
|
|
2483
|
-
|
|
2484
|
-
// src/actions/getContract.ts
|
|
2485
|
-
function getContract(params) {
|
|
2486
|
-
const { client, address, name: contractName, abi } = params;
|
|
2487
|
-
const contractId = `${address}.${contractName}`;
|
|
2488
|
-
const fnByName = new Map;
|
|
2489
|
-
for (const fn of abi.functions) {
|
|
2490
|
-
fnByName.set(fn.name, fn);
|
|
2491
|
-
}
|
|
2492
|
-
const mapByName = new Map;
|
|
2493
|
-
if (abi.maps) {
|
|
2494
|
-
for (const m of abi.maps) {
|
|
2495
|
-
mapByName.set(m.name, m);
|
|
2496
|
-
}
|
|
2497
|
-
}
|
|
2498
|
-
const camelToKebab = new Map;
|
|
2499
|
-
for (const fn of abi.functions) {
|
|
2500
|
-
camelToKebab.set(toCamelCase(fn.name), fn.name);
|
|
2501
|
-
}
|
|
2502
|
-
if (abi.maps) {
|
|
2503
|
-
for (const m of abi.maps) {
|
|
2504
|
-
camelToKebab.set(toCamelCase(m.name), m.name);
|
|
2505
|
-
}
|
|
2506
|
-
}
|
|
2507
|
-
const read = new Proxy({}, {
|
|
2508
|
-
get(_target, prop) {
|
|
2509
|
-
const fnName = camelToKebab.get(prop) ?? prop;
|
|
2510
|
-
const fn = fnByName.get(fnName);
|
|
2511
|
-
if (!fn || fn.access !== "read-only")
|
|
2512
|
-
return;
|
|
2513
|
-
return async (args = {}) => {
|
|
2514
|
-
const clarityArgs = buildFunctionArgs(fn, args);
|
|
2515
|
-
const result = await readContract(client, {
|
|
2516
|
-
contract: contractId,
|
|
2517
|
-
functionName: fn.name,
|
|
2518
|
-
args: clarityArgs
|
|
2519
|
-
});
|
|
2520
|
-
const jsValue = clarityValueToJSUntyped(fn.outputs, result);
|
|
2521
|
-
if (isResponseOutput(fn.outputs)) {
|
|
2522
|
-
const resp = jsValue;
|
|
2523
|
-
if ("ok" in resp)
|
|
2524
|
-
return resp.ok;
|
|
2525
|
-
throw new ContractResponseError(`${contractId}::${fn.name} returned (err ${formatErrValue(resp.err)})`, resp.err);
|
|
2526
|
-
}
|
|
2527
|
-
return jsValue;
|
|
2528
|
-
};
|
|
2529
|
-
}
|
|
2530
|
-
});
|
|
2531
|
-
const call = new Proxy({}, {
|
|
2532
|
-
get(_target, prop) {
|
|
2533
|
-
const fnName = camelToKebab.get(prop) ?? prop;
|
|
2534
|
-
const fn = fnByName.get(fnName);
|
|
2535
|
-
if (!fn || fn.access !== "public")
|
|
2536
|
-
return;
|
|
2537
|
-
return async (args = {}, options) => {
|
|
2538
|
-
const clarityArgs = buildFunctionArgs(fn, args);
|
|
2539
|
-
return callContract(client, {
|
|
2540
|
-
contract: contractId,
|
|
2541
|
-
functionName: fn.name,
|
|
2542
|
-
functionArgs: clarityArgs,
|
|
2543
|
-
...options
|
|
2544
|
-
});
|
|
2545
|
-
};
|
|
2546
|
-
}
|
|
2547
|
-
});
|
|
2548
|
-
const buildCall = new Proxy({}, {
|
|
2549
|
-
get(_target, prop) {
|
|
2550
|
-
const fnName = camelToKebab.get(prop) ?? prop;
|
|
2551
|
-
const fn = fnByName.get(fnName);
|
|
2552
|
-
if (!fn || fn.access !== "public")
|
|
2553
|
-
return;
|
|
2554
|
-
return async (args = {}, options) => {
|
|
2555
|
-
const publicKey = options?.publicKey ?? client.account?.publicKey;
|
|
2556
|
-
if (!publicKey) {
|
|
2557
|
-
throw new Error("buildCall requires a publicKey (pass options.publicKey or configure a client account)");
|
|
2558
|
-
}
|
|
2559
|
-
const functionArgs = buildFunctionArgs(fn, args);
|
|
2560
|
-
const network = client.chain?.network ?? "mainnet";
|
|
2561
|
-
const nonce = options?.nonce ?? await getNonce(client, {
|
|
2562
|
-
address: publicKeyToAddress(publicKey, network)
|
|
2563
|
-
});
|
|
2564
|
-
const unsigned = buildContractCall({
|
|
2565
|
-
contractAddress: address,
|
|
2566
|
-
contractName,
|
|
2567
|
-
functionName: fn.name,
|
|
2568
|
-
functionArgs,
|
|
2569
|
-
fee: options?.fee ?? 0n,
|
|
2570
|
-
nonce,
|
|
2571
|
-
publicKey,
|
|
2572
|
-
chain: client.chain,
|
|
2573
|
-
postConditionMode: options?.postConditionMode,
|
|
2574
|
-
postConditions: options?.postConditions,
|
|
2575
|
-
sponsored: options?.sponsored
|
|
2576
|
-
});
|
|
2577
|
-
if (options?.fee === undefined) {
|
|
2578
|
-
const { fee } = await resolveFee(client, unsigned, undefined);
|
|
2579
|
-
setUnsignedFee(unsigned, fee);
|
|
2580
|
-
}
|
|
2581
|
-
return unsigned;
|
|
2582
|
-
};
|
|
2583
|
-
}
|
|
2584
|
-
});
|
|
2585
|
-
const maps = new Proxy({}, {
|
|
2586
|
-
get(_target, prop) {
|
|
2587
|
-
const mapName = camelToKebab.get(prop) ?? prop;
|
|
2588
|
-
const map = mapByName.get(mapName);
|
|
2589
|
-
if (!map)
|
|
2590
|
-
return;
|
|
2591
|
-
return async (key) => {
|
|
2592
|
-
const clarityKey = jsToClarityValue(map.key, key);
|
|
2593
|
-
const result = await getMapEntry(client, {
|
|
2594
|
-
contract: contractId,
|
|
2595
|
-
mapName: map.name,
|
|
2596
|
-
key: clarityKey
|
|
2597
|
-
});
|
|
2598
|
-
if (result.type === "none")
|
|
2599
|
-
return null;
|
|
2600
|
-
if (result.type === "some") {
|
|
2601
|
-
return clarityValueToJSUntyped(map.value, result.value);
|
|
2602
|
-
}
|
|
2603
|
-
return clarityValueToJSUntyped(map.value, result);
|
|
2604
|
-
};
|
|
2605
|
-
}
|
|
2606
|
-
});
|
|
2607
|
-
return { read, call, buildCall, maps };
|
|
2608
|
-
}
|
|
2609
|
-
function resolveNetworkContract(client, contracts) {
|
|
2610
|
-
if (!client.chain) {
|
|
2611
|
-
throw new Error("Client must have a chain configured");
|
|
2612
|
-
}
|
|
2613
|
-
return contracts[client.chain.network];
|
|
2614
|
-
}
|
|
2615
|
-
function buildFunctionArgs(fn, args = {}) {
|
|
2616
|
-
return fn.args.map((arg) => {
|
|
2617
|
-
const camelKey = toCamelCase(arg.name);
|
|
2618
|
-
const hasOriginal = arg.name in args;
|
|
2619
|
-
const hasCamel = camelKey in args;
|
|
2620
|
-
const value = hasOriginal ? args[arg.name] : hasCamel ? args[camelKey] : undefined;
|
|
2621
|
-
if (value === undefined)
|
|
2622
|
-
throw new Error(`Missing argument: ${arg.name}`);
|
|
2623
|
-
return jsToClarityValue(arg.type, value);
|
|
2624
|
-
});
|
|
2625
|
-
}
|
|
2626
|
-
function isResponseOutput(type) {
|
|
2627
|
-
return typeof type === "object" && type !== null && "response" in type;
|
|
2628
|
-
}
|
|
2629
|
-
function formatErrValue(value) {
|
|
2630
|
-
if (typeof value === "bigint")
|
|
2631
|
-
return value.toString();
|
|
2632
|
-
if (typeof value === "string")
|
|
2633
|
-
return `"${value}"`;
|
|
2634
|
-
return String(value);
|
|
2635
|
-
}
|
|
2636
|
-
|
|
2637
|
-
class ContractResponseError extends Error {
|
|
2638
|
-
errorValue;
|
|
2639
|
-
name = "ContractResponseError";
|
|
2640
|
-
constructor(message, errorValue) {
|
|
2641
|
-
super(message);
|
|
2642
|
-
this.errorValue = errorValue;
|
|
2643
|
-
}
|
|
2644
|
-
}
|
|
2645
|
-
// src/clarity/structuredData.ts
|
|
2646
|
-
import { sha256 as sha2564 } from "@noble/hashes/sha2.js";
|
|
2647
|
-
var SIP018_PREFIX = new Uint8Array([
|
|
2648
|
-
83,
|
|
2649
|
-
73,
|
|
2650
|
-
80,
|
|
2651
|
-
48,
|
|
2652
|
-
49,
|
|
2653
|
-
56
|
|
2654
|
-
]);
|
|
2655
|
-
// src/clarity/prettyPrint.ts
|
|
2656
|
-
function cvToJSON(val) {
|
|
2657
|
-
switch (val.type) {
|
|
2658
|
-
case "true":
|
|
2659
|
-
return { type: "bool", value: true };
|
|
2660
|
-
case "false":
|
|
2661
|
-
return { type: "bool", value: false };
|
|
2662
|
-
case "int":
|
|
2663
|
-
return { type: "int", value: val.value.toString() };
|
|
2664
|
-
case "uint":
|
|
2665
|
-
return { type: "uint", value: val.value.toString() };
|
|
2666
|
-
case "buffer": {
|
|
2667
|
-
const hex = without0x(val.value);
|
|
2668
|
-
return {
|
|
2669
|
-
type: `(buff ${Math.ceil(hex.length / 2)})`,
|
|
2670
|
-
value: `0x${hex}`
|
|
2671
|
-
};
|
|
2672
|
-
}
|
|
2673
|
-
case "none":
|
|
2674
|
-
return { type: "(optional none)", value: null };
|
|
2675
|
-
case "some":
|
|
2676
|
-
return { type: "(optional)", value: cvToJSON(val.value) };
|
|
2677
|
-
case "ok":
|
|
2678
|
-
return { type: "(response)", value: cvToJSON(val.value), success: true };
|
|
2679
|
-
case "err":
|
|
2680
|
-
return { type: "(response)", value: cvToJSON(val.value), success: false };
|
|
2681
|
-
case "address":
|
|
2682
|
-
case "contract":
|
|
2683
|
-
return { type: "principal", value: val.value };
|
|
2684
|
-
case "list":
|
|
2685
|
-
return { type: "(list)", value: val.value.map(cvToJSON) };
|
|
2686
|
-
case "tuple": {
|
|
2687
|
-
const result = {};
|
|
2688
|
-
for (const key of Object.keys(val.value)) {
|
|
2689
|
-
result[key] = cvToJSON(val.value[key]);
|
|
2690
|
-
}
|
|
2691
|
-
return { type: "(tuple)", value: result };
|
|
2692
|
-
}
|
|
2693
|
-
case "ascii":
|
|
2694
|
-
return {
|
|
2695
|
-
type: `(string-ascii ${asciiToBytes(val.value).length})`,
|
|
2696
|
-
value: val.value
|
|
2697
|
-
};
|
|
2698
|
-
case "utf8":
|
|
2699
|
-
return {
|
|
2700
|
-
type: `(string-utf8 ${utf8ToBytes(val.value).length})`,
|
|
2701
|
-
value: val.value
|
|
2702
|
-
};
|
|
2703
|
-
}
|
|
2704
|
-
}
|
|
2705
|
-
// src/clarity/abi/standards.ts
|
|
2706
|
-
var SIP010_ABI = {
|
|
2707
|
-
functions: [
|
|
2708
|
-
{
|
|
2709
|
-
name: "transfer",
|
|
2710
|
-
access: "public",
|
|
2711
|
-
args: [
|
|
2712
|
-
{ name: "amount", type: "uint128" },
|
|
2713
|
-
{ name: "sender", type: "principal" },
|
|
2714
|
-
{ name: "recipient", type: "principal" },
|
|
2715
|
-
{ name: "memo", type: { optional: { buff: { length: 34 } } } }
|
|
2716
|
-
],
|
|
2717
|
-
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
2718
|
-
},
|
|
2719
|
-
{
|
|
2720
|
-
name: "get-balance",
|
|
2721
|
-
access: "read-only",
|
|
2722
|
-
args: [{ name: "account", type: "principal" }],
|
|
2723
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
2724
|
-
},
|
|
2725
|
-
{
|
|
2726
|
-
name: "get-total-supply",
|
|
2727
|
-
access: "read-only",
|
|
2728
|
-
args: [],
|
|
2729
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
2730
|
-
},
|
|
2731
|
-
{
|
|
2732
|
-
name: "get-name",
|
|
2733
|
-
access: "read-only",
|
|
2734
|
-
args: [],
|
|
2735
|
-
outputs: {
|
|
2736
|
-
response: {
|
|
2737
|
-
ok: { "string-ascii": { length: 32 } },
|
|
2738
|
-
error: "uint128"
|
|
2739
|
-
}
|
|
2740
|
-
}
|
|
2741
|
-
},
|
|
2742
|
-
{
|
|
2743
|
-
name: "get-symbol",
|
|
2744
|
-
access: "read-only",
|
|
2745
|
-
args: [],
|
|
2746
|
-
outputs: {
|
|
2747
|
-
response: {
|
|
2748
|
-
ok: { "string-ascii": { length: 10 } },
|
|
2749
|
-
error: "uint128"
|
|
2750
|
-
}
|
|
2751
|
-
}
|
|
2752
|
-
},
|
|
2753
|
-
{
|
|
2754
|
-
name: "get-decimals",
|
|
2755
|
-
access: "read-only",
|
|
2756
|
-
args: [],
|
|
2757
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
2758
|
-
},
|
|
2759
|
-
{
|
|
2760
|
-
name: "get-token-uri",
|
|
2761
|
-
access: "read-only",
|
|
2762
|
-
args: [],
|
|
2763
|
-
outputs: {
|
|
2764
|
-
response: {
|
|
2765
|
-
ok: { optional: { "string-utf8": { length: 256 } } },
|
|
2766
|
-
error: "uint128"
|
|
2767
|
-
}
|
|
2768
|
-
}
|
|
2769
|
-
}
|
|
2770
|
-
],
|
|
2771
|
-
fungible_tokens: [{ name: "token" }]
|
|
2772
|
-
};
|
|
2773
|
-
var SIP009_ABI = {
|
|
2774
|
-
functions: [
|
|
2775
|
-
{
|
|
2776
|
-
name: "transfer",
|
|
2777
|
-
access: "public",
|
|
2778
|
-
args: [
|
|
2779
|
-
{ name: "id", type: "uint128" },
|
|
2780
|
-
{ name: "sender", type: "principal" },
|
|
2781
|
-
{ name: "recipient", type: "principal" }
|
|
2782
|
-
],
|
|
2783
|
-
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
2784
|
-
},
|
|
2785
|
-
{
|
|
2786
|
-
name: "get-owner",
|
|
2787
|
-
access: "read-only",
|
|
2788
|
-
args: [{ name: "id", type: "uint128" }],
|
|
2789
|
-
outputs: {
|
|
2790
|
-
response: { ok: { optional: "principal" }, error: "uint128" }
|
|
2791
|
-
}
|
|
2792
|
-
},
|
|
2793
|
-
{
|
|
2794
|
-
name: "get-last-token-id",
|
|
2795
|
-
access: "read-only",
|
|
2796
|
-
args: [],
|
|
2797
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
2798
|
-
},
|
|
2799
|
-
{
|
|
2800
|
-
name: "get-token-uri",
|
|
2801
|
-
access: "read-only",
|
|
2802
|
-
args: [{ name: "id", type: "uint128" }],
|
|
2803
|
-
outputs: {
|
|
2804
|
-
response: {
|
|
2805
|
-
ok: { optional: { "string-utf8": { length: 256 } } },
|
|
2806
|
-
error: "uint128"
|
|
2807
|
-
}
|
|
2808
|
-
}
|
|
2809
|
-
}
|
|
2810
|
-
],
|
|
2811
|
-
non_fungible_tokens: [{ name: "nft", type: "uint128" }]
|
|
2812
|
-
};
|
|
2813
|
-
var SIP013_ABI = {
|
|
2814
|
-
functions: [
|
|
2815
|
-
{
|
|
2816
|
-
name: "transfer",
|
|
2817
|
-
access: "public",
|
|
2818
|
-
args: [
|
|
2819
|
-
{ name: "token-id", type: "uint128" },
|
|
2820
|
-
{ name: "amount", type: "uint128" },
|
|
2821
|
-
{ name: "sender", type: "principal" },
|
|
2822
|
-
{ name: "recipient", type: "principal" }
|
|
2823
|
-
],
|
|
2824
|
-
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
2825
|
-
},
|
|
2826
|
-
{
|
|
2827
|
-
name: "transfer-memo",
|
|
2828
|
-
access: "public",
|
|
2829
|
-
args: [
|
|
2830
|
-
{ name: "token-id", type: "uint128" },
|
|
2831
|
-
{ name: "amount", type: "uint128" },
|
|
2832
|
-
{ name: "sender", type: "principal" },
|
|
2833
|
-
{ name: "recipient", type: "principal" },
|
|
2834
|
-
{ name: "memo", type: { buff: { length: 34 } } }
|
|
2835
|
-
],
|
|
2836
|
-
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
2837
|
-
},
|
|
2838
|
-
{
|
|
2839
|
-
name: "transfer-many",
|
|
2840
|
-
access: "public",
|
|
2841
|
-
args: [
|
|
2842
|
-
{
|
|
2843
|
-
name: "transfers",
|
|
2844
|
-
type: {
|
|
2845
|
-
list: {
|
|
2846
|
-
type: {
|
|
2847
|
-
tuple: [
|
|
2848
|
-
{ name: "token-id", type: "uint128" },
|
|
2849
|
-
{ name: "amount", type: "uint128" },
|
|
2850
|
-
{ name: "sender", type: "principal" },
|
|
2851
|
-
{ name: "recipient", type: "principal" }
|
|
2852
|
-
]
|
|
2853
|
-
},
|
|
2854
|
-
length: 200
|
|
2855
|
-
}
|
|
2856
|
-
}
|
|
2857
|
-
}
|
|
2858
|
-
],
|
|
2859
|
-
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
2860
|
-
},
|
|
2861
|
-
{
|
|
2862
|
-
name: "transfer-many-memo",
|
|
2863
|
-
access: "public",
|
|
2864
|
-
args: [
|
|
2865
|
-
{
|
|
2866
|
-
name: "transfers",
|
|
2867
|
-
type: {
|
|
2868
|
-
list: {
|
|
2869
|
-
type: {
|
|
2870
|
-
tuple: [
|
|
2871
|
-
{ name: "token-id", type: "uint128" },
|
|
2872
|
-
{ name: "amount", type: "uint128" },
|
|
2873
|
-
{ name: "sender", type: "principal" },
|
|
2874
|
-
{ name: "recipient", type: "principal" },
|
|
2875
|
-
{ name: "memo", type: { buff: { length: 34 } } }
|
|
2876
|
-
]
|
|
2877
|
-
},
|
|
2878
|
-
length: 200
|
|
2879
|
-
}
|
|
2880
|
-
}
|
|
2881
|
-
}
|
|
2882
|
-
],
|
|
2883
|
-
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
2884
|
-
},
|
|
2885
|
-
{
|
|
2886
|
-
name: "get-balance",
|
|
2887
|
-
access: "read-only",
|
|
2888
|
-
args: [
|
|
2889
|
-
{ name: "token-id", type: "uint128" },
|
|
2890
|
-
{ name: "account", type: "principal" }
|
|
2891
|
-
],
|
|
2892
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
2893
|
-
},
|
|
2894
|
-
{
|
|
2895
|
-
name: "get-overall-balance",
|
|
2896
|
-
access: "read-only",
|
|
2897
|
-
args: [{ name: "account", type: "principal" }],
|
|
2898
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
2899
|
-
},
|
|
2900
|
-
{
|
|
2901
|
-
name: "get-total-supply",
|
|
2902
|
-
access: "read-only",
|
|
2903
|
-
args: [{ name: "token-id", type: "uint128" }],
|
|
2904
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
2905
|
-
},
|
|
2906
|
-
{
|
|
2907
|
-
name: "get-overall-supply",
|
|
2908
|
-
access: "read-only",
|
|
2909
|
-
args: [],
|
|
2910
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
2911
|
-
},
|
|
2912
|
-
{
|
|
2913
|
-
name: "get-decimals",
|
|
2914
|
-
access: "read-only",
|
|
2915
|
-
args: [{ name: "token-id", type: "uint128" }],
|
|
2916
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
2917
|
-
},
|
|
2918
|
-
{
|
|
2919
|
-
name: "get-token-uri",
|
|
2920
|
-
access: "read-only",
|
|
2921
|
-
args: [{ name: "token-id", type: "uint128" }],
|
|
2922
|
-
outputs: {
|
|
2923
|
-
response: {
|
|
2924
|
-
ok: { optional: { "string-utf8": { length: 256 } } },
|
|
2925
|
-
error: "uint128"
|
|
2926
|
-
}
|
|
2927
|
-
}
|
|
2928
|
-
}
|
|
2929
|
-
],
|
|
2930
|
-
fungible_tokens: [],
|
|
2931
|
-
non_fungible_tokens: []
|
|
2932
|
-
};
|
|
2933
|
-
// src/clarity/abi/classify.ts
|
|
2934
|
-
var STANDARDS = [
|
|
2935
|
-
{ id: "sip-010", abi: SIP010_ABI, optional: new Set(["get-token-uri"]) },
|
|
2936
|
-
{ id: "sip-009", abi: SIP009_ABI, optional: new Set(["get-token-uri"]) },
|
|
2937
|
-
{
|
|
2938
|
-
id: "sip-013",
|
|
2939
|
-
abi: SIP013_ABI,
|
|
2940
|
-
optional: new Set([
|
|
2941
|
-
"transfer-memo",
|
|
2942
|
-
"transfer-many",
|
|
2943
|
-
"transfer-many-memo",
|
|
2944
|
-
"get-token-uri",
|
|
2945
|
-
"get-overall-balance",
|
|
2946
|
-
"get-overall-supply"
|
|
2947
|
-
])
|
|
2948
|
-
}
|
|
2949
|
-
];
|
|
2950
|
-
// src/bns/abi.ts
|
|
2951
|
-
var BNS_ABI = {
|
|
2952
|
-
functions: [
|
|
2953
|
-
{
|
|
2954
|
-
name: "get-owner-name",
|
|
2955
|
-
access: "read-only",
|
|
2956
|
-
args: [
|
|
2957
|
-
{ name: "name", type: { buff: { length: 48 } } },
|
|
2958
|
-
{ name: "namespace", type: { buff: { length: 20 } } }
|
|
2959
|
-
],
|
|
2960
|
-
outputs: {
|
|
2961
|
-
response: {
|
|
2962
|
-
ok: { optional: "principal" },
|
|
2963
|
-
error: "uint128"
|
|
2964
|
-
}
|
|
2965
|
-
}
|
|
2966
|
-
},
|
|
2967
|
-
{
|
|
2968
|
-
name: "get-id-from-bns",
|
|
2969
|
-
access: "read-only",
|
|
2970
|
-
args: [
|
|
2971
|
-
{ name: "name", type: { buff: { length: 48 } } },
|
|
2972
|
-
{ name: "namespace", type: { buff: { length: 20 } } }
|
|
2973
|
-
],
|
|
2974
|
-
outputs: { optional: "uint128" }
|
|
2975
|
-
},
|
|
2976
|
-
{
|
|
2977
|
-
name: "get-bns-from-id",
|
|
2978
|
-
access: "read-only",
|
|
2979
|
-
args: [{ name: "id", type: "uint128" }],
|
|
2980
|
-
outputs: {
|
|
2981
|
-
optional: {
|
|
2982
|
-
tuple: [
|
|
2983
|
-
{ name: "name", type: { buff: { length: 48 } } },
|
|
2984
|
-
{ name: "namespace", type: { buff: { length: 20 } } }
|
|
2985
|
-
]
|
|
2986
|
-
}
|
|
2987
|
-
}
|
|
2988
|
-
},
|
|
2989
|
-
{
|
|
2990
|
-
name: "get-owner",
|
|
2991
|
-
access: "read-only",
|
|
2992
|
-
args: [{ name: "id", type: "uint128" }],
|
|
2993
|
-
outputs: {
|
|
2994
|
-
response: {
|
|
2995
|
-
ok: { optional: "principal" },
|
|
2996
|
-
error: "none"
|
|
2997
|
-
}
|
|
2998
|
-
}
|
|
2999
|
-
},
|
|
3000
|
-
{
|
|
3001
|
-
name: "get-primary",
|
|
3002
|
-
access: "read-only",
|
|
3003
|
-
args: [{ name: "owner", type: "principal" }],
|
|
3004
|
-
outputs: {
|
|
3005
|
-
response: {
|
|
3006
|
-
ok: {
|
|
3007
|
-
optional: {
|
|
3008
|
-
tuple: [
|
|
3009
|
-
{ name: "name", type: { buff: { length: 48 } } },
|
|
3010
|
-
{ name: "namespace", type: { buff: { length: 20 } } }
|
|
3011
|
-
]
|
|
3012
|
-
}
|
|
3013
|
-
},
|
|
3014
|
-
error: "none"
|
|
3015
|
-
}
|
|
3016
|
-
}
|
|
3017
|
-
},
|
|
3018
|
-
{
|
|
3019
|
-
name: "can-resolve-name",
|
|
3020
|
-
access: "read-only",
|
|
3021
|
-
args: [
|
|
3022
|
-
{ name: "namespace", type: { buff: { length: 20 } } },
|
|
3023
|
-
{ name: "name", type: { buff: { length: 48 } } }
|
|
3024
|
-
],
|
|
3025
|
-
outputs: {
|
|
3026
|
-
response: {
|
|
3027
|
-
ok: {
|
|
3028
|
-
tuple: [
|
|
3029
|
-
{ name: "renewal", type: "uint128" },
|
|
3030
|
-
{ name: "owner", type: "principal" }
|
|
3031
|
-
]
|
|
3032
|
-
},
|
|
3033
|
-
error: "uint128"
|
|
3034
|
-
}
|
|
3035
|
-
}
|
|
3036
|
-
},
|
|
3037
|
-
{
|
|
3038
|
-
name: "get-renewal-height",
|
|
3039
|
-
access: "read-only",
|
|
3040
|
-
args: [{ name: "id", type: "uint128" }],
|
|
3041
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
3042
|
-
},
|
|
3043
|
-
{
|
|
3044
|
-
name: "get-name-price",
|
|
3045
|
-
access: "read-only",
|
|
3046
|
-
args: [
|
|
3047
|
-
{ name: "namespace", type: { buff: { length: 20 } } },
|
|
3048
|
-
{ name: "name", type: { buff: { length: 48 } } }
|
|
3049
|
-
],
|
|
3050
|
-
outputs: {
|
|
3051
|
-
response: {
|
|
3052
|
-
ok: { response: { ok: "uint128", error: "uint128" } },
|
|
3053
|
-
error: "uint128"
|
|
3054
|
-
}
|
|
3055
|
-
}
|
|
3056
|
-
},
|
|
3057
|
-
{
|
|
3058
|
-
name: "get-bns-info",
|
|
3059
|
-
access: "read-only",
|
|
3060
|
-
args: [
|
|
3061
|
-
{ name: "name", type: { buff: { length: 48 } } },
|
|
3062
|
-
{ name: "namespace", type: { buff: { length: 20 } } }
|
|
3063
|
-
],
|
|
3064
|
-
outputs: {
|
|
3065
|
-
optional: {
|
|
3066
|
-
tuple: [
|
|
3067
|
-
{
|
|
3068
|
-
name: "hashed-salted-fqn-preorder",
|
|
3069
|
-
type: { optional: { buff: { length: 20 } } }
|
|
3070
|
-
},
|
|
3071
|
-
{ name: "imported-at", type: { optional: "uint128" } },
|
|
3072
|
-
{ name: "owner", type: "principal" },
|
|
3073
|
-
{ name: "preordered-by", type: { optional: "principal" } },
|
|
3074
|
-
{ name: "registered-at", type: { optional: "uint128" } },
|
|
3075
|
-
{ name: "renewal-height", type: "uint128" },
|
|
3076
|
-
{ name: "stx-burn", type: "uint128" }
|
|
3077
|
-
]
|
|
3078
|
-
}
|
|
3079
|
-
}
|
|
3080
|
-
},
|
|
3081
|
-
{
|
|
3082
|
-
name: "name-preorder",
|
|
3083
|
-
access: "public",
|
|
3084
|
-
args: [
|
|
3085
|
-
{ name: "hashed-salted-fqn", type: { buff: { length: 20 } } },
|
|
3086
|
-
{ name: "stx-to-burn", type: "uint128" }
|
|
3087
|
-
],
|
|
3088
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
3089
|
-
},
|
|
3090
|
-
{
|
|
3091
|
-
name: "name-register",
|
|
3092
|
-
access: "public",
|
|
3093
|
-
args: [
|
|
3094
|
-
{ name: "namespace", type: { buff: { length: 20 } } },
|
|
3095
|
-
{ name: "name", type: { buff: { length: 48 } } },
|
|
3096
|
-
{ name: "salt", type: { buff: { length: 20 } } }
|
|
3097
|
-
],
|
|
3098
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
3099
|
-
},
|
|
3100
|
-
{
|
|
3101
|
-
name: "name-claim-fast",
|
|
3102
|
-
access: "public",
|
|
3103
|
-
args: [
|
|
3104
|
-
{ name: "name", type: { buff: { length: 48 } } },
|
|
3105
|
-
{ name: "namespace", type: { buff: { length: 20 } } },
|
|
3106
|
-
{ name: "send-to", type: "principal" }
|
|
3107
|
-
],
|
|
3108
|
-
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
3109
|
-
},
|
|
3110
|
-
{
|
|
3111
|
-
name: "name-renewal",
|
|
3112
|
-
access: "public",
|
|
3113
|
-
args: [
|
|
3114
|
-
{ name: "namespace", type: { buff: { length: 20 } } },
|
|
3115
|
-
{ name: "name", type: { buff: { length: 48 } } }
|
|
3116
|
-
],
|
|
3117
|
-
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
3118
|
-
},
|
|
3119
|
-
{
|
|
3120
|
-
name: "transfer",
|
|
3121
|
-
access: "public",
|
|
3122
|
-
args: [
|
|
3123
|
-
{ name: "id", type: "uint128" },
|
|
3124
|
-
{ name: "owner", type: "principal" },
|
|
3125
|
-
{ name: "recipient", type: "principal" }
|
|
3126
|
-
],
|
|
3127
|
-
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
3128
|
-
},
|
|
3129
|
-
{
|
|
3130
|
-
name: "set-primary-name",
|
|
3131
|
-
access: "public",
|
|
3132
|
-
args: [{ name: "primary-name-id", type: "uint128" }],
|
|
3133
|
-
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
3134
|
-
}
|
|
3135
|
-
],
|
|
3136
|
-
non_fungible_tokens: [{ name: "BNS-V2", type: "uint128" }]
|
|
3137
|
-
};
|
|
3138
|
-
|
|
3139
|
-
// src/bns/constants.ts
|
|
3140
|
-
var BNS_CONTRACTS = {
|
|
3141
|
-
mainnet: {
|
|
3142
|
-
address: "SP2QEZ06AGJ3RKJPBV14SY1V5BBFNAW33D96YPGZF",
|
|
3143
|
-
name: "BNS-V2"
|
|
3144
|
-
},
|
|
3145
|
-
testnet: {
|
|
3146
|
-
address: "ST2QEZ06AGJ3RKJPBV14SY1V5BBFNAW33D9SZJQ0M",
|
|
3147
|
-
name: "BNS-V2"
|
|
3148
|
-
}
|
|
3149
|
-
};
|
|
3150
|
-
var DEFAULT_NAMESPACE = "btc";
|
|
3151
|
-
|
|
3152
|
-
// src/bns/utils.ts
|
|
3153
|
-
function parseFQN(fqn) {
|
|
3154
|
-
const parts = fqn.split(".");
|
|
3155
|
-
if (parts.length === 1) {
|
|
3156
|
-
return {
|
|
3157
|
-
name: parts[0],
|
|
3158
|
-
namespace: DEFAULT_NAMESPACE
|
|
3159
|
-
};
|
|
3160
|
-
}
|
|
3161
|
-
if (parts.length === 2) {
|
|
3162
|
-
return {
|
|
3163
|
-
name: parts[0],
|
|
3164
|
-
namespace: parts[1]
|
|
3165
|
-
};
|
|
3166
|
-
}
|
|
3167
|
-
throw new Error(`Invalid fully qualified name: ${fqn}. Expected format: "name.namespace" or "name"`);
|
|
3168
|
-
}
|
|
3169
|
-
function formatFQN(name, namespace) {
|
|
3170
|
-
return `${name}.${namespace}`;
|
|
3171
|
-
}
|
|
3172
|
-
function validateName(name) {
|
|
3173
|
-
if (name.length < 1 || name.length > 48)
|
|
3174
|
-
return false;
|
|
3175
|
-
const regex = /^[a-z0-9]([a-z0-9_-]*[a-z0-9])?$/;
|
|
3176
|
-
return regex.test(name);
|
|
3177
|
-
}
|
|
3178
|
-
function validateNamespace(namespace) {
|
|
3179
|
-
if (namespace.length < 1 || namespace.length > 20)
|
|
3180
|
-
return false;
|
|
3181
|
-
const regex = /^[a-z0-9]+$/;
|
|
3182
|
-
return regex.test(namespace);
|
|
3183
|
-
}
|
|
3184
|
-
function validateFQN(fqn) {
|
|
3185
|
-
try {
|
|
3186
|
-
const { name, namespace } = parseFQN(fqn);
|
|
3187
|
-
return validateName(name) && validateNamespace(namespace);
|
|
3188
|
-
} catch {
|
|
3189
|
-
return false;
|
|
3190
|
-
}
|
|
3191
|
-
}
|
|
3192
|
-
|
|
3193
|
-
// src/bns/actions.ts
|
|
3194
|
-
function getBnsContract(client) {
|
|
3195
|
-
const contract = resolveNetworkContract(client, BNS_CONTRACTS);
|
|
3196
|
-
return getContract({
|
|
3197
|
-
client,
|
|
3198
|
-
address: contract.address,
|
|
3199
|
-
name: contract.name,
|
|
3200
|
-
abi: BNS_ABI
|
|
3201
|
-
});
|
|
3202
|
-
}
|
|
3203
|
-
function stringToBytes(str) {
|
|
3204
|
-
return new TextEncoder().encode(str);
|
|
3205
|
-
}
|
|
3206
|
-
async function resolveName(client, nameOrFQN) {
|
|
3207
|
-
if (!validateFQN(nameOrFQN)) {
|
|
3208
|
-
throw new Error(`Invalid name format: ${nameOrFQN}`);
|
|
3209
|
-
}
|
|
3210
|
-
const { name, namespace } = parseFQN(nameOrFQN);
|
|
3211
|
-
const bns = getBnsContract(client);
|
|
3212
|
-
try {
|
|
3213
|
-
return await bns.read.getOwnerName({
|
|
3214
|
-
name: stringToBytes(name),
|
|
3215
|
-
namespace: stringToBytes(namespace)
|
|
3216
|
-
});
|
|
3217
|
-
} catch (e) {
|
|
3218
|
-
if (e instanceof ContractResponseError)
|
|
3219
|
-
return null;
|
|
3220
|
-
throw e;
|
|
3221
|
-
}
|
|
3222
|
-
}
|
|
3223
|
-
async function getPrimaryName(client, address) {
|
|
3224
|
-
const bns = getBnsContract(client);
|
|
3225
|
-
try {
|
|
3226
|
-
const result = await bns.read.getPrimary({
|
|
3227
|
-
owner: address
|
|
3228
|
-
});
|
|
3229
|
-
if (result === null)
|
|
3230
|
-
return null;
|
|
3231
|
-
const name = new TextDecoder().decode(result.name);
|
|
3232
|
-
const namespace = new TextDecoder().decode(result.namespace);
|
|
3233
|
-
return formatFQN(name, namespace);
|
|
3234
|
-
} catch (e) {
|
|
3235
|
-
if (e instanceof ContractResponseError)
|
|
3236
|
-
return null;
|
|
3237
|
-
throw e;
|
|
3238
|
-
}
|
|
3239
|
-
}
|
|
3240
|
-
|
|
3241
|
-
// src/chains/definitions.ts
|
|
3242
|
-
var mainnet = {
|
|
3243
|
-
id: 1,
|
|
3244
|
-
name: "Stacks Mainnet",
|
|
3245
|
-
network: "mainnet",
|
|
3246
|
-
transactionVersion: 0,
|
|
3247
|
-
peerNetworkId: 385875968,
|
|
3248
|
-
addressVersion: { singleSig: 22, multiSig: 20 },
|
|
3249
|
-
magicBytes: "X2",
|
|
3250
|
-
bootAddress: "SP000000000000000000002Q6VF78",
|
|
3251
|
-
nativeCurrency: { name: "Stacks", symbol: "STX", decimals: 6 },
|
|
3252
|
-
rpcUrls: {
|
|
3253
|
-
default: {
|
|
3254
|
-
http: ["https://api.mainnet.hiro.so"],
|
|
3255
|
-
ws: ["wss://api.mainnet.hiro.so/extended/v1/ws"]
|
|
3256
|
-
}
|
|
3257
|
-
},
|
|
3258
|
-
blockExplorers: {
|
|
3259
|
-
default: { name: "Hiro Explorer", url: "https://explorer.hiro.so" }
|
|
3260
|
-
}
|
|
3261
|
-
};
|
|
3262
|
-
var testnet = {
|
|
3263
|
-
id: 2147483648,
|
|
3264
|
-
name: "Stacks Testnet",
|
|
3265
|
-
network: "testnet",
|
|
3266
|
-
transactionVersion: 128,
|
|
3267
|
-
peerNetworkId: 4278190080,
|
|
3268
|
-
addressVersion: { singleSig: 26, multiSig: 21 },
|
|
3269
|
-
magicBytes: "T2",
|
|
3270
|
-
bootAddress: "ST000000000000000000002AMW42H",
|
|
3271
|
-
nativeCurrency: { name: "Stacks", symbol: "STX", decimals: 6 },
|
|
3272
|
-
rpcUrls: {
|
|
3273
|
-
default: {
|
|
3274
|
-
http: ["https://api.testnet.hiro.so"],
|
|
3275
|
-
ws: ["wss://api.testnet.hiro.so/extended/v1/ws"]
|
|
3276
|
-
}
|
|
3277
|
-
},
|
|
3278
|
-
blockExplorers: {
|
|
3279
|
-
default: {
|
|
3280
|
-
name: "Hiro Explorer",
|
|
3281
|
-
url: "https://explorer.hiro.so/?chain=testnet"
|
|
3282
|
-
}
|
|
3283
|
-
}
|
|
3284
|
-
};
|
|
3285
|
-
var devnet = {
|
|
3286
|
-
id: 2147483648,
|
|
3287
|
-
name: "Stacks Devnet",
|
|
3288
|
-
network: "testnet",
|
|
3289
|
-
transactionVersion: 128,
|
|
3290
|
-
peerNetworkId: 4278190080,
|
|
3291
|
-
addressVersion: { singleSig: 26, multiSig: 21 },
|
|
3292
|
-
magicBytes: "id",
|
|
3293
|
-
bootAddress: "ST000000000000000000002AMW42H",
|
|
3294
|
-
nativeCurrency: { name: "Stacks", symbol: "STX", decimals: 6 },
|
|
3295
|
-
rpcUrls: {
|
|
3296
|
-
default: {
|
|
3297
|
-
http: ["http://localhost:3999"],
|
|
3298
|
-
ws: ["ws://localhost:3999/extended/v1/ws"]
|
|
3299
|
-
}
|
|
3300
|
-
}
|
|
3301
|
-
};
|
|
3302
|
-
var mocknet = {
|
|
3303
|
-
...devnet,
|
|
3304
|
-
name: "Stacks Mocknet",
|
|
3305
|
-
addressVersion: { ...devnet.addressVersion }
|
|
3306
|
-
};
|
|
3307
|
-
|
|
3308
|
-
// src/clients/createClient.ts
|
|
3309
|
-
var BASE_KEYS = new Set([
|
|
3310
|
-
"chain",
|
|
3311
|
-
"account",
|
|
3312
|
-
"transport",
|
|
3313
|
-
"request",
|
|
3314
|
-
"nonceManager",
|
|
3315
|
-
"extend"
|
|
3316
|
-
]);
|
|
3317
|
-
function bindExtend(base) {
|
|
3318
|
-
return (fn) => {
|
|
3319
|
-
const extensions = fn(base);
|
|
3320
|
-
const next = { ...base };
|
|
3321
|
-
for (const [key, value] of Object.entries(extensions)) {
|
|
3322
|
-
if (BASE_KEYS.has(key))
|
|
3323
|
-
continue;
|
|
3324
|
-
next[key] = value;
|
|
3325
|
-
}
|
|
3326
|
-
next.extend = bindExtend(next);
|
|
3327
|
-
return next;
|
|
3328
|
-
};
|
|
3329
|
-
}
|
|
3330
|
-
function createClient(config) {
|
|
3331
|
-
const transport = config.transport({ chain: config.chain });
|
|
3332
|
-
const client = {
|
|
3333
|
-
chain: config.chain,
|
|
3334
|
-
account: config.account,
|
|
3335
|
-
transport,
|
|
3336
|
-
request: transport.request,
|
|
3337
|
-
nonceManager: config.nonceManager,
|
|
3338
|
-
extend: null
|
|
3339
|
-
};
|
|
3340
|
-
client.extend = bindExtend(client);
|
|
3341
|
-
return client;
|
|
3342
|
-
}
|
|
3343
|
-
|
|
3344
|
-
// src/actions/public/getContractAbi.ts
|
|
3345
|
-
async function getContractAbi(client, params) {
|
|
3346
|
-
const [address, name] = parseContractId(params.contract);
|
|
3347
|
-
return client.request(`/v2/contracts/interface/${address}/${name}`, {
|
|
3348
|
-
method: "GET"
|
|
3349
|
-
});
|
|
3350
|
-
}
|
|
3351
|
-
|
|
3352
|
-
// src/actions/public/getContractSource.ts
|
|
3353
|
-
async function getContractSource(client, params) {
|
|
3354
|
-
const [address, name] = parseContractId(params.contract);
|
|
3355
|
-
try {
|
|
3356
|
-
const data = await client.request(`/v2/contracts/source/${address}/${name}`, { method: "GET" });
|
|
3357
|
-
return data?.source ? data : null;
|
|
3358
|
-
} catch (error) {
|
|
3359
|
-
if (error instanceof HttpRequestError && error.status === 404)
|
|
3360
|
-
return null;
|
|
3361
|
-
throw error;
|
|
3362
|
-
}
|
|
3363
|
-
}
|
|
3364
|
-
|
|
3365
|
-
// src/actions/public/getDataVar.ts
|
|
3366
|
-
async function getDataVar(client, params) {
|
|
3367
|
-
const [address, name] = parseContractId(params.contract);
|
|
3368
|
-
const path = `/v2/data_var/${address}/${name}/${params.varName}?proof=0`;
|
|
3369
|
-
const data = await client.request(path, { method: "GET" });
|
|
3370
|
-
if (typeof data?.data !== "string") {
|
|
3371
|
-
throw new MalformedResponseError(`getDataVar: /v2/data_var/${address}/${name}/${params.varName} response is missing "data"`);
|
|
3372
|
-
}
|
|
3373
|
-
return deserializeCVBytes(data.data);
|
|
3374
|
-
}
|
|
3375
|
-
|
|
3376
|
-
// src/actions/public/getRawBlock.ts
|
|
3377
|
-
async function getRawBlock(client, params) {
|
|
3378
|
-
try {
|
|
3379
|
-
const data = await client.request(`/v2/blocks/${params.height}`, {
|
|
3380
|
-
method: "GET"
|
|
3381
|
-
});
|
|
3382
|
-
return data?.hash ? data : null;
|
|
3383
|
-
} catch (error) {
|
|
3384
|
-
if (error instanceof HttpRequestError && error.status === 404)
|
|
3385
|
-
return null;
|
|
3386
|
-
throw error;
|
|
3387
|
-
}
|
|
3388
|
-
}
|
|
3389
|
-
|
|
3390
|
-
// src/actions/public/multicall.ts
|
|
3391
|
-
async function mapWithConcurrency(items, limit, fn) {
|
|
3392
|
-
const results = new Array(items.length);
|
|
3393
|
-
let cursor = 0;
|
|
3394
|
-
const worker = async () => {
|
|
3395
|
-
while (cursor < items.length) {
|
|
3396
|
-
const index = cursor++;
|
|
3397
|
-
try {
|
|
3398
|
-
results[index] = {
|
|
3399
|
-
status: "fulfilled",
|
|
3400
|
-
value: await fn(items[index])
|
|
3401
|
-
};
|
|
3402
|
-
} catch (reason) {
|
|
3403
|
-
results[index] = { status: "rejected", reason };
|
|
3404
|
-
}
|
|
3405
|
-
}
|
|
3406
|
-
};
|
|
3407
|
-
const workers = Math.max(1, Math.min(limit, items.length));
|
|
3408
|
-
await Promise.all(Array.from({ length: workers }, worker));
|
|
3409
|
-
return results;
|
|
3410
|
-
}
|
|
3411
|
-
async function multicall(client, params) {
|
|
3412
|
-
const { calls, allowFailure = true, concurrency = 8 } = params;
|
|
3413
|
-
if (!Number.isInteger(concurrency) || concurrency < 1) {
|
|
3414
|
-
throw new RangeError(`multicall concurrency must be a positive integer, got ${concurrency}`);
|
|
3415
|
-
}
|
|
3416
|
-
const settled = await mapWithConcurrency(calls, concurrency, (call) => readContract(client, call));
|
|
3417
|
-
if (allowFailure) {
|
|
3418
|
-
return settled.map((r) => r.status === "fulfilled" ? { status: "success", result: r.value } : {
|
|
3419
|
-
status: "failure",
|
|
3420
|
-
error: r.reason instanceof Error ? r.reason : new Error(String(r.reason))
|
|
3421
|
-
});
|
|
3422
|
-
}
|
|
3423
|
-
const results = [];
|
|
3424
|
-
for (const r of settled) {
|
|
3425
|
-
if (r.status === "rejected")
|
|
3426
|
-
throw r.reason;
|
|
3427
|
-
results.push(r.value);
|
|
3428
|
-
}
|
|
3429
|
-
return results;
|
|
3430
|
-
}
|
|
3431
|
-
|
|
3432
|
-
// src/errors/simulation.ts
|
|
3433
|
-
class SimulationError extends BaseError {
|
|
3434
|
-
name = "SimulationError";
|
|
3435
|
-
writesDetected;
|
|
3436
|
-
constructor(message, options) {
|
|
3437
|
-
super(message, { details: options.details });
|
|
3438
|
-
this.writesDetected = options.writesDetected;
|
|
3439
|
-
}
|
|
3440
|
-
}
|
|
3441
|
-
|
|
3442
|
-
// src/actions/public/simulateCall.ts
|
|
3443
|
-
async function simulateCall(client, params) {
|
|
3444
|
-
const [address, name] = parseContractId(params.contract);
|
|
3445
|
-
const sender = params.sender ?? address;
|
|
3446
|
-
const serializedArgs = (params.args ?? []).map((arg) => with0x(bytesToHex(serializeCVBytes(arg))));
|
|
3447
|
-
let path = `/v2/contracts/call-read/${address}/${name}/${params.functionName}`;
|
|
3448
|
-
if (params.tip) {
|
|
3449
|
-
path += `?tip=${params.tip}`;
|
|
3450
|
-
}
|
|
3451
|
-
const data = await client.request(path, {
|
|
3452
|
-
method: "POST",
|
|
3453
|
-
body: {
|
|
3454
|
-
sender,
|
|
3455
|
-
arguments: serializedArgs
|
|
3456
|
-
}
|
|
3457
|
-
});
|
|
3458
|
-
if (data.okay) {
|
|
3459
|
-
return { success: true, result: deserializeCVBytes(data.result) };
|
|
3460
|
-
}
|
|
3461
|
-
const cause = data.cause ?? "Simulation failed";
|
|
3462
|
-
const writesDetected = cause.includes("NotReadOnly") || cause.includes("CostBalanceExceeded");
|
|
3463
|
-
return {
|
|
3464
|
-
success: false,
|
|
3465
|
-
error: new SimulationError(writesDetected ? "Function mutates state and cannot be simulated" : "Simulation failed", { writesDetected, details: cause })
|
|
3466
|
-
};
|
|
3467
|
-
}
|
|
3468
|
-
|
|
3469
|
-
// src/actions/public/simulateTransaction.ts
|
|
3470
|
-
function isMultiSig(hashMode) {
|
|
3471
|
-
return hashMode === AddressHashMode.P2SH || hashMode === AddressHashMode.P2WSH || hashMode === AddressHashMode.P2SH_NonSequential || hashMode === AddressHashMode.P2WSH_P2SH_NonSequential;
|
|
3472
|
-
}
|
|
3473
|
-
function extractSender(tx, client) {
|
|
3474
|
-
const { hashMode, signer } = tx.auth.spendingCondition;
|
|
3475
|
-
const chain = client.chain;
|
|
3476
|
-
const version = isMultiSig(hashMode) ? chain?.addressVersion.multiSig ?? 20 : chain?.addressVersion.singleSig ?? 22;
|
|
3477
|
-
return c32address(version, signer);
|
|
3478
|
-
}
|
|
3479
|
-
async function simulateTransaction(client, params) {
|
|
3480
|
-
const { transaction, tip } = params;
|
|
3481
|
-
const { payload } = transaction;
|
|
3482
|
-
if (payload.payloadType === PayloadType.ContractCall) {
|
|
3483
|
-
const sender = params.sender ?? extractSender(transaction, client);
|
|
3484
|
-
const contract = `${payload.contractAddress}.${payload.contractName}`;
|
|
3485
|
-
const [execution, fees2] = await Promise.all([
|
|
3486
|
-
simulateCall(client, {
|
|
3487
|
-
contract,
|
|
3488
|
-
functionName: payload.functionName,
|
|
3489
|
-
args: payload.functionArgs,
|
|
3490
|
-
sender,
|
|
3491
|
-
tip
|
|
3492
|
-
}),
|
|
3493
|
-
estimateFee(client, { transaction })
|
|
3494
|
-
]);
|
|
3495
|
-
return { type: "contract-call", execution, fees: fees2 };
|
|
3496
|
-
}
|
|
3497
|
-
const fees = await estimateFee(client, { transaction });
|
|
3498
|
-
if (payload.payloadType === PayloadType.SmartContract || payload.payloadType === PayloadType.VersionedSmartContract) {
|
|
3499
|
-
return { type: "contract-deploy", fees };
|
|
3500
|
-
}
|
|
3501
|
-
return { type: "token-transfer", fees };
|
|
3502
|
-
}
|
|
3503
|
-
|
|
3504
|
-
// src/errors/websocket.ts
|
|
3505
|
-
class WebSocketError extends BaseError {
|
|
3506
|
-
name = "WebSocketError";
|
|
3507
|
-
}
|
|
3508
|
-
|
|
3509
|
-
// src/subscriptions/actions.ts
|
|
3510
|
-
function getWsTransport(client) {
|
|
3511
|
-
if (client.transport.type !== "webSocket") {
|
|
3512
|
-
throw new WebSocketError("Watch actions require a webSocket transport. Use `webSocket()` when creating your client.");
|
|
3513
|
-
}
|
|
3514
|
-
return client.transport;
|
|
3515
|
-
}
|
|
3516
|
-
async function watchBlocks(client, params) {
|
|
3517
|
-
const transport = getWsTransport(client);
|
|
3518
|
-
return transport.subscribe({ event: "block" }, params.onBlock);
|
|
3519
|
-
}
|
|
3520
|
-
async function watchMempool(client, params) {
|
|
3521
|
-
const transport = getWsTransport(client);
|
|
3522
|
-
return transport.subscribe({ event: "mempool" }, params.onTransaction);
|
|
3523
|
-
}
|
|
3524
|
-
async function watchTransaction(client, params) {
|
|
3525
|
-
const transport = getWsTransport(client);
|
|
3526
|
-
return transport.subscribe({ event: "tx_update", tx_id: params.txId }, params.onUpdate);
|
|
3527
|
-
}
|
|
3528
|
-
async function watchAddress(client, params) {
|
|
3529
|
-
const transport = getWsTransport(client);
|
|
3530
|
-
return transport.subscribe({ event: "address_tx_update", address: params.address }, params.onTransaction);
|
|
3531
|
-
}
|
|
3532
|
-
async function watchAddressBalance(client, params) {
|
|
3533
|
-
const transport = getWsTransport(client);
|
|
3534
|
-
return transport.subscribe({ event: "address_balance_update", address: params.address }, params.onBalance);
|
|
3535
|
-
}
|
|
3536
|
-
async function watchNftEvent(client, params) {
|
|
3537
|
-
const transport = getWsTransport(client);
|
|
3538
|
-
let event;
|
|
3539
|
-
if (params.assetIdentifier && params.value) {
|
|
3540
|
-
event = "nft_event";
|
|
3541
|
-
} else if (params.assetIdentifier) {
|
|
3542
|
-
event = "nft_collection_event";
|
|
3543
|
-
} else {
|
|
3544
|
-
event = "nft_event";
|
|
3545
|
-
}
|
|
3546
|
-
return transport.subscribe({
|
|
3547
|
-
event,
|
|
3548
|
-
asset_identifier: params.assetIdentifier,
|
|
3549
|
-
value: params.value
|
|
3550
|
-
}, params.onEvent);
|
|
3551
|
-
}
|
|
3552
|
-
|
|
3553
|
-
// src/clients/decorators/public.ts
|
|
3554
|
-
function publicActions(client) {
|
|
3555
|
-
return {
|
|
3556
|
-
getNonce: (params) => getNonce(client, params),
|
|
3557
|
-
getBalance: (params) => getBalance(client, params),
|
|
3558
|
-
getAccountInfo: (params) => getAccountInfo(client, params),
|
|
3559
|
-
getBlock: (params) => getBlock(client, params),
|
|
3560
|
-
getRawBlock: (params) => getRawBlock(client, params),
|
|
3561
|
-
getBlockHeight: () => getBlockHeight(client),
|
|
3562
|
-
readContract: (params) => readContract(client, params),
|
|
3563
|
-
getContractAbi: (params) => getContractAbi(client, params),
|
|
3564
|
-
getContractSource: (params) => getContractSource(client, params),
|
|
3565
|
-
getDataVar: (params) => getDataVar(client, params),
|
|
3566
|
-
getMapEntry: (params) => getMapEntry(client, params),
|
|
3567
|
-
estimateFee: (params) => estimateFee(client, params),
|
|
3568
|
-
multicall: (params) => multicall(client, params),
|
|
3569
|
-
simulateCall: (params) => simulateCall(client, params),
|
|
3570
|
-
simulateTransaction: (params) => simulateTransaction(client, params),
|
|
3571
|
-
getTransaction: (params) => getTransaction(client, params),
|
|
3572
|
-
getAccountHistory: (params) => getAccountHistory(client, params),
|
|
3573
|
-
getMempoolStats: () => getMempoolStats(client),
|
|
3574
|
-
getNftHoldings: (params) => getNftHoldings(client, params),
|
|
3575
|
-
waitForTransactionReceipt: (params) => waitForTransactionReceipt(client, params),
|
|
3576
|
-
watchBlocks: (params) => watchBlocks(client, params),
|
|
3577
|
-
watchMempool: (params) => watchMempool(client, params),
|
|
3578
|
-
watchTransaction: (params) => watchTransaction(client, params),
|
|
3579
|
-
watchAddress: (params) => watchAddress(client, params),
|
|
3580
|
-
watchAddressBalance: (params) => watchAddressBalance(client, params),
|
|
3581
|
-
watchNftEvent: (params) => watchNftEvent(client, params)
|
|
3582
|
-
};
|
|
3583
|
-
}
|
|
3584
|
-
|
|
3585
|
-
// src/clients/createPublicClient.ts
|
|
3586
|
-
function createPublicClient(config) {
|
|
3587
|
-
return createClient(config).extend(publicActions);
|
|
3588
|
-
}
|
|
3589
|
-
|
|
3590
|
-
// src/transports/http.ts
|
|
3591
|
-
function http(url, config) {
|
|
3592
|
-
return (params) => {
|
|
3593
|
-
const resolvedUrl = url ?? params?.chain?.rpcUrls.default.http[0] ?? "http://localhost:3999";
|
|
3594
|
-
const mergedConfig = {
|
|
3595
|
-
...config,
|
|
3596
|
-
url: resolvedUrl
|
|
3597
|
-
};
|
|
3598
|
-
return createTransport("http", {
|
|
3599
|
-
...mergedConfig,
|
|
3600
|
-
request: buildRequestFn(resolvedUrl, mergedConfig)
|
|
3601
|
-
});
|
|
3602
|
-
};
|
|
3603
|
-
}
|
|
3604
|
-
|
|
3605
|
-
// src/tools/client.ts
|
|
3606
|
-
var _defaultClient = null;
|
|
3607
|
-
function getDefaultPublicClient() {
|
|
3608
|
-
if (_defaultClient)
|
|
3609
|
-
return _defaultClient;
|
|
3610
|
-
const network = process.env.STACKS_NETWORK ?? process.env.STACKS_CHAIN;
|
|
3611
|
-
const chain = network === "testnet" ? testnet : mainnet;
|
|
3612
|
-
const url = process.env.STACKS_NODE_RPC_URL ?? process.env.SL_API_URL ?? process.env.STACKS_RPC_URL;
|
|
3613
|
-
_defaultClient = createPublicClient({
|
|
3614
|
-
chain,
|
|
3615
|
-
transport: http(url)
|
|
3616
|
-
});
|
|
3617
|
-
return _defaultClient;
|
|
3618
|
-
}
|
|
3619
|
-
|
|
3620
|
-
// src/tools/index.ts
|
|
3621
|
-
var PRINCIPAL = z.string().refine((v) => parsePrincipal(v) !== null, {
|
|
3622
|
-
message: "Expected a Stacks principal: a c32 address (SP…/SM… mainnet, ST… testnet), optionally followed by .contract-name"
|
|
3623
|
-
}).describe("Stacks principal (SP…/SM… mainnet, ST… testnet)");
|
|
3624
|
-
var CONTRACT_ID = z.string().refine((v) => parsePrincipal(v)?.contractName !== undefined, {
|
|
3625
|
-
message: "Expected a contract id in '{address}.{name}' form"
|
|
3626
|
-
}).describe("Fully-qualified contract id: '{address}.{name}'");
|
|
3627
|
-
var FUNCTION_NAME = z.string().refine(isClarityName, { message: "Expected a Clarity function name" });
|
|
3628
|
-
var HASH_32 = /^(0x)?[0-9a-fA-F]{64}$/;
|
|
3629
|
-
var TX_ID = z.string().regex(HASH_32, "Expected a 32-byte hex transaction id").describe("Transaction id, with or without 0x prefix");
|
|
3630
|
-
var BLOCK_HASH = z.string().regex(HASH_32, "Expected a 32-byte hex block hash");
|
|
3631
|
-
async function stxBalance(resolve, principal) {
|
|
3632
|
-
const balance = await getBalance(resolve(), { address: principal });
|
|
3633
|
-
return { microStx: balance.toString() };
|
|
3634
|
-
}
|
|
3635
|
-
async function accountInfo(resolve, principal) {
|
|
3636
|
-
const info = await getAccountInfo(resolve(), { address: principal });
|
|
3637
|
-
return {
|
|
3638
|
-
balance: info.balance.toString(),
|
|
3639
|
-
nonce: info.nonce.toString()
|
|
3640
|
-
};
|
|
3641
|
-
}
|
|
3642
|
-
async function block(resolve, args) {
|
|
3643
|
-
return getBlock(resolve(), args);
|
|
3644
|
-
}
|
|
3645
|
-
async function blockHeight(resolve) {
|
|
3646
|
-
return { height: await getBlockHeight(resolve()) };
|
|
3647
|
-
}
|
|
3648
|
-
async function contractRead(resolve, args) {
|
|
3649
|
-
const result = await readContract(resolve(), args);
|
|
3650
|
-
return { result: cvToJSON(result) };
|
|
3651
|
-
}
|
|
3652
|
-
function assertValidHex(raw) {
|
|
3653
|
-
if (raw.length % 2 !== 0) {
|
|
3654
|
-
throw new Error("serializedTxHex: odd-length hex string");
|
|
3655
|
-
}
|
|
3656
|
-
if (!/^[0-9a-fA-F]+$/.test(raw)) {
|
|
3657
|
-
throw new Error("serializedTxHex: contains non-hex characters");
|
|
3658
|
-
}
|
|
3659
|
-
}
|
|
3660
|
-
async function fee(resolve, serializedTxHex) {
|
|
3661
|
-
const raw = serializedTxHex.startsWith("0x") ? serializedTxHex.slice(2) : serializedTxHex;
|
|
3662
|
-
assertValidHex(raw);
|
|
3663
|
-
const txBytes = hexToBytes(raw);
|
|
3664
|
-
let transaction;
|
|
3665
|
-
try {
|
|
3666
|
-
transaction = deserializeTransaction(txBytes);
|
|
3667
|
-
} catch (e) {
|
|
3668
|
-
throw new Error(`serializedTxHex: deserialization failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
3669
|
-
}
|
|
3670
|
-
const fees = await estimateFee(resolve(), { transaction });
|
|
3671
|
-
if (fees.length === 0) {
|
|
3672
|
-
const min = Number(minimumFee(transaction));
|
|
3673
|
-
return {
|
|
3674
|
-
low: min,
|
|
3675
|
-
medium: min,
|
|
3676
|
-
high: min,
|
|
3677
|
-
source: "min",
|
|
3678
|
-
tiers: 0
|
|
3679
|
-
};
|
|
3680
|
-
}
|
|
3681
|
-
const low = fees[0]?.fee ?? 0;
|
|
3682
|
-
return {
|
|
3683
|
-
low,
|
|
3684
|
-
medium: fees[1]?.fee ?? low,
|
|
3685
|
-
high: fees[2]?.fee ?? fees[1]?.fee ?? low,
|
|
3686
|
-
source: "node",
|
|
3687
|
-
tiers: fees.length
|
|
3688
|
-
};
|
|
3689
|
-
}
|
|
3690
|
-
async function bnsResolveImpl(resolve, name) {
|
|
3691
|
-
return { owner: await resolveName(resolve(), name) };
|
|
3692
|
-
}
|
|
3693
|
-
async function bnsReverseImpl(resolve, principal) {
|
|
3694
|
-
return { name: await getPrimaryName(resolve(), principal) };
|
|
3695
|
-
}
|
|
3696
|
-
async function transactionByTxId(resolve, txId) {
|
|
3697
|
-
const receipt = await getTransaction(resolve(), { txid: txId });
|
|
3698
|
-
if (!receipt)
|
|
3699
|
-
return null;
|
|
3700
|
-
const { result, ...rest } = receipt;
|
|
3701
|
-
return result === undefined ? rest : { ...rest, result: cvToJSON(result) };
|
|
3702
|
-
}
|
|
3703
|
-
async function accountHistory(resolve, principal, limit) {
|
|
3704
|
-
return getAccountHistory(resolve(), { address: principal, limit });
|
|
3705
|
-
}
|
|
3706
|
-
async function mempoolStats(resolve) {
|
|
3707
|
-
return getMempoolStats(resolve());
|
|
3708
|
-
}
|
|
3709
|
-
async function nftHoldings(resolve, principal, limit) {
|
|
3710
|
-
return getNftHoldings(resolve(), { address: principal, limit });
|
|
3711
|
-
}
|
|
3712
|
-
var EXTENDED = "Needs a host that serves the extended API.";
|
|
3713
|
-
function buildTools(resolve) {
|
|
3714
|
-
return {
|
|
3715
|
-
getStxBalance: tool({
|
|
3716
|
-
description: "Get the STX balance (in micro-STX) for a Stacks principal.",
|
|
3717
|
-
inputSchema: z.object({ principal: PRINCIPAL }),
|
|
3718
|
-
execute: ({ principal }) => stxBalance(resolve, principal)
|
|
3719
|
-
}),
|
|
3720
|
-
getAccountInfo: tool({
|
|
3721
|
-
description: "Get the STX balance (micro-STX) and next nonce for a Stacks principal.",
|
|
3722
|
-
inputSchema: z.object({ principal: PRINCIPAL }),
|
|
3723
|
-
execute: ({ principal }) => accountInfo(resolve, principal)
|
|
3724
|
-
}),
|
|
3725
|
-
getBlock: tool({
|
|
3726
|
-
description: "Fetch one Stacks block by height or hash. Omit both for the latest block. Always returns a single block object.",
|
|
3727
|
-
inputSchema: z.object({
|
|
3728
|
-
height: z.number().int().nonnegative().optional(),
|
|
3729
|
-
hash: BLOCK_HASH.optional()
|
|
3730
|
-
}),
|
|
3731
|
-
execute: (args) => block(resolve, args)
|
|
3732
|
-
}),
|
|
3733
|
-
getBlockHeight: tool({
|
|
3734
|
-
description: "Get the current Stacks chain tip height.",
|
|
3735
|
-
inputSchema: z.object({}),
|
|
3736
|
-
execute: () => blockHeight(resolve)
|
|
3737
|
-
}),
|
|
3738
|
-
readContract: tool({
|
|
3739
|
-
description: "Call a read-only Clarity function that takes no arguments. Returns the decoded value as JSON; uint and int arrive as decimal strings.",
|
|
3740
|
-
inputSchema: z.object({
|
|
3741
|
-
contract: CONTRACT_ID,
|
|
3742
|
-
functionName: FUNCTION_NAME,
|
|
3743
|
-
sender: PRINCIPAL.optional()
|
|
3744
|
-
}),
|
|
3745
|
-
execute: (args) => contractRead(resolve, args)
|
|
3746
|
-
}),
|
|
3747
|
-
estimateFee: tool({
|
|
3748
|
-
description: "Estimate fee tiers (low / medium / high, in micro-STX) for a serialized Stacks transaction. `source` is 'node' for a live estimate or 'min' when the node had none and the relay minimum was used. `tiers` is how many estimates the node returned; when it is below 3 the missing tiers repeat the nearest lower one.",
|
|
3749
|
-
inputSchema: z.object({
|
|
3750
|
-
serializedTxHex: z.string().describe("Hex-encoded serialized transaction")
|
|
3751
|
-
}),
|
|
3752
|
-
execute: ({ serializedTxHex }) => fee(resolve, serializedTxHex)
|
|
3753
|
-
}),
|
|
3754
|
-
bnsResolve: tool({
|
|
3755
|
-
description: "Resolve a BNS name (e.g. 'satoshi.btc') to its owning Stacks principal.",
|
|
3756
|
-
inputSchema: z.object({
|
|
3757
|
-
name: z.string().describe("BNS name in 'name.namespace' form")
|
|
3758
|
-
}),
|
|
3759
|
-
execute: ({ name }) => bnsResolveImpl(resolve, name)
|
|
3760
|
-
}),
|
|
3761
|
-
bnsReverse: tool({
|
|
3762
|
-
description: "Reverse-lookup the primary BNS name for a Stacks principal, if set.",
|
|
3763
|
-
inputSchema: z.object({ principal: PRINCIPAL }),
|
|
3764
|
-
execute: ({ principal }) => bnsReverseImpl(resolve, principal)
|
|
3765
|
-
}),
|
|
3766
|
-
getTransaction: tool({
|
|
3767
|
-
description: `Fetch a confirmed Stacks transaction by txId, with its decoded result as JSON. ${EXTENDED}`,
|
|
3768
|
-
inputSchema: z.object({ txId: TX_ID }),
|
|
3769
|
-
execute: ({ txId }) => transactionByTxId(resolve, txId)
|
|
3770
|
-
}),
|
|
3771
|
-
getAccountHistory: tool({
|
|
3772
|
-
description: `List the most recent transactions for a Stacks principal (first page only, up to 50). ${EXTENDED}`,
|
|
3773
|
-
inputSchema: z.object({
|
|
3774
|
-
principal: PRINCIPAL,
|
|
3775
|
-
limit: z.number().int().min(1).max(50).default(20)
|
|
3776
|
-
}),
|
|
3777
|
-
execute: ({ principal, limit }) => accountHistory(resolve, principal, limit)
|
|
3778
|
-
}),
|
|
3779
|
-
getMempoolStats: tool({
|
|
3780
|
-
description: `Current mempool statistics: pending count, fee distribution, age buckets. ${EXTENDED}`,
|
|
3781
|
-
inputSchema: z.object({}),
|
|
3782
|
-
execute: () => mempoolStats(resolve)
|
|
3783
|
-
}),
|
|
3784
|
-
getNftHoldings: tool({
|
|
3785
|
-
description: `List NFTs held by a Stacks principal across all collections (first page only, up to 50). ${EXTENDED}`,
|
|
3786
|
-
inputSchema: z.object({
|
|
3787
|
-
principal: PRINCIPAL,
|
|
3788
|
-
limit: z.number().int().min(1).max(50).default(20)
|
|
3789
|
-
}),
|
|
3790
|
-
execute: ({ principal, limit }) => nftHoldings(resolve, principal, limit)
|
|
3791
|
-
})
|
|
3792
|
-
};
|
|
3793
|
-
}
|
|
3794
|
-
function createStacksTools(client) {
|
|
3795
|
-
return buildTools(() => client);
|
|
3796
|
-
}
|
|
3797
|
-
var defaultTools = buildTools(getDefaultPublicClient);
|
|
3798
|
-
var getStxBalance = defaultTools.getStxBalance;
|
|
3799
|
-
var getAccountInfo2 = defaultTools.getAccountInfo;
|
|
3800
|
-
var getBlock2 = defaultTools.getBlock;
|
|
3801
|
-
var getBlockHeight2 = defaultTools.getBlockHeight;
|
|
3802
|
-
var readContract2 = defaultTools.readContract;
|
|
3803
|
-
var estimateFee2 = defaultTools.estimateFee;
|
|
3804
|
-
var bnsResolve = defaultTools.bnsResolve;
|
|
3805
|
-
var bnsReverse = defaultTools.bnsReverse;
|
|
3806
|
-
var getTransaction2 = defaultTools.getTransaction;
|
|
3807
|
-
var getAccountHistory2 = defaultTools.getAccountHistory;
|
|
3808
|
-
var getMempoolStats2 = defaultTools.getMempoolStats;
|
|
3809
|
-
var getNftHoldings2 = defaultTools.getNftHoldings;
|
|
3810
|
-
export {
|
|
3811
|
-
readContract2 as readContract,
|
|
3812
|
-
getTransaction2 as getTransaction,
|
|
3813
|
-
getStxBalance,
|
|
3814
|
-
getNftHoldings2 as getNftHoldings,
|
|
3815
|
-
getMempoolStats2 as getMempoolStats,
|
|
3816
|
-
getBlockHeight2 as getBlockHeight,
|
|
3817
|
-
getBlock2 as getBlock,
|
|
3818
|
-
getAccountInfo2 as getAccountInfo,
|
|
3819
|
-
getAccountHistory2 as getAccountHistory,
|
|
3820
|
-
estimateFee2 as estimateFee,
|
|
3821
|
-
createStacksTools,
|
|
3822
|
-
bnsReverse,
|
|
3823
|
-
bnsResolve
|
|
3824
|
-
};
|
|
3825
|
-
|
|
3826
|
-
//# debugId=BF92A0AEA897CFBD64756E2164756E21
|
|
3827
|
-
//# sourceMappingURL=index.js.map
|