@secondlayer/stacks 6.0.0 → 6.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/shared/{stacks-qt8ehebn.js → stacks-esm-0rdxcta7.js} +2 -2
- package/dist/shared/{stacks-qt8ehebn.js.map → stacks-esm-0rdxcta7.js.map} +1 -1
- package/dist/shared/{stacks-4hs8r4q2.js → stacks-esm-1jae0a3r.js} +2 -2
- package/dist/shared/{stacks-xjkn3en1.cjs.map → stacks-esm-1jae0a3r.js.map} +1 -1
- package/dist/shared/{stacks-4d7c3x27.js → stacks-esm-2mc7ebrm.js} +3 -3
- package/dist/shared/{stacks-4d7c3x27.js.map → stacks-esm-2mc7ebrm.js.map} +1 -1
- package/dist/shared/{stacks-8brgfvqx.js → stacks-esm-3g33bqsm.js} +4 -4
- package/dist/shared/{stacks-8brgfvqx.js.map → stacks-esm-3g33bqsm.js.map} +1 -1
- package/dist/shared/{stacks-gjz26k6b.js → stacks-esm-3pv5avgr.js} +59 -15
- package/dist/shared/stacks-esm-3pv5avgr.js.map +12 -0
- package/dist/shared/{stacks-qex691bh.js → stacks-esm-743jfh10.js} +6 -6
- package/dist/shared/{stacks-qex691bh.js.map → stacks-esm-743jfh10.js.map} +1 -1
- package/dist/shared/{stacks-wxfd6r4b.js → stacks-esm-7fpqgtyx.js} +3 -3
- package/dist/shared/{stacks-wxfd6r4b.js.map → stacks-esm-7fpqgtyx.js.map} +1 -1
- package/dist/shared/{stacks-71k0vmct.js → stacks-esm-9rnx0zxr.js} +5 -5
- package/dist/shared/{stacks-71k0vmct.js.map → stacks-esm-9rnx0zxr.js.map} +1 -1
- package/dist/shared/{stacks-fd4rx56e.js → stacks-esm-aw2mj3sj.js} +7 -7
- package/dist/shared/{stacks-fd4rx56e.js.map → stacks-esm-aw2mj3sj.js.map} +1 -1
- package/dist/shared/{stacks-qs5fzts5.js → stacks-esm-cvhazvhd.js} +2 -2
- package/dist/shared/{stacks-qs5fzts5.js.map → stacks-esm-cvhazvhd.js.map} +1 -1
- package/dist/shared/{stacks-69nq48jp.js → stacks-esm-fcfdn2zx.js} +5 -5
- package/dist/shared/{stacks-69nq48jp.js.map → stacks-esm-fcfdn2zx.js.map} +1 -1
- package/dist/shared/{stacks-x0qqwrev.js → stacks-esm-hr7fpxtj.js} +4 -4
- package/dist/shared/{stacks-x0qqwrev.js.map → stacks-esm-hr7fpxtj.js.map} +1 -1
- package/dist/shared/{stacks-mbt36bzt.js → stacks-esm-kds4n82p.js} +11 -11
- package/dist/shared/{stacks-mbt36bzt.js.map → stacks-esm-kds4n82p.js.map} +1 -1
- package/dist/shared/{stacks-kg1npstf.js → stacks-esm-n53kvwmt.js} +2 -2
- package/dist/shared/{stacks-kg1npstf.js.map → stacks-esm-n53kvwmt.js.map} +1 -1
- package/dist/shared/{stacks-v2rfr46a.js → stacks-esm-pxhfqfff.js} +4 -4
- package/dist/shared/{stacks-v2rfr46a.js.map → stacks-esm-pxhfqfff.js.map} +1 -1
- package/dist/shared/{stacks-yajyej2y.js → stacks-esm-q19a17fd.js} +3 -3
- package/dist/shared/{stacks-yajyej2y.js.map → stacks-esm-q19a17fd.js.map} +1 -1
- package/dist/shared/{stacks-v03zef3g.js → stacks-esm-qk0p9fr6.js} +9 -9
- package/dist/shared/{stacks-v03zef3g.js.map → stacks-esm-qk0p9fr6.js.map} +1 -1
- package/dist/shared/{stacks-qcae5852.js → stacks-esm-qkj67g80.js} +2 -2
- package/dist/shared/{stacks-qcae5852.js.map → stacks-esm-qkj67g80.js.map} +1 -1
- package/dist/shared/{stacks-mftyrc60.js → stacks-esm-r6dejrgr.js} +4 -4
- package/dist/shared/{stacks-mftyrc60.js.map → stacks-esm-r6dejrgr.js.map} +1 -1
- package/dist/shared/{stacks-9c1yam8b.js → stacks-esm-r9q4wnyw.js} +5 -5
- package/dist/shared/{stacks-9c1yam8b.js.map → stacks-esm-r9q4wnyw.js.map} +1 -1
- package/dist/shared/{stacks-51ybf135.js → stacks-esm-skmcf5n2.js} +5 -5
- package/dist/shared/{stacks-51ybf135.js.map → stacks-esm-skmcf5n2.js.map} +1 -1
- package/dist/shared/{stacks-yvb7rvwk.js → stacks-esm-v45990hx.js} +2 -2
- package/dist/shared/{stacks-8vzxax5e.cjs.map → stacks-esm-v45990hx.js.map} +1 -1
- package/dist/shared/{stacks-z90xdr1x.js → stacks-esm-wv67m4g6.js} +3 -3
- package/dist/shared/{stacks-z90xdr1x.js.map → stacks-esm-wv67m4g6.js.map} +1 -1
- package/dist/shared/{stacks-1m3m1agc.js → stacks-esm-x1r01353.js} +5 -5
- package/dist/shared/{stacks-1m3m1agc.js.map → stacks-esm-x1r01353.js.map} +1 -1
- package/dist/src/accounts/index.cjs +558 -4
- package/dist/src/accounts/index.cjs.map +10 -4
- package/dist/src/accounts/index.js +3 -3
- package/dist/src/actions/index.cjs +3815 -1
- package/dist/src/actions/index.cjs.map +65 -3
- package/dist/src/actions/index.js +14 -14
- package/dist/src/bitcoin/index.cjs +2477 -1
- package/dist/src/bitcoin/index.cjs.map +31 -3
- package/dist/src/bitcoin/index.js +11 -11
- package/dist/src/bns/index.cjs +4439 -17
- package/dist/src/bns/index.cjs.map +50 -3
- package/dist/src/bns/index.js +14 -14
- package/dist/src/chains/index.cjs +135 -1
- package/dist/src/chains/index.cjs.map +5 -3
- package/dist/src/chains/index.js +1 -1
- package/dist/src/clarity/index.cjs +2019 -1
- package/dist/src/clarity/index.cjs.map +24 -3
- package/dist/src/clarity/index.js +8 -8
- package/dist/src/filters/index.cjs +725 -1
- package/dist/src/filters/index.cjs.map +11 -3
- package/dist/src/filters/index.d.cts +76 -13
- package/dist/src/filters/index.d.ts +76 -13
- package/dist/src/filters/index.js +8 -4
- package/dist/src/filters/index.js.map +1 -1
- package/dist/src/index.cjs +3935 -62
- package/dist/src/index.cjs.map +69 -4
- package/dist/src/index.d.cts +62 -11
- package/dist/src/index.d.ts +62 -11
- package/dist/src/index.js +16 -16
- package/dist/src/postconditions/index.cjs +1726 -1
- package/dist/src/postconditions/index.cjs.map +20 -3
- package/dist/src/postconditions/index.js +6 -6
- package/dist/src/pox/index.cjs +3855 -1
- package/dist/src/pox/index.cjs.map +48 -3
- package/dist/src/pox/index.js +13 -13
- package/dist/src/pox5/index.cjs +4054 -29
- package/dist/src/pox5/index.cjs.map +54 -3
- package/dist/src/pox5/index.js +15 -15
- package/dist/src/sbtc/index.cjs +3705 -4
- package/dist/src/sbtc/index.cjs.map +47 -3
- package/dist/src/sbtc/index.js +12 -12
- package/dist/src/stackingdao/index.cjs +3751 -8
- package/dist/src/stackingdao/index.cjs.map +45 -3
- package/dist/src/stackingdao/index.js +12 -12
- package/dist/src/subscriptions/index.cjs +153 -1
- package/dist/src/subscriptions/index.cjs.map +6 -3
- package/dist/src/subscriptions/index.js +2 -2
- package/dist/src/transactions/index.cjs +2139 -1
- package/dist/src/transactions/index.cjs.map +23 -3
- package/dist/src/transactions/index.js +6 -6
- package/dist/src/utils/index.cjs +435 -3
- package/dist/src/utils/index.cjs.map +9 -3
- package/dist/src/utils/index.js +3 -3
- package/package.json +1 -1
- package/dist/shared/stacks-02actsrx.cjs +0 -17
- package/dist/shared/stacks-02actsrx.cjs.map +0 -10
- package/dist/shared/stacks-03vfm21t.cjs +0 -222
- package/dist/shared/stacks-03vfm21t.cjs.map +0 -12
- package/dist/shared/stacks-24h5k94q.cjs +0 -74
- package/dist/shared/stacks-24h5k94q.cjs.map +0 -11
- package/dist/shared/stacks-37kz5t9f.cjs +0 -764
- package/dist/shared/stacks-37kz5t9f.cjs.map +0 -23
- package/dist/shared/stacks-3mt2q2na.cjs +0 -65
- package/dist/shared/stacks-3mt2q2na.cjs.map +0 -9
- package/dist/shared/stacks-4hs8r4q2.js.map +0 -10
- package/dist/shared/stacks-8vzxax5e.cjs +0 -45
- package/dist/shared/stacks-agk106zs.cjs +0 -267
- package/dist/shared/stacks-agk106zs.cjs.map +0 -12
- package/dist/shared/stacks-bdgh9n83.cjs +0 -212
- package/dist/shared/stacks-bdgh9n83.cjs.map +0 -11
- package/dist/shared/stacks-dpxnxhqb.cjs +0 -51
- package/dist/shared/stacks-dpxnxhqb.cjs.map +0 -11
- package/dist/shared/stacks-ee53k9j2.cjs +0 -651
- package/dist/shared/stacks-ee53k9j2.cjs.map +0 -13
- package/dist/shared/stacks-enpj9krt.cjs +0 -38
- package/dist/shared/stacks-enpj9krt.cjs.map +0 -10
- package/dist/shared/stacks-f35mnrmg.cjs +0 -164
- package/dist/shared/stacks-f35mnrmg.cjs.map +0 -10
- package/dist/shared/stacks-fhzwsn5d.cjs +0 -261
- package/dist/shared/stacks-fhzwsn5d.cjs.map +0 -12
- package/dist/shared/stacks-gjz26k6b.js.map +0 -12
- package/dist/shared/stacks-gza2n1zs.cjs +0 -73
- package/dist/shared/stacks-gza2n1zs.cjs.map +0 -11
- package/dist/shared/stacks-kem68d80.cjs +0 -156
- package/dist/shared/stacks-kem68d80.cjs.map +0 -10
- package/dist/shared/stacks-n98w7g57.cjs +0 -234
- package/dist/shared/stacks-n98w7g57.cjs.map +0 -10
- package/dist/shared/stacks-p337hp6m.cjs +0 -336
- package/dist/shared/stacks-p337hp6m.cjs.map +0 -25
- package/dist/shared/stacks-q34k4vnc.cjs +0 -286
- package/dist/shared/stacks-q34k4vnc.cjs.map +0 -12
- package/dist/shared/stacks-rryme9bv.cjs +0 -569
- package/dist/shared/stacks-rryme9bv.cjs.map +0 -13
- package/dist/shared/stacks-s5vej5z6.cjs +0 -410
- package/dist/shared/stacks-s5vej5z6.cjs.map +0 -15
- package/dist/shared/stacks-sdqkapct.cjs +0 -67
- package/dist/shared/stacks-sdqkapct.cjs.map +0 -12
- package/dist/shared/stacks-vea7nde7.cjs +0 -731
- package/dist/shared/stacks-vea7nde7.cjs.map +0 -13
- package/dist/shared/stacks-wk8yp13j.cjs +0 -33
- package/dist/shared/stacks-wk8yp13j.cjs.map +0 -11
- package/dist/shared/stacks-xjkn3en1.cjs +0 -42
- package/dist/shared/stacks-xnrywjf1.cjs +0 -131
- package/dist/shared/stacks-xnrywjf1.cjs.map +0 -11
- package/dist/shared/stacks-yvb7rvwk.js.map +0 -10
package/dist/src/bns/index.cjs
CHANGED
|
@@ -1,18 +1,4440 @@
|
|
|
1
|
-
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
1
|
+
var import_node_module = require("node:module");
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
function __accessProp(key) {
|
|
9
|
+
return this[key];
|
|
10
|
+
}
|
|
11
|
+
var __toESMCache_node;
|
|
12
|
+
var __toESMCache_esm;
|
|
13
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
14
|
+
var canCache = mod != null && typeof mod === "object";
|
|
15
|
+
if (canCache) {
|
|
16
|
+
var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
|
|
17
|
+
var cached = cache.get(mod);
|
|
18
|
+
if (cached)
|
|
19
|
+
return cached;
|
|
20
|
+
}
|
|
21
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
22
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
23
|
+
for (let key of __getOwnPropNames(mod))
|
|
24
|
+
if (!__hasOwnProp.call(to, key))
|
|
25
|
+
__defProp(to, key, {
|
|
26
|
+
get: __accessProp.bind(mod, key),
|
|
27
|
+
enumerable: true
|
|
28
|
+
});
|
|
29
|
+
if (canCache)
|
|
30
|
+
cache.set(mod, to);
|
|
31
|
+
return to;
|
|
32
|
+
};
|
|
33
|
+
var __toCommonJS = (from) => {
|
|
34
|
+
var entry = (__moduleCache ??= new WeakMap).get(from), desc;
|
|
35
|
+
if (entry)
|
|
36
|
+
return entry;
|
|
37
|
+
entry = __defProp({}, "__esModule", { value: true });
|
|
38
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
39
|
+
for (var key of __getOwnPropNames(from))
|
|
40
|
+
if (!__hasOwnProp.call(entry, key))
|
|
41
|
+
__defProp(entry, key, {
|
|
42
|
+
get: __accessProp.bind(from, key),
|
|
43
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
__moduleCache.set(from, entry);
|
|
47
|
+
return entry;
|
|
48
|
+
};
|
|
49
|
+
var __moduleCache;
|
|
50
|
+
var __returnValue = (v) => v;
|
|
51
|
+
function __exportSetter(name, newValue) {
|
|
52
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
53
|
+
}
|
|
54
|
+
var __export = (target, all) => {
|
|
55
|
+
for (var name in all)
|
|
56
|
+
__defProp(target, name, {
|
|
57
|
+
get: all[name],
|
|
58
|
+
enumerable: true,
|
|
59
|
+
configurable: true,
|
|
60
|
+
set: __exportSetter.bind(all, name)
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
// src/clarity/index.ts
|
|
65
|
+
var exports_clarity = {};
|
|
66
|
+
__export(exports_clarity, {
|
|
67
|
+
validateArgsArray: () => validateArgsArray,
|
|
68
|
+
validateArgs: () => validateArgs,
|
|
69
|
+
uintCV: () => uintCV,
|
|
70
|
+
tupleCV: () => tupleCV,
|
|
71
|
+
trueCV: () => trueCV,
|
|
72
|
+
toCamelCase: () => toCamelCase,
|
|
73
|
+
structuredDataHash: () => structuredDataHash,
|
|
74
|
+
stringUtf8CV: () => stringUtf8CV,
|
|
75
|
+
stringAsciiCV: () => stringAsciiCV,
|
|
76
|
+
standardPrincipalCV: () => standardPrincipalCV,
|
|
77
|
+
someCV: () => someCV,
|
|
78
|
+
sip013Abi: () => sip013Abi,
|
|
79
|
+
sip010Abi: () => sip010Abi,
|
|
80
|
+
sip009Abi: () => sip009Abi,
|
|
81
|
+
signStructuredData: () => signStructuredData,
|
|
82
|
+
serializeCVBytes: () => serializeCVBytes,
|
|
83
|
+
serializeCV: () => serializeCV,
|
|
84
|
+
responseOkCV: () => responseOkCV,
|
|
85
|
+
responseErrorCV: () => responseErrorCV,
|
|
86
|
+
prettyPrint: () => prettyPrint,
|
|
87
|
+
prepareArgs: () => prepareArgs,
|
|
88
|
+
parseDeclaredStandards: () => parseDeclaredStandards,
|
|
89
|
+
normalizeType: () => normalizeType,
|
|
90
|
+
normalizeAccess: () => normalizeAccess,
|
|
91
|
+
normalizeAbi: () => normalizeAbi,
|
|
92
|
+
noneCV: () => noneCV,
|
|
93
|
+
listCV: () => listCV,
|
|
94
|
+
jsToClarityValue: () => jsToClarityValue,
|
|
95
|
+
jsToClarity: () => jsToClarity,
|
|
96
|
+
isUint8Array: () => isUint8Array,
|
|
97
|
+
isUint128: () => isUint128,
|
|
98
|
+
isTraitReference: () => isTraitReference,
|
|
99
|
+
isString: () => isString,
|
|
100
|
+
isStandardPrincipal: () => isStandardPrincipal,
|
|
101
|
+
isResponse: () => isResponse,
|
|
102
|
+
isPrincipal: () => isPrincipal,
|
|
103
|
+
isOptional: () => isOptional,
|
|
104
|
+
isOkResponse: () => isOkResponse,
|
|
105
|
+
isInt128: () => isInt128,
|
|
106
|
+
isErrResponse: () => isErrResponse,
|
|
107
|
+
isContractPrincipal: () => isContractPrincipal,
|
|
108
|
+
isClarityValue: () => isClarityValue,
|
|
109
|
+
isBool: () => isBool,
|
|
110
|
+
isArray: () => isArray,
|
|
111
|
+
isAbiTuple: () => isAbiTuple,
|
|
112
|
+
isAbiTraitReference: () => isAbiTraitReference,
|
|
113
|
+
isAbiStringUtf8: () => isAbiStringUtf8,
|
|
114
|
+
isAbiStringAscii: () => isAbiStringAscii,
|
|
115
|
+
isAbiResponse: () => isAbiResponse,
|
|
116
|
+
isAbiOptional: () => isAbiOptional,
|
|
117
|
+
isAbiList: () => isAbiList,
|
|
118
|
+
isAbiBuffer: () => isAbiBuffer,
|
|
119
|
+
intCV: () => intCV,
|
|
120
|
+
hashStructuredData: () => hashStructuredData,
|
|
121
|
+
falseCV: () => falseCV,
|
|
122
|
+
encodeStructuredData: () => encodeStructuredData,
|
|
123
|
+
deserializeCVBytes: () => deserializeCVBytes,
|
|
124
|
+
deserializeCV: () => deserializeCV,
|
|
125
|
+
cvToValue: () => cvToValue,
|
|
126
|
+
cvToString: () => cvToString,
|
|
127
|
+
cvToPrincipal: () => cvToPrincipal,
|
|
128
|
+
cvToJSON: () => cvToJSON,
|
|
129
|
+
cvToBuffer: () => cvToBuffer,
|
|
130
|
+
cvToBoolean: () => cvToBoolean,
|
|
131
|
+
cvToBigInt: () => cvToBigInt,
|
|
132
|
+
contractPrincipalCV: () => contractPrincipalCV,
|
|
133
|
+
classifyContract: () => classifyContract,
|
|
134
|
+
clarityValueToJSUntyped: () => clarityValueToJSUntyped,
|
|
135
|
+
clarityValueToJS: () => clarityValueToJS,
|
|
136
|
+
clarityTypeFromByte: () => clarityTypeFromByte,
|
|
137
|
+
bufferCV: () => bufferCV,
|
|
138
|
+
boolCV: () => boolCV,
|
|
139
|
+
TRAIT_STANDARDS: () => TRAIT_STANDARDS,
|
|
140
|
+
SIP018_PREFIX: () => SIP018_PREFIX,
|
|
141
|
+
SIP013_ABI: () => SIP013_ABI,
|
|
142
|
+
SIP010_ABI: () => SIP010_ABI,
|
|
143
|
+
SIP009_ABI: () => SIP009_ABI,
|
|
144
|
+
ClarityWireType: () => ClarityWireType,
|
|
145
|
+
ClarityConversionError: () => ClarityConversionError,
|
|
146
|
+
Cl: () => Cl,
|
|
147
|
+
CONTRACT_NAME_REGEX: () => CONTRACT_NAME_REGEX
|
|
14
148
|
});
|
|
15
|
-
module.exports = __toCommonJS(
|
|
149
|
+
module.exports = __toCommonJS(exports_clarity);
|
|
150
|
+
|
|
151
|
+
// src/clarity/types.ts
|
|
152
|
+
var ClarityWireType = {
|
|
153
|
+
int: 0,
|
|
154
|
+
uint: 1,
|
|
155
|
+
buffer: 2,
|
|
156
|
+
true: 3,
|
|
157
|
+
false: 4,
|
|
158
|
+
address: 5,
|
|
159
|
+
contract: 6,
|
|
160
|
+
ok: 7,
|
|
161
|
+
err: 8,
|
|
162
|
+
none: 9,
|
|
163
|
+
some: 10,
|
|
164
|
+
list: 11,
|
|
165
|
+
tuple: 12,
|
|
166
|
+
ascii: 13,
|
|
167
|
+
utf8: 14
|
|
168
|
+
};
|
|
169
|
+
var wireTypeToClarity = Object.fromEntries(Object.entries(ClarityWireType).map(([k, v]) => [v, k]));
|
|
170
|
+
function clarityTypeFromByte(byte) {
|
|
171
|
+
const type = wireTypeToClarity[byte];
|
|
172
|
+
if (!type)
|
|
173
|
+
throw new Error(`Unknown clarity wire type: ${byte}`);
|
|
174
|
+
return type;
|
|
175
|
+
}
|
|
176
|
+
// src/utils/c32.ts
|
|
177
|
+
var import_sha2 = require("@noble/hashes/sha2.js");
|
|
178
|
+
|
|
179
|
+
// src/utils/encoding.ts
|
|
180
|
+
var hexes = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
181
|
+
function bytesToHex(bytes) {
|
|
182
|
+
let hex = "";
|
|
183
|
+
for (const b of bytes) {
|
|
184
|
+
hex += hexes[b];
|
|
185
|
+
}
|
|
186
|
+
return hex;
|
|
187
|
+
}
|
|
188
|
+
function hexToBytes(hex) {
|
|
189
|
+
let h = without0x(hex);
|
|
190
|
+
if (h.length % 2)
|
|
191
|
+
h = `0${h}`;
|
|
192
|
+
const array = new Uint8Array(h.length / 2);
|
|
193
|
+
for (let i = 0;i < array.length; i++) {
|
|
194
|
+
const j = i * 2;
|
|
195
|
+
const byte = Number.parseInt(h.slice(j, j + 2), 16);
|
|
196
|
+
if (Number.isNaN(byte) || byte < 0)
|
|
197
|
+
throw new Error("Invalid byte sequence");
|
|
198
|
+
array[i] = byte;
|
|
199
|
+
}
|
|
200
|
+
return array;
|
|
201
|
+
}
|
|
202
|
+
function with0x(value) {
|
|
203
|
+
return /^0x/i.test(value) ? value : `0x${value}`;
|
|
204
|
+
}
|
|
205
|
+
function without0x(value) {
|
|
206
|
+
return /^0x/i.test(value) ? value.slice(2) : value;
|
|
207
|
+
}
|
|
208
|
+
function utf8ToBytes(str) {
|
|
209
|
+
return new TextEncoder().encode(str);
|
|
210
|
+
}
|
|
211
|
+
function bytesToUtf8(bytes) {
|
|
212
|
+
return new TextDecoder().decode(bytes);
|
|
213
|
+
}
|
|
214
|
+
function asciiToBytes(str) {
|
|
215
|
+
const bytes = new Uint8Array(str.length);
|
|
216
|
+
for (let i = 0;i < str.length; i++) {
|
|
217
|
+
bytes[i] = str.charCodeAt(i) & 255;
|
|
218
|
+
}
|
|
219
|
+
return bytes;
|
|
220
|
+
}
|
|
221
|
+
function bytesToAscii(bytes) {
|
|
222
|
+
return String.fromCharCode(...bytes);
|
|
223
|
+
}
|
|
224
|
+
function concatBytes(...arrays) {
|
|
225
|
+
if (arrays.length === 1)
|
|
226
|
+
return arrays[0];
|
|
227
|
+
const length = arrays.reduce((a, arr) => a + arr.length, 0);
|
|
228
|
+
const result = new Uint8Array(length);
|
|
229
|
+
let pad = 0;
|
|
230
|
+
for (const arr of arrays) {
|
|
231
|
+
result.set(arr, pad);
|
|
232
|
+
pad += arr.length;
|
|
233
|
+
}
|
|
234
|
+
return result;
|
|
235
|
+
}
|
|
236
|
+
function intToBigInt(value) {
|
|
237
|
+
if (typeof value === "bigint")
|
|
238
|
+
return value;
|
|
239
|
+
if (typeof value === "string")
|
|
240
|
+
return BigInt(value);
|
|
241
|
+
if (typeof value === "number") {
|
|
242
|
+
if (!Number.isInteger(value))
|
|
243
|
+
throw new RangeError("Values of type 'number' must be an integer.");
|
|
244
|
+
if (value > Number.MAX_SAFE_INTEGER)
|
|
245
|
+
throw new RangeError(`Values of type 'number' must be <= ${Number.MAX_SAFE_INTEGER}. Use BigInt instead.`);
|
|
246
|
+
return BigInt(value);
|
|
247
|
+
}
|
|
248
|
+
if (value instanceof Uint8Array)
|
|
249
|
+
return BigInt(`0x${bytesToHex(value)}`);
|
|
250
|
+
throw new TypeError("Must be a number, bigint, string, or Uint8Array.");
|
|
251
|
+
}
|
|
252
|
+
function intToBytes(value, byteLength) {
|
|
253
|
+
return bigIntToBytes(intToBigInt(value), byteLength);
|
|
254
|
+
}
|
|
255
|
+
function bigIntToBytes(value, length = 16) {
|
|
256
|
+
const hex = value.toString(16).padStart(length * 2, "0");
|
|
257
|
+
return hexToBytes(hex);
|
|
258
|
+
}
|
|
259
|
+
function intToHex(integer, byteLength = 8) {
|
|
260
|
+
const value = typeof integer === "bigint" ? integer : intToBigInt(integer);
|
|
261
|
+
return value.toString(16).padStart(byteLength * 2, "0");
|
|
262
|
+
}
|
|
263
|
+
function toTwos(value, width) {
|
|
264
|
+
const limit = BigInt(1) << width - BigInt(1);
|
|
265
|
+
if (value < -limit || value > limit - BigInt(1)) {
|
|
266
|
+
throw new Error(`Unable to represent integer in width: ${width}`);
|
|
267
|
+
}
|
|
268
|
+
if (value >= BigInt(0))
|
|
269
|
+
return value;
|
|
270
|
+
return value + (BigInt(1) << width);
|
|
271
|
+
}
|
|
272
|
+
function fromTwos(value, width) {
|
|
273
|
+
if (value & BigInt(1) << width - BigInt(1)) {
|
|
274
|
+
return value - (BigInt(1) << width);
|
|
275
|
+
}
|
|
276
|
+
return value;
|
|
277
|
+
}
|
|
278
|
+
function bytesToTwosBigInt(bytes) {
|
|
279
|
+
if (bytes.length === 0)
|
|
280
|
+
return 0n;
|
|
281
|
+
const hex = bytesToHex(bytes);
|
|
282
|
+
if (hex.length === 0)
|
|
283
|
+
return 0n;
|
|
284
|
+
return fromTwos(BigInt(`0x${hex}`), BigInt(bytes.byteLength * 8));
|
|
285
|
+
}
|
|
286
|
+
function writeUInt32BE(value) {
|
|
287
|
+
const buf = new Uint8Array(4);
|
|
288
|
+
buf[0] = value >>> 24 & 255;
|
|
289
|
+
buf[1] = value >>> 16 & 255;
|
|
290
|
+
buf[2] = value >>> 8 & 255;
|
|
291
|
+
buf[3] = value & 255;
|
|
292
|
+
return buf;
|
|
293
|
+
}
|
|
294
|
+
function readUInt32BE(bytes, offset = 0) {
|
|
295
|
+
return (bytes[offset] << 24 | bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3]) >>> 0;
|
|
296
|
+
}
|
|
297
|
+
function writeUInt16BE(value) {
|
|
298
|
+
const buf = new Uint8Array(2);
|
|
299
|
+
buf[0] = value >>> 8 & 255;
|
|
300
|
+
buf[1] = value & 255;
|
|
301
|
+
return buf;
|
|
302
|
+
}
|
|
303
|
+
function readUInt16BE(bytes, offset = 0) {
|
|
304
|
+
return (bytes[offset] << 8 | bytes[offset + 1]) >>> 0;
|
|
305
|
+
}
|
|
306
|
+
function writeUInt8(value) {
|
|
307
|
+
return new Uint8Array([value & 255]);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// src/utils/c32.ts
|
|
311
|
+
var C32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
312
|
+
var HEX = "0123456789abcdef";
|
|
313
|
+
function c32normalize(input) {
|
|
314
|
+
return input.toUpperCase().replace(/O/g, "0").replace(/L|I/g, "1");
|
|
315
|
+
}
|
|
316
|
+
function c32encode(inputHex) {
|
|
317
|
+
let hex = inputHex;
|
|
318
|
+
if (hex.length % 2 !== 0)
|
|
319
|
+
hex = `0${hex}`;
|
|
320
|
+
hex = hex.toLowerCase();
|
|
321
|
+
const res = [];
|
|
322
|
+
let carry = 0;
|
|
323
|
+
for (let i = hex.length - 1;i >= 0; i--) {
|
|
324
|
+
if (carry < 4) {
|
|
325
|
+
const currentCode = HEX.indexOf(hex[i]) >> carry;
|
|
326
|
+
const nextCode = i !== 0 ? HEX.indexOf(hex[i - 1]) : 0;
|
|
327
|
+
const nextBits = 1 + carry;
|
|
328
|
+
const nextLowBits = nextCode % (1 << nextBits) << 5 - nextBits;
|
|
329
|
+
res.unshift(C32[currentCode + nextLowBits]);
|
|
330
|
+
carry = nextBits;
|
|
331
|
+
} else {
|
|
332
|
+
carry = 0;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
let leadingZeros = 0;
|
|
336
|
+
while (leadingZeros < res.length && res[leadingZeros] === "0")
|
|
337
|
+
leadingZeros++;
|
|
338
|
+
const stripped = res.slice(leadingZeros);
|
|
339
|
+
const bytes = hexToBytes(hex);
|
|
340
|
+
let zeroBytesCount = 0;
|
|
341
|
+
while (zeroBytesCount < bytes.length && bytes[zeroBytesCount] === 0)
|
|
342
|
+
zeroBytesCount++;
|
|
343
|
+
const prefix = Array(zeroBytesCount).fill(C32[0]);
|
|
344
|
+
return [...prefix, ...stripped].join("");
|
|
345
|
+
}
|
|
346
|
+
function c32decode(c32input) {
|
|
347
|
+
const input = c32normalize(c32input);
|
|
348
|
+
if (!input.match(`^[${C32}]*$`))
|
|
349
|
+
throw new Error("Not a c32-encoded string");
|
|
350
|
+
const zeroPrefix = input.match(`^${C32[0]}*`);
|
|
351
|
+
const numLeadingZeroBytes = zeroPrefix ? zeroPrefix[0]?.length : 0;
|
|
352
|
+
const res = [];
|
|
353
|
+
let carry = 0;
|
|
354
|
+
let carryBits = 0;
|
|
355
|
+
for (let i = input.length - 1;i >= 0; i--) {
|
|
356
|
+
if (carryBits === 4) {
|
|
357
|
+
res.unshift(HEX[carry]);
|
|
358
|
+
carryBits = 0;
|
|
359
|
+
carry = 0;
|
|
360
|
+
}
|
|
361
|
+
const currentValue = (C32.indexOf(input[i]) << carryBits) + carry;
|
|
362
|
+
res.unshift(HEX[currentValue % 16]);
|
|
363
|
+
carryBits += 1;
|
|
364
|
+
carry = currentValue >> 4;
|
|
365
|
+
if (carry > 1 << carryBits)
|
|
366
|
+
throw new Error("Panic error in c32 decoding");
|
|
367
|
+
}
|
|
368
|
+
res.unshift(HEX[carry]);
|
|
369
|
+
if (res.length % 2 === 1)
|
|
370
|
+
res.unshift("0");
|
|
371
|
+
let hexLeadingZeros = 0;
|
|
372
|
+
while (hexLeadingZeros < res.length && res[hexLeadingZeros] === "0")
|
|
373
|
+
hexLeadingZeros++;
|
|
374
|
+
let hexStr = res.slice(hexLeadingZeros - hexLeadingZeros % 2).join("");
|
|
375
|
+
for (let i = 0;i < numLeadingZeroBytes; i++)
|
|
376
|
+
hexStr = `00${hexStr}`;
|
|
377
|
+
return hexStr;
|
|
378
|
+
}
|
|
379
|
+
function c32checksum(dataHex) {
|
|
380
|
+
return bytesToHex(import_sha2.sha256(import_sha2.sha256(hexToBytes(dataHex))).slice(0, 4));
|
|
381
|
+
}
|
|
382
|
+
function c32checkEncode(version, data) {
|
|
383
|
+
if (version < 0 || version >= 32)
|
|
384
|
+
throw new Error("Invalid version (must be between 0 and 31)");
|
|
385
|
+
if (!data.match(/^[0-9a-fA-F]*$/))
|
|
386
|
+
throw new Error("Invalid data (not a hex string)");
|
|
387
|
+
let d = data.toLowerCase();
|
|
388
|
+
if (d.length % 2 !== 0)
|
|
389
|
+
d = `0${d}`;
|
|
390
|
+
let versionHex = version.toString(16);
|
|
391
|
+
if (versionHex.length === 1)
|
|
392
|
+
versionHex = `0${versionHex}`;
|
|
393
|
+
const checksumHex = c32checksum(`${versionHex}${d}`);
|
|
394
|
+
return `${C32[version]}${c32encode(`${d}${checksumHex}`)}`;
|
|
395
|
+
}
|
|
396
|
+
function c32checkDecode(c32data) {
|
|
397
|
+
const normalized = c32normalize(c32data);
|
|
398
|
+
const dataHex = c32decode(normalized.slice(1));
|
|
399
|
+
const version = C32.indexOf(normalized[0]);
|
|
400
|
+
const checksum = dataHex.slice(-8);
|
|
401
|
+
let versionHex = version.toString(16);
|
|
402
|
+
if (versionHex.length === 1)
|
|
403
|
+
versionHex = `0${versionHex}`;
|
|
404
|
+
if (c32checksum(`${versionHex}${dataHex.substring(0, dataHex.length - 8)}`) !== checksum) {
|
|
405
|
+
throw new Error("Invalid c32check string: checksum mismatch");
|
|
406
|
+
}
|
|
407
|
+
return [version, dataHex.substring(0, dataHex.length - 8)];
|
|
408
|
+
}
|
|
409
|
+
function c32address(version, hash160hex) {
|
|
410
|
+
if (!hash160hex.match(/^[0-9a-fA-F]{40}$/)) {
|
|
411
|
+
throw new Error("Invalid argument: not a hash160 hex string");
|
|
412
|
+
}
|
|
413
|
+
return `S${c32checkEncode(version, hash160hex)}`;
|
|
414
|
+
}
|
|
415
|
+
function c32addressDecode(c32addr) {
|
|
416
|
+
if (c32addr.length <= 5)
|
|
417
|
+
throw new Error("Invalid c32 address: invalid length");
|
|
418
|
+
if (c32addr[0] !== "S")
|
|
419
|
+
throw new Error('Invalid c32 address: must start with "S"');
|
|
420
|
+
return c32checkDecode(c32addr.slice(1));
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// src/utils/constants.ts
|
|
424
|
+
var MAX_U128 = (1n << 128n) - 1n;
|
|
425
|
+
var MAX_I128 = (1n << 127n) - 1n;
|
|
426
|
+
var MIN_I128 = -(1n << 127n);
|
|
427
|
+
var AddressVersion = {
|
|
428
|
+
MainnetSingleSig: 22,
|
|
429
|
+
MainnetMultiSig: 20,
|
|
430
|
+
TestnetSingleSig: 26,
|
|
431
|
+
TestnetMultiSig: 21
|
|
432
|
+
};
|
|
433
|
+
var ZERO_ADDRESS = "SP000000000000000000002Q6VF78";
|
|
434
|
+
var TESTNET_ZERO_ADDRESS = "ST000000000000000000002AMW42H";
|
|
435
|
+
var MICROSTX_PER_STX = 1000000n;
|
|
436
|
+
|
|
437
|
+
// src/utils/hash.ts
|
|
438
|
+
var import_legacy = require("@noble/hashes/legacy.js");
|
|
439
|
+
var import_sha22 = require("@noble/hashes/sha2.js");
|
|
440
|
+
var import_sha23 = require("@noble/hashes/sha2.js");
|
|
441
|
+
function hash160(input) {
|
|
442
|
+
return import_legacy.ripemd160(import_sha22.sha256(input));
|
|
443
|
+
}
|
|
444
|
+
function txidFromBytes(data) {
|
|
445
|
+
return bytesToHex(import_sha23.sha512_256(data));
|
|
446
|
+
}
|
|
447
|
+
function hashP2PKH(input) {
|
|
448
|
+
return bytesToHex(hash160(input));
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// src/utils/address.ts
|
|
452
|
+
function publicKeyToAddress(publicKey, network = "mainnet") {
|
|
453
|
+
const bytes = typeof publicKey === "string" ? hexToBytes(without0x(publicKey)) : publicKey;
|
|
454
|
+
const version = network === "mainnet" ? AddressVersion.MainnetSingleSig : AddressVersion.TestnetSingleSig;
|
|
455
|
+
return c32address(version, bytesToHex(hash160(bytes)));
|
|
456
|
+
}
|
|
457
|
+
var CONTRACT_NAME_REGEX = /^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/;
|
|
458
|
+
function validateStacksAddress(address) {
|
|
459
|
+
try {
|
|
460
|
+
c32addressDecode(address);
|
|
461
|
+
return true;
|
|
462
|
+
} catch {
|
|
463
|
+
return false;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
var isValidAddress = validateStacksAddress;
|
|
467
|
+
function parsePrincipal(value) {
|
|
468
|
+
const parts = value.split(".");
|
|
469
|
+
if (parts.length > 2)
|
|
470
|
+
return null;
|
|
471
|
+
const [address, contractName] = parts;
|
|
472
|
+
if (!validateStacksAddress(address))
|
|
473
|
+
return null;
|
|
474
|
+
if (contractName === undefined)
|
|
475
|
+
return { address };
|
|
476
|
+
if (!CONTRACT_NAME_REGEX.test(contractName))
|
|
477
|
+
return null;
|
|
478
|
+
return { address, contractName };
|
|
479
|
+
}
|
|
480
|
+
function parseContractId(contractId) {
|
|
481
|
+
const parsed = parsePrincipal(contractId);
|
|
482
|
+
if (!parsed?.contractName)
|
|
483
|
+
throw new Error(`Invalid contract identifier: ${contractId}`);
|
|
484
|
+
return [parsed.address, parsed.contractName];
|
|
485
|
+
}
|
|
486
|
+
function isClarityName(name) {
|
|
487
|
+
const regex = /^[a-zA-Z]([a-zA-Z0-9]|[-_!?+<>=/*])*$|^[-+=/*]$|^[<>]=?$/;
|
|
488
|
+
return regex.test(name) && name.length < 128;
|
|
489
|
+
}
|
|
490
|
+
function isAddressEqual(a, b) {
|
|
491
|
+
const [versionA, hashA] = c32addressDecode(a);
|
|
492
|
+
const [versionB, hashB] = c32addressDecode(b);
|
|
493
|
+
return versionA === versionB && hashA.toLowerCase() === hashB.toLowerCase();
|
|
494
|
+
}
|
|
495
|
+
function addressToVersion(address) {
|
|
496
|
+
return c32addressDecode(address)[0];
|
|
497
|
+
}
|
|
498
|
+
function getContractAddress(deployer, contractName) {
|
|
499
|
+
if (!validateStacksAddress(deployer)) {
|
|
500
|
+
throw new Error(`Invalid deployer address: ${deployer}`);
|
|
501
|
+
}
|
|
502
|
+
if (!isClarityName(contractName)) {
|
|
503
|
+
throw new Error(`Invalid contract name: ${contractName}`);
|
|
504
|
+
}
|
|
505
|
+
return `${deployer}.${contractName}`;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// src/errors/base.ts
|
|
509
|
+
function codeFromName(name) {
|
|
510
|
+
return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toUpperCase();
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
class BaseError extends Error {
|
|
514
|
+
name = "StacksError";
|
|
515
|
+
#code;
|
|
516
|
+
shortMessage;
|
|
517
|
+
details;
|
|
518
|
+
constructor(shortMessage, options) {
|
|
519
|
+
const message = [
|
|
520
|
+
shortMessage,
|
|
521
|
+
options?.details ? `
|
|
522
|
+
${options.details}` : ""
|
|
523
|
+
].join("");
|
|
524
|
+
super(message, { cause: options?.cause });
|
|
525
|
+
if (options?.code !== undefined)
|
|
526
|
+
this.#code = options.code;
|
|
527
|
+
this.shortMessage = shortMessage;
|
|
528
|
+
this.details = options?.details;
|
|
529
|
+
}
|
|
530
|
+
get code() {
|
|
531
|
+
return this.#code ?? codeFromName(this.name);
|
|
532
|
+
}
|
|
533
|
+
set code(value) {
|
|
534
|
+
this.#code = value;
|
|
535
|
+
}
|
|
536
|
+
toJSON() {
|
|
537
|
+
return {
|
|
538
|
+
name: this.name,
|
|
539
|
+
code: this.code,
|
|
540
|
+
message: this.message,
|
|
541
|
+
shortMessage: this.shortMessage,
|
|
542
|
+
details: this.details,
|
|
543
|
+
cause: this.cause instanceof Error ? this.cause.message : undefined
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// src/errors/transaction.ts
|
|
549
|
+
class TransactionError extends BaseError {
|
|
550
|
+
name = "TransactionError";
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
class BroadcastError extends BaseError {
|
|
554
|
+
name = "BroadcastError";
|
|
555
|
+
txid;
|
|
556
|
+
reason;
|
|
557
|
+
reasonData;
|
|
558
|
+
constructor(message, options) {
|
|
559
|
+
super(message, options);
|
|
560
|
+
this.txid = options?.txid;
|
|
561
|
+
this.reason = options?.reason;
|
|
562
|
+
this.reasonData = options?.reasonData;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
class TransactionAbortedError extends BaseError {
|
|
567
|
+
name = "TransactionAbortedError";
|
|
568
|
+
receipt;
|
|
569
|
+
constructor(message, options) {
|
|
570
|
+
super(message, options);
|
|
571
|
+
this.receipt = options.receipt;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
class TransactionDroppedError extends BaseError {
|
|
576
|
+
name = "TransactionDroppedError";
|
|
577
|
+
txid;
|
|
578
|
+
constructor(message, options) {
|
|
579
|
+
super(message, options);
|
|
580
|
+
this.txid = options.txid;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
class WaitForTransactionTimeoutError extends BaseError {
|
|
585
|
+
name = "WaitForTransactionTimeoutError";
|
|
586
|
+
txid;
|
|
587
|
+
constructor(message, options) {
|
|
588
|
+
super(message, options);
|
|
589
|
+
this.txid = options.txid;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
class SerializationError extends BaseError {
|
|
594
|
+
name = "SerializationError";
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
class SigningError extends BaseError {
|
|
598
|
+
name = "SigningError";
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// src/utils/bytes-reader.ts
|
|
602
|
+
class BytesReader {
|
|
603
|
+
data;
|
|
604
|
+
offset = 0;
|
|
605
|
+
constructor(data) {
|
|
606
|
+
this.data = data;
|
|
607
|
+
}
|
|
608
|
+
remaining() {
|
|
609
|
+
return this.data.length - this.offset;
|
|
610
|
+
}
|
|
611
|
+
ensure(length) {
|
|
612
|
+
if (this.offset + length > this.data.length) {
|
|
613
|
+
throw new SerializationError(`Buffer underflow: need ${length} bytes at offset ${this.offset}, have ${this.data.length}`);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
readUInt8() {
|
|
617
|
+
this.ensure(1);
|
|
618
|
+
return this.data[this.offset++];
|
|
619
|
+
}
|
|
620
|
+
readUInt16BE() {
|
|
621
|
+
this.ensure(2);
|
|
622
|
+
const val = (this.data[this.offset] << 8 | this.data[this.offset + 1]) >>> 0;
|
|
623
|
+
this.offset += 2;
|
|
624
|
+
return val;
|
|
625
|
+
}
|
|
626
|
+
readUInt32BE() {
|
|
627
|
+
this.ensure(4);
|
|
628
|
+
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;
|
|
629
|
+
this.offset += 4;
|
|
630
|
+
return val;
|
|
631
|
+
}
|
|
632
|
+
readBytes(length) {
|
|
633
|
+
this.ensure(length);
|
|
634
|
+
const slice = this.data.slice(this.offset, this.offset + length);
|
|
635
|
+
this.offset += length;
|
|
636
|
+
return slice;
|
|
637
|
+
}
|
|
638
|
+
readBigUInt64BE() {
|
|
639
|
+
const hex = bytesToHex(this.readBytes(8));
|
|
640
|
+
return hex.length > 0 ? BigInt(`0x${hex}`) : 0n;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// src/clarity/deserialize.ts
|
|
645
|
+
function readAddress(reader) {
|
|
646
|
+
const version = reader.readUInt8();
|
|
647
|
+
const hash1602 = bytesToHex(reader.readBytes(20));
|
|
648
|
+
return c32address(version, hash1602);
|
|
649
|
+
}
|
|
650
|
+
function readLPString(reader, prefixBytes = 1) {
|
|
651
|
+
let length = 0;
|
|
652
|
+
for (let i = 0;i < prefixBytes; i++) {
|
|
653
|
+
length = length << 8 | reader.readUInt8();
|
|
654
|
+
}
|
|
655
|
+
return bytesToUtf8(reader.readBytes(length));
|
|
656
|
+
}
|
|
657
|
+
var MAX_CV_DEPTH = 64;
|
|
658
|
+
var MIN_LIST_ITEM_BYTES = 1;
|
|
659
|
+
var MIN_TUPLE_ENTRY_BYTES = 2;
|
|
660
|
+
function checkCount(reader, count, minBytes) {
|
|
661
|
+
if (count * minBytes > reader.remaining()) {
|
|
662
|
+
throw new SerializationError(`Clarity value declares ${count} elements but only ${reader.remaining()} bytes remain`);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
function readCV(reader, depth = 0) {
|
|
666
|
+
if (depth > MAX_CV_DEPTH) {
|
|
667
|
+
throw new SerializationError(`Clarity value nests deeper than ${MAX_CV_DEPTH} levels`);
|
|
668
|
+
}
|
|
669
|
+
const typeByte = reader.readUInt8();
|
|
670
|
+
const type = clarityTypeFromByte(typeByte);
|
|
671
|
+
switch (type) {
|
|
672
|
+
case "int":
|
|
673
|
+
return intCV(bytesToTwosBigInt(reader.readBytes(16)));
|
|
674
|
+
case "uint":
|
|
675
|
+
return uintCV(reader.readBytes(16));
|
|
676
|
+
case "true":
|
|
677
|
+
return trueCV();
|
|
678
|
+
case "false":
|
|
679
|
+
return falseCV();
|
|
680
|
+
case "buffer": {
|
|
681
|
+
const len = reader.readUInt32BE();
|
|
682
|
+
return bufferCV(reader.readBytes(len));
|
|
683
|
+
}
|
|
684
|
+
case "none":
|
|
685
|
+
return noneCV();
|
|
686
|
+
case "some":
|
|
687
|
+
return someCV(readCV(reader, depth + 1));
|
|
688
|
+
case "ok":
|
|
689
|
+
return responseOkCV(readCV(reader, depth + 1));
|
|
690
|
+
case "err":
|
|
691
|
+
return responseErrorCV(readCV(reader, depth + 1));
|
|
692
|
+
case "address":
|
|
693
|
+
return standardPrincipalCV(readAddress(reader));
|
|
694
|
+
case "contract": {
|
|
695
|
+
const addr = readAddress(reader);
|
|
696
|
+
const name = readLPString(reader);
|
|
697
|
+
return contractPrincipalCV(addr, name);
|
|
698
|
+
}
|
|
699
|
+
case "list": {
|
|
700
|
+
const len = reader.readUInt32BE();
|
|
701
|
+
checkCount(reader, len, MIN_LIST_ITEM_BYTES);
|
|
702
|
+
const items = [];
|
|
703
|
+
for (let i = 0;i < len; i++) {
|
|
704
|
+
items.push(readCV(reader, depth + 1));
|
|
705
|
+
}
|
|
706
|
+
return listCV(items);
|
|
707
|
+
}
|
|
708
|
+
case "tuple": {
|
|
709
|
+
const len = reader.readUInt32BE();
|
|
710
|
+
checkCount(reader, len, MIN_TUPLE_ENTRY_BYTES);
|
|
711
|
+
const data = {};
|
|
712
|
+
for (let i = 0;i < len; i++) {
|
|
713
|
+
const key = readLPString(reader);
|
|
714
|
+
data[key] = readCV(reader, depth + 1);
|
|
715
|
+
}
|
|
716
|
+
return tupleCV(data);
|
|
717
|
+
}
|
|
718
|
+
case "ascii": {
|
|
719
|
+
const len = reader.readUInt32BE();
|
|
720
|
+
return stringAsciiCV(bytesToAscii(reader.readBytes(len)));
|
|
721
|
+
}
|
|
722
|
+
case "utf8": {
|
|
723
|
+
const len = reader.readUInt32BE();
|
|
724
|
+
return stringUtf8CV(bytesToUtf8(reader.readBytes(len)));
|
|
725
|
+
}
|
|
726
|
+
default:
|
|
727
|
+
throw new SerializationError(`Cannot deserialize unknown clarity type: ${type}`);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
function deserializeCVBytes(input) {
|
|
731
|
+
const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
|
|
732
|
+
return readCV(new BytesReader(bytes));
|
|
733
|
+
}
|
|
734
|
+
function deserializeCV(input) {
|
|
735
|
+
return deserializeCVBytes(input);
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
// src/clarity/serialize.ts
|
|
739
|
+
var CLARITY_INT_SIZE = 128n;
|
|
740
|
+
var CLARITY_INT_BYTE_SIZE = 16;
|
|
741
|
+
function typeIdByte(type) {
|
|
742
|
+
return ClarityWireType[type];
|
|
743
|
+
}
|
|
744
|
+
function withTypeId(type, bytes) {
|
|
745
|
+
return concatBytes(new Uint8Array([typeIdByte(type)]), bytes);
|
|
746
|
+
}
|
|
747
|
+
function serializeAddress(c32Address) {
|
|
748
|
+
const [version, hash1602] = c32addressDecode(c32Address);
|
|
749
|
+
return concatBytes(new Uint8Array([version]), hexToBytes(hash1602));
|
|
750
|
+
}
|
|
751
|
+
function serializeLPString(str, prefixBytes = 1) {
|
|
752
|
+
const content = utf8ToBytes(str);
|
|
753
|
+
const lengthPrefix = hexToBytes(intToHex(content.byteLength, prefixBytes));
|
|
754
|
+
return concatBytes(lengthPrefix, content);
|
|
755
|
+
}
|
|
756
|
+
function serializeCVBytes(value) {
|
|
757
|
+
switch (value.type) {
|
|
758
|
+
case "true":
|
|
759
|
+
case "false":
|
|
760
|
+
return new Uint8Array([typeIdByte(value.type)]);
|
|
761
|
+
case "int": {
|
|
762
|
+
const bytes = bigIntToBytes(toTwos(BigInt(value.value), CLARITY_INT_SIZE), CLARITY_INT_BYTE_SIZE);
|
|
763
|
+
return withTypeId(value.type, bytes);
|
|
764
|
+
}
|
|
765
|
+
case "uint": {
|
|
766
|
+
const bytes = bigIntToBytes(BigInt(value.value), CLARITY_INT_BYTE_SIZE);
|
|
767
|
+
return withTypeId(value.type, bytes);
|
|
768
|
+
}
|
|
769
|
+
case "buffer": {
|
|
770
|
+
const bufBytes = hexToBytes(value.value);
|
|
771
|
+
return withTypeId(value.type, concatBytes(writeUInt32BE(bufBytes.length), bufBytes));
|
|
772
|
+
}
|
|
773
|
+
case "none":
|
|
774
|
+
return new Uint8Array([typeIdByte(value.type)]);
|
|
775
|
+
case "some":
|
|
776
|
+
return withTypeId(value.type, serializeCVBytes(value.value));
|
|
777
|
+
case "ok":
|
|
778
|
+
case "err":
|
|
779
|
+
return withTypeId(value.type, serializeCVBytes(value.value));
|
|
780
|
+
case "address":
|
|
781
|
+
return withTypeId(value.type, serializeAddress(value.value));
|
|
782
|
+
case "contract": {
|
|
783
|
+
const [addr, name] = value.value.split(".");
|
|
784
|
+
if (!addr || !name)
|
|
785
|
+
throw new Error(`Invalid contract principal: ${value.value}`);
|
|
786
|
+
return withTypeId(value.type, concatBytes(serializeAddress(addr), serializeLPString(name)));
|
|
787
|
+
}
|
|
788
|
+
case "list": {
|
|
789
|
+
const parts = [writeUInt32BE(value.value.length)];
|
|
790
|
+
for (const item of value.value) {
|
|
791
|
+
parts.push(serializeCVBytes(item));
|
|
792
|
+
}
|
|
793
|
+
return withTypeId(value.type, concatBytes(...parts));
|
|
794
|
+
}
|
|
795
|
+
case "tuple": {
|
|
796
|
+
const keys = Object.keys(value.value).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
797
|
+
const parts = [writeUInt32BE(keys.length)];
|
|
798
|
+
for (const key of keys) {
|
|
799
|
+
parts.push(serializeLPString(key));
|
|
800
|
+
parts.push(serializeCVBytes(value.value[key]));
|
|
801
|
+
}
|
|
802
|
+
return withTypeId(value.type, concatBytes(...parts));
|
|
803
|
+
}
|
|
804
|
+
case "ascii": {
|
|
805
|
+
const strBytes = asciiToBytes(value.value);
|
|
806
|
+
return withTypeId(value.type, concatBytes(writeUInt32BE(strBytes.length), strBytes));
|
|
807
|
+
}
|
|
808
|
+
case "utf8": {
|
|
809
|
+
const strBytes = utf8ToBytes(value.value);
|
|
810
|
+
return withTypeId(value.type, concatBytes(writeUInt32BE(strBytes.length), strBytes));
|
|
811
|
+
}
|
|
812
|
+
default:
|
|
813
|
+
throw new Error("Cannot serialize unknown clarity type");
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
function serializeCV(value) {
|
|
817
|
+
return bytesToHex(serializeCVBytes(value));
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
// src/clarity/values.ts
|
|
821
|
+
var MAX_U1282 = BigInt("0xffffffffffffffffffffffffffffffff");
|
|
822
|
+
var MIN_I1282 = BigInt("-170141183460469231731687303715884105728");
|
|
823
|
+
var MAX_I1282 = BigInt("0x7fffffffffffffffffffffffffffffff");
|
|
824
|
+
function intCV(value) {
|
|
825
|
+
let v = value;
|
|
826
|
+
if (typeof v === "string" && v.toLowerCase().startsWith("0x")) {
|
|
827
|
+
v = bytesToTwosBigInt(hexToBytes(v));
|
|
828
|
+
}
|
|
829
|
+
if (v instanceof Uint8Array)
|
|
830
|
+
v = bytesToTwosBigInt(v);
|
|
831
|
+
const n = intToBigInt(v);
|
|
832
|
+
if (n > MAX_I1282)
|
|
833
|
+
throw new RangeError(`Int exceeds max i128: ${MAX_I1282}`);
|
|
834
|
+
if (n < MIN_I1282)
|
|
835
|
+
throw new RangeError(`Int below min i128: ${MIN_I1282}`);
|
|
836
|
+
return { type: "int", value: n };
|
|
837
|
+
}
|
|
838
|
+
function uintCV(value) {
|
|
839
|
+
const n = intToBigInt(value);
|
|
840
|
+
if (n < 0n)
|
|
841
|
+
throw new RangeError("Cannot construct unsigned int from negative value");
|
|
842
|
+
if (n > MAX_U1282)
|
|
843
|
+
throw new RangeError(`UInt exceeds max u128: ${MAX_U1282}`);
|
|
844
|
+
return { type: "uint", value: n };
|
|
845
|
+
}
|
|
846
|
+
var trueCV = () => ({ type: "true" });
|
|
847
|
+
var falseCV = () => ({ type: "false" });
|
|
848
|
+
var boolCV = (v) => v ? trueCV() : falseCV();
|
|
849
|
+
function bufferCV(buffer) {
|
|
850
|
+
if (buffer.byteLength > 1048576) {
|
|
851
|
+
throw new Error("Buffer exceeds max size of 1MB");
|
|
852
|
+
}
|
|
853
|
+
return { type: "buffer", value: bytesToHex(buffer) };
|
|
854
|
+
}
|
|
855
|
+
function standardPrincipalCV(address) {
|
|
856
|
+
const [version, hash1602] = c32addressDecode(address);
|
|
857
|
+
const normalized = c32address(version, hash1602);
|
|
858
|
+
return { type: "address", value: normalized };
|
|
859
|
+
}
|
|
860
|
+
function contractPrincipalCV(address, contractName) {
|
|
861
|
+
const [version, hash1602] = c32addressDecode(address);
|
|
862
|
+
const normalized = c32address(version, hash1602);
|
|
863
|
+
if (utf8ToBytes(contractName).byteLength >= 128) {
|
|
864
|
+
throw new Error("Contract name must be less than 128 bytes");
|
|
865
|
+
}
|
|
866
|
+
return { type: "contract", value: `${normalized}.${contractName}` };
|
|
867
|
+
}
|
|
868
|
+
function noneCV() {
|
|
869
|
+
return { type: "none" };
|
|
870
|
+
}
|
|
871
|
+
function someCV(value) {
|
|
872
|
+
return { type: "some", value };
|
|
873
|
+
}
|
|
874
|
+
function responseOkCV(value) {
|
|
875
|
+
return { type: "ok", value };
|
|
876
|
+
}
|
|
877
|
+
function responseErrorCV(value) {
|
|
878
|
+
return { type: "err", value };
|
|
879
|
+
}
|
|
880
|
+
function listCV(values) {
|
|
881
|
+
return { type: "list", value: values };
|
|
882
|
+
}
|
|
883
|
+
function tupleCV(data) {
|
|
884
|
+
for (const key in data) {
|
|
885
|
+
if (!isClarityName(key)) {
|
|
886
|
+
throw new Error(`"${key}" is not a valid Clarity name`);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
return { type: "tuple", value: data };
|
|
890
|
+
}
|
|
891
|
+
function stringAsciiCV(value) {
|
|
892
|
+
return { type: "ascii", value };
|
|
893
|
+
}
|
|
894
|
+
function stringUtf8CV(value) {
|
|
895
|
+
return { type: "utf8", value };
|
|
896
|
+
}
|
|
897
|
+
var Cl = {
|
|
898
|
+
int: intCV,
|
|
899
|
+
uint: uintCV,
|
|
900
|
+
bool: boolCV,
|
|
901
|
+
principal(address) {
|
|
902
|
+
const parsed = parsePrincipal(address);
|
|
903
|
+
if (!parsed)
|
|
904
|
+
throw new Error(`Invalid principal: ${address}`);
|
|
905
|
+
return parsed.contractName ? contractPrincipalCV(parsed.address, parsed.contractName) : standardPrincipalCV(parsed.address);
|
|
906
|
+
},
|
|
907
|
+
address(address) {
|
|
908
|
+
return Cl.principal(address);
|
|
909
|
+
},
|
|
910
|
+
contractPrincipal: contractPrincipalCV,
|
|
911
|
+
standardPrincipal: standardPrincipalCV,
|
|
912
|
+
buffer: bufferCV,
|
|
913
|
+
bufferFromHex: (hex) => bufferCV(hexToBytes(hex)),
|
|
914
|
+
bufferFromAscii: (ascii) => bufferCV(asciiToBytes(ascii)),
|
|
915
|
+
bufferFromUtf8: (utf8) => bufferCV(utf8ToBytes(utf8)),
|
|
916
|
+
none: noneCV,
|
|
917
|
+
some: someCV,
|
|
918
|
+
ok: responseOkCV,
|
|
919
|
+
error: responseErrorCV,
|
|
920
|
+
list: listCV,
|
|
921
|
+
tuple: tupleCV,
|
|
922
|
+
stringAscii: stringAsciiCV,
|
|
923
|
+
stringUtf8: stringUtf8CV,
|
|
924
|
+
serialize(value) {
|
|
925
|
+
return bytesToHex(serializeCVBytes(value));
|
|
926
|
+
},
|
|
927
|
+
deserialize: deserializeCVBytes
|
|
928
|
+
};
|
|
929
|
+
// src/clarity/structuredData.ts
|
|
930
|
+
var import_sha24 = require("@noble/hashes/sha2.js");
|
|
931
|
+
var SIP018_PREFIX = new Uint8Array([
|
|
932
|
+
83,
|
|
933
|
+
73,
|
|
934
|
+
80,
|
|
935
|
+
48,
|
|
936
|
+
49,
|
|
937
|
+
56
|
|
938
|
+
]);
|
|
939
|
+
function hashStructuredData(structuredData) {
|
|
940
|
+
return import_sha24.sha256(serializeCVBytes(structuredData));
|
|
941
|
+
}
|
|
942
|
+
function isDomain(value) {
|
|
943
|
+
if (value.type !== "tuple")
|
|
944
|
+
return false;
|
|
945
|
+
const { name, version, "chain-id": chainId } = value.value;
|
|
946
|
+
return name?.type === "ascii" && version?.type === "ascii" && chainId?.type === "uint";
|
|
947
|
+
}
|
|
948
|
+
function encodeStructuredData(opts) {
|
|
949
|
+
if (!isDomain(opts.domain)) {
|
|
950
|
+
throw new Error("domain must be a tuple { name: ascii, version: ascii, chain-id: uint }");
|
|
951
|
+
}
|
|
952
|
+
return concatBytes(SIP018_PREFIX, hashStructuredData(opts.domain), hashStructuredData(opts.message));
|
|
953
|
+
}
|
|
954
|
+
function structuredDataHash(opts) {
|
|
955
|
+
return import_sha24.sha256(encodeStructuredData(opts));
|
|
956
|
+
}
|
|
957
|
+
async function signStructuredData(account, opts) {
|
|
958
|
+
const vrs = await account.sign(structuredDataHash(opts));
|
|
959
|
+
if (vrs.length !== 65) {
|
|
960
|
+
throw new Error(`Expected 65-byte recoverable signature, got ${vrs.length}`);
|
|
961
|
+
}
|
|
962
|
+
return bytesToHex(concatBytes(vrs.slice(1), vrs.slice(0, 1)));
|
|
963
|
+
}
|
|
964
|
+
// src/clarity/prettyPrint.ts
|
|
965
|
+
function prettyPrint(val, encoding = "hex") {
|
|
966
|
+
switch (val.type) {
|
|
967
|
+
case "true":
|
|
968
|
+
return "true";
|
|
969
|
+
case "false":
|
|
970
|
+
return "false";
|
|
971
|
+
case "int":
|
|
972
|
+
return val.value.toString();
|
|
973
|
+
case "uint":
|
|
974
|
+
return `u${val.value.toString()}`;
|
|
975
|
+
case "buffer":
|
|
976
|
+
if (encoding === "tryAscii") {
|
|
977
|
+
const str = bytesToAscii(hexToBytes(val.value));
|
|
978
|
+
if (/^[ -~]*$/.test(str))
|
|
979
|
+
return JSON.stringify(str);
|
|
980
|
+
}
|
|
981
|
+
return `0x${val.value}`;
|
|
982
|
+
case "none":
|
|
983
|
+
return "none";
|
|
984
|
+
case "some":
|
|
985
|
+
return `(some ${prettyPrint(val.value, encoding)})`;
|
|
986
|
+
case "ok":
|
|
987
|
+
return `(ok ${prettyPrint(val.value, encoding)})`;
|
|
988
|
+
case "err":
|
|
989
|
+
return `(err ${prettyPrint(val.value, encoding)})`;
|
|
990
|
+
case "address":
|
|
991
|
+
case "contract":
|
|
992
|
+
return val.value;
|
|
993
|
+
case "list":
|
|
994
|
+
return `(list ${val.value.map((v) => prettyPrint(v, encoding)).join(" ")})`;
|
|
995
|
+
case "tuple":
|
|
996
|
+
return `(tuple ${Object.keys(val.value).map((key) => `(${key} ${prettyPrint(val.value[key], encoding)})`).join(" ")})`;
|
|
997
|
+
case "ascii":
|
|
998
|
+
return `"${val.value}"`;
|
|
999
|
+
case "utf8":
|
|
1000
|
+
return `u"${val.value}"`;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
function cvToJSON(val) {
|
|
1004
|
+
switch (val.type) {
|
|
1005
|
+
case "true":
|
|
1006
|
+
return { type: "bool", value: true };
|
|
1007
|
+
case "false":
|
|
1008
|
+
return { type: "bool", value: false };
|
|
1009
|
+
case "int":
|
|
1010
|
+
return { type: "int", value: val.value.toString() };
|
|
1011
|
+
case "uint":
|
|
1012
|
+
return { type: "uint", value: val.value.toString() };
|
|
1013
|
+
case "buffer": {
|
|
1014
|
+
const hex = without0x(val.value);
|
|
1015
|
+
return {
|
|
1016
|
+
type: `(buff ${Math.ceil(hex.length / 2)})`,
|
|
1017
|
+
value: `0x${hex}`
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
case "none":
|
|
1021
|
+
return { type: "(optional none)", value: null };
|
|
1022
|
+
case "some":
|
|
1023
|
+
return { type: "(optional)", value: cvToJSON(val.value) };
|
|
1024
|
+
case "ok":
|
|
1025
|
+
return { type: "(response)", value: cvToJSON(val.value), success: true };
|
|
1026
|
+
case "err":
|
|
1027
|
+
return { type: "(response)", value: cvToJSON(val.value), success: false };
|
|
1028
|
+
case "address":
|
|
1029
|
+
case "contract":
|
|
1030
|
+
return { type: "principal", value: val.value };
|
|
1031
|
+
case "list":
|
|
1032
|
+
return { type: "(list)", value: val.value.map(cvToJSON) };
|
|
1033
|
+
case "tuple": {
|
|
1034
|
+
const result = {};
|
|
1035
|
+
for (const key of Object.keys(val.value)) {
|
|
1036
|
+
result[key] = cvToJSON(val.value[key]);
|
|
1037
|
+
}
|
|
1038
|
+
return { type: "(tuple)", value: result };
|
|
1039
|
+
}
|
|
1040
|
+
case "ascii":
|
|
1041
|
+
return {
|
|
1042
|
+
type: `(string-ascii ${asciiToBytes(val.value).length})`,
|
|
1043
|
+
value: val.value
|
|
1044
|
+
};
|
|
1045
|
+
case "utf8":
|
|
1046
|
+
return {
|
|
1047
|
+
type: `(string-utf8 ${utf8ToBytes(val.value).length})`,
|
|
1048
|
+
value: val.value
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
function cvToValue(val) {
|
|
1053
|
+
switch (val.type) {
|
|
1054
|
+
case "true":
|
|
1055
|
+
return true;
|
|
1056
|
+
case "false":
|
|
1057
|
+
return false;
|
|
1058
|
+
case "int":
|
|
1059
|
+
case "uint":
|
|
1060
|
+
return val.value;
|
|
1061
|
+
case "buffer":
|
|
1062
|
+
return `0x${val.value}`;
|
|
1063
|
+
case "none":
|
|
1064
|
+
return null;
|
|
1065
|
+
case "some":
|
|
1066
|
+
return cvToValue(val.value);
|
|
1067
|
+
case "ok":
|
|
1068
|
+
case "err":
|
|
1069
|
+
return cvToValue(val.value);
|
|
1070
|
+
case "address":
|
|
1071
|
+
case "contract":
|
|
1072
|
+
return val.value;
|
|
1073
|
+
case "list":
|
|
1074
|
+
return val.value.map(cvToValue);
|
|
1075
|
+
case "tuple": {
|
|
1076
|
+
const result = {};
|
|
1077
|
+
for (const key of Object.keys(val.value)) {
|
|
1078
|
+
result[key] = cvToValue(val.value[key]);
|
|
1079
|
+
}
|
|
1080
|
+
return result;
|
|
1081
|
+
}
|
|
1082
|
+
case "ascii":
|
|
1083
|
+
case "utf8":
|
|
1084
|
+
return val.value;
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
function cvToBigInt(val) {
|
|
1088
|
+
if (val.type !== "int" && val.type !== "uint") {
|
|
1089
|
+
throw new Error(`cvToBigInt: expected int or uint, got ${val.type}`);
|
|
1090
|
+
}
|
|
1091
|
+
return val.value;
|
|
1092
|
+
}
|
|
1093
|
+
function cvToString(val) {
|
|
1094
|
+
if (val.type !== "ascii" && val.type !== "utf8") {
|
|
1095
|
+
throw new Error(`cvToString: expected ascii or utf8, got ${val.type}`);
|
|
1096
|
+
}
|
|
1097
|
+
return val.value;
|
|
1098
|
+
}
|
|
1099
|
+
function cvToBuffer(val) {
|
|
1100
|
+
if (val.type !== "buffer") {
|
|
1101
|
+
throw new Error(`cvToBuffer: expected buffer, got ${val.type}`);
|
|
1102
|
+
}
|
|
1103
|
+
return val.value;
|
|
1104
|
+
}
|
|
1105
|
+
function cvToBoolean(val) {
|
|
1106
|
+
if (val.type !== "true" && val.type !== "false") {
|
|
1107
|
+
throw new Error(`cvToBoolean: expected bool, got ${val.type}`);
|
|
1108
|
+
}
|
|
1109
|
+
return val.type === "true";
|
|
1110
|
+
}
|
|
1111
|
+
function cvToPrincipal(val) {
|
|
1112
|
+
if (val.type !== "address" && val.type !== "contract") {
|
|
1113
|
+
throw new Error(`cvToPrincipal: expected principal or contract, got ${val.type}`);
|
|
1114
|
+
}
|
|
1115
|
+
return val.value;
|
|
1116
|
+
}
|
|
1117
|
+
// src/clarity/abi/guards.ts
|
|
1118
|
+
function isUint128(value) {
|
|
1119
|
+
return typeof value === "bigint" && value >= 0n && value <= MAX_U128;
|
|
1120
|
+
}
|
|
1121
|
+
function isInt128(value) {
|
|
1122
|
+
return typeof value === "bigint" && value >= MIN_I128 && value <= MAX_I128;
|
|
1123
|
+
}
|
|
1124
|
+
function isBool(value) {
|
|
1125
|
+
return typeof value === "boolean";
|
|
1126
|
+
}
|
|
1127
|
+
function isPrincipal(value) {
|
|
1128
|
+
return typeof value === "string" && parsePrincipal(value) !== null;
|
|
1129
|
+
}
|
|
1130
|
+
function isStandardPrincipal(value) {
|
|
1131
|
+
if (typeof value !== "string")
|
|
1132
|
+
return false;
|
|
1133
|
+
const parsed = parsePrincipal(value);
|
|
1134
|
+
return parsed !== null && parsed.contractName === undefined;
|
|
1135
|
+
}
|
|
1136
|
+
function isContractPrincipal(value) {
|
|
1137
|
+
if (typeof value !== "string")
|
|
1138
|
+
return false;
|
|
1139
|
+
const parsed = parsePrincipal(value);
|
|
1140
|
+
return parsed !== null && parsed.contractName !== undefined;
|
|
1141
|
+
}
|
|
1142
|
+
function isTraitReference(value) {
|
|
1143
|
+
return isContractPrincipal(value);
|
|
1144
|
+
}
|
|
1145
|
+
function isString(value) {
|
|
1146
|
+
return typeof value === "string";
|
|
1147
|
+
}
|
|
1148
|
+
function isUint8Array(value) {
|
|
1149
|
+
return value instanceof Uint8Array;
|
|
1150
|
+
}
|
|
1151
|
+
function isArray(value, itemGuard) {
|
|
1152
|
+
return Array.isArray(value) && value.every(itemGuard);
|
|
1153
|
+
}
|
|
1154
|
+
function isOptional(value, guard) {
|
|
1155
|
+
return value === null || guard(value);
|
|
1156
|
+
}
|
|
1157
|
+
function isOkResponse(response) {
|
|
1158
|
+
return "ok" in response && !("err" in response);
|
|
1159
|
+
}
|
|
1160
|
+
function isErrResponse(response) {
|
|
1161
|
+
return "err" in response && !("ok" in response);
|
|
1162
|
+
}
|
|
1163
|
+
function isResponse(value, okGuard, errGuard) {
|
|
1164
|
+
if (typeof value !== "object" || value === null)
|
|
1165
|
+
return false;
|
|
1166
|
+
const obj = value;
|
|
1167
|
+
if ("ok" in value && !("err" in value))
|
|
1168
|
+
return okGuard(obj.ok);
|
|
1169
|
+
if ("err" in value && !("ok" in value))
|
|
1170
|
+
return errGuard(obj.err);
|
|
1171
|
+
return false;
|
|
1172
|
+
}
|
|
1173
|
+
function isAbiList(type) {
|
|
1174
|
+
return typeof type === "object" && type !== null && "list" in type;
|
|
1175
|
+
}
|
|
1176
|
+
function isAbiTuple(type) {
|
|
1177
|
+
return typeof type === "object" && type !== null && "tuple" in type;
|
|
1178
|
+
}
|
|
1179
|
+
function isAbiOptional(type) {
|
|
1180
|
+
return typeof type === "object" && type !== null && "optional" in type;
|
|
1181
|
+
}
|
|
1182
|
+
function isAbiResponse(type) {
|
|
1183
|
+
return typeof type === "object" && type !== null && "response" in type;
|
|
1184
|
+
}
|
|
1185
|
+
function isAbiBuffer(type) {
|
|
1186
|
+
return typeof type === "object" && type !== null && "buff" in type;
|
|
1187
|
+
}
|
|
1188
|
+
function isAbiStringAscii(type) {
|
|
1189
|
+
return typeof type === "object" && type !== null && "string-ascii" in type;
|
|
1190
|
+
}
|
|
1191
|
+
function isAbiStringUtf8(type) {
|
|
1192
|
+
return typeof type === "object" && type !== null && "string-utf8" in type;
|
|
1193
|
+
}
|
|
1194
|
+
function isAbiTraitReference(type) {
|
|
1195
|
+
return type === "trait_reference";
|
|
1196
|
+
}
|
|
1197
|
+
// src/clarity/abi/utils.ts
|
|
1198
|
+
function toCamelCase(str) {
|
|
1199
|
+
return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()).replace(/-([A-Z])/g, (_, letter) => letter).replace(/-(\d)/g, (_, digit) => digit).replace(/-/g, "").replace(/^\d/, "_$&");
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
// src/clarity/abi/converters.ts
|
|
1203
|
+
class ClarityConversionError extends Error {
|
|
1204
|
+
type;
|
|
1205
|
+
value;
|
|
1206
|
+
constructor(message, type, value) {
|
|
1207
|
+
super(message);
|
|
1208
|
+
this.type = type;
|
|
1209
|
+
this.value = value;
|
|
1210
|
+
this.name = "ClarityConversionError";
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
function jsToClarity(type, value) {
|
|
1214
|
+
if (type === "none")
|
|
1215
|
+
return null;
|
|
1216
|
+
if (type === "uint128") {
|
|
1217
|
+
if (!isUint128(value))
|
|
1218
|
+
throw new ClarityConversionError("Invalid uint128 value", type, value);
|
|
1219
|
+
return value;
|
|
1220
|
+
}
|
|
1221
|
+
if (type === "int128") {
|
|
1222
|
+
if (!isInt128(value))
|
|
1223
|
+
throw new ClarityConversionError("Invalid int128 value", type, value);
|
|
1224
|
+
return value;
|
|
1225
|
+
}
|
|
1226
|
+
if (type === "bool") {
|
|
1227
|
+
if (!isBool(value))
|
|
1228
|
+
throw new ClarityConversionError("Invalid bool value", type, value);
|
|
1229
|
+
return value;
|
|
1230
|
+
}
|
|
1231
|
+
if (type === "principal") {
|
|
1232
|
+
if (!isPrincipal(value))
|
|
1233
|
+
throw new ClarityConversionError("Invalid principal value", type, value);
|
|
1234
|
+
return value;
|
|
1235
|
+
}
|
|
1236
|
+
if (type === "trait_reference") {
|
|
1237
|
+
if (!isPrincipal(value))
|
|
1238
|
+
throw new ClarityConversionError("Invalid trait_reference value", type, value);
|
|
1239
|
+
return value;
|
|
1240
|
+
}
|
|
1241
|
+
if (isAbiStringAscii(type)) {
|
|
1242
|
+
if (!isString(value))
|
|
1243
|
+
throw new ClarityConversionError("Invalid string-ascii value", type, value);
|
|
1244
|
+
const str = value;
|
|
1245
|
+
for (let i = 0;i < str.length; i++) {
|
|
1246
|
+
if (str.charCodeAt(i) > 127) {
|
|
1247
|
+
throw new ClarityConversionError(`Non-ASCII character at position ${i}: '${str[i]}' (code ${str.charCodeAt(i)})`, type, value);
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
if (str.length > type["string-ascii"].length) {
|
|
1251
|
+
throw new ClarityConversionError(`String length ${str.length} exceeds max ${type["string-ascii"].length}`, type, value);
|
|
1252
|
+
}
|
|
1253
|
+
return value;
|
|
1254
|
+
}
|
|
1255
|
+
if (isAbiStringUtf8(type)) {
|
|
1256
|
+
if (!isString(value))
|
|
1257
|
+
throw new ClarityConversionError("Invalid string-utf8 value", type, value);
|
|
1258
|
+
const str = value;
|
|
1259
|
+
const byteLength = new TextEncoder().encode(str).length;
|
|
1260
|
+
if (byteLength > type["string-utf8"].length) {
|
|
1261
|
+
throw new ClarityConversionError(`String byte length ${byteLength} exceeds max ${type["string-utf8"].length}`, type, value);
|
|
1262
|
+
}
|
|
1263
|
+
return value;
|
|
1264
|
+
}
|
|
1265
|
+
if (isAbiBuffer(type)) {
|
|
1266
|
+
if (!isUint8Array(value))
|
|
1267
|
+
throw new ClarityConversionError("Invalid buffer value", type, value);
|
|
1268
|
+
const buff = value;
|
|
1269
|
+
if (buff.length > type.buff.length) {
|
|
1270
|
+
throw new ClarityConversionError(`Buffer length ${buff.length} exceeds max ${type.buff.length}`, type, value);
|
|
1271
|
+
}
|
|
1272
|
+
return value;
|
|
1273
|
+
}
|
|
1274
|
+
if (isAbiList(type)) {
|
|
1275
|
+
if (!Array.isArray(value))
|
|
1276
|
+
throw new ClarityConversionError("Expected array for list type", type, value);
|
|
1277
|
+
if (value.length > type.list.length) {
|
|
1278
|
+
throw new ClarityConversionError(`List length ${value.length} exceeds max ${type.list.length}`, type, value);
|
|
1279
|
+
}
|
|
1280
|
+
return value.map((item) => jsToClarity(type.list.type, item));
|
|
1281
|
+
}
|
|
1282
|
+
if (isAbiTuple(type)) {
|
|
1283
|
+
if (typeof value !== "object" || value === null)
|
|
1284
|
+
throw new ClarityConversionError("Expected object for tuple type", type, value);
|
|
1285
|
+
const result = {};
|
|
1286
|
+
for (const field of type.tuple) {
|
|
1287
|
+
const camelKey = toCamelCase(field.name);
|
|
1288
|
+
const hasOriginal = field.name in value;
|
|
1289
|
+
const hasCamel = camelKey in value;
|
|
1290
|
+
if (!hasOriginal && !hasCamel) {
|
|
1291
|
+
throw new ClarityConversionError(`Missing tuple field: ${field.name}`, type, value);
|
|
1292
|
+
}
|
|
1293
|
+
const fieldValue = hasOriginal ? value[field.name] : value[camelKey];
|
|
1294
|
+
result[field.name] = jsToClarity(field.type, fieldValue);
|
|
1295
|
+
}
|
|
1296
|
+
return result;
|
|
1297
|
+
}
|
|
1298
|
+
if (isAbiOptional(type)) {
|
|
1299
|
+
if (value === null || value === undefined)
|
|
1300
|
+
return null;
|
|
1301
|
+
return jsToClarity(type.optional, value);
|
|
1302
|
+
}
|
|
1303
|
+
if (isAbiResponse(type)) {
|
|
1304
|
+
if (typeof value !== "object" || value === null)
|
|
1305
|
+
throw new ClarityConversionError("Expected object for response type", type, value);
|
|
1306
|
+
const hasOk = "ok" in value;
|
|
1307
|
+
const hasErr = "err" in value;
|
|
1308
|
+
if (hasOk && !hasErr) {
|
|
1309
|
+
return {
|
|
1310
|
+
ok: jsToClarity(type.response.ok, value.ok)
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
if (hasErr && !hasOk) {
|
|
1314
|
+
return {
|
|
1315
|
+
err: jsToClarity(type.response.error, value.err)
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
throw new ClarityConversionError("Response must have exactly 'ok' or 'err' property", type, value);
|
|
1319
|
+
}
|
|
1320
|
+
throw new ClarityConversionError("Unknown Clarity type", type, value);
|
|
1321
|
+
}
|
|
1322
|
+
function prepareArgs(func, args) {
|
|
1323
|
+
return func.args.map((arg) => {
|
|
1324
|
+
if (!(arg.name in args)) {
|
|
1325
|
+
throw new ClarityConversionError(`Missing argument: ${arg.name}`, arg.type, undefined);
|
|
1326
|
+
}
|
|
1327
|
+
return jsToClarity(arg.type, args[arg.name]);
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
function validateArgs(func, args) {
|
|
1331
|
+
for (const arg of func.args) {
|
|
1332
|
+
if (!(arg.name in args)) {
|
|
1333
|
+
throw new ClarityConversionError(`Missing argument: ${arg.name}`, arg.type, undefined);
|
|
1334
|
+
}
|
|
1335
|
+
jsToClarity(arg.type, args[arg.name]);
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
function validateArgsArray(func, args) {
|
|
1339
|
+
if (args.length !== func.args.length) {
|
|
1340
|
+
throw new ClarityConversionError(`Expected ${func.args.length} arguments, got ${args.length}`, func.args[0]?.type ?? "bool", args);
|
|
1341
|
+
}
|
|
1342
|
+
func.args.forEach((arg, i) => {
|
|
1343
|
+
jsToClarity(arg.type, args[i]);
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
// src/clarity/abi/standards.ts
|
|
1347
|
+
var SIP010_ABI = {
|
|
1348
|
+
functions: [
|
|
1349
|
+
{
|
|
1350
|
+
name: "transfer",
|
|
1351
|
+
access: "public",
|
|
1352
|
+
args: [
|
|
1353
|
+
{ name: "amount", type: "uint128" },
|
|
1354
|
+
{ name: "sender", type: "principal" },
|
|
1355
|
+
{ name: "recipient", type: "principal" },
|
|
1356
|
+
{ name: "memo", type: { optional: { buff: { length: 34 } } } }
|
|
1357
|
+
],
|
|
1358
|
+
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
1359
|
+
},
|
|
1360
|
+
{
|
|
1361
|
+
name: "get-balance",
|
|
1362
|
+
access: "read-only",
|
|
1363
|
+
args: [{ name: "account", type: "principal" }],
|
|
1364
|
+
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
1365
|
+
},
|
|
1366
|
+
{
|
|
1367
|
+
name: "get-total-supply",
|
|
1368
|
+
access: "read-only",
|
|
1369
|
+
args: [],
|
|
1370
|
+
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
1371
|
+
},
|
|
1372
|
+
{
|
|
1373
|
+
name: "get-name",
|
|
1374
|
+
access: "read-only",
|
|
1375
|
+
args: [],
|
|
1376
|
+
outputs: {
|
|
1377
|
+
response: {
|
|
1378
|
+
ok: { "string-ascii": { length: 32 } },
|
|
1379
|
+
error: "uint128"
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
},
|
|
1383
|
+
{
|
|
1384
|
+
name: "get-symbol",
|
|
1385
|
+
access: "read-only",
|
|
1386
|
+
args: [],
|
|
1387
|
+
outputs: {
|
|
1388
|
+
response: {
|
|
1389
|
+
ok: { "string-ascii": { length: 10 } },
|
|
1390
|
+
error: "uint128"
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
},
|
|
1394
|
+
{
|
|
1395
|
+
name: "get-decimals",
|
|
1396
|
+
access: "read-only",
|
|
1397
|
+
args: [],
|
|
1398
|
+
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
1399
|
+
},
|
|
1400
|
+
{
|
|
1401
|
+
name: "get-token-uri",
|
|
1402
|
+
access: "read-only",
|
|
1403
|
+
args: [],
|
|
1404
|
+
outputs: {
|
|
1405
|
+
response: {
|
|
1406
|
+
ok: { optional: { "string-utf8": { length: 256 } } },
|
|
1407
|
+
error: "uint128"
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
],
|
|
1412
|
+
fungible_tokens: [{ name: "token" }]
|
|
1413
|
+
};
|
|
1414
|
+
var SIP009_ABI = {
|
|
1415
|
+
functions: [
|
|
1416
|
+
{
|
|
1417
|
+
name: "transfer",
|
|
1418
|
+
access: "public",
|
|
1419
|
+
args: [
|
|
1420
|
+
{ name: "id", type: "uint128" },
|
|
1421
|
+
{ name: "sender", type: "principal" },
|
|
1422
|
+
{ name: "recipient", type: "principal" }
|
|
1423
|
+
],
|
|
1424
|
+
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
1425
|
+
},
|
|
1426
|
+
{
|
|
1427
|
+
name: "get-owner",
|
|
1428
|
+
access: "read-only",
|
|
1429
|
+
args: [{ name: "id", type: "uint128" }],
|
|
1430
|
+
outputs: {
|
|
1431
|
+
response: { ok: { optional: "principal" }, error: "uint128" }
|
|
1432
|
+
}
|
|
1433
|
+
},
|
|
1434
|
+
{
|
|
1435
|
+
name: "get-last-token-id",
|
|
1436
|
+
access: "read-only",
|
|
1437
|
+
args: [],
|
|
1438
|
+
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
1439
|
+
},
|
|
1440
|
+
{
|
|
1441
|
+
name: "get-token-uri",
|
|
1442
|
+
access: "read-only",
|
|
1443
|
+
args: [{ name: "id", type: "uint128" }],
|
|
1444
|
+
outputs: {
|
|
1445
|
+
response: {
|
|
1446
|
+
ok: { optional: { "string-utf8": { length: 256 } } },
|
|
1447
|
+
error: "uint128"
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
],
|
|
1452
|
+
non_fungible_tokens: [{ name: "nft", type: "uint128" }]
|
|
1453
|
+
};
|
|
1454
|
+
var SIP013_ABI = {
|
|
1455
|
+
functions: [
|
|
1456
|
+
{
|
|
1457
|
+
name: "transfer",
|
|
1458
|
+
access: "public",
|
|
1459
|
+
args: [
|
|
1460
|
+
{ name: "token-id", type: "uint128" },
|
|
1461
|
+
{ name: "amount", type: "uint128" },
|
|
1462
|
+
{ name: "sender", type: "principal" },
|
|
1463
|
+
{ name: "recipient", type: "principal" }
|
|
1464
|
+
],
|
|
1465
|
+
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
1466
|
+
},
|
|
1467
|
+
{
|
|
1468
|
+
name: "transfer-memo",
|
|
1469
|
+
access: "public",
|
|
1470
|
+
args: [
|
|
1471
|
+
{ name: "token-id", type: "uint128" },
|
|
1472
|
+
{ name: "amount", type: "uint128" },
|
|
1473
|
+
{ name: "sender", type: "principal" },
|
|
1474
|
+
{ name: "recipient", type: "principal" },
|
|
1475
|
+
{ name: "memo", type: { buff: { length: 34 } } }
|
|
1476
|
+
],
|
|
1477
|
+
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
1478
|
+
},
|
|
1479
|
+
{
|
|
1480
|
+
name: "transfer-many",
|
|
1481
|
+
access: "public",
|
|
1482
|
+
args: [
|
|
1483
|
+
{
|
|
1484
|
+
name: "transfers",
|
|
1485
|
+
type: {
|
|
1486
|
+
list: {
|
|
1487
|
+
type: {
|
|
1488
|
+
tuple: [
|
|
1489
|
+
{ name: "token-id", type: "uint128" },
|
|
1490
|
+
{ name: "amount", type: "uint128" },
|
|
1491
|
+
{ name: "sender", type: "principal" },
|
|
1492
|
+
{ name: "recipient", type: "principal" }
|
|
1493
|
+
]
|
|
1494
|
+
},
|
|
1495
|
+
length: 200
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
],
|
|
1500
|
+
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
1501
|
+
},
|
|
1502
|
+
{
|
|
1503
|
+
name: "transfer-many-memo",
|
|
1504
|
+
access: "public",
|
|
1505
|
+
args: [
|
|
1506
|
+
{
|
|
1507
|
+
name: "transfers",
|
|
1508
|
+
type: {
|
|
1509
|
+
list: {
|
|
1510
|
+
type: {
|
|
1511
|
+
tuple: [
|
|
1512
|
+
{ name: "token-id", type: "uint128" },
|
|
1513
|
+
{ name: "amount", type: "uint128" },
|
|
1514
|
+
{ name: "sender", type: "principal" },
|
|
1515
|
+
{ name: "recipient", type: "principal" },
|
|
1516
|
+
{ name: "memo", type: { buff: { length: 34 } } }
|
|
1517
|
+
]
|
|
1518
|
+
},
|
|
1519
|
+
length: 200
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
],
|
|
1524
|
+
outputs: { response: { ok: "bool", error: "uint128" } }
|
|
1525
|
+
},
|
|
1526
|
+
{
|
|
1527
|
+
name: "get-balance",
|
|
1528
|
+
access: "read-only",
|
|
1529
|
+
args: [
|
|
1530
|
+
{ name: "token-id", type: "uint128" },
|
|
1531
|
+
{ name: "account", type: "principal" }
|
|
1532
|
+
],
|
|
1533
|
+
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
1534
|
+
},
|
|
1535
|
+
{
|
|
1536
|
+
name: "get-overall-balance",
|
|
1537
|
+
access: "read-only",
|
|
1538
|
+
args: [{ name: "account", type: "principal" }],
|
|
1539
|
+
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
1540
|
+
},
|
|
1541
|
+
{
|
|
1542
|
+
name: "get-total-supply",
|
|
1543
|
+
access: "read-only",
|
|
1544
|
+
args: [{ name: "token-id", type: "uint128" }],
|
|
1545
|
+
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
1546
|
+
},
|
|
1547
|
+
{
|
|
1548
|
+
name: "get-overall-supply",
|
|
1549
|
+
access: "read-only",
|
|
1550
|
+
args: [],
|
|
1551
|
+
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
1552
|
+
},
|
|
1553
|
+
{
|
|
1554
|
+
name: "get-decimals",
|
|
1555
|
+
access: "read-only",
|
|
1556
|
+
args: [{ name: "token-id", type: "uint128" }],
|
|
1557
|
+
outputs: { response: { ok: "uint128", error: "uint128" } }
|
|
1558
|
+
},
|
|
1559
|
+
{
|
|
1560
|
+
name: "get-token-uri",
|
|
1561
|
+
access: "read-only",
|
|
1562
|
+
args: [{ name: "token-id", type: "uint128" }],
|
|
1563
|
+
outputs: {
|
|
1564
|
+
response: {
|
|
1565
|
+
ok: { optional: { "string-utf8": { length: 256 } } },
|
|
1566
|
+
error: "uint128"
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
],
|
|
1571
|
+
fungible_tokens: [],
|
|
1572
|
+
non_fungible_tokens: []
|
|
1573
|
+
};
|
|
1574
|
+
var sip010Abi = SIP010_ABI;
|
|
1575
|
+
var sip009Abi = SIP009_ABI;
|
|
1576
|
+
var sip013Abi = SIP013_ABI;
|
|
1577
|
+
// src/clarity/abi/classify.ts
|
|
1578
|
+
var TRAIT_STANDARDS = ["sip-009", "sip-010", "sip-013"];
|
|
1579
|
+
var STANDARDS = [
|
|
1580
|
+
{ id: "sip-010", abi: SIP010_ABI, optional: new Set(["get-token-uri"]) },
|
|
1581
|
+
{ id: "sip-009", abi: SIP009_ABI, optional: new Set(["get-token-uri"]) },
|
|
1582
|
+
{
|
|
1583
|
+
id: "sip-013",
|
|
1584
|
+
abi: SIP013_ABI,
|
|
1585
|
+
optional: new Set([
|
|
1586
|
+
"transfer-memo",
|
|
1587
|
+
"transfer-many",
|
|
1588
|
+
"transfer-many-memo",
|
|
1589
|
+
"get-token-uri",
|
|
1590
|
+
"get-overall-balance",
|
|
1591
|
+
"get-overall-supply"
|
|
1592
|
+
])
|
|
1593
|
+
}
|
|
1594
|
+
];
|
|
1595
|
+
function indexByName(abi) {
|
|
1596
|
+
const m = new Map;
|
|
1597
|
+
for (const f of abi.functions)
|
|
1598
|
+
m.set(f.name, f);
|
|
1599
|
+
return m;
|
|
1600
|
+
}
|
|
1601
|
+
function conformsTo(candidate, spec) {
|
|
1602
|
+
const fns = indexByName(candidate);
|
|
1603
|
+
for (const required of spec.abi.functions) {
|
|
1604
|
+
if (spec.optional.has(required.name))
|
|
1605
|
+
continue;
|
|
1606
|
+
const got = fns.get(required.name);
|
|
1607
|
+
if (!got)
|
|
1608
|
+
return false;
|
|
1609
|
+
if (got.access !== required.access)
|
|
1610
|
+
return false;
|
|
1611
|
+
if (got.args.length !== required.args.length)
|
|
1612
|
+
return false;
|
|
1613
|
+
}
|
|
1614
|
+
return true;
|
|
1615
|
+
}
|
|
1616
|
+
function classifyContract(abi) {
|
|
1617
|
+
if (!abi || !Array.isArray(abi.functions))
|
|
1618
|
+
return [];
|
|
1619
|
+
return STANDARDS.filter((s) => conformsTo(abi, s)).map((s) => s.id);
|
|
1620
|
+
}
|
|
1621
|
+
function parseDeclaredStandards(claritySource) {
|
|
1622
|
+
const out = new Set;
|
|
1623
|
+
const matches = claritySource.matchAll(/\(impl-trait\s+[^)]+\)/gi);
|
|
1624
|
+
for (const m of matches) {
|
|
1625
|
+
const ref = m[0].toLowerCase();
|
|
1626
|
+
if (ref.includes("sip-010") || ref.includes(".ft-trait"))
|
|
1627
|
+
out.add("sip-010");
|
|
1628
|
+
if (ref.includes("sip-009") || ref.includes("nft-trait"))
|
|
1629
|
+
out.add("sip-009");
|
|
1630
|
+
if (ref.includes("sip-013") || ref.includes("semi-fungible"))
|
|
1631
|
+
out.add("sip-013");
|
|
1632
|
+
}
|
|
1633
|
+
return [...out];
|
|
1634
|
+
}
|
|
1635
|
+
// src/clarity/abi/normalize.ts
|
|
1636
|
+
function normalizeAccess(access) {
|
|
1637
|
+
if (access === "read_only")
|
|
1638
|
+
return "read-only";
|
|
1639
|
+
return access;
|
|
1640
|
+
}
|
|
1641
|
+
function normalizeType(type) {
|
|
1642
|
+
if (typeof type === "string") {
|
|
1643
|
+
switch (type) {
|
|
1644
|
+
case "uint128":
|
|
1645
|
+
case "int128":
|
|
1646
|
+
case "bool":
|
|
1647
|
+
case "principal":
|
|
1648
|
+
case "trait_reference":
|
|
1649
|
+
return type;
|
|
1650
|
+
default:
|
|
1651
|
+
return type;
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
if (typeof type !== "object" || type === null) {
|
|
1655
|
+
throw new Error(`Invalid ABI type: expected object, got ${typeof type}`);
|
|
1656
|
+
}
|
|
1657
|
+
const typeObj = type;
|
|
1658
|
+
if ("buffer" in typeObj) {
|
|
1659
|
+
const buffer = typeObj.buffer;
|
|
1660
|
+
return {
|
|
1661
|
+
buff: {
|
|
1662
|
+
length: buffer?.length ?? 32
|
|
1663
|
+
}
|
|
1664
|
+
};
|
|
1665
|
+
}
|
|
1666
|
+
if ("buff" in typeObj) {
|
|
1667
|
+
const buff = typeObj.buff;
|
|
1668
|
+
return {
|
|
1669
|
+
buff: {
|
|
1670
|
+
length: buff?.length ?? 32
|
|
1671
|
+
}
|
|
1672
|
+
};
|
|
1673
|
+
}
|
|
1674
|
+
if ("string-ascii" in typeObj) {
|
|
1675
|
+
const strAscii = typeObj["string-ascii"];
|
|
1676
|
+
return {
|
|
1677
|
+
"string-ascii": {
|
|
1678
|
+
length: strAscii?.length ?? 256
|
|
1679
|
+
}
|
|
1680
|
+
};
|
|
1681
|
+
}
|
|
1682
|
+
if ("string-utf8" in typeObj) {
|
|
1683
|
+
const strUtf8 = typeObj["string-utf8"];
|
|
1684
|
+
return {
|
|
1685
|
+
"string-utf8": {
|
|
1686
|
+
length: strUtf8?.length ?? 256
|
|
1687
|
+
}
|
|
1688
|
+
};
|
|
1689
|
+
}
|
|
1690
|
+
if ("response" in typeObj) {
|
|
1691
|
+
const response = typeObj.response;
|
|
1692
|
+
return {
|
|
1693
|
+
response: {
|
|
1694
|
+
ok: normalizeType(response?.ok ?? "bool"),
|
|
1695
|
+
error: normalizeType(response?.error ?? "uint128")
|
|
1696
|
+
}
|
|
1697
|
+
};
|
|
1698
|
+
}
|
|
1699
|
+
if ("optional" in typeObj) {
|
|
1700
|
+
return {
|
|
1701
|
+
optional: normalizeType(typeObj.optional)
|
|
1702
|
+
};
|
|
1703
|
+
}
|
|
1704
|
+
if ("list" in typeObj) {
|
|
1705
|
+
const list = typeObj.list;
|
|
1706
|
+
return {
|
|
1707
|
+
list: {
|
|
1708
|
+
type: normalizeType(list?.type ?? "uint128"),
|
|
1709
|
+
length: list?.length ?? 100
|
|
1710
|
+
}
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
if ("tuple" in typeObj) {
|
|
1714
|
+
const tuple = typeObj.tuple;
|
|
1715
|
+
return {
|
|
1716
|
+
tuple: tuple.map((field) => ({
|
|
1717
|
+
name: field.name,
|
|
1718
|
+
type: normalizeType(field.type)
|
|
1719
|
+
}))
|
|
1720
|
+
};
|
|
1721
|
+
}
|
|
1722
|
+
throw new Error(`Unknown ABI type structure: ${JSON.stringify(type)}`);
|
|
1723
|
+
}
|
|
1724
|
+
function normalizeFunction(func) {
|
|
1725
|
+
const access = normalizeAccess(func.access);
|
|
1726
|
+
const args = func.args ?? [];
|
|
1727
|
+
const outputs = func.outputs;
|
|
1728
|
+
return {
|
|
1729
|
+
name: func.name,
|
|
1730
|
+
access,
|
|
1731
|
+
args: args.map((arg) => ({
|
|
1732
|
+
name: arg.name,
|
|
1733
|
+
type: normalizeType(arg.type)
|
|
1734
|
+
})),
|
|
1735
|
+
outputs: normalizeType(typeof outputs === "object" && outputs !== null && "type" in outputs ? outputs.type : outputs)
|
|
1736
|
+
};
|
|
1737
|
+
}
|
|
1738
|
+
function normalizeMap(map) {
|
|
1739
|
+
return {
|
|
1740
|
+
name: map.name,
|
|
1741
|
+
key: normalizeType(map.key),
|
|
1742
|
+
value: normalizeType(map.value)
|
|
1743
|
+
};
|
|
1744
|
+
}
|
|
1745
|
+
function normalizeVariable(variable) {
|
|
1746
|
+
return {
|
|
1747
|
+
name: variable.name,
|
|
1748
|
+
type: normalizeType(variable.type),
|
|
1749
|
+
access: variable.access
|
|
1750
|
+
};
|
|
1751
|
+
}
|
|
1752
|
+
function normalizeFungibleToken(token) {
|
|
1753
|
+
return { name: token.name };
|
|
1754
|
+
}
|
|
1755
|
+
function normalizeNonFungibleToken(token) {
|
|
1756
|
+
return { name: token.name, type: normalizeType(token.type) };
|
|
1757
|
+
}
|
|
1758
|
+
function normalizeTraitDefinition(trait) {
|
|
1759
|
+
const rawFunctions = Array.isArray(trait.functions) ? trait.functions : [];
|
|
1760
|
+
const functions = [];
|
|
1761
|
+
for (const func of rawFunctions) {
|
|
1762
|
+
if (typeof func !== "object" || func === null)
|
|
1763
|
+
continue;
|
|
1764
|
+
const normalized = normalizeFunction(func);
|
|
1765
|
+
if (normalized.access === "private")
|
|
1766
|
+
continue;
|
|
1767
|
+
functions.push(normalized);
|
|
1768
|
+
}
|
|
1769
|
+
return { name: trait.name, functions };
|
|
1770
|
+
}
|
|
1771
|
+
function normalizeAbi(abi) {
|
|
1772
|
+
if (typeof abi !== "object" || abi === null) {
|
|
1773
|
+
return { functions: [] };
|
|
1774
|
+
}
|
|
1775
|
+
const abiObj = abi;
|
|
1776
|
+
const functions = [];
|
|
1777
|
+
const maps = [];
|
|
1778
|
+
const variables = [];
|
|
1779
|
+
const fungibleTokens = [];
|
|
1780
|
+
const nonFungibleTokens = [];
|
|
1781
|
+
const implementedTraits = [];
|
|
1782
|
+
const definedTraits = [];
|
|
1783
|
+
if (Array.isArray(abiObj.functions)) {
|
|
1784
|
+
for (const func of abiObj.functions) {
|
|
1785
|
+
if (typeof func === "object" && func !== null) {
|
|
1786
|
+
functions.push(normalizeFunction(func));
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
if (Array.isArray(abiObj.maps)) {
|
|
1791
|
+
for (const map of abiObj.maps) {
|
|
1792
|
+
if (typeof map === "object" && map !== null) {
|
|
1793
|
+
maps.push(normalizeMap(map));
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
if (Array.isArray(abiObj.variables)) {
|
|
1798
|
+
for (const variable of abiObj.variables) {
|
|
1799
|
+
if (typeof variable === "object" && variable !== null) {
|
|
1800
|
+
variables.push(normalizeVariable(variable));
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
if (Array.isArray(abiObj.fungible_tokens)) {
|
|
1805
|
+
for (const token of abiObj.fungible_tokens) {
|
|
1806
|
+
if (typeof token === "object" && token !== null) {
|
|
1807
|
+
fungibleTokens.push(normalizeFungibleToken(token));
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
if (Array.isArray(abiObj.non_fungible_tokens)) {
|
|
1812
|
+
for (const token of abiObj.non_fungible_tokens) {
|
|
1813
|
+
if (typeof token === "object" && token !== null) {
|
|
1814
|
+
nonFungibleTokens.push(normalizeNonFungibleToken(token));
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
if (Array.isArray(abiObj.implemented_traits)) {
|
|
1819
|
+
for (const trait of abiObj.implemented_traits) {
|
|
1820
|
+
if (typeof trait === "string")
|
|
1821
|
+
implementedTraits.push(trait);
|
|
1822
|
+
}
|
|
1823
|
+
}
|
|
1824
|
+
if (Array.isArray(abiObj.defined_traits)) {
|
|
1825
|
+
for (const trait of abiObj.defined_traits) {
|
|
1826
|
+
if (typeof trait === "object" && trait !== null) {
|
|
1827
|
+
definedTraits.push(normalizeTraitDefinition(trait));
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
}
|
|
1831
|
+
return {
|
|
1832
|
+
functions,
|
|
1833
|
+
maps: maps.length > 0 ? maps : undefined,
|
|
1834
|
+
variables: variables.length > 0 ? variables : undefined,
|
|
1835
|
+
fungible_tokens: fungibleTokens.length > 0 ? fungibleTokens : undefined,
|
|
1836
|
+
non_fungible_tokens: nonFungibleTokens.length > 0 ? nonFungibleTokens : undefined,
|
|
1837
|
+
implemented_traits: implementedTraits.length > 0 ? implementedTraits : undefined,
|
|
1838
|
+
defined_traits: definedTraits.length > 0 ? definedTraits : undefined
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
// src/clarity/bridge.ts
|
|
1842
|
+
var CV_TYPE_TAGS = new Set([
|
|
1843
|
+
"int",
|
|
1844
|
+
"uint",
|
|
1845
|
+
"true",
|
|
1846
|
+
"false",
|
|
1847
|
+
"address",
|
|
1848
|
+
"contract",
|
|
1849
|
+
"ascii",
|
|
1850
|
+
"utf8",
|
|
1851
|
+
"buffer",
|
|
1852
|
+
"list",
|
|
1853
|
+
"tuple",
|
|
1854
|
+
"none",
|
|
1855
|
+
"some",
|
|
1856
|
+
"ok",
|
|
1857
|
+
"err"
|
|
1858
|
+
]);
|
|
1859
|
+
function isClarityValue(value) {
|
|
1860
|
+
if (typeof value !== "object" || value === null)
|
|
1861
|
+
return false;
|
|
1862
|
+
const type = value.type;
|
|
1863
|
+
if (typeof type !== "string" || !CV_TYPE_TAGS.has(type))
|
|
1864
|
+
return false;
|
|
1865
|
+
if (type === "true" || type === "false" || type === "none")
|
|
1866
|
+
return true;
|
|
1867
|
+
return "value" in value;
|
|
1868
|
+
}
|
|
1869
|
+
var HEX_PAIRS_REGEX = /^(?:[0-9a-fA-F]{2})+$/;
|
|
1870
|
+
function coerceBuffer(value) {
|
|
1871
|
+
if (value instanceof Uint8Array)
|
|
1872
|
+
return bufferCV(value);
|
|
1873
|
+
if (typeof value === "object" && value !== null && "type" in value) {
|
|
1874
|
+
const tagged = value;
|
|
1875
|
+
if (tagged.type === "buffer" && isClarityValue(value))
|
|
1876
|
+
return value;
|
|
1877
|
+
if (typeof tagged.value === "string") {
|
|
1878
|
+
if (tagged.type === "ascii")
|
|
1879
|
+
return Cl.bufferFromAscii(tagged.value);
|
|
1880
|
+
if (tagged.type === "utf8")
|
|
1881
|
+
return Cl.bufferFromUtf8(tagged.value);
|
|
1882
|
+
if (tagged.type === "hex")
|
|
1883
|
+
return Cl.bufferFromHex(tagged.value);
|
|
1884
|
+
}
|
|
1885
|
+
throw new Error(`Unsupported buffer input: ${JSON.stringify(value)}`);
|
|
1886
|
+
}
|
|
1887
|
+
if (typeof value === "string") {
|
|
1888
|
+
const hex = value.startsWith("0x") ? value.slice(2) : value;
|
|
1889
|
+
if (HEX_PAIRS_REGEX.test(hex))
|
|
1890
|
+
return Cl.bufferFromHex(hex);
|
|
1891
|
+
return Cl.bufferFromUtf8(value);
|
|
1892
|
+
}
|
|
1893
|
+
throw new Error("buffer arg expects Uint8Array, hex string, { type, value }, or BufferCV");
|
|
1894
|
+
}
|
|
1895
|
+
function jsToClarityValue(abiType, value) {
|
|
1896
|
+
if (isAbiBuffer(abiType))
|
|
1897
|
+
return coerceBuffer(value);
|
|
1898
|
+
if (isClarityValue(value))
|
|
1899
|
+
return value;
|
|
1900
|
+
if (abiType === "uint128")
|
|
1901
|
+
return uintCV(value);
|
|
1902
|
+
if (abiType === "int128")
|
|
1903
|
+
return intCV(value);
|
|
1904
|
+
if (abiType === "bool")
|
|
1905
|
+
return boolCV(value);
|
|
1906
|
+
if (abiType === "principal" || abiType === "trait_reference")
|
|
1907
|
+
return Cl.principal(value);
|
|
1908
|
+
if (isAbiStringAscii(abiType))
|
|
1909
|
+
return stringAsciiCV(value);
|
|
1910
|
+
if (isAbiStringUtf8(abiType))
|
|
1911
|
+
return stringUtf8CV(value);
|
|
1912
|
+
if (isAbiList(abiType)) {
|
|
1913
|
+
const arr = value;
|
|
1914
|
+
return listCV(arr.map((item) => jsToClarityValue(abiType.list.type, item)));
|
|
1915
|
+
}
|
|
1916
|
+
if (isAbiTuple(abiType)) {
|
|
1917
|
+
const obj = value;
|
|
1918
|
+
const data = {};
|
|
1919
|
+
for (const field of abiType.tuple) {
|
|
1920
|
+
const camelKey = toCamelCase(field.name);
|
|
1921
|
+
const hasOriginal = field.name in obj;
|
|
1922
|
+
const hasCamel = camelKey in obj;
|
|
1923
|
+
const fieldValue = hasOriginal ? obj[field.name] : hasCamel ? obj[camelKey] : undefined;
|
|
1924
|
+
if (fieldValue === undefined && !isAbiOptional(field.type)) {
|
|
1925
|
+
throw new Error(`Missing tuple field: ${field.name}`);
|
|
1926
|
+
}
|
|
1927
|
+
data[field.name] = jsToClarityValue(field.type, fieldValue);
|
|
1928
|
+
}
|
|
1929
|
+
return tupleCV(data);
|
|
1930
|
+
}
|
|
1931
|
+
if (isAbiOptional(abiType)) {
|
|
1932
|
+
if (value === null || value === undefined)
|
|
1933
|
+
return noneCV();
|
|
1934
|
+
return someCV(jsToClarityValue(abiType.optional, value));
|
|
1935
|
+
}
|
|
1936
|
+
if (isAbiResponse(abiType)) {
|
|
1937
|
+
const obj = value;
|
|
1938
|
+
if ("ok" in obj && !("err" in obj))
|
|
1939
|
+
return responseOkCV(jsToClarityValue(abiType.response.ok, obj.ok));
|
|
1940
|
+
if ("err" in obj && !("ok" in obj))
|
|
1941
|
+
return responseErrorCV(jsToClarityValue(abiType.response.error, obj.err));
|
|
1942
|
+
throw new Error("Response must have exactly 'ok' or 'err' property");
|
|
1943
|
+
}
|
|
1944
|
+
throw new Error(`Unknown ABI type: ${JSON.stringify(abiType)}`);
|
|
1945
|
+
}
|
|
1946
|
+
function clarityValueToJS(abiType, cv) {
|
|
1947
|
+
return clarityValueToJSInner(abiType, cv);
|
|
1948
|
+
}
|
|
1949
|
+
function clarityValueToJSUntyped(abiType, cv) {
|
|
1950
|
+
return clarityValueToJSInner(abiType, cv);
|
|
1951
|
+
}
|
|
1952
|
+
function clarityValueToJSInner(abiType, cv) {
|
|
1953
|
+
if (abiType === "uint128" || abiType === "int128") {
|
|
1954
|
+
if (cv.type !== "int" && cv.type !== "uint")
|
|
1955
|
+
throw new Error(`Expected int/uint CV, got ${cv.type}`);
|
|
1956
|
+
return cv.value;
|
|
1957
|
+
}
|
|
1958
|
+
if (abiType === "bool") {
|
|
1959
|
+
if (cv.type === "true")
|
|
1960
|
+
return true;
|
|
1961
|
+
if (cv.type === "false")
|
|
1962
|
+
return false;
|
|
1963
|
+
throw new Error(`Expected bool CV, got ${cv.type}`);
|
|
1964
|
+
}
|
|
1965
|
+
if (abiType === "principal" || abiType === "trait_reference") {
|
|
1966
|
+
if (cv.type !== "address" && cv.type !== "contract")
|
|
1967
|
+
throw new Error(`Expected principal CV, got ${cv.type}`);
|
|
1968
|
+
return cv.value;
|
|
1969
|
+
}
|
|
1970
|
+
if (isAbiStringAscii(abiType) || isAbiStringUtf8(abiType)) {
|
|
1971
|
+
if (cv.type !== "ascii" && cv.type !== "utf8")
|
|
1972
|
+
throw new Error(`Expected string CV, got ${cv.type}`);
|
|
1973
|
+
return cv.value;
|
|
1974
|
+
}
|
|
1975
|
+
if (isAbiBuffer(abiType)) {
|
|
1976
|
+
if (cv.type !== "buffer")
|
|
1977
|
+
throw new Error(`Expected buffer CV, got ${cv.type}`);
|
|
1978
|
+
const hex = cv.value;
|
|
1979
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
1980
|
+
for (let i = 0;i < bytes.length; i++) {
|
|
1981
|
+
bytes[i] = Number.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
|
1982
|
+
}
|
|
1983
|
+
return bytes;
|
|
1984
|
+
}
|
|
1985
|
+
if (isAbiList(abiType)) {
|
|
1986
|
+
if (cv.type !== "list")
|
|
1987
|
+
throw new Error(`Expected list CV, got ${cv.type}`);
|
|
1988
|
+
return cv.value.map((item) => clarityValueToJSInner(abiType.list.type, item));
|
|
1989
|
+
}
|
|
1990
|
+
if (isAbiTuple(abiType)) {
|
|
1991
|
+
if (cv.type !== "tuple")
|
|
1992
|
+
throw new Error(`Expected tuple CV, got ${cv.type}`);
|
|
1993
|
+
const result = {};
|
|
1994
|
+
for (const field of abiType.tuple) {
|
|
1995
|
+
const fieldCV = cv.value[field.name];
|
|
1996
|
+
if (!fieldCV)
|
|
1997
|
+
throw new Error(`Missing tuple field in CV: ${field.name}`);
|
|
1998
|
+
const camelKey = toCamelCase(field.name);
|
|
1999
|
+
result[camelKey] = clarityValueToJSInner(field.type, fieldCV);
|
|
2000
|
+
}
|
|
2001
|
+
return result;
|
|
2002
|
+
}
|
|
2003
|
+
if (isAbiOptional(abiType)) {
|
|
2004
|
+
if (cv.type === "none")
|
|
2005
|
+
return null;
|
|
2006
|
+
if (cv.type === "some")
|
|
2007
|
+
return clarityValueToJSInner(abiType.optional, cv.value);
|
|
2008
|
+
throw new Error(`Expected optional CV, got ${cv.type}`);
|
|
2009
|
+
}
|
|
2010
|
+
if (isAbiResponse(abiType)) {
|
|
2011
|
+
if (cv.type === "ok")
|
|
2012
|
+
return { ok: clarityValueToJSInner(abiType.response.ok, cv.value) };
|
|
2013
|
+
if (cv.type === "err")
|
|
2014
|
+
return { err: clarityValueToJSInner(abiType.response.error, cv.value) };
|
|
2015
|
+
throw new Error(`Expected response CV, got ${cv.type}`);
|
|
2016
|
+
}
|
|
2017
|
+
throw new Error(`Unknown ABI type: ${JSON.stringify(abiType)}`);
|
|
2018
|
+
}
|
|
2019
|
+
// src/postconditions/index.ts
|
|
2020
|
+
var exports_postconditions = {};
|
|
2021
|
+
__export(exports_postconditions, {
|
|
2022
|
+
wireToPostCondition: () => wireToPostCondition,
|
|
2023
|
+
postConditionToHex: () => postConditionToHex,
|
|
2024
|
+
parsePostConditionAmount: () => parsePostConditionAmount,
|
|
2025
|
+
fromHex: () => fromHex,
|
|
2026
|
+
Pc: () => Pc
|
|
2027
|
+
});
|
|
2028
|
+
module.exports = __toCommonJS(exports_postconditions);
|
|
2029
|
+
|
|
2030
|
+
// src/transactions/types.ts
|
|
2031
|
+
var AuthType = {
|
|
2032
|
+
Standard: 4,
|
|
2033
|
+
Sponsored: 5
|
|
2034
|
+
};
|
|
2035
|
+
var PayloadType = {
|
|
2036
|
+
TokenTransfer: 0,
|
|
2037
|
+
SmartContract: 1,
|
|
2038
|
+
ContractCall: 2,
|
|
2039
|
+
PoisonMicroblock: 3,
|
|
2040
|
+
Coinbase: 4,
|
|
2041
|
+
CoinbaseToAltRecipient: 5,
|
|
2042
|
+
VersionedSmartContract: 6,
|
|
2043
|
+
TenureChange: 7,
|
|
2044
|
+
NakamotoCoinbase: 8
|
|
2045
|
+
};
|
|
2046
|
+
var ClarityVersion = {
|
|
2047
|
+
Clarity1: 1,
|
|
2048
|
+
Clarity2: 2,
|
|
2049
|
+
Clarity3: 3,
|
|
2050
|
+
Clarity4: 4,
|
|
2051
|
+
Clarity5: 5,
|
|
2052
|
+
Clarity6: 6
|
|
2053
|
+
};
|
|
2054
|
+
var AnchorMode = {
|
|
2055
|
+
OnChainOnly: 1,
|
|
2056
|
+
OffChainOnly: 2,
|
|
2057
|
+
Any: 3
|
|
2058
|
+
};
|
|
2059
|
+
var PostConditionModeWire = {
|
|
2060
|
+
Allow: 1,
|
|
2061
|
+
Deny: 2,
|
|
2062
|
+
Originator: 3
|
|
2063
|
+
};
|
|
2064
|
+
var AddressHashMode = {
|
|
2065
|
+
P2PKH: 0,
|
|
2066
|
+
P2SH: 1,
|
|
2067
|
+
P2WPKH: 2,
|
|
2068
|
+
P2WSH: 3,
|
|
2069
|
+
P2SH_NonSequential: 5,
|
|
2070
|
+
P2WSH_P2SH_NonSequential: 7
|
|
2071
|
+
};
|
|
2072
|
+
var PubKeyEncoding = {
|
|
2073
|
+
Compressed: 0,
|
|
2074
|
+
Uncompressed: 1
|
|
2075
|
+
};
|
|
2076
|
+
var FungibleConditionCode = {
|
|
2077
|
+
Equal: 1,
|
|
2078
|
+
Greater: 2,
|
|
2079
|
+
GreaterEqual: 3,
|
|
2080
|
+
Less: 4,
|
|
2081
|
+
LessEqual: 5
|
|
2082
|
+
};
|
|
2083
|
+
var NonFungibleConditionCode = {
|
|
2084
|
+
Sends: 16,
|
|
2085
|
+
DoesNotSend: 17,
|
|
2086
|
+
MaybeSent: 18
|
|
2087
|
+
};
|
|
2088
|
+
var PoxConditionCode = {
|
|
2089
|
+
WillNotPerform: 48,
|
|
2090
|
+
MayPerform: 49,
|
|
2091
|
+
WillPerform: 50
|
|
2092
|
+
};
|
|
2093
|
+
var PostConditionPrincipalId = {
|
|
2094
|
+
Origin: 1,
|
|
2095
|
+
Standard: 2,
|
|
2096
|
+
Contract: 3
|
|
2097
|
+
};
|
|
2098
|
+
var AssetType = {
|
|
2099
|
+
STX: 0,
|
|
2100
|
+
Fungible: 1,
|
|
2101
|
+
NonFungible: 2,
|
|
2102
|
+
Staking: 3,
|
|
2103
|
+
Pox: 4
|
|
2104
|
+
};
|
|
2105
|
+
var AuthFieldType = {
|
|
2106
|
+
PublicKeyCompressed: 0,
|
|
2107
|
+
PublicKeyUncompressed: 1,
|
|
2108
|
+
SignatureCompressed: 2,
|
|
2109
|
+
SignatureUncompressed: 3
|
|
2110
|
+
};
|
|
2111
|
+
var RECOVERABLE_ECDSA_SIG_LENGTH_BYTES = 65;
|
|
2112
|
+
var MEMO_MAX_LENGTH_BYTES = 34;
|
|
2113
|
+
var MAX_STRING_LENGTH_BYTES = 128;
|
|
2114
|
+
var COINBASE_BYTES_LENGTH = 32;
|
|
2115
|
+
var VRF_PROOF_BYTES_LENGTH = 80;
|
|
2116
|
+
var MICROBLOCK_HEADER_BYTES_LENGTH = 132;
|
|
2117
|
+
var TenureChangeCause = {
|
|
2118
|
+
BlockFound: 0,
|
|
2119
|
+
Extended: 1,
|
|
2120
|
+
ExtendedRuntime: 2,
|
|
2121
|
+
ExtendedReadCount: 3,
|
|
2122
|
+
ExtendedReadLength: 4,
|
|
2123
|
+
ExtendedWriteCount: 5,
|
|
2124
|
+
ExtendedWriteLength: 6
|
|
2125
|
+
};
|
|
2126
|
+
|
|
2127
|
+
// src/transactions/wire/deserialize.ts
|
|
2128
|
+
function readSpendingCondition(r) {
|
|
2129
|
+
const hashMode = r.readUInt8();
|
|
2130
|
+
const signer = bytesToHex(r.readBytes(20));
|
|
2131
|
+
const nonce = r.readBigUInt64BE();
|
|
2132
|
+
const fee = r.readBigUInt64BE();
|
|
2133
|
+
if (hashMode === AddressHashMode.P2PKH || hashMode === AddressHashMode.P2WPKH) {
|
|
2134
|
+
const keyEncoding = r.readUInt8();
|
|
2135
|
+
const signature = bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES));
|
|
2136
|
+
return {
|
|
2137
|
+
hashMode,
|
|
2138
|
+
signer,
|
|
2139
|
+
nonce,
|
|
2140
|
+
fee,
|
|
2141
|
+
keyEncoding,
|
|
2142
|
+
signature
|
|
2143
|
+
};
|
|
2144
|
+
}
|
|
2145
|
+
const fieldCount = r.readUInt32BE();
|
|
2146
|
+
const fields = [];
|
|
2147
|
+
for (let i = 0;i < fieldCount; i++) {
|
|
2148
|
+
const fieldType = r.readUInt8();
|
|
2149
|
+
if (fieldType <= 1) {
|
|
2150
|
+
const keyLen = fieldType === 0 ? 33 : 65;
|
|
2151
|
+
fields.push({
|
|
2152
|
+
type: "publicKey",
|
|
2153
|
+
pubKeyEncoding: fieldType,
|
|
2154
|
+
data: bytesToHex(r.readBytes(keyLen))
|
|
2155
|
+
});
|
|
2156
|
+
} else {
|
|
2157
|
+
fields.push({
|
|
2158
|
+
type: "signature",
|
|
2159
|
+
pubKeyEncoding: fieldType === 2 ? 0 : 1,
|
|
2160
|
+
data: bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES))
|
|
2161
|
+
});
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
const signaturesRequired = r.readUInt16BE();
|
|
2165
|
+
return {
|
|
2166
|
+
hashMode,
|
|
2167
|
+
signer,
|
|
2168
|
+
nonce,
|
|
2169
|
+
fee,
|
|
2170
|
+
fields,
|
|
2171
|
+
signaturesRequired
|
|
2172
|
+
};
|
|
2173
|
+
}
|
|
2174
|
+
function readAuthorization(r) {
|
|
2175
|
+
const authType = r.readUInt8();
|
|
2176
|
+
const spendingCondition = readSpendingCondition(r);
|
|
2177
|
+
if (authType === AuthType.Standard) {
|
|
2178
|
+
return { authType: AuthType.Standard, spendingCondition };
|
|
2179
|
+
}
|
|
2180
|
+
const sponsorSpendingCondition = readSpendingCondition(r);
|
|
2181
|
+
return {
|
|
2182
|
+
authType: AuthType.Sponsored,
|
|
2183
|
+
spendingCondition,
|
|
2184
|
+
sponsorSpendingCondition
|
|
2185
|
+
};
|
|
2186
|
+
}
|
|
2187
|
+
function readAssetInfo(r) {
|
|
2188
|
+
return {
|
|
2189
|
+
address: readAddress(r),
|
|
2190
|
+
contractName: readLPString(r),
|
|
2191
|
+
assetName: readLPString(r)
|
|
2192
|
+
};
|
|
2193
|
+
}
|
|
2194
|
+
function readPostConditionPrincipal(r) {
|
|
2195
|
+
const type = r.readUInt8();
|
|
2196
|
+
switch (type) {
|
|
2197
|
+
case PostConditionPrincipalId.Origin:
|
|
2198
|
+
return { type: "origin" };
|
|
2199
|
+
case PostConditionPrincipalId.Standard:
|
|
2200
|
+
return { type: "standard", address: readAddress(r) };
|
|
2201
|
+
case PostConditionPrincipalId.Contract:
|
|
2202
|
+
return {
|
|
2203
|
+
type: "contract",
|
|
2204
|
+
address: readAddress(r),
|
|
2205
|
+
contractName: readLPString(r)
|
|
2206
|
+
};
|
|
2207
|
+
default:
|
|
2208
|
+
return { type: "origin" };
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
function readPostCondition(r) {
|
|
2212
|
+
const assetType = r.readUInt8();
|
|
2213
|
+
const principal = readPostConditionPrincipal(r);
|
|
2214
|
+
switch (assetType) {
|
|
2215
|
+
case AssetType.STX:
|
|
2216
|
+
return {
|
|
2217
|
+
type: "stx",
|
|
2218
|
+
principal,
|
|
2219
|
+
conditionCode: r.readUInt8(),
|
|
2220
|
+
amount: r.readBigUInt64BE()
|
|
2221
|
+
};
|
|
2222
|
+
case AssetType.Fungible:
|
|
2223
|
+
return {
|
|
2224
|
+
type: "ft",
|
|
2225
|
+
principal,
|
|
2226
|
+
asset: readAssetInfo(r),
|
|
2227
|
+
conditionCode: r.readUInt8(),
|
|
2228
|
+
amount: r.readBigUInt64BE()
|
|
2229
|
+
};
|
|
2230
|
+
case AssetType.NonFungible:
|
|
2231
|
+
return {
|
|
2232
|
+
type: "nft",
|
|
2233
|
+
principal,
|
|
2234
|
+
asset: readAssetInfo(r),
|
|
2235
|
+
assetId: readCV(r),
|
|
2236
|
+
conditionCode: r.readUInt8()
|
|
2237
|
+
};
|
|
2238
|
+
case AssetType.Staking:
|
|
2239
|
+
return {
|
|
2240
|
+
type: "staking",
|
|
2241
|
+
principal,
|
|
2242
|
+
conditionCode: r.readUInt8(),
|
|
2243
|
+
amount: r.readBigUInt64BE()
|
|
2244
|
+
};
|
|
2245
|
+
case AssetType.Pox:
|
|
2246
|
+
return {
|
|
2247
|
+
type: "pox",
|
|
2248
|
+
principal,
|
|
2249
|
+
conditionCode: r.readUInt8()
|
|
2250
|
+
};
|
|
2251
|
+
default:
|
|
2252
|
+
throw new Error(`Unknown post-condition asset type: 0x${assetType.toString(16).padStart(2, "0")}`);
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
function readPostConditions(r) {
|
|
2256
|
+
const count = r.readUInt32BE();
|
|
2257
|
+
const pcs = [];
|
|
2258
|
+
for (let i = 0;i < count; i++) {
|
|
2259
|
+
try {
|
|
2260
|
+
pcs.push(readPostCondition(r));
|
|
2261
|
+
} catch (e) {
|
|
2262
|
+
if (e instanceof Error && e.message.startsWith("Unknown post-condition asset type:")) {
|
|
2263
|
+
throw new Error(`${e.message} (post-condition ${i + 1}/${count})`);
|
|
2264
|
+
}
|
|
2265
|
+
throw e;
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
return pcs;
|
|
2269
|
+
}
|
|
2270
|
+
function readPayload(r) {
|
|
2271
|
+
const payloadType = r.readUInt8();
|
|
2272
|
+
switch (payloadType) {
|
|
2273
|
+
case PayloadType.TokenTransfer: {
|
|
2274
|
+
const recipient = readCV(r);
|
|
2275
|
+
const amount = r.readBigUInt64BE();
|
|
2276
|
+
const memoBytes = r.readBytes(MEMO_MAX_LENGTH_BYTES);
|
|
2277
|
+
const memo = bytesToAscii(memoBytes).replace(/\0+$/, "");
|
|
2278
|
+
return {
|
|
2279
|
+
payloadType: PayloadType.TokenTransfer,
|
|
2280
|
+
recipient,
|
|
2281
|
+
amount,
|
|
2282
|
+
memo
|
|
2283
|
+
};
|
|
2284
|
+
}
|
|
2285
|
+
case PayloadType.ContractCall: {
|
|
2286
|
+
const contractAddress = readAddress(r);
|
|
2287
|
+
const contractName = readLPString(r);
|
|
2288
|
+
const functionName = readLPString(r);
|
|
2289
|
+
const numArgs = r.readUInt32BE();
|
|
2290
|
+
const functionArgs = [];
|
|
2291
|
+
for (let i = 0;i < numArgs; i++)
|
|
2292
|
+
functionArgs.push(readCV(r));
|
|
2293
|
+
return {
|
|
2294
|
+
payloadType: PayloadType.ContractCall,
|
|
2295
|
+
contractAddress,
|
|
2296
|
+
contractName,
|
|
2297
|
+
functionName,
|
|
2298
|
+
functionArgs
|
|
2299
|
+
};
|
|
2300
|
+
}
|
|
2301
|
+
case PayloadType.SmartContract: {
|
|
2302
|
+
const contractName = readLPString(r);
|
|
2303
|
+
const codeBody = readLPString(r, 4);
|
|
2304
|
+
return { payloadType: PayloadType.SmartContract, contractName, codeBody };
|
|
2305
|
+
}
|
|
2306
|
+
case PayloadType.VersionedSmartContract: {
|
|
2307
|
+
const clarityVersion = r.readUInt8();
|
|
2308
|
+
const contractName = readLPString(r);
|
|
2309
|
+
const codeBody = readLPString(r, 4);
|
|
2310
|
+
return {
|
|
2311
|
+
payloadType: PayloadType.VersionedSmartContract,
|
|
2312
|
+
clarityVersion,
|
|
2313
|
+
contractName,
|
|
2314
|
+
codeBody
|
|
2315
|
+
};
|
|
2316
|
+
}
|
|
2317
|
+
case PayloadType.Coinbase: {
|
|
2318
|
+
const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
|
|
2319
|
+
return { payloadType: PayloadType.Coinbase, coinbaseBuffer };
|
|
2320
|
+
}
|
|
2321
|
+
case PayloadType.CoinbaseToAltRecipient: {
|
|
2322
|
+
const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
|
|
2323
|
+
const recipient = readCV(r);
|
|
2324
|
+
return {
|
|
2325
|
+
payloadType: PayloadType.CoinbaseToAltRecipient,
|
|
2326
|
+
coinbaseBuffer,
|
|
2327
|
+
recipient
|
|
2328
|
+
};
|
|
2329
|
+
}
|
|
2330
|
+
case PayloadType.PoisonMicroblock: {
|
|
2331
|
+
const header1 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));
|
|
2332
|
+
const header2 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));
|
|
2333
|
+
return { payloadType: PayloadType.PoisonMicroblock, header1, header2 };
|
|
2334
|
+
}
|
|
2335
|
+
case PayloadType.TenureChange: {
|
|
2336
|
+
const tenureConsensusHash = bytesToHex(r.readBytes(20));
|
|
2337
|
+
const prevTenureConsensusHash = bytesToHex(r.readBytes(20));
|
|
2338
|
+
const burnViewConsensusHash = bytesToHex(r.readBytes(20));
|
|
2339
|
+
const previousTenureEnd = bytesToHex(r.readBytes(32));
|
|
2340
|
+
const previousTenureBlocks = r.readUInt32BE();
|
|
2341
|
+
const cause = r.readUInt8();
|
|
2342
|
+
const pubkeyHash = bytesToHex(r.readBytes(20));
|
|
2343
|
+
return {
|
|
2344
|
+
payloadType: PayloadType.TenureChange,
|
|
2345
|
+
tenureConsensusHash,
|
|
2346
|
+
prevTenureConsensusHash,
|
|
2347
|
+
burnViewConsensusHash,
|
|
2348
|
+
previousTenureEnd,
|
|
2349
|
+
previousTenureBlocks,
|
|
2350
|
+
cause,
|
|
2351
|
+
pubkeyHash
|
|
2352
|
+
};
|
|
2353
|
+
}
|
|
2354
|
+
case PayloadType.NakamotoCoinbase: {
|
|
2355
|
+
const coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));
|
|
2356
|
+
const optionalCV = readCV(r);
|
|
2357
|
+
const recipient = optionalCV.type === "none" ? null : optionalCV.type === "some" ? optionalCV.value : optionalCV;
|
|
2358
|
+
const vrfProof = bytesToHex(r.readBytes(VRF_PROOF_BYTES_LENGTH));
|
|
2359
|
+
return {
|
|
2360
|
+
payloadType: PayloadType.NakamotoCoinbase,
|
|
2361
|
+
coinbaseBuffer,
|
|
2362
|
+
recipient,
|
|
2363
|
+
vrfProof
|
|
2364
|
+
};
|
|
2365
|
+
}
|
|
2366
|
+
default:
|
|
2367
|
+
throw new Error(`Unknown payload type: ${payloadType}`);
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
function deserializePostConditionWire(input) {
|
|
2371
|
+
const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
|
|
2372
|
+
return readPostCondition(new BytesReader(bytes));
|
|
2373
|
+
}
|
|
2374
|
+
function deserializeTransaction(input, meta) {
|
|
2375
|
+
const bytes = typeof input === "string" ? hexToBytes(without0x(input)) : input;
|
|
2376
|
+
const r = new BytesReader(bytes);
|
|
2377
|
+
const tx = {
|
|
2378
|
+
version: r.readUInt8(),
|
|
2379
|
+
chainId: r.readUInt32BE(),
|
|
2380
|
+
auth: readAuthorization(r),
|
|
2381
|
+
anchorMode: r.readUInt8(),
|
|
2382
|
+
postConditionMode: r.readUInt8(),
|
|
2383
|
+
postConditions: readPostConditions(r),
|
|
2384
|
+
payload: readPayload(r)
|
|
2385
|
+
};
|
|
2386
|
+
if (meta?._multisig) {
|
|
2387
|
+
tx._multisig = meta._multisig;
|
|
2388
|
+
}
|
|
2389
|
+
return tx;
|
|
2390
|
+
}
|
|
2391
|
+
|
|
2392
|
+
// src/transactions/wire/serialize.ts
|
|
2393
|
+
function serializeAddress2(c32Address) {
|
|
2394
|
+
const [version, hash1602] = c32addressDecode(c32Address);
|
|
2395
|
+
return concatBytes(new Uint8Array([version]), hexToBytes(hash1602));
|
|
2396
|
+
}
|
|
2397
|
+
function serializeLPString2(str, prefixBytes = 1) {
|
|
2398
|
+
const content = utf8ToBytes(str);
|
|
2399
|
+
const prefix = hexToBytes(intToHex(content.byteLength, prefixBytes));
|
|
2400
|
+
return concatBytes(prefix, content);
|
|
2401
|
+
}
|
|
2402
|
+
function serializeLPStringLong(str) {
|
|
2403
|
+
return serializeLPString2(str, 4);
|
|
2404
|
+
}
|
|
2405
|
+
function serializeMemo(memo) {
|
|
2406
|
+
const content = asciiToBytes(memo);
|
|
2407
|
+
const padded = new Uint8Array(MEMO_MAX_LENGTH_BYTES);
|
|
2408
|
+
padded.set(content.slice(0, MEMO_MAX_LENGTH_BYTES));
|
|
2409
|
+
return padded;
|
|
2410
|
+
}
|
|
2411
|
+
function serializeSpendingCondition(condition) {
|
|
2412
|
+
const parts = [
|
|
2413
|
+
writeUInt8(condition.hashMode),
|
|
2414
|
+
hexToBytes(condition.signer),
|
|
2415
|
+
intToBytes(condition.nonce, 8),
|
|
2416
|
+
intToBytes(condition.fee, 8)
|
|
2417
|
+
];
|
|
2418
|
+
if ("signature" in condition) {
|
|
2419
|
+
const sc = condition;
|
|
2420
|
+
parts.push(writeUInt8(sc.keyEncoding));
|
|
2421
|
+
parts.push(hexToBytes(sc.signature));
|
|
2422
|
+
} else {
|
|
2423
|
+
const mc = condition;
|
|
2424
|
+
parts.push(writeUInt32BE(mc.fields.length));
|
|
2425
|
+
for (const field of mc.fields) {
|
|
2426
|
+
parts.push(serializeAuthField(field));
|
|
2427
|
+
}
|
|
2428
|
+
parts.push(writeUInt16BE(mc.signaturesRequired));
|
|
2429
|
+
}
|
|
2430
|
+
return concatBytes(...parts);
|
|
2431
|
+
}
|
|
2432
|
+
function serializeAuthField(field) {
|
|
2433
|
+
if (field.type === "publicKey") {
|
|
2434
|
+
const typeId2 = field.pubKeyEncoding === 0 ? 0 : 1;
|
|
2435
|
+
return concatBytes(writeUInt8(typeId2), hexToBytes(field.data));
|
|
2436
|
+
}
|
|
2437
|
+
const typeId = field.pubKeyEncoding === 0 ? 2 : 3;
|
|
2438
|
+
return concatBytes(writeUInt8(typeId), hexToBytes(field.data));
|
|
2439
|
+
}
|
|
2440
|
+
function serializeAuthorization(auth) {
|
|
2441
|
+
const parts = [writeUInt8(auth.authType)];
|
|
2442
|
+
parts.push(serializeSpendingCondition(auth.spendingCondition));
|
|
2443
|
+
if (auth.authType === AuthType.Sponsored) {
|
|
2444
|
+
parts.push(serializeSpendingCondition(auth.sponsorSpendingCondition));
|
|
2445
|
+
}
|
|
2446
|
+
return concatBytes(...parts);
|
|
2447
|
+
}
|
|
2448
|
+
function serializePrincipal(principal) {
|
|
2449
|
+
switch (principal.type) {
|
|
2450
|
+
case "origin":
|
|
2451
|
+
return writeUInt8(PostConditionPrincipalId.Origin);
|
|
2452
|
+
case "standard":
|
|
2453
|
+
return concatBytes(writeUInt8(PostConditionPrincipalId.Standard), serializeAddress2(principal.address));
|
|
2454
|
+
case "contract":
|
|
2455
|
+
return concatBytes(writeUInt8(PostConditionPrincipalId.Contract), serializeAddress2(principal.address), serializeLPString2(principal.contractName));
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2458
|
+
function serializeAssetInfo(asset) {
|
|
2459
|
+
return concatBytes(serializeAddress2(asset.address), serializeLPString2(asset.contractName), serializeLPString2(asset.assetName));
|
|
2460
|
+
}
|
|
2461
|
+
function serializePostConditionWire(pc) {
|
|
2462
|
+
const parts = [];
|
|
2463
|
+
switch (pc.type) {
|
|
2464
|
+
case "stx":
|
|
2465
|
+
parts.push(writeUInt8(AssetType.STX));
|
|
2466
|
+
parts.push(serializePrincipal(pc.principal));
|
|
2467
|
+
parts.push(writeUInt8(pc.conditionCode));
|
|
2468
|
+
parts.push(intToBytes(pc.amount, 8));
|
|
2469
|
+
break;
|
|
2470
|
+
case "ft":
|
|
2471
|
+
parts.push(writeUInt8(AssetType.Fungible));
|
|
2472
|
+
parts.push(serializePrincipal(pc.principal));
|
|
2473
|
+
parts.push(serializeAssetInfo(pc.asset));
|
|
2474
|
+
parts.push(writeUInt8(pc.conditionCode));
|
|
2475
|
+
parts.push(intToBytes(pc.amount, 8));
|
|
2476
|
+
break;
|
|
2477
|
+
case "nft":
|
|
2478
|
+
parts.push(writeUInt8(AssetType.NonFungible));
|
|
2479
|
+
parts.push(serializePrincipal(pc.principal));
|
|
2480
|
+
parts.push(serializeAssetInfo(pc.asset));
|
|
2481
|
+
parts.push(serializeCVBytes(pc.assetId));
|
|
2482
|
+
parts.push(writeUInt8(pc.conditionCode));
|
|
2483
|
+
break;
|
|
2484
|
+
case "staking":
|
|
2485
|
+
parts.push(writeUInt8(AssetType.Staking));
|
|
2486
|
+
parts.push(serializePrincipal(pc.principal));
|
|
2487
|
+
parts.push(writeUInt8(pc.conditionCode));
|
|
2488
|
+
parts.push(intToBytes(pc.amount, 8));
|
|
2489
|
+
break;
|
|
2490
|
+
case "pox":
|
|
2491
|
+
parts.push(writeUInt8(AssetType.Pox));
|
|
2492
|
+
parts.push(serializePrincipal(pc.principal));
|
|
2493
|
+
parts.push(writeUInt8(pc.conditionCode));
|
|
2494
|
+
break;
|
|
2495
|
+
}
|
|
2496
|
+
return concatBytes(...parts);
|
|
2497
|
+
}
|
|
2498
|
+
function serializePostConditions(pcs) {
|
|
2499
|
+
const parts = [writeUInt32BE(pcs.length)];
|
|
2500
|
+
for (const pc of pcs)
|
|
2501
|
+
parts.push(serializePostConditionWire(pc));
|
|
2502
|
+
return concatBytes(...parts);
|
|
2503
|
+
}
|
|
2504
|
+
function serializePayload(payload) {
|
|
2505
|
+
const parts = [writeUInt8(payload.payloadType)];
|
|
2506
|
+
switch (payload.payloadType) {
|
|
2507
|
+
case PayloadType.TokenTransfer:
|
|
2508
|
+
parts.push(serializeCVBytes(payload.recipient));
|
|
2509
|
+
parts.push(intToBytes(payload.amount, 8));
|
|
2510
|
+
parts.push(serializeMemo(payload.memo));
|
|
2511
|
+
break;
|
|
2512
|
+
case PayloadType.ContractCall:
|
|
2513
|
+
parts.push(serializeAddress2(payload.contractAddress));
|
|
2514
|
+
parts.push(serializeLPString2(payload.contractName));
|
|
2515
|
+
parts.push(serializeLPString2(payload.functionName));
|
|
2516
|
+
parts.push(writeUInt32BE(payload.functionArgs.length));
|
|
2517
|
+
for (const arg of payload.functionArgs) {
|
|
2518
|
+
parts.push(serializeCVBytes(arg));
|
|
2519
|
+
}
|
|
2520
|
+
break;
|
|
2521
|
+
case PayloadType.SmartContract:
|
|
2522
|
+
parts.push(serializeLPString2(payload.contractName));
|
|
2523
|
+
parts.push(serializeLPStringLong(payload.codeBody));
|
|
2524
|
+
break;
|
|
2525
|
+
case PayloadType.VersionedSmartContract:
|
|
2526
|
+
parts.push(writeUInt8(payload.clarityVersion ?? 2));
|
|
2527
|
+
parts.push(serializeLPString2(payload.contractName));
|
|
2528
|
+
parts.push(serializeLPStringLong(payload.codeBody));
|
|
2529
|
+
break;
|
|
2530
|
+
case PayloadType.Coinbase:
|
|
2531
|
+
parts.push(hexToBytes(payload.coinbaseBuffer));
|
|
2532
|
+
break;
|
|
2533
|
+
case PayloadType.CoinbaseToAltRecipient: {
|
|
2534
|
+
const cbAlt = payload;
|
|
2535
|
+
parts.push(hexToBytes(cbAlt.coinbaseBuffer));
|
|
2536
|
+
parts.push(serializeCVBytes(cbAlt.recipient));
|
|
2537
|
+
break;
|
|
2538
|
+
}
|
|
2539
|
+
case PayloadType.PoisonMicroblock: {
|
|
2540
|
+
const pm = payload;
|
|
2541
|
+
parts.push(hexToBytes(pm.header1));
|
|
2542
|
+
parts.push(hexToBytes(pm.header2));
|
|
2543
|
+
break;
|
|
2544
|
+
}
|
|
2545
|
+
case PayloadType.TenureChange: {
|
|
2546
|
+
const tc = payload;
|
|
2547
|
+
parts.push(hexToBytes(tc.tenureConsensusHash));
|
|
2548
|
+
parts.push(hexToBytes(tc.prevTenureConsensusHash));
|
|
2549
|
+
parts.push(hexToBytes(tc.burnViewConsensusHash));
|
|
2550
|
+
parts.push(hexToBytes(tc.previousTenureEnd));
|
|
2551
|
+
parts.push(writeUInt32BE(tc.previousTenureBlocks));
|
|
2552
|
+
parts.push(writeUInt8(tc.cause));
|
|
2553
|
+
parts.push(hexToBytes(tc.pubkeyHash));
|
|
2554
|
+
break;
|
|
2555
|
+
}
|
|
2556
|
+
case PayloadType.NakamotoCoinbase: {
|
|
2557
|
+
const nc = payload;
|
|
2558
|
+
parts.push(hexToBytes(nc.coinbaseBuffer));
|
|
2559
|
+
if (nc.recipient) {
|
|
2560
|
+
parts.push(serializeCVBytes({ type: "some", value: nc.recipient }));
|
|
2561
|
+
} else {
|
|
2562
|
+
parts.push(serializeCVBytes({ type: "none" }));
|
|
2563
|
+
}
|
|
2564
|
+
parts.push(hexToBytes(nc.vrfProof));
|
|
2565
|
+
break;
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
return concatBytes(...parts);
|
|
2569
|
+
}
|
|
2570
|
+
var _txCache = new WeakMap;
|
|
2571
|
+
function clearTxCache(tx) {
|
|
2572
|
+
_txCache.delete(tx);
|
|
2573
|
+
}
|
|
2574
|
+
function serializeTransaction(tx) {
|
|
2575
|
+
const cached = _txCache.get(tx);
|
|
2576
|
+
if (cached)
|
|
2577
|
+
return cached;
|
|
2578
|
+
const bytes = concatBytes(writeUInt8(tx.version), writeUInt32BE(tx.chainId), serializeAuthorization(tx.auth), writeUInt8(tx.anchorMode), writeUInt8(tx.postConditionMode), serializePostConditions(tx.postConditions), serializePayload(tx.payload));
|
|
2579
|
+
_txCache.set(tx, bytes);
|
|
2580
|
+
return bytes;
|
|
2581
|
+
}
|
|
2582
|
+
function serializeTransactionHex(tx) {
|
|
2583
|
+
return bytesToHex(serializeTransaction(tx));
|
|
2584
|
+
}
|
|
2585
|
+
|
|
2586
|
+
// src/postconditions/convert.ts
|
|
2587
|
+
var MAX_U64 = 18446744073709551615n;
|
|
2588
|
+
function parsePostConditionAmount(amount) {
|
|
2589
|
+
const value = intToBigInt(amount);
|
|
2590
|
+
if (value < 0n || value > MAX_U64) {
|
|
2591
|
+
throw new RangeError(`Post-condition amount must be between 0 and ${MAX_U64} (u64 max), received: ${value}`);
|
|
2592
|
+
}
|
|
2593
|
+
return value;
|
|
2594
|
+
}
|
|
2595
|
+
var FUNGIBLE_CODE_MAP = {
|
|
2596
|
+
eq: FungibleConditionCode.Equal,
|
|
2597
|
+
gt: FungibleConditionCode.Greater,
|
|
2598
|
+
gte: FungibleConditionCode.GreaterEqual,
|
|
2599
|
+
lt: FungibleConditionCode.Less,
|
|
2600
|
+
lte: FungibleConditionCode.LessEqual
|
|
2601
|
+
};
|
|
2602
|
+
var FUNGIBLE_CODE_REVERSE = {
|
|
2603
|
+
[FungibleConditionCode.Equal]: "eq",
|
|
2604
|
+
[FungibleConditionCode.Greater]: "gt",
|
|
2605
|
+
[FungibleConditionCode.GreaterEqual]: "gte",
|
|
2606
|
+
[FungibleConditionCode.Less]: "lt",
|
|
2607
|
+
[FungibleConditionCode.LessEqual]: "lte"
|
|
2608
|
+
};
|
|
2609
|
+
var NFT_CODE_MAP = {
|
|
2610
|
+
sent: NonFungibleConditionCode.Sends,
|
|
2611
|
+
"not-sent": NonFungibleConditionCode.DoesNotSend,
|
|
2612
|
+
"maybe-sent": NonFungibleConditionCode.MaybeSent
|
|
2613
|
+
};
|
|
2614
|
+
var NFT_CODE_REVERSE = {
|
|
2615
|
+
[NonFungibleConditionCode.Sends]: "sent",
|
|
2616
|
+
[NonFungibleConditionCode.DoesNotSend]: "not-sent",
|
|
2617
|
+
[NonFungibleConditionCode.MaybeSent]: "maybe-sent"
|
|
2618
|
+
};
|
|
2619
|
+
var POX_CODE_MAP = {
|
|
2620
|
+
"will-not-perform": PoxConditionCode.WillNotPerform,
|
|
2621
|
+
"may-perform": PoxConditionCode.MayPerform,
|
|
2622
|
+
"will-perform": PoxConditionCode.WillPerform
|
|
2623
|
+
};
|
|
2624
|
+
var POX_CODE_REVERSE = {
|
|
2625
|
+
[PoxConditionCode.WillNotPerform]: "will-not-perform",
|
|
2626
|
+
[PoxConditionCode.MayPerform]: "may-perform",
|
|
2627
|
+
[PoxConditionCode.WillPerform]: "will-perform"
|
|
2628
|
+
};
|
|
2629
|
+
function resolvePrincipal(address) {
|
|
2630
|
+
if (address === "origin")
|
|
2631
|
+
return { type: "origin" };
|
|
2632
|
+
const [addr, name] = address.split(".");
|
|
2633
|
+
if (name) {
|
|
2634
|
+
return { type: "contract", address: addr, contractName: name };
|
|
2635
|
+
}
|
|
2636
|
+
return { type: "standard", address: addr };
|
|
2637
|
+
}
|
|
2638
|
+
function principalToString(principal) {
|
|
2639
|
+
if (principal.type === "origin")
|
|
2640
|
+
return "origin";
|
|
2641
|
+
if (principal.type === "contract") {
|
|
2642
|
+
return `${principal.address}.${principal.contractName}`;
|
|
2643
|
+
}
|
|
2644
|
+
return principal.address;
|
|
2645
|
+
}
|
|
2646
|
+
function assetToString(asset) {
|
|
2647
|
+
return `${asset.address}.${asset.contractName}::${asset.assetName}`;
|
|
2648
|
+
}
|
|
2649
|
+
function parseAsset(asset) {
|
|
2650
|
+
const [contractId, tokenName] = asset.split("::");
|
|
2651
|
+
const [addr, name] = parseContractId(contractId);
|
|
2652
|
+
return { address: addr, contractName: name, assetName: tokenName };
|
|
2653
|
+
}
|
|
2654
|
+
function convertPostCondition(pc) {
|
|
2655
|
+
switch (pc.type) {
|
|
2656
|
+
case "stx-postcondition":
|
|
2657
|
+
return {
|
|
2658
|
+
type: "stx",
|
|
2659
|
+
principal: resolvePrincipal(pc.address),
|
|
2660
|
+
conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
|
|
2661
|
+
amount: parsePostConditionAmount(pc.amount)
|
|
2662
|
+
};
|
|
2663
|
+
case "ft-postcondition":
|
|
2664
|
+
return {
|
|
2665
|
+
type: "ft",
|
|
2666
|
+
principal: resolvePrincipal(pc.address),
|
|
2667
|
+
asset: parseAsset(pc.asset),
|
|
2668
|
+
conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
|
|
2669
|
+
amount: parsePostConditionAmount(pc.amount)
|
|
2670
|
+
};
|
|
2671
|
+
case "nft-postcondition":
|
|
2672
|
+
return {
|
|
2673
|
+
type: "nft",
|
|
2674
|
+
principal: resolvePrincipal(pc.address),
|
|
2675
|
+
asset: parseAsset(pc.asset),
|
|
2676
|
+
conditionCode: NFT_CODE_MAP[pc.condition],
|
|
2677
|
+
assetId: pc.assetId
|
|
2678
|
+
};
|
|
2679
|
+
case "staking-postcondition":
|
|
2680
|
+
return {
|
|
2681
|
+
type: "staking",
|
|
2682
|
+
principal: resolvePrincipal(pc.address),
|
|
2683
|
+
conditionCode: FUNGIBLE_CODE_MAP[pc.condition],
|
|
2684
|
+
amount: parsePostConditionAmount(pc.amount)
|
|
2685
|
+
};
|
|
2686
|
+
case "pox-postcondition":
|
|
2687
|
+
return {
|
|
2688
|
+
type: "pox",
|
|
2689
|
+
principal: resolvePrincipal(pc.address),
|
|
2690
|
+
conditionCode: POX_CODE_MAP[pc.condition]
|
|
2691
|
+
};
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
function wireToPostCondition(wire) {
|
|
2695
|
+
switch (wire.type) {
|
|
2696
|
+
case "stx":
|
|
2697
|
+
return {
|
|
2698
|
+
type: "stx-postcondition",
|
|
2699
|
+
address: principalToString(wire.principal),
|
|
2700
|
+
condition: fungibleName(wire.conditionCode),
|
|
2701
|
+
amount: wire.amount.toString()
|
|
2702
|
+
};
|
|
2703
|
+
case "ft":
|
|
2704
|
+
return {
|
|
2705
|
+
type: "ft-postcondition",
|
|
2706
|
+
address: principalToString(wire.principal),
|
|
2707
|
+
condition: fungibleName(wire.conditionCode),
|
|
2708
|
+
amount: wire.amount.toString(),
|
|
2709
|
+
asset: assetToString(wire.asset)
|
|
2710
|
+
};
|
|
2711
|
+
case "nft":
|
|
2712
|
+
return {
|
|
2713
|
+
type: "nft-postcondition",
|
|
2714
|
+
address: principalToString(wire.principal),
|
|
2715
|
+
condition: nftName(wire.conditionCode),
|
|
2716
|
+
asset: assetToString(wire.asset),
|
|
2717
|
+
assetId: wire.assetId
|
|
2718
|
+
};
|
|
2719
|
+
case "staking":
|
|
2720
|
+
return {
|
|
2721
|
+
type: "staking-postcondition",
|
|
2722
|
+
address: principalToString(wire.principal),
|
|
2723
|
+
condition: fungibleName(wire.conditionCode),
|
|
2724
|
+
amount: wire.amount.toString()
|
|
2725
|
+
};
|
|
2726
|
+
case "pox":
|
|
2727
|
+
return {
|
|
2728
|
+
type: "pox-postcondition",
|
|
2729
|
+
address: principalToString(wire.principal),
|
|
2730
|
+
condition: poxName(wire.conditionCode)
|
|
2731
|
+
};
|
|
2732
|
+
}
|
|
2733
|
+
}
|
|
2734
|
+
function fungibleName(code) {
|
|
2735
|
+
const name = FUNGIBLE_CODE_REVERSE[code];
|
|
2736
|
+
if (!name)
|
|
2737
|
+
throw new Error(`Unknown fungible post-condition code: ${code}`);
|
|
2738
|
+
return name;
|
|
2739
|
+
}
|
|
2740
|
+
function nftName(code) {
|
|
2741
|
+
const name = NFT_CODE_REVERSE[code];
|
|
2742
|
+
if (!name)
|
|
2743
|
+
throw new Error(`Unknown nft post-condition code: ${code}`);
|
|
2744
|
+
return name;
|
|
2745
|
+
}
|
|
2746
|
+
function poxName(code) {
|
|
2747
|
+
const name = POX_CODE_REVERSE[code];
|
|
2748
|
+
if (!name)
|
|
2749
|
+
throw new Error(`Unknown pox post-condition code: ${code}`);
|
|
2750
|
+
return name;
|
|
2751
|
+
}
|
|
2752
|
+
function fromHex(hex) {
|
|
2753
|
+
return wireToPostCondition(deserializePostConditionWire(hex));
|
|
2754
|
+
}
|
|
2755
|
+
function postConditionToHex(pc) {
|
|
2756
|
+
return bytesToHex(serializePostConditionWire(convertPostCondition(pc)));
|
|
2757
|
+
}
|
|
2758
|
+
|
|
2759
|
+
// src/postconditions/builder.ts
|
|
2760
|
+
class PartialPcWithPrincipal {
|
|
2761
|
+
address;
|
|
2762
|
+
constructor(address) {
|
|
2763
|
+
this.address = address;
|
|
2764
|
+
}
|
|
2765
|
+
willSendEq(amount) {
|
|
2766
|
+
return new PartialPcFtWithCode(this.address, amount, "eq");
|
|
2767
|
+
}
|
|
2768
|
+
willSendGte(amount) {
|
|
2769
|
+
return new PartialPcFtWithCode(this.address, amount, "gte");
|
|
2770
|
+
}
|
|
2771
|
+
willSendGt(amount) {
|
|
2772
|
+
return new PartialPcFtWithCode(this.address, amount, "gt");
|
|
2773
|
+
}
|
|
2774
|
+
willSendLte(amount) {
|
|
2775
|
+
return new PartialPcFtWithCode(this.address, amount, "lte");
|
|
2776
|
+
}
|
|
2777
|
+
willSendLt(amount) {
|
|
2778
|
+
return new PartialPcFtWithCode(this.address, amount, "lt");
|
|
2779
|
+
}
|
|
2780
|
+
willSendAsset() {
|
|
2781
|
+
return new PartialPcNftWithCode(this.address, "sent");
|
|
2782
|
+
}
|
|
2783
|
+
willNotSendAsset() {
|
|
2784
|
+
return new PartialPcNftWithCode(this.address, "not-sent");
|
|
2785
|
+
}
|
|
2786
|
+
willMaybeSendAsset() {
|
|
2787
|
+
return new PartialPcNftWithCode(this.address, "maybe-sent");
|
|
2788
|
+
}
|
|
2789
|
+
willPerformPox() {
|
|
2790
|
+
return {
|
|
2791
|
+
type: "pox-postcondition",
|
|
2792
|
+
address: this.address,
|
|
2793
|
+
condition: "will-perform"
|
|
2794
|
+
};
|
|
2795
|
+
}
|
|
2796
|
+
willNotPerformPox() {
|
|
2797
|
+
return {
|
|
2798
|
+
type: "pox-postcondition",
|
|
2799
|
+
address: this.address,
|
|
2800
|
+
condition: "will-not-perform"
|
|
2801
|
+
};
|
|
2802
|
+
}
|
|
2803
|
+
mayPerformPox() {
|
|
2804
|
+
return {
|
|
2805
|
+
type: "pox-postcondition",
|
|
2806
|
+
address: this.address,
|
|
2807
|
+
condition: "may-perform"
|
|
2808
|
+
};
|
|
2809
|
+
}
|
|
2810
|
+
}
|
|
2811
|
+
|
|
2812
|
+
class PartialPcFtWithCode {
|
|
2813
|
+
address;
|
|
2814
|
+
amount;
|
|
2815
|
+
code;
|
|
2816
|
+
constructor(address, amount, code) {
|
|
2817
|
+
this.address = address;
|
|
2818
|
+
this.amount = amount;
|
|
2819
|
+
this.code = code;
|
|
2820
|
+
}
|
|
2821
|
+
ustx() {
|
|
2822
|
+
return {
|
|
2823
|
+
type: "stx-postcondition",
|
|
2824
|
+
address: this.address,
|
|
2825
|
+
condition: this.code,
|
|
2826
|
+
amount: parsePostConditionAmount(this.amount).toString()
|
|
2827
|
+
};
|
|
2828
|
+
}
|
|
2829
|
+
ustxToLock() {
|
|
2830
|
+
return {
|
|
2831
|
+
type: "staking-postcondition",
|
|
2832
|
+
address: this.address,
|
|
2833
|
+
condition: this.code,
|
|
2834
|
+
amount: parsePostConditionAmount(this.amount).toString()
|
|
2835
|
+
};
|
|
2836
|
+
}
|
|
2837
|
+
ft(contractId, tokenName) {
|
|
2838
|
+
const [address, name] = contractId.split(".");
|
|
2839
|
+
if (!address || !validateStacksAddress(address) || !name) {
|
|
2840
|
+
throw new Error(`Invalid contract id: ${contractId}`);
|
|
2841
|
+
}
|
|
2842
|
+
return {
|
|
2843
|
+
type: "ft-postcondition",
|
|
2844
|
+
address: this.address,
|
|
2845
|
+
condition: this.code,
|
|
2846
|
+
amount: parsePostConditionAmount(this.amount).toString(),
|
|
2847
|
+
asset: `${contractId}::${tokenName}`
|
|
2848
|
+
};
|
|
2849
|
+
}
|
|
2850
|
+
}
|
|
2851
|
+
|
|
2852
|
+
class PartialPcNftWithCode {
|
|
2853
|
+
address;
|
|
2854
|
+
code;
|
|
2855
|
+
constructor(address, code) {
|
|
2856
|
+
this.address = address;
|
|
2857
|
+
this.code = code;
|
|
2858
|
+
}
|
|
2859
|
+
nft(assetOrContractId, tokenNameOrAssetId, assetId) {
|
|
2860
|
+
let contractAddress;
|
|
2861
|
+
let contractName;
|
|
2862
|
+
let tokenName;
|
|
2863
|
+
let id;
|
|
2864
|
+
if (assetId !== undefined) {
|
|
2865
|
+
[contractAddress, contractName] = parseContractId(assetOrContractId);
|
|
2866
|
+
tokenName = tokenNameOrAssetId;
|
|
2867
|
+
id = assetId;
|
|
2868
|
+
} else {
|
|
2869
|
+
const [principal, tName] = assetOrContractId.split("::");
|
|
2870
|
+
if (!principal || !tName)
|
|
2871
|
+
throw new Error(`Invalid asset name: ${assetOrContractId}`);
|
|
2872
|
+
[contractAddress, contractName] = parseContractId(principal);
|
|
2873
|
+
tokenName = tName;
|
|
2874
|
+
id = tokenNameOrAssetId;
|
|
2875
|
+
}
|
|
2876
|
+
if (!validateStacksAddress(contractAddress)) {
|
|
2877
|
+
throw new Error(`Invalid contract address: ${contractAddress}`);
|
|
2878
|
+
}
|
|
2879
|
+
return {
|
|
2880
|
+
type: "nft-postcondition",
|
|
2881
|
+
address: this.address,
|
|
2882
|
+
condition: this.code,
|
|
2883
|
+
asset: `${contractAddress}.${contractName}::${tokenName}`,
|
|
2884
|
+
assetId: id
|
|
2885
|
+
};
|
|
2886
|
+
}
|
|
2887
|
+
}
|
|
2888
|
+
var Pc = {
|
|
2889
|
+
principal(address) {
|
|
2890
|
+
const [addr, name] = address.split(".");
|
|
2891
|
+
if (!addr || !validateStacksAddress(addr) || typeof name === "string" && !name) {
|
|
2892
|
+
throw new Error(`Invalid principal: ${address}`);
|
|
2893
|
+
}
|
|
2894
|
+
return new PartialPcWithPrincipal(address);
|
|
2895
|
+
},
|
|
2896
|
+
origin() {
|
|
2897
|
+
return new PartialPcWithPrincipal("origin");
|
|
2898
|
+
},
|
|
2899
|
+
fromHex: (hex) => fromHex(hex)
|
|
2900
|
+
};
|
|
2901
|
+
// src/bns/index.ts
|
|
2902
|
+
var exports_bns = {};
|
|
2903
|
+
__export(exports_bns, {
|
|
2904
|
+
validateNamespace: () => validateNamespace,
|
|
2905
|
+
validateName: () => validateName,
|
|
2906
|
+
validateFQN: () => validateFQN,
|
|
2907
|
+
parseFQN: () => parseFQN,
|
|
2908
|
+
hashPreorder: () => hashPreorder,
|
|
2909
|
+
generateSalt: () => generateSalt,
|
|
2910
|
+
formatFQN: () => formatFQN,
|
|
2911
|
+
bns: () => bns,
|
|
2912
|
+
ZONEFILE_RESOLVER_CONTRACTS: () => ZONEFILE_RESOLVER_CONTRACTS,
|
|
2913
|
+
BNS_CONTRACTS: () => BNS_CONTRACTS
|
|
2914
|
+
});
|
|
2915
|
+
module.exports = __toCommonJS(exports_bns);
|
|
2916
|
+
|
|
2917
|
+
// src/transactions/authorization.ts
|
|
2918
|
+
var import_hmac = require("@noble/hashes/hmac.js");
|
|
2919
|
+
var import_sha25 = require("@noble/hashes/sha2.js");
|
|
2920
|
+
var import_secp256k1 = require("@noble/secp256k1");
|
|
2921
|
+
import_secp256k1.etc.hmacSha256Sync = (key, ...msgs) => {
|
|
2922
|
+
const h = import_hmac.hmac.create(import_sha25.sha256, key);
|
|
2923
|
+
for (const msg of msgs)
|
|
2924
|
+
h.update(msg);
|
|
2925
|
+
return h.digest();
|
|
2926
|
+
};
|
|
2927
|
+
var EMPTY_SIG = bytesToHex(new Uint8Array(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES));
|
|
2928
|
+
function createSingleSigSpendingCondition(publicKey, nonce, fee) {
|
|
2929
|
+
const pubKeyBytes = hexToBytes(publicKey);
|
|
2930
|
+
const signer = hashP2PKH(pubKeyBytes);
|
|
2931
|
+
const isCompressed = pubKeyBytes.length === 33;
|
|
2932
|
+
return {
|
|
2933
|
+
hashMode: AddressHashMode.P2PKH,
|
|
2934
|
+
signer,
|
|
2935
|
+
nonce,
|
|
2936
|
+
fee,
|
|
2937
|
+
keyEncoding: isCompressed ? PubKeyEncoding.Compressed : PubKeyEncoding.Uncompressed,
|
|
2938
|
+
signature: EMPTY_SIG
|
|
2939
|
+
};
|
|
2940
|
+
}
|
|
2941
|
+
function createStandardAuth(spendingCondition) {
|
|
2942
|
+
return { authType: AuthType.Standard, spendingCondition };
|
|
2943
|
+
}
|
|
2944
|
+
function createSponsoredAuth(spendingCondition, sponsorSpendingCondition) {
|
|
2945
|
+
return {
|
|
2946
|
+
authType: AuthType.Sponsored,
|
|
2947
|
+
spendingCondition,
|
|
2948
|
+
sponsorSpendingCondition: sponsorSpendingCondition ?? createSingleSigSpendingCondition("0".repeat(66), 0n, 0n)
|
|
2949
|
+
};
|
|
2950
|
+
}
|
|
2951
|
+
function clearCondition(condition) {
|
|
2952
|
+
if ("signature" in condition) {
|
|
2953
|
+
return {
|
|
2954
|
+
...condition,
|
|
2955
|
+
nonce: 0n,
|
|
2956
|
+
fee: 0n,
|
|
2957
|
+
signature: EMPTY_SIG
|
|
2958
|
+
};
|
|
2959
|
+
}
|
|
2960
|
+
return {
|
|
2961
|
+
...condition,
|
|
2962
|
+
nonce: 0n,
|
|
2963
|
+
fee: 0n,
|
|
2964
|
+
fields: []
|
|
2965
|
+
};
|
|
2966
|
+
}
|
|
2967
|
+
function sponsorSigningSentinel() {
|
|
2968
|
+
return {
|
|
2969
|
+
hashMode: AddressHashMode.P2PKH,
|
|
2970
|
+
signer: "00".repeat(20),
|
|
2971
|
+
nonce: 0n,
|
|
2972
|
+
fee: 0n,
|
|
2973
|
+
keyEncoding: PubKeyEncoding.Compressed,
|
|
2974
|
+
signature: EMPTY_SIG
|
|
2975
|
+
};
|
|
2976
|
+
}
|
|
2977
|
+
function intoInitialSighashAuth(auth) {
|
|
2978
|
+
if (auth.authType === AuthType.Standard) {
|
|
2979
|
+
return createStandardAuth(clearCondition(auth.spendingCondition));
|
|
2980
|
+
}
|
|
2981
|
+
return createSponsoredAuth(clearCondition(auth.spendingCondition), sponsorSigningSentinel());
|
|
2982
|
+
}
|
|
2983
|
+
function sigHashPreSign(curSigHash, authType, fee, nonce) {
|
|
2984
|
+
const data = concatBytes(hexToBytes(curSigHash), new Uint8Array([authType]), intToBytes(fee, 8), intToBytes(nonce, 8));
|
|
2985
|
+
return txidFromBytes(data);
|
|
2986
|
+
}
|
|
2987
|
+
function sigHashPostSign(curSigHash, pubKeyEncoding, signature) {
|
|
2988
|
+
const data = concatBytes(hexToBytes(curSigHash), new Uint8Array([pubKeyEncoding]), hexToBytes(signature));
|
|
2989
|
+
return txidFromBytes(data);
|
|
2990
|
+
}
|
|
2991
|
+
function signWithKey(privateKey, messageHash) {
|
|
2992
|
+
const keyBytes = hexToBytes(privateKey).slice(0, 32);
|
|
2993
|
+
const sig = import_secp256k1.sign(messageHash, keyBytes, { lowS: true });
|
|
2994
|
+
const recoveryIdHex = intToHex(sig.recovery, 1);
|
|
2995
|
+
return recoveryIdHex + sig.toCompactHex();
|
|
2996
|
+
}
|
|
2997
|
+
function nextSignature(curSigHash, authType, fee, nonce, privateKey) {
|
|
2998
|
+
const sigHashPre = sigHashPreSign(curSigHash, authType, fee, nonce);
|
|
2999
|
+
const keyBytes = hexToBytes(privateKey).slice(0, 32);
|
|
3000
|
+
const pubKey = import_secp256k1.getPublicKey(keyBytes, true);
|
|
3001
|
+
const isCompressed = pubKey.length === 33;
|
|
3002
|
+
const pubKeyEncoding = isCompressed ? PubKeyEncoding.Compressed : PubKeyEncoding.Uncompressed;
|
|
3003
|
+
const nextSig = signWithKey(privateKey, sigHashPre);
|
|
3004
|
+
const nextSigHash = sigHashPostSign(sigHashPre, pubKeyEncoding, nextSig);
|
|
3005
|
+
return { nextSig, nextSigHash };
|
|
3006
|
+
}
|
|
3007
|
+
|
|
3008
|
+
// src/transactions/multisig.ts
|
|
3009
|
+
var import_secp256k12 = require("@noble/secp256k1");
|
|
3010
|
+
var OP_CHECKMULTISIG = 174;
|
|
3011
|
+
function isNonSequential(hashMode) {
|
|
3012
|
+
return (hashMode & 4) !== 0;
|
|
3013
|
+
}
|
|
3014
|
+
function makeRedeemScript(publicKeys, signaturesRequired) {
|
|
3015
|
+
const parts = [];
|
|
3016
|
+
parts.push(new Uint8Array([80 + signaturesRequired]));
|
|
3017
|
+
for (const pk of publicKeys) {
|
|
3018
|
+
const pkBytes = hexToBytes(pk);
|
|
3019
|
+
parts.push(new Uint8Array([pkBytes.length]));
|
|
3020
|
+
parts.push(pkBytes);
|
|
3021
|
+
}
|
|
3022
|
+
parts.push(new Uint8Array([80 + publicKeys.length]));
|
|
3023
|
+
parts.push(new Uint8Array([OP_CHECKMULTISIG]));
|
|
3024
|
+
return concatBytes(...parts);
|
|
3025
|
+
}
|
|
3026
|
+
function makeMultiSigAddress(publicKeys, signaturesRequired, chain) {
|
|
3027
|
+
if (signaturesRequired < 1 || signaturesRequired > publicKeys.length) {
|
|
3028
|
+
throw new Error(`signaturesRequired must be between 1 and ${publicKeys.length}`);
|
|
3029
|
+
}
|
|
3030
|
+
const redeemScript = makeRedeemScript(publicKeys, signaturesRequired);
|
|
3031
|
+
const signer = hash160(redeemScript);
|
|
3032
|
+
const version = chain?.addressVersion?.multiSig ?? 20;
|
|
3033
|
+
return c32address(version, bytesToHex(signer));
|
|
3034
|
+
}
|
|
3035
|
+
function createMultiSigSpendingCondition(publicKeys, signaturesRequired, nonce, fee, hashMode = AddressHashMode.P2SH) {
|
|
3036
|
+
const redeemScript = makeRedeemScript(publicKeys, signaturesRequired);
|
|
3037
|
+
const signer = bytesToHex(hash160(redeemScript));
|
|
3038
|
+
return {
|
|
3039
|
+
hashMode,
|
|
3040
|
+
signer,
|
|
3041
|
+
nonce,
|
|
3042
|
+
fee,
|
|
3043
|
+
fields: [],
|
|
3044
|
+
signaturesRequired
|
|
3045
|
+
};
|
|
3046
|
+
}
|
|
3047
|
+
function initialSigHash(tx) {
|
|
3048
|
+
const cleared = {
|
|
3049
|
+
...tx,
|
|
3050
|
+
auth: intoInitialSighashAuth(tx.auth)
|
|
3051
|
+
};
|
|
3052
|
+
return txidFromBytes(serializeTransaction(cleared));
|
|
3053
|
+
}
|
|
3054
|
+
function nonSequentialPreSignHash(tx) {
|
|
3055
|
+
const condition = tx.auth.spendingCondition;
|
|
3056
|
+
const initHash = initialSigHash(tx);
|
|
3057
|
+
return sigHashPreSign(initHash, AuthType.Standard, condition.fee, condition.nonce);
|
|
3058
|
+
}
|
|
3059
|
+
function replayMultiSigSigHash(tx) {
|
|
3060
|
+
const condition = tx.auth.spendingCondition;
|
|
3061
|
+
if (isNonSequential(condition.hashMode)) {
|
|
3062
|
+
const preSign = nonSequentialPreSignHash(tx);
|
|
3063
|
+
let curSigHash2 = preSign;
|
|
3064
|
+
for (const field of condition.fields) {
|
|
3065
|
+
curSigHash2 = sigHashPostSign(curSigHash2, field.pubKeyEncoding, field.data);
|
|
3066
|
+
}
|
|
3067
|
+
return curSigHash2;
|
|
3068
|
+
}
|
|
3069
|
+
let curSigHash = initialSigHash(tx);
|
|
3070
|
+
for (const field of condition.fields) {
|
|
3071
|
+
const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
|
|
3072
|
+
curSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);
|
|
3073
|
+
}
|
|
3074
|
+
return curSigHash;
|
|
3075
|
+
}
|
|
3076
|
+
function signMultiSig(tx, privateKey, publicKeys) {
|
|
3077
|
+
const keyBytes = hexToBytes(privateKey).slice(0, 32);
|
|
3078
|
+
const signerPubKey = bytesToHex(import_secp256k12.getPublicKey(keyBytes, true));
|
|
3079
|
+
const signerIndex = publicKeys.findIndex((pk) => pk === signerPubKey);
|
|
3080
|
+
if (signerIndex === -1) {
|
|
3081
|
+
throw new Error("Private key does not correspond to any signer in the multi-sig");
|
|
3082
|
+
}
|
|
3083
|
+
const condition = {
|
|
3084
|
+
...tx.auth.spendingCondition
|
|
3085
|
+
};
|
|
3086
|
+
if (isNonSequential(condition.hashMode)) {
|
|
3087
|
+
return signNonSequential(tx, condition, privateKey);
|
|
3088
|
+
}
|
|
3089
|
+
return signSequential(tx, condition, privateKey, publicKeys, signerIndex);
|
|
3090
|
+
}
|
|
3091
|
+
function signNonSequential(tx, condition, privateKey) {
|
|
3092
|
+
const fields = [...condition.fields];
|
|
3093
|
+
const preSignHash = nonSequentialPreSignHash(tx);
|
|
3094
|
+
const keyBytes = hexToBytes(privateKey).slice(0, 32);
|
|
3095
|
+
const sig = import_secp256k12.sign(preSignHash, keyBytes, { lowS: true });
|
|
3096
|
+
const recoveryIdHex = intToHex(sig.recovery, 1);
|
|
3097
|
+
const nextSig = recoveryIdHex + sig.toCompactHex();
|
|
3098
|
+
fields.push({
|
|
3099
|
+
type: "signature",
|
|
3100
|
+
pubKeyEncoding: PubKeyEncoding.Compressed,
|
|
3101
|
+
data: nextSig
|
|
3102
|
+
});
|
|
3103
|
+
const newCondition = { ...condition, fields };
|
|
3104
|
+
const sigCount = fields.filter((f) => f.type === "signature").length;
|
|
3105
|
+
if (sigCount >= condition.signaturesRequired) {
|
|
3106
|
+
return {
|
|
3107
|
+
...tx,
|
|
3108
|
+
auth: { ...tx.auth, spendingCondition: newCondition }
|
|
3109
|
+
};
|
|
3110
|
+
}
|
|
3111
|
+
return {
|
|
3112
|
+
...tx,
|
|
3113
|
+
auth: { ...tx.auth, spendingCondition: newCondition }
|
|
3114
|
+
};
|
|
3115
|
+
}
|
|
3116
|
+
function signSequential(tx, condition, privateKey, publicKeys, signerIndex) {
|
|
3117
|
+
const fields = [...condition.fields];
|
|
3118
|
+
let curSigHash = initialSigHash(tx);
|
|
3119
|
+
for (const field of fields) {
|
|
3120
|
+
const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
|
|
3121
|
+
curSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);
|
|
3122
|
+
}
|
|
3123
|
+
for (let i = fields.length;i < signerIndex; i++) {
|
|
3124
|
+
const pubKeyField = {
|
|
3125
|
+
type: "publicKey",
|
|
3126
|
+
pubKeyEncoding: PubKeyEncoding.Compressed,
|
|
3127
|
+
data: publicKeys[i]
|
|
3128
|
+
};
|
|
3129
|
+
fields.push(pubKeyField);
|
|
3130
|
+
const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
|
|
3131
|
+
curSigHash = sigHashPostSign(preSign, pubKeyField.pubKeyEncoding, pubKeyField.data);
|
|
3132
|
+
}
|
|
3133
|
+
const { nextSig, nextSigHash } = nextSignature(curSigHash, AuthType.Standard, condition.fee, condition.nonce, privateKey);
|
|
3134
|
+
fields.push({
|
|
3135
|
+
type: "signature",
|
|
3136
|
+
pubKeyEncoding: PubKeyEncoding.Compressed,
|
|
3137
|
+
data: nextSig
|
|
3138
|
+
});
|
|
3139
|
+
curSigHash = nextSigHash;
|
|
3140
|
+
const newCondition = { ...condition, fields };
|
|
3141
|
+
const sigCount = fields.filter((f) => f.type === "signature").length;
|
|
3142
|
+
let finalCondition = newCondition;
|
|
3143
|
+
if (sigCount >= condition.signaturesRequired) {
|
|
3144
|
+
finalCondition = finalizeMultiSigCondition(newCondition, publicKeys, curSigHash);
|
|
3145
|
+
}
|
|
3146
|
+
return {
|
|
3147
|
+
...tx,
|
|
3148
|
+
auth: {
|
|
3149
|
+
...tx.auth,
|
|
3150
|
+
spendingCondition: finalCondition
|
|
3151
|
+
}
|
|
3152
|
+
};
|
|
3153
|
+
}
|
|
3154
|
+
async function signMultiSigWithAccount(tx, account, publicKeys) {
|
|
3155
|
+
const signerPubKey = account.publicKey;
|
|
3156
|
+
const signerIndex = publicKeys.findIndex((pk) => pk === signerPubKey);
|
|
3157
|
+
if (signerIndex === -1) {
|
|
3158
|
+
throw new Error("Account does not correspond to any signer in the multi-sig");
|
|
3159
|
+
}
|
|
3160
|
+
const condition = {
|
|
3161
|
+
...tx.auth.spendingCondition
|
|
3162
|
+
};
|
|
3163
|
+
if (isNonSequential(condition.hashMode)) {
|
|
3164
|
+
return signNonSequentialWithAccount(tx, condition, account);
|
|
3165
|
+
}
|
|
3166
|
+
return signSequentialWithAccount(tx, condition, account, publicKeys, signerIndex);
|
|
3167
|
+
}
|
|
3168
|
+
async function signNonSequentialWithAccount(tx, condition, account) {
|
|
3169
|
+
const fields = [...condition.fields];
|
|
3170
|
+
const preSignHash = nonSequentialPreSignHash(tx);
|
|
3171
|
+
const sigBytes = await account.sign(hexToBytes(preSignHash));
|
|
3172
|
+
const nextSig = bytesToHex(sigBytes);
|
|
3173
|
+
fields.push({
|
|
3174
|
+
type: "signature",
|
|
3175
|
+
pubKeyEncoding: PubKeyEncoding.Compressed,
|
|
3176
|
+
data: nextSig
|
|
3177
|
+
});
|
|
3178
|
+
const newCondition = { ...condition, fields };
|
|
3179
|
+
return {
|
|
3180
|
+
...tx,
|
|
3181
|
+
auth: { ...tx.auth, spendingCondition: newCondition }
|
|
3182
|
+
};
|
|
3183
|
+
}
|
|
3184
|
+
async function signSequentialWithAccount(tx, condition, account, publicKeys, signerIndex) {
|
|
3185
|
+
const fields = [...condition.fields];
|
|
3186
|
+
let curSigHash = initialSigHash(tx);
|
|
3187
|
+
for (const field of fields) {
|
|
3188
|
+
const preSign2 = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
|
|
3189
|
+
curSigHash = sigHashPostSign(preSign2, field.pubKeyEncoding, field.data);
|
|
3190
|
+
}
|
|
3191
|
+
for (let i = fields.length;i < signerIndex; i++) {
|
|
3192
|
+
const pubKeyField = {
|
|
3193
|
+
type: "publicKey",
|
|
3194
|
+
pubKeyEncoding: PubKeyEncoding.Compressed,
|
|
3195
|
+
data: publicKeys[i]
|
|
3196
|
+
};
|
|
3197
|
+
fields.push(pubKeyField);
|
|
3198
|
+
const preSign2 = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
|
|
3199
|
+
curSigHash = sigHashPostSign(preSign2, pubKeyField.pubKeyEncoding, pubKeyField.data);
|
|
3200
|
+
}
|
|
3201
|
+
const preSign = sigHashPreSign(curSigHash, AuthType.Standard, condition.fee, condition.nonce);
|
|
3202
|
+
const sigBytes = await account.sign(hexToBytes(preSign));
|
|
3203
|
+
const nextSig = bytesToHex(sigBytes);
|
|
3204
|
+
const nextSigHash = sigHashPostSign(preSign, PubKeyEncoding.Compressed, nextSig);
|
|
3205
|
+
fields.push({
|
|
3206
|
+
type: "signature",
|
|
3207
|
+
pubKeyEncoding: PubKeyEncoding.Compressed,
|
|
3208
|
+
data: nextSig
|
|
3209
|
+
});
|
|
3210
|
+
curSigHash = nextSigHash;
|
|
3211
|
+
const newCondition = { ...condition, fields };
|
|
3212
|
+
const sigCount = fields.filter((f) => f.type === "signature").length;
|
|
3213
|
+
let finalCondition = newCondition;
|
|
3214
|
+
if (sigCount >= condition.signaturesRequired) {
|
|
3215
|
+
finalCondition = finalizeMultiSigCondition(newCondition, publicKeys, curSigHash);
|
|
3216
|
+
}
|
|
3217
|
+
return {
|
|
3218
|
+
...tx,
|
|
3219
|
+
auth: {
|
|
3220
|
+
...tx.auth,
|
|
3221
|
+
spendingCondition: finalCondition
|
|
3222
|
+
}
|
|
3223
|
+
};
|
|
3224
|
+
}
|
|
3225
|
+
function finalizeMultiSig(tx, publicKeys) {
|
|
3226
|
+
const condition = tx.auth.spendingCondition;
|
|
3227
|
+
if (isNonSequential(condition.hashMode)) {
|
|
3228
|
+
return tx;
|
|
3229
|
+
}
|
|
3230
|
+
const curSigHash = replayMultiSigSigHash(tx);
|
|
3231
|
+
const finalCondition = finalizeMultiSigCondition(condition, publicKeys, curSigHash);
|
|
3232
|
+
return {
|
|
3233
|
+
...tx,
|
|
3234
|
+
auth: {
|
|
3235
|
+
...tx.auth,
|
|
3236
|
+
spendingCondition: finalCondition
|
|
3237
|
+
}
|
|
3238
|
+
};
|
|
3239
|
+
}
|
|
3240
|
+
function finalizeMultiSigCondition(condition, publicKeys, curSigHash) {
|
|
3241
|
+
const fields = [...condition.fields];
|
|
3242
|
+
let sigHash = curSigHash;
|
|
3243
|
+
for (let i = fields.length;i < publicKeys.length; i++) {
|
|
3244
|
+
const pubKeyField = {
|
|
3245
|
+
type: "publicKey",
|
|
3246
|
+
pubKeyEncoding: PubKeyEncoding.Compressed,
|
|
3247
|
+
data: publicKeys[i]
|
|
3248
|
+
};
|
|
3249
|
+
fields.push(pubKeyField);
|
|
3250
|
+
const preSign = sigHashPreSign(sigHash, AuthType.Standard, condition.fee, condition.nonce);
|
|
3251
|
+
sigHash = sigHashPostSign(preSign, pubKeyField.pubKeyEncoding, pubKeyField.data);
|
|
3252
|
+
}
|
|
3253
|
+
return { ...condition, fields };
|
|
3254
|
+
}
|
|
3255
|
+
function combineMultiSigSignatures(baseTx, signedTxs) {
|
|
3256
|
+
const condition = baseTx.auth.spendingCondition;
|
|
3257
|
+
if (!isNonSequential(condition.hashMode)) {
|
|
3258
|
+
throw new Error("combineMultiSigSignatures only works with non-sequential hash modes (SIP-027)");
|
|
3259
|
+
}
|
|
3260
|
+
const seenSigs = new Set;
|
|
3261
|
+
const signatures = [];
|
|
3262
|
+
for (const stx of signedTxs) {
|
|
3263
|
+
const stxCondition = stx.auth.spendingCondition;
|
|
3264
|
+
for (const field of stxCondition.fields) {
|
|
3265
|
+
if (field.type === "signature" && !seenSigs.has(field.data)) {
|
|
3266
|
+
seenSigs.add(field.data);
|
|
3267
|
+
signatures.push(field);
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
3270
|
+
}
|
|
3271
|
+
if (signatures.length === 0) {
|
|
3272
|
+
throw new Error("No signatures found in the provided transactions");
|
|
3273
|
+
}
|
|
3274
|
+
const newCondition = {
|
|
3275
|
+
...condition,
|
|
3276
|
+
fields: signatures
|
|
3277
|
+
};
|
|
3278
|
+
return {
|
|
3279
|
+
...baseTx,
|
|
3280
|
+
auth: { ...baseTx.auth, spendingCondition: newCondition }
|
|
3281
|
+
};
|
|
3282
|
+
}
|
|
3283
|
+
|
|
3284
|
+
// src/transactions/build.ts
|
|
3285
|
+
function resolvePcMode(mode) {
|
|
3286
|
+
if (mode === "allow")
|
|
3287
|
+
return PostConditionModeWire.Allow;
|
|
3288
|
+
if (mode === "originator")
|
|
3289
|
+
return PostConditionModeWire.Originator;
|
|
3290
|
+
return PostConditionModeWire.Deny;
|
|
3291
|
+
}
|
|
3292
|
+
function convertPostConditions(pcs) {
|
|
3293
|
+
if (!pcs || pcs.length === 0)
|
|
3294
|
+
return [];
|
|
3295
|
+
return pcs.map((pc) => convertPostCondition(typeof pc === "string" ? fromHex(pc) : pc));
|
|
3296
|
+
}
|
|
3297
|
+
function resolveSpendingCondition(opts, nonce, fee) {
|
|
3298
|
+
if (opts.publicKeys) {
|
|
3299
|
+
return createMultiSigSpendingCondition(opts.publicKeys, opts.signaturesRequired, nonce, fee, opts.hashMode);
|
|
3300
|
+
}
|
|
3301
|
+
return createSingleSigSpendingCondition(opts.publicKey, nonce, fee);
|
|
3302
|
+
}
|
|
3303
|
+
function resolveAuth(spendingCondition, sponsored) {
|
|
3304
|
+
return sponsored ? createSponsoredAuth(spendingCondition) : createStandardAuth(spendingCondition);
|
|
3305
|
+
}
|
|
3306
|
+
function resolveVersionAndChainId(chain) {
|
|
3307
|
+
if (!chain)
|
|
3308
|
+
return { version: 0, chainId: 1 };
|
|
3309
|
+
return { version: chain.transactionVersion, chainId: chain.id };
|
|
3310
|
+
}
|
|
3311
|
+
function buildTokenTransfer(options) {
|
|
3312
|
+
const { version, chainId } = resolveVersionAndChainId(options.chain);
|
|
3313
|
+
const fee = intToBigInt(options.fee);
|
|
3314
|
+
const nonce = intToBigInt(options.nonce);
|
|
3315
|
+
const spendingCondition = resolveSpendingCondition(options, nonce, fee);
|
|
3316
|
+
const recipient = Cl.principal(options.recipient);
|
|
3317
|
+
const tx = {
|
|
3318
|
+
version,
|
|
3319
|
+
chainId,
|
|
3320
|
+
auth: resolveAuth(spendingCondition, options.sponsored),
|
|
3321
|
+
anchorMode: AnchorMode.Any,
|
|
3322
|
+
postConditionMode: resolvePcMode(options.postConditionMode),
|
|
3323
|
+
postConditions: convertPostConditions(options.postConditions),
|
|
3324
|
+
payload: {
|
|
3325
|
+
payloadType: PayloadType.TokenTransfer,
|
|
3326
|
+
recipient,
|
|
3327
|
+
amount: intToBigInt(options.amount),
|
|
3328
|
+
memo: options.memo ?? ""
|
|
3329
|
+
}
|
|
3330
|
+
};
|
|
3331
|
+
if (options.publicKeys) {
|
|
3332
|
+
tx._multisig = { publicKeys: options.publicKeys };
|
|
3333
|
+
}
|
|
3334
|
+
return tx;
|
|
3335
|
+
}
|
|
3336
|
+
function buildContractCall(options) {
|
|
3337
|
+
const { version, chainId } = resolveVersionAndChainId(options.chain);
|
|
3338
|
+
const fee = intToBigInt(options.fee);
|
|
3339
|
+
const nonce = intToBigInt(options.nonce);
|
|
3340
|
+
const spendingCondition = resolveSpendingCondition(options, nonce, fee);
|
|
3341
|
+
const tx = {
|
|
3342
|
+
version,
|
|
3343
|
+
chainId,
|
|
3344
|
+
auth: resolveAuth(spendingCondition, options.sponsored),
|
|
3345
|
+
anchorMode: AnchorMode.Any,
|
|
3346
|
+
postConditionMode: resolvePcMode(options.postConditionMode),
|
|
3347
|
+
postConditions: convertPostConditions(options.postConditions),
|
|
3348
|
+
payload: {
|
|
3349
|
+
payloadType: PayloadType.ContractCall,
|
|
3350
|
+
contractAddress: options.contractAddress,
|
|
3351
|
+
contractName: options.contractName,
|
|
3352
|
+
functionName: options.functionName,
|
|
3353
|
+
functionArgs: options.functionArgs
|
|
3354
|
+
}
|
|
3355
|
+
};
|
|
3356
|
+
if (options.publicKeys) {
|
|
3357
|
+
tx._multisig = { publicKeys: options.publicKeys };
|
|
3358
|
+
}
|
|
3359
|
+
return tx;
|
|
3360
|
+
}
|
|
3361
|
+
function buildContractDeploy(options) {
|
|
3362
|
+
const { version, chainId } = resolveVersionAndChainId(options.chain);
|
|
3363
|
+
const fee = intToBigInt(options.fee);
|
|
3364
|
+
const nonce = intToBigInt(options.nonce);
|
|
3365
|
+
const spendingCondition = resolveSpendingCondition(options, nonce, fee);
|
|
3366
|
+
const clarityVersion = options.clarityVersion ?? ClarityVersion.Clarity4;
|
|
3367
|
+
const tx = {
|
|
3368
|
+
version,
|
|
3369
|
+
chainId,
|
|
3370
|
+
auth: resolveAuth(spendingCondition, options.sponsored),
|
|
3371
|
+
anchorMode: AnchorMode.Any,
|
|
3372
|
+
postConditionMode: resolvePcMode(options.postConditionMode),
|
|
3373
|
+
postConditions: convertPostConditions(options.postConditions),
|
|
3374
|
+
payload: {
|
|
3375
|
+
payloadType: PayloadType.VersionedSmartContract,
|
|
3376
|
+
clarityVersion,
|
|
3377
|
+
contractName: options.contractName,
|
|
3378
|
+
codeBody: options.codeBody
|
|
3379
|
+
}
|
|
3380
|
+
};
|
|
3381
|
+
if (options.publicKeys) {
|
|
3382
|
+
tx._multisig = { publicKeys: options.publicKeys };
|
|
3383
|
+
}
|
|
3384
|
+
return tx;
|
|
3385
|
+
}
|
|
3386
|
+
|
|
3387
|
+
// src/errors/response.ts
|
|
3388
|
+
class MalformedResponseError extends BaseError {
|
|
3389
|
+
name = "MalformedResponseError";
|
|
3390
|
+
}
|
|
3391
|
+
|
|
3392
|
+
class ReadContractError extends BaseError {
|
|
3393
|
+
name = "ReadContractError";
|
|
3394
|
+
}
|
|
3395
|
+
|
|
3396
|
+
// src/actions/public/getMapEntry.ts
|
|
3397
|
+
async function getMapEntry(client, params) {
|
|
3398
|
+
const [address, name] = parseContractId(params.contract);
|
|
3399
|
+
const serializedKey = with0x(bytesToHex(serializeCVBytes(params.key)));
|
|
3400
|
+
const data = await client.request(`/v2/map_entry/${address}/${name}/${params.mapName}`, {
|
|
3401
|
+
method: "POST",
|
|
3402
|
+
body: serializedKey
|
|
3403
|
+
});
|
|
3404
|
+
if (typeof data?.data !== "string") {
|
|
3405
|
+
throw new MalformedResponseError(`getMapEntry: /v2/map_entry/${address}/${name}/${params.mapName} response is missing "data"`);
|
|
3406
|
+
}
|
|
3407
|
+
return deserializeCVBytes(data.data);
|
|
3408
|
+
}
|
|
3409
|
+
|
|
3410
|
+
// src/actions/public/getNonce.ts
|
|
3411
|
+
async function getNonce(client, params) {
|
|
3412
|
+
const data = await client.request(`/v2/accounts/${encodeURIComponent(params.address)}`, { method: "GET" });
|
|
3413
|
+
const nonce = data?.nonce;
|
|
3414
|
+
if (typeof nonce !== "number" && typeof nonce !== "string") {
|
|
3415
|
+
throw new MalformedResponseError(`getNonce: /v2/accounts/${params.address} response is missing "nonce"`);
|
|
3416
|
+
}
|
|
3417
|
+
return BigInt(nonce);
|
|
3418
|
+
}
|
|
3419
|
+
|
|
3420
|
+
// src/actions/public/readContract.ts
|
|
3421
|
+
async function readContract(client, params) {
|
|
3422
|
+
const [address, name] = parseContractId(params.contract);
|
|
3423
|
+
const sender = params.sender ?? address;
|
|
3424
|
+
const serializedArgs = (params.args ?? []).map((arg) => with0x(bytesToHex(serializeCVBytes(arg))));
|
|
3425
|
+
const path = `/v2/contracts/call-read/${encodeURIComponent(address)}/${encodeURIComponent(name)}/${encodeURIComponent(params.functionName)}`;
|
|
3426
|
+
const data = await client.request(params.tip ? `${path}?tip=${encodeURIComponent(params.tip)}` : path, {
|
|
3427
|
+
method: "POST",
|
|
3428
|
+
body: {
|
|
3429
|
+
sender,
|
|
3430
|
+
arguments: serializedArgs
|
|
3431
|
+
}
|
|
3432
|
+
});
|
|
3433
|
+
if (data.okay) {
|
|
3434
|
+
if (typeof data.result !== "string") {
|
|
3435
|
+
throw new MalformedResponseError(`readContract: /v2/contracts/call-read response is missing "result"`);
|
|
3436
|
+
}
|
|
3437
|
+
return deserializeCVBytes(data.result);
|
|
3438
|
+
}
|
|
3439
|
+
throw new ReadContractError(data.cause ?? "Read-only call failed");
|
|
3440
|
+
}
|
|
3441
|
+
|
|
3442
|
+
// src/transactions/signer.ts
|
|
3443
|
+
function txid(tx) {
|
|
3444
|
+
return txidFromBytes(serializeTransaction(tx));
|
|
3445
|
+
}
|
|
3446
|
+
function signBegin(tx) {
|
|
3447
|
+
const cleared = {
|
|
3448
|
+
...tx,
|
|
3449
|
+
auth: intoInitialSighashAuth(tx.auth)
|
|
3450
|
+
};
|
|
3451
|
+
return txid(cleared);
|
|
3452
|
+
}
|
|
3453
|
+
function signTransaction(tx, privateKey) {
|
|
3454
|
+
const sigHash = signBegin(tx);
|
|
3455
|
+
const condition = tx.auth.spendingCondition;
|
|
3456
|
+
const { nextSig } = nextSignature(sigHash, AuthType.Standard, condition.fee, condition.nonce, privateKey);
|
|
3457
|
+
return {
|
|
3458
|
+
...tx,
|
|
3459
|
+
auth: {
|
|
3460
|
+
...tx.auth,
|
|
3461
|
+
spendingCondition: {
|
|
3462
|
+
...condition,
|
|
3463
|
+
signature: nextSig
|
|
3464
|
+
}
|
|
3465
|
+
}
|
|
3466
|
+
};
|
|
3467
|
+
}
|
|
3468
|
+
async function signTransactionWithAccount(tx, account) {
|
|
3469
|
+
const sigHash = signBegin(tx);
|
|
3470
|
+
const condition = tx.auth.spendingCondition;
|
|
3471
|
+
const sigHashPre = sigHashPreSign(sigHash, AuthType.Standard, condition.fee, condition.nonce);
|
|
3472
|
+
const sigBytes = await account.sign(hexToBytes(sigHashPre));
|
|
3473
|
+
const nextSig = bytesToHex(sigBytes);
|
|
3474
|
+
return {
|
|
3475
|
+
...tx,
|
|
3476
|
+
auth: {
|
|
3477
|
+
...tx.auth,
|
|
3478
|
+
spendingCondition: {
|
|
3479
|
+
...condition,
|
|
3480
|
+
signature: nextSig
|
|
3481
|
+
}
|
|
3482
|
+
}
|
|
3483
|
+
};
|
|
3484
|
+
}
|
|
3485
|
+
function getTransactionId(tx) {
|
|
3486
|
+
return txid(tx);
|
|
3487
|
+
}
|
|
3488
|
+
function getOriginSigHash(tx) {
|
|
3489
|
+
const condition = tx.auth.spendingCondition;
|
|
3490
|
+
if ("fields" in condition) {
|
|
3491
|
+
return replayMultiSigSigHash(tx);
|
|
3492
|
+
}
|
|
3493
|
+
const initialSigHash2 = signBegin(tx);
|
|
3494
|
+
const sc = condition;
|
|
3495
|
+
const preSign = sigHashPreSign(initialSigHash2, AuthType.Standard, sc.fee, sc.nonce);
|
|
3496
|
+
return sigHashPostSign(preSign, sc.keyEncoding, sc.signature);
|
|
3497
|
+
}
|
|
3498
|
+
function signSponsor(tx, privateKey) {
|
|
3499
|
+
if (tx.auth.authType !== AuthType.Sponsored) {
|
|
3500
|
+
throw new Error("Transaction must be sponsored");
|
|
3501
|
+
}
|
|
3502
|
+
const auth = tx.auth;
|
|
3503
|
+
const sponsorCondition = auth.sponsorSpendingCondition;
|
|
3504
|
+
const originSigHash = getOriginSigHash(tx);
|
|
3505
|
+
const { nextSig } = nextSignature(originSigHash, AuthType.Sponsored, sponsorCondition.fee, sponsorCondition.nonce, privateKey);
|
|
3506
|
+
return {
|
|
3507
|
+
...tx,
|
|
3508
|
+
auth: {
|
|
3509
|
+
...auth,
|
|
3510
|
+
sponsorSpendingCondition: {
|
|
3511
|
+
...sponsorCondition,
|
|
3512
|
+
signature: nextSig
|
|
3513
|
+
}
|
|
3514
|
+
}
|
|
3515
|
+
};
|
|
3516
|
+
}
|
|
3517
|
+
async function signSponsorWithAccount(tx, account) {
|
|
3518
|
+
if (tx.auth.authType !== AuthType.Sponsored) {
|
|
3519
|
+
throw new Error("Transaction must be sponsored");
|
|
3520
|
+
}
|
|
3521
|
+
const auth = tx.auth;
|
|
3522
|
+
const sponsorCondition = auth.sponsorSpendingCondition;
|
|
3523
|
+
const originSigHash = getOriginSigHash(tx);
|
|
3524
|
+
const sigHashPre = sigHashPreSign(originSigHash, AuthType.Sponsored, sponsorCondition.fee, sponsorCondition.nonce);
|
|
3525
|
+
const sigBytes = await account.sign(hexToBytes(sigHashPre));
|
|
3526
|
+
const nextSig = bytesToHex(sigBytes);
|
|
3527
|
+
return {
|
|
3528
|
+
...tx,
|
|
3529
|
+
auth: {
|
|
3530
|
+
...auth,
|
|
3531
|
+
sponsorSpendingCondition: {
|
|
3532
|
+
...sponsorCondition,
|
|
3533
|
+
signature: nextSig
|
|
3534
|
+
}
|
|
3535
|
+
}
|
|
3536
|
+
};
|
|
3537
|
+
}
|
|
3538
|
+
|
|
3539
|
+
// src/errors/http.ts
|
|
3540
|
+
class HttpRequestError extends BaseError {
|
|
3541
|
+
name = "HttpRequestError";
|
|
3542
|
+
status;
|
|
3543
|
+
url;
|
|
3544
|
+
method;
|
|
3545
|
+
constructor(status, options) {
|
|
3546
|
+
const where = options?.url !== undefined ? ` (${options.method ?? "GET"} ${options.url})` : "";
|
|
3547
|
+
super(`HTTP request failed with status ${status}${where}`, options);
|
|
3548
|
+
this.status = status;
|
|
3549
|
+
this.url = options?.url;
|
|
3550
|
+
this.method = options?.method;
|
|
3551
|
+
}
|
|
3552
|
+
}
|
|
3553
|
+
|
|
3554
|
+
// src/errors/transport.ts
|
|
3555
|
+
class TimeoutError extends BaseError {
|
|
3556
|
+
name = "TimeoutError";
|
|
3557
|
+
method;
|
|
3558
|
+
url;
|
|
3559
|
+
timeout;
|
|
3560
|
+
attempt;
|
|
3561
|
+
constructor(params) {
|
|
3562
|
+
super(`${params.method} ${params.url} did not complete within ${params.timeout}ms (attempt ${params.attempt + 1})`);
|
|
3563
|
+
this.method = params.method;
|
|
3564
|
+
this.url = params.url;
|
|
3565
|
+
this.timeout = params.timeout;
|
|
3566
|
+
this.attempt = params.attempt;
|
|
3567
|
+
}
|
|
3568
|
+
}
|
|
3569
|
+
|
|
3570
|
+
// src/transports/createTransport.ts
|
|
3571
|
+
function createTransport(type, config) {
|
|
3572
|
+
const { request, apiKey: _apiKey, ...exposed } = config;
|
|
3573
|
+
return {
|
|
3574
|
+
type,
|
|
3575
|
+
request,
|
|
3576
|
+
config: exposed
|
|
3577
|
+
};
|
|
3578
|
+
}
|
|
3579
|
+
var MAX_ERROR_DETAILS_BYTES = 4096;
|
|
3580
|
+
function capDetails(body) {
|
|
3581
|
+
if (body === undefined)
|
|
3582
|
+
return;
|
|
3583
|
+
const bytes = new TextEncoder().encode(body);
|
|
3584
|
+
if (bytes.length <= MAX_ERROR_DETAILS_BYTES)
|
|
3585
|
+
return body;
|
|
3586
|
+
const head = new TextDecoder().decode(bytes.subarray(0, MAX_ERROR_DETAILS_BYTES));
|
|
3587
|
+
return `${head}... [truncated ${bytes.length - MAX_ERROR_DETAILS_BYTES} bytes]`;
|
|
3588
|
+
}
|
|
3589
|
+
function isRetryableStatus(status) {
|
|
3590
|
+
return status === 429 || status >= 500;
|
|
3591
|
+
}
|
|
3592
|
+
var MAX_RETRY_AFTER_MS = 60000;
|
|
3593
|
+
function retryAfterMs(response) {
|
|
3594
|
+
const value = response.headers.get("Retry-After");
|
|
3595
|
+
if (!value)
|
|
3596
|
+
return;
|
|
3597
|
+
const seconds = Number(value);
|
|
3598
|
+
const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - Date.now();
|
|
3599
|
+
if (!Number.isFinite(ms) || ms < 0 || ms > MAX_RETRY_AFTER_MS)
|
|
3600
|
+
return;
|
|
3601
|
+
return ms;
|
|
3602
|
+
}
|
|
3603
|
+
function abortReason(signal) {
|
|
3604
|
+
const reason = signal.reason;
|
|
3605
|
+
if (reason instanceof Error)
|
|
3606
|
+
return reason;
|
|
3607
|
+
return new DOMException(typeof reason === "string" ? reason : "The operation was aborted", "AbortError");
|
|
3608
|
+
}
|
|
3609
|
+
function sleep(ms, signal) {
|
|
3610
|
+
return new Promise((resolve, reject) => {
|
|
3611
|
+
if (signal?.aborted)
|
|
3612
|
+
return reject(abortReason(signal));
|
|
3613
|
+
const onAbort = () => {
|
|
3614
|
+
clearTimeout(id);
|
|
3615
|
+
reject(abortReason(signal));
|
|
3616
|
+
};
|
|
3617
|
+
const id = setTimeout(() => {
|
|
3618
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3619
|
+
resolve();
|
|
3620
|
+
}, ms);
|
|
3621
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3622
|
+
});
|
|
3623
|
+
}
|
|
3624
|
+
async function fetchWithRetry(url, options, retryCount, retryDelay, timeout, extra = {}) {
|
|
3625
|
+
const { signal } = extra;
|
|
3626
|
+
const read = extra.read ?? (async (response) => response);
|
|
3627
|
+
const method = options.method ?? "GET";
|
|
3628
|
+
let lastError;
|
|
3629
|
+
for (let attempt = 0;attempt <= retryCount; attempt++) {
|
|
3630
|
+
if (signal?.aborted)
|
|
3631
|
+
throw abortReason(signal);
|
|
3632
|
+
const controller = new AbortController;
|
|
3633
|
+
let timedOut = false;
|
|
3634
|
+
const timeoutId = setTimeout(() => {
|
|
3635
|
+
timedOut = true;
|
|
3636
|
+
controller.abort(new TimeoutError({ method, url, timeout, attempt }));
|
|
3637
|
+
}, timeout);
|
|
3638
|
+
const onCallerAbort = () => controller.abort(abortReason(signal));
|
|
3639
|
+
signal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
3640
|
+
const aborted = new Promise((_, reject) => {
|
|
3641
|
+
if (controller.signal.aborted)
|
|
3642
|
+
return reject(controller.signal.reason);
|
|
3643
|
+
controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
|
|
3644
|
+
});
|
|
3645
|
+
let response;
|
|
3646
|
+
try {
|
|
3647
|
+
try {
|
|
3648
|
+
response = await Promise.race([
|
|
3649
|
+
fetch(url, { ...options, signal: controller.signal }),
|
|
3650
|
+
aborted
|
|
3651
|
+
]);
|
|
3652
|
+
} catch (error) {
|
|
3653
|
+
if (signal?.aborted)
|
|
3654
|
+
throw abortReason(signal);
|
|
3655
|
+
lastError = timedOut ? new TimeoutError({ method, url, timeout, attempt }) : error instanceof Error ? error : new Error(String(error));
|
|
3656
|
+
if (attempt < retryCount) {
|
|
3657
|
+
clearTimeout(timeoutId);
|
|
3658
|
+
await sleep(retryDelay * (attempt + 1), signal);
|
|
3659
|
+
continue;
|
|
3660
|
+
}
|
|
3661
|
+
throw lastError;
|
|
3662
|
+
}
|
|
3663
|
+
if (response.ok) {
|
|
3664
|
+
try {
|
|
3665
|
+
return await Promise.race([read(response), aborted]);
|
|
3666
|
+
} catch (error) {
|
|
3667
|
+
response.body?.cancel().catch(() => {});
|
|
3668
|
+
if (signal?.aborted)
|
|
3669
|
+
throw abortReason(signal);
|
|
3670
|
+
if (!timedOut)
|
|
3671
|
+
throw error;
|
|
3672
|
+
lastError = new TimeoutError({ method, url, timeout, attempt });
|
|
3673
|
+
if (attempt < retryCount) {
|
|
3674
|
+
clearTimeout(timeoutId);
|
|
3675
|
+
await sleep(retryDelay * (attempt + 1), signal);
|
|
3676
|
+
continue;
|
|
3677
|
+
}
|
|
3678
|
+
throw lastError;
|
|
3679
|
+
}
|
|
3680
|
+
}
|
|
3681
|
+
const retryable = isRetryableStatus(response.status);
|
|
3682
|
+
if (!retryable || attempt === retryCount) {
|
|
3683
|
+
const body = await Promise.race([
|
|
3684
|
+
response.text().catch(() => {
|
|
3685
|
+
return;
|
|
3686
|
+
}),
|
|
3687
|
+
aborted.catch(() => {
|
|
3688
|
+
return;
|
|
3689
|
+
})
|
|
3690
|
+
]);
|
|
3691
|
+
throw new HttpRequestError(response.status, {
|
|
3692
|
+
details: capDetails(body),
|
|
3693
|
+
url,
|
|
3694
|
+
method
|
|
3695
|
+
});
|
|
3696
|
+
}
|
|
3697
|
+
lastError = new HttpRequestError(response.status, { url, method });
|
|
3698
|
+
const delay = retryAfterMs(response) ?? retryDelay * (attempt + 1);
|
|
3699
|
+
response.body?.cancel().catch(() => {});
|
|
3700
|
+
clearTimeout(timeoutId);
|
|
3701
|
+
await sleep(delay, signal);
|
|
3702
|
+
} finally {
|
|
3703
|
+
clearTimeout(timeoutId);
|
|
3704
|
+
signal?.removeEventListener("abort", onCallerAbort);
|
|
3705
|
+
}
|
|
3706
|
+
}
|
|
3707
|
+
throw lastError ?? new Error("Request failed");
|
|
3708
|
+
}
|
|
3709
|
+
async function readBody(response) {
|
|
3710
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
3711
|
+
if (contentType.includes("application/json")) {
|
|
3712
|
+
return response.json();
|
|
3713
|
+
}
|
|
3714
|
+
return response.text();
|
|
3715
|
+
}
|
|
3716
|
+
function buildRequestFn(baseUrl, config) {
|
|
3717
|
+
const {
|
|
3718
|
+
timeout = 30000,
|
|
3719
|
+
retryCount = 3,
|
|
3720
|
+
retryDelay = 150,
|
|
3721
|
+
fetchOptions = {},
|
|
3722
|
+
apiKey
|
|
3723
|
+
} = config;
|
|
3724
|
+
return async (path, options) => {
|
|
3725
|
+
const url = `${baseUrl.replace(/\/$/, "")}${path}`;
|
|
3726
|
+
const headers = {
|
|
3727
|
+
"Content-Type": "application/json",
|
|
3728
|
+
...fetchOptions.headers,
|
|
3729
|
+
...options?.headers
|
|
3730
|
+
};
|
|
3731
|
+
if (apiKey) {
|
|
3732
|
+
headers["x-api-key"] = apiKey;
|
|
3733
|
+
}
|
|
3734
|
+
const init = {
|
|
3735
|
+
...fetchOptions,
|
|
3736
|
+
method: options?.method ?? "GET",
|
|
3737
|
+
headers
|
|
3738
|
+
};
|
|
3739
|
+
if (options?.body !== undefined) {
|
|
3740
|
+
init.body = JSON.stringify(options.body);
|
|
3741
|
+
}
|
|
3742
|
+
return fetchWithRetry(url, init, options?.retryCount ?? retryCount, retryDelay, timeout, { signal: options?.signal, read: readBody });
|
|
3743
|
+
};
|
|
3744
|
+
}
|
|
3745
|
+
|
|
3746
|
+
// src/actions/public/txSources.ts
|
|
3747
|
+
class IndexSourceConfigError extends Error {
|
|
3748
|
+
name = "IndexSourceConfigError";
|
|
3749
|
+
}
|
|
3750
|
+
function isHiroHost(url, client) {
|
|
3751
|
+
let hostname;
|
|
3752
|
+
try {
|
|
3753
|
+
hostname = new URL(url).hostname;
|
|
3754
|
+
} catch {
|
|
3755
|
+
return false;
|
|
3756
|
+
}
|
|
3757
|
+
if (hostname === "hiro.so" || hostname.endsWith(".hiro.so"))
|
|
3758
|
+
return true;
|
|
3759
|
+
const defaults = client.chain?.rpcUrls?.default?.http ?? [];
|
|
3760
|
+
return defaults.some((d) => {
|
|
3761
|
+
try {
|
|
3762
|
+
return new URL(d).hostname === hostname && hostname !== "localhost";
|
|
3763
|
+
} catch {
|
|
3764
|
+
return false;
|
|
3765
|
+
}
|
|
3766
|
+
});
|
|
3767
|
+
}
|
|
3768
|
+
function indexRequestFn(client, baseUrl, sourceName) {
|
|
3769
|
+
const transportUrl = client.transport.config.url?.replace(/\/$/, "");
|
|
3770
|
+
if (baseUrl === undefined) {
|
|
3771
|
+
if (!transportUrl) {
|
|
3772
|
+
throw new IndexSourceConfigError(`${sourceName} needs the URL of your Secondlayer instance: pass baseUrl, or use an http() transport pointed at the instance`);
|
|
3773
|
+
}
|
|
3774
|
+
if (isHiroHost(transportUrl, client)) {
|
|
3775
|
+
throw new IndexSourceConfigError(`${sourceName} reads /v1/index on a Secondlayer instance, and ${transportUrl} is a Hiro host: pass baseUrl with the URL of your instance`);
|
|
3776
|
+
}
|
|
3777
|
+
return client.request;
|
|
3778
|
+
}
|
|
3779
|
+
const target = baseUrl.replace(/\/$/, "");
|
|
3780
|
+
if (target === transportUrl)
|
|
3781
|
+
return client.request;
|
|
3782
|
+
const { timeout, retryCount, retryDelay } = client.transport.config;
|
|
3783
|
+
return buildRequestFn(target, { timeout, retryCount, retryDelay });
|
|
3784
|
+
}
|
|
3785
|
+
function indexNotFound(error, sourceName) {
|
|
3786
|
+
if (!(error instanceof HttpRequestError) || error.status !== 404) {
|
|
3787
|
+
return false;
|
|
3788
|
+
}
|
|
3789
|
+
const body = error.details;
|
|
3790
|
+
if (body !== undefined) {
|
|
3791
|
+
try {
|
|
3792
|
+
JSON.parse(body);
|
|
3793
|
+
} catch {
|
|
3794
|
+
throw new IndexSourceConfigError(`${sourceName} got a non-JSON 404 from ${error.url ?? "the transport host"}: it does not serve /v1/index, pass baseUrl with the URL of your Secondlayer instance`, { cause: error });
|
|
3795
|
+
}
|
|
3796
|
+
}
|
|
3797
|
+
return true;
|
|
3798
|
+
}
|
|
3799
|
+
function normalizeTxid(txid2) {
|
|
3800
|
+
return txid2.startsWith("0x") ? txid2 : `0x${txid2}`;
|
|
3801
|
+
}
|
|
3802
|
+
function decodeResultHex(hex) {
|
|
3803
|
+
if (!hex)
|
|
3804
|
+
return {};
|
|
3805
|
+
try {
|
|
3806
|
+
return { result: deserializeCVBytes(hex), resultHex: hex };
|
|
3807
|
+
} catch {
|
|
3808
|
+
return { resultHex: hex };
|
|
3809
|
+
}
|
|
3810
|
+
}
|
|
3811
|
+
function normalizeStatus(txStatus) {
|
|
3812
|
+
switch (txStatus) {
|
|
3813
|
+
case "pending":
|
|
3814
|
+
case "success":
|
|
3815
|
+
case "abort_by_response":
|
|
3816
|
+
case "abort_by_post_condition":
|
|
3817
|
+
return txStatus;
|
|
3818
|
+
default:
|
|
3819
|
+
return txStatus.startsWith("dropped") ? "dropped" : undefined;
|
|
3820
|
+
}
|
|
3821
|
+
}
|
|
3822
|
+
function extendedApiSource() {
|
|
3823
|
+
return {
|
|
3824
|
+
async get({ client, txid: txid2 }) {
|
|
3825
|
+
let data;
|
|
3826
|
+
try {
|
|
3827
|
+
data = await client.request(`/extended/v1/tx/${encodeURIComponent(normalizeTxid(txid2))}`, { method: "GET" });
|
|
3828
|
+
} catch (error) {
|
|
3829
|
+
if (error instanceof HttpRequestError && error.status === 404) {
|
|
3830
|
+
return { receipt: null };
|
|
3831
|
+
}
|
|
3832
|
+
throw error;
|
|
3833
|
+
}
|
|
3834
|
+
const txStatus = typeof data?.tx_status === "string" ? data.tx_status : undefined;
|
|
3835
|
+
if (!txStatus)
|
|
3836
|
+
return { receipt: null };
|
|
3837
|
+
const status = normalizeStatus(txStatus);
|
|
3838
|
+
if (!status)
|
|
3839
|
+
return { receipt: null };
|
|
3840
|
+
return {
|
|
3841
|
+
receipt: {
|
|
3842
|
+
txid: normalizeTxid(txid2),
|
|
3843
|
+
status,
|
|
3844
|
+
blockHeight: typeof data.block_height === "number" && data.block_height > 0 ? data.block_height : undefined,
|
|
3845
|
+
blockHash: data.block_hash ?? undefined,
|
|
3846
|
+
...decodeResultHex(data.tx_result?.hex),
|
|
3847
|
+
events: Array.isArray(data.events) ? data.events : [],
|
|
3848
|
+
raw: data
|
|
3849
|
+
}
|
|
3850
|
+
};
|
|
3851
|
+
}
|
|
3852
|
+
};
|
|
3853
|
+
}
|
|
3854
|
+
function indexTxSource(params = {}) {
|
|
3855
|
+
const headers = params.apiKey ? { authorization: `Bearer ${params.apiKey}` } : undefined;
|
|
3856
|
+
return {
|
|
3857
|
+
canonicalOnly: true,
|
|
3858
|
+
async get({ client, txid: txid2 }) {
|
|
3859
|
+
const request = indexRequestFn(client, params.baseUrl, "indexTxSource");
|
|
3860
|
+
let data;
|
|
3861
|
+
try {
|
|
3862
|
+
data = await request(`/v1/index/transactions/${normalizeTxid(txid2)}`, {
|
|
3863
|
+
method: "GET",
|
|
3864
|
+
headers
|
|
3865
|
+
});
|
|
3866
|
+
} catch (error) {
|
|
3867
|
+
if (indexNotFound(error, "indexTxSource"))
|
|
3868
|
+
return { receipt: null };
|
|
3869
|
+
throw error;
|
|
3870
|
+
}
|
|
3871
|
+
const tx = data.transaction;
|
|
3872
|
+
const tip = data.tip?.block_height;
|
|
3873
|
+
if (!tx)
|
|
3874
|
+
return { receipt: null, tip };
|
|
3875
|
+
const status = normalizeStatus(tx.status) ?? "success";
|
|
3876
|
+
return {
|
|
3877
|
+
receipt: {
|
|
3878
|
+
txid: normalizeTxid(tx.tx_id),
|
|
3879
|
+
status,
|
|
3880
|
+
blockHeight: tx.block_height,
|
|
3881
|
+
...decodeResultHex(tx.contract_call?.result_hex),
|
|
3882
|
+
events: [],
|
|
3883
|
+
raw: data
|
|
3884
|
+
},
|
|
3885
|
+
tip
|
|
3886
|
+
};
|
|
3887
|
+
}
|
|
3888
|
+
};
|
|
3889
|
+
}
|
|
3890
|
+
|
|
3891
|
+
// src/actions/public/getTransaction.ts
|
|
3892
|
+
async function getTransaction(client, params) {
|
|
3893
|
+
const source = params.source ?? extendedApiSource();
|
|
3894
|
+
const { receipt } = await source.get({ client, txid: params.txid });
|
|
3895
|
+
return receipt;
|
|
3896
|
+
}
|
|
3897
|
+
|
|
3898
|
+
// src/actions/public/getBlockHeight.ts
|
|
3899
|
+
async function getBlockHeight(client) {
|
|
3900
|
+
const data = await client.request("/v2/info", { method: "GET" });
|
|
3901
|
+
if (typeof data?.stacks_tip_height !== "number") {
|
|
3902
|
+
throw new MalformedResponseError('getBlockHeight: /v2/info response is missing "stacks_tip_height"');
|
|
3903
|
+
}
|
|
3904
|
+
return data.stacks_tip_height;
|
|
3905
|
+
}
|
|
3906
|
+
|
|
3907
|
+
// src/actions/public/waitForTransactionReceipt.ts
|
|
3908
|
+
var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3909
|
+
async function waitForTransactionReceipt(client, params) {
|
|
3910
|
+
const {
|
|
3911
|
+
txid: txid2,
|
|
3912
|
+
confirmations = 1,
|
|
3913
|
+
timeout = 180000,
|
|
3914
|
+
pollingInterval = 3000
|
|
3915
|
+
} = params;
|
|
3916
|
+
const source = params.source ?? extendedApiSource();
|
|
3917
|
+
const droppedGracePeriod = params.droppedGracePeriod ?? (source.canonicalOnly ? timeout : 30000);
|
|
3918
|
+
const startedAt = Date.now();
|
|
3919
|
+
let unknownSince = null;
|
|
3920
|
+
let everPending = false;
|
|
3921
|
+
while (true) {
|
|
3922
|
+
const snapshot = await source.get({ client, txid: txid2 });
|
|
3923
|
+
const receipt = snapshot.receipt;
|
|
3924
|
+
if (receipt === null) {
|
|
3925
|
+
unknownSince ??= Date.now();
|
|
3926
|
+
if (Date.now() - unknownSince >= droppedGracePeriod) {
|
|
3927
|
+
throw new TransactionDroppedError(everPending ? `Transaction ${txid2} left the mempool without being mined` : `Transaction ${txid2} was never observed by the status source`, { txid: txid2 });
|
|
3928
|
+
}
|
|
3929
|
+
} else {
|
|
3930
|
+
unknownSince = null;
|
|
3931
|
+
switch (receipt.status) {
|
|
3932
|
+
case "dropped":
|
|
3933
|
+
throw new TransactionDroppedError(`Transaction ${txid2} was dropped from the mempool`, { txid: txid2 });
|
|
3934
|
+
case "abort_by_response":
|
|
3935
|
+
case "abort_by_post_condition":
|
|
3936
|
+
throw new TransactionAbortedError(`Transaction ${txid2} aborted (${receipt.status})`, { receipt });
|
|
3937
|
+
case "pending":
|
|
3938
|
+
everPending = true;
|
|
3939
|
+
break;
|
|
3940
|
+
case "success": {
|
|
3941
|
+
if (confirmations <= 1)
|
|
3942
|
+
return receipt;
|
|
3943
|
+
if (receipt.blockHeight !== undefined) {
|
|
3944
|
+
const tip = snapshot.tip ?? await getBlockHeight(client);
|
|
3945
|
+
if (tip - receipt.blockHeight + 1 >= confirmations)
|
|
3946
|
+
return receipt;
|
|
3947
|
+
}
|
|
3948
|
+
break;
|
|
3949
|
+
}
|
|
3950
|
+
}
|
|
3951
|
+
}
|
|
3952
|
+
if (Date.now() - startedAt >= timeout) {
|
|
3953
|
+
throw new WaitForTransactionTimeoutError(`Timed out after ${timeout}ms waiting for transaction ${txid2}`, { txid: txid2 });
|
|
3954
|
+
}
|
|
3955
|
+
await sleep2(pollingInterval);
|
|
3956
|
+
}
|
|
3957
|
+
}
|
|
3958
|
+
|
|
3959
|
+
// src/actions/wallet/sendTransaction.ts
|
|
3960
|
+
async function sendTransaction(client, params) {
|
|
3961
|
+
const hex = bytesToHex(serializeTransaction(params.transaction));
|
|
3962
|
+
const body = { tx: hex };
|
|
3963
|
+
if (params.attachment) {
|
|
3964
|
+
body.attachment = typeof params.attachment === "string" ? params.attachment : bytesToHex(params.attachment);
|
|
3965
|
+
}
|
|
3966
|
+
let data;
|
|
3967
|
+
try {
|
|
3968
|
+
data = await client.request("/v2/transactions", {
|
|
3969
|
+
method: "POST",
|
|
3970
|
+
body,
|
|
3971
|
+
retryCount: 0
|
|
3972
|
+
});
|
|
3973
|
+
} catch (error) {
|
|
3974
|
+
if (error instanceof HttpRequestError && error.details) {
|
|
3975
|
+
try {
|
|
3976
|
+
data = JSON.parse(error.details);
|
|
3977
|
+
} catch {
|
|
3978
|
+
throw error;
|
|
3979
|
+
}
|
|
3980
|
+
} else if (error instanceof TimeoutError) {
|
|
3981
|
+
const txid3 = getTransactionId(params.transaction);
|
|
3982
|
+
const receipt = await getTransaction(client, { txid: txid3 }).catch(() => null);
|
|
3983
|
+
if (receipt === null)
|
|
3984
|
+
throw error;
|
|
3985
|
+
data = { txid: txid3 };
|
|
3986
|
+
} else {
|
|
3987
|
+
throw error;
|
|
3988
|
+
}
|
|
3989
|
+
}
|
|
3990
|
+
if (data.error) {
|
|
3991
|
+
throw new BroadcastError(data.reason ?? data.error, {
|
|
3992
|
+
reason: data.reason,
|
|
3993
|
+
reasonData: data.reason_data,
|
|
3994
|
+
txid: data.txid ?? getTransactionId(params.transaction)
|
|
3995
|
+
});
|
|
3996
|
+
}
|
|
3997
|
+
const txid2 = typeof data === "string" ? data.replace(/"/g, "") : data.txid ?? getTransactionId(params.transaction);
|
|
3998
|
+
if (params.wait) {
|
|
3999
|
+
const confirmations = params.wait === true ? 1 : params.wait;
|
|
4000
|
+
const receipt = await waitForTransactionReceipt(client, {
|
|
4001
|
+
txid: txid2,
|
|
4002
|
+
confirmations
|
|
4003
|
+
});
|
|
4004
|
+
return { txid: txid2, receipt };
|
|
4005
|
+
}
|
|
4006
|
+
return { txid: txid2 };
|
|
4007
|
+
}
|
|
4008
|
+
|
|
4009
|
+
// src/actions/wallet/nonceManager.ts
|
|
4010
|
+
function jsonRpcSource() {
|
|
4011
|
+
return {
|
|
4012
|
+
get: ({ client, address }) => getNonce(client, { address })
|
|
4013
|
+
};
|
|
4014
|
+
}
|
|
4015
|
+
function memoryStore() {
|
|
4016
|
+
const next = new Map;
|
|
4017
|
+
const locks = new Map;
|
|
4018
|
+
function withLock(key, fn) {
|
|
4019
|
+
const prev = locks.get(key) ?? Promise.resolve();
|
|
4020
|
+
const run = prev.then(fn, fn);
|
|
4021
|
+
locks.set(key, run.catch(() => {}));
|
|
4022
|
+
return run;
|
|
4023
|
+
}
|
|
4024
|
+
return {
|
|
4025
|
+
reserve(key, getFloor) {
|
|
4026
|
+
return withLock(key, async () => {
|
|
4027
|
+
let current = next.get(key);
|
|
4028
|
+
if (current === undefined)
|
|
4029
|
+
current = await getFloor();
|
|
4030
|
+
next.set(key, current + 1n);
|
|
4031
|
+
return current;
|
|
4032
|
+
});
|
|
4033
|
+
},
|
|
4034
|
+
reset(key) {
|
|
4035
|
+
next.delete(key);
|
|
4036
|
+
},
|
|
4037
|
+
release(key, nonce) {
|
|
4038
|
+
return withLock(key, async () => {
|
|
4039
|
+
if (next.get(key) === nonce + 1n)
|
|
4040
|
+
next.set(key, nonce);
|
|
4041
|
+
});
|
|
4042
|
+
},
|
|
4043
|
+
peek(key) {
|
|
4044
|
+
return next.get(key);
|
|
4045
|
+
}
|
|
4046
|
+
};
|
|
4047
|
+
}
|
|
4048
|
+
function nonceKey(client, address) {
|
|
4049
|
+
return `${client.chain?.id ?? "stacks"}:${address}`;
|
|
4050
|
+
}
|
|
4051
|
+
function createNonceManager(params = {}) {
|
|
4052
|
+
const source = params.source ?? jsonRpcSource();
|
|
4053
|
+
const store = params.store ?? memoryStore();
|
|
4054
|
+
return {
|
|
4055
|
+
consume({ client, address }) {
|
|
4056
|
+
return store.reserve(nonceKey(client, address), () => source.get({ client, address }));
|
|
4057
|
+
},
|
|
4058
|
+
reset({ client, address }) {
|
|
4059
|
+
return store.reset(nonceKey(client, address));
|
|
4060
|
+
},
|
|
4061
|
+
release({ client, address, nonce }) {
|
|
4062
|
+
return store.release?.(nonceKey(client, address), nonce);
|
|
4063
|
+
},
|
|
4064
|
+
async peek({ client, address }) {
|
|
4065
|
+
return store.peek?.(nonceKey(client, address));
|
|
4066
|
+
}
|
|
4067
|
+
};
|
|
4068
|
+
}
|
|
4069
|
+
async function resolveNonce(client, address) {
|
|
4070
|
+
if (client.nonceManager)
|
|
4071
|
+
return client.nonceManager.consume({ client, address });
|
|
4072
|
+
return getNonce(client, { address });
|
|
4073
|
+
}
|
|
4074
|
+
async function releaseNonce(client, address, nonce) {
|
|
4075
|
+
if (!client.nonceManager)
|
|
4076
|
+
return;
|
|
4077
|
+
try {
|
|
4078
|
+
await client.nonceManager.release({ client, address, nonce });
|
|
4079
|
+
} catch {}
|
|
4080
|
+
}
|
|
4081
|
+
async function reconcileNonce(manager, params) {
|
|
4082
|
+
const { client, address, source } = params;
|
|
4083
|
+
const downward = params.downward ?? true;
|
|
4084
|
+
const authoritative = await source.get({ client, address });
|
|
4085
|
+
const tracked = await manager.peek({ client, address });
|
|
4086
|
+
if (tracked === undefined || authoritative === tracked) {
|
|
4087
|
+
return { reset: false, authoritative, tracked };
|
|
4088
|
+
}
|
|
4089
|
+
if (authoritative < tracked && !downward) {
|
|
4090
|
+
return { reset: false, authoritative, tracked };
|
|
4091
|
+
}
|
|
4092
|
+
await manager.reset({ client, address });
|
|
4093
|
+
return { reset: true, authoritative, tracked };
|
|
4094
|
+
}
|
|
4095
|
+
function startNonceReconciler(manager, params) {
|
|
4096
|
+
const { client, addresses, source, clock } = params;
|
|
4097
|
+
const intervalMs = params.intervalMs ?? 60000;
|
|
4098
|
+
let running = true;
|
|
4099
|
+
const tick = async () => {
|
|
4100
|
+
if (!running)
|
|
4101
|
+
return;
|
|
4102
|
+
for (const address of addresses) {
|
|
4103
|
+
try {
|
|
4104
|
+
const result = await reconcileNonce(manager, {
|
|
4105
|
+
client,
|
|
4106
|
+
address,
|
|
4107
|
+
source,
|
|
4108
|
+
downward: params.downward
|
|
4109
|
+
});
|
|
4110
|
+
params.onReconcile?.(address, result);
|
|
4111
|
+
} catch (error) {
|
|
4112
|
+
try {
|
|
4113
|
+
params.onError?.(address, error);
|
|
4114
|
+
} catch {}
|
|
4115
|
+
}
|
|
4116
|
+
}
|
|
4117
|
+
if (running && clock) {
|
|
4118
|
+
await clock.advance(intervalMs);
|
|
4119
|
+
tick();
|
|
4120
|
+
}
|
|
4121
|
+
};
|
|
4122
|
+
if (clock) {
|
|
4123
|
+
tick();
|
|
4124
|
+
return {
|
|
4125
|
+
stop: () => {
|
|
4126
|
+
running = false;
|
|
4127
|
+
}
|
|
4128
|
+
};
|
|
4129
|
+
}
|
|
4130
|
+
const timer = setInterval(tick, intervalMs);
|
|
4131
|
+
timer.unref?.();
|
|
4132
|
+
return {
|
|
4133
|
+
stop: () => clearInterval(timer)
|
|
4134
|
+
};
|
|
4135
|
+
}
|
|
4136
|
+
function isNonceConflictError(error) {
|
|
4137
|
+
if (!(error instanceof BroadcastError))
|
|
4138
|
+
return false;
|
|
4139
|
+
if (error.reason === "ConflictingNonceInMempool" || error.reason === "BadNonce") {
|
|
4140
|
+
return true;
|
|
4141
|
+
}
|
|
4142
|
+
if (error.reason !== undefined)
|
|
4143
|
+
return false;
|
|
4144
|
+
return error.message.toLowerCase().includes("nonce");
|
|
4145
|
+
}
|
|
4146
|
+
async function broadcastWithNonceReset(client, params) {
|
|
4147
|
+
try {
|
|
4148
|
+
const result = await sendTransaction(client, {
|
|
4149
|
+
transaction: params.transaction
|
|
4150
|
+
});
|
|
4151
|
+
return result.txid;
|
|
4152
|
+
} catch (error) {
|
|
4153
|
+
if (client.nonceManager && isNonceConflictError(error)) {
|
|
4154
|
+
await client.nonceManager.reset({ client, address: params.address });
|
|
4155
|
+
}
|
|
4156
|
+
throw error;
|
|
4157
|
+
}
|
|
4158
|
+
}
|
|
4159
|
+
|
|
4160
|
+
// src/actions/public/estimateFee.ts
|
|
4161
|
+
function isValidEstimation(e) {
|
|
4162
|
+
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");
|
|
4163
|
+
}
|
|
4164
|
+
async function estimateFee(client, params) {
|
|
4165
|
+
const payloadHex = bytesToHex(serializePayload(params.transaction.payload));
|
|
4166
|
+
const txHex = bytesToHex(serializeTransaction(params.transaction));
|
|
4167
|
+
const data = await client.request("/v2/fees/transaction", {
|
|
4168
|
+
method: "POST",
|
|
4169
|
+
body: {
|
|
4170
|
+
estimated_len: Math.ceil(txHex.length / 2),
|
|
4171
|
+
transaction_payload: `0x${payloadHex}`
|
|
4172
|
+
}
|
|
4173
|
+
});
|
|
4174
|
+
const raw = data?.estimations ?? [];
|
|
4175
|
+
return raw.map((e) => {
|
|
4176
|
+
if (!isValidEstimation(e)) {
|
|
4177
|
+
throw new MalformedResponseError("estimateFee: node response contains invalid fee estimation entry");
|
|
4178
|
+
}
|
|
4179
|
+
return {
|
|
4180
|
+
feeRate: Number(e.fee_rate),
|
|
4181
|
+
fee: Number(e.fee)
|
|
4182
|
+
};
|
|
4183
|
+
});
|
|
4184
|
+
}
|
|
4185
|
+
|
|
4186
|
+
// src/actions/wallet/utils.ts
|
|
4187
|
+
function isProviderAccount(account) {
|
|
4188
|
+
return account.type === "provider";
|
|
4189
|
+
}
|
|
4190
|
+
var FEE_TIERS = ["min", "low", "mid", "high"];
|
|
4191
|
+
var TIER_INDEX = { low: 0, mid: 1, high: 2 };
|
|
4192
|
+
function isFeeTier(fee) {
|
|
4193
|
+
return typeof fee === "string" && FEE_TIERS.includes(fee);
|
|
4194
|
+
}
|
|
4195
|
+
function minimumFee(transaction) {
|
|
4196
|
+
return BigInt(serializeTransaction(transaction).length);
|
|
4197
|
+
}
|
|
4198
|
+
function isNoEstimateAvailable(error) {
|
|
4199
|
+
return error instanceof HttpRequestError && error.status === 400 && (error.details?.includes("NoEstimateAvailable") ?? false);
|
|
4200
|
+
}
|
|
4201
|
+
async function resolveFee(client, transaction, fee) {
|
|
4202
|
+
if (fee !== undefined && !isFeeTier(fee))
|
|
4203
|
+
return { fee: intToBigInt(fee) };
|
|
4204
|
+
const tier = fee ?? "mid";
|
|
4205
|
+
if (tier === "min")
|
|
4206
|
+
return { fee: minimumFee(transaction), tier };
|
|
4207
|
+
let estimates;
|
|
4208
|
+
try {
|
|
4209
|
+
estimates = await estimateFee(client, { transaction });
|
|
4210
|
+
} catch (error) {
|
|
4211
|
+
if (!isNoEstimateAvailable(error))
|
|
4212
|
+
throw error;
|
|
4213
|
+
return { fee: minimumFee(transaction), tier: "min" };
|
|
4214
|
+
}
|
|
4215
|
+
const pick = estimates[TIER_INDEX[tier]] ?? estimates[estimates.length - 1];
|
|
4216
|
+
if (pick)
|
|
4217
|
+
return { fee: BigInt(pick.fee), tier };
|
|
4218
|
+
return { fee: minimumFee(transaction), tier: "min" };
|
|
4219
|
+
}
|
|
4220
|
+
function setUnsignedFee(transaction, fee) {
|
|
4221
|
+
transaction.auth.spendingCondition.fee = fee;
|
|
4222
|
+
clearTxCache(transaction);
|
|
4223
|
+
}
|
|
4224
|
+
function assertNoFeeTierForProvider(fee) {
|
|
4225
|
+
if (isFeeTier(fee)) {
|
|
4226
|
+
throw new Error(`Fee tier '${fee}' requires local signing; provider (wallet) accounts set their own fee`);
|
|
4227
|
+
}
|
|
4228
|
+
}
|
|
4229
|
+
|
|
4230
|
+
// src/actions/wallet/callContract.ts
|
|
4231
|
+
async function callContract(client, params) {
|
|
4232
|
+
const account = client.account;
|
|
4233
|
+
if (!account)
|
|
4234
|
+
throw new Error("Account required");
|
|
4235
|
+
const [contractAddress, contractName] = parseContractId(params.contract);
|
|
4236
|
+
if (isProviderAccount(account)) {
|
|
4237
|
+
assertNoFeeTierForProvider(params.fee);
|
|
4238
|
+
const result = await account.provider.request("stx_callContract", {
|
|
4239
|
+
contract: params.contract,
|
|
4240
|
+
functionName: params.functionName,
|
|
4241
|
+
functionArgs: params.functionArgs ?? []
|
|
4242
|
+
});
|
|
4243
|
+
return result.txid;
|
|
4244
|
+
}
|
|
4245
|
+
const managed = params.nonce === undefined && client.nonceManager !== undefined;
|
|
4246
|
+
const nonce = params.nonce ?? await resolveNonce(client, account.address);
|
|
4247
|
+
try {
|
|
4248
|
+
const needsFeeResolution = params.fee === undefined || isFeeTier(params.fee);
|
|
4249
|
+
const unsigned = buildContractCall({
|
|
4250
|
+
contractAddress,
|
|
4251
|
+
contractName,
|
|
4252
|
+
functionName: params.functionName,
|
|
4253
|
+
functionArgs: params.functionArgs ?? [],
|
|
4254
|
+
fee: needsFeeResolution ? 0n : params.fee,
|
|
4255
|
+
nonce,
|
|
4256
|
+
publicKey: account.publicKey,
|
|
4257
|
+
chain: client.chain,
|
|
4258
|
+
postConditionMode: params.postConditionMode,
|
|
4259
|
+
postConditions: params.postConditions
|
|
4260
|
+
});
|
|
4261
|
+
if (needsFeeResolution) {
|
|
4262
|
+
const { fee } = await resolveFee(client, unsigned, params.fee);
|
|
4263
|
+
setUnsignedFee(unsigned, fee);
|
|
4264
|
+
}
|
|
4265
|
+
const signed = await signTransactionWithAccount(unsigned, account);
|
|
4266
|
+
return await broadcastWithNonceReset(client, {
|
|
4267
|
+
transaction: signed,
|
|
4268
|
+
address: account.address
|
|
4269
|
+
});
|
|
4270
|
+
} catch (error) {
|
|
4271
|
+
if (managed)
|
|
4272
|
+
await releaseNonce(client, account.address, nonce);
|
|
4273
|
+
throw error;
|
|
4274
|
+
}
|
|
4275
|
+
}
|
|
4276
|
+
|
|
4277
|
+
// src/actions/getContract.ts
|
|
4278
|
+
function getContract(params) {
|
|
4279
|
+
const { client, address, name: contractName, abi: abi2 } = params;
|
|
4280
|
+
const contractId = `${address}.${contractName}`;
|
|
4281
|
+
const fnByName = new Map;
|
|
4282
|
+
for (const fn of abi2.functions) {
|
|
4283
|
+
fnByName.set(fn.name, fn);
|
|
4284
|
+
}
|
|
4285
|
+
const mapByName = new Map;
|
|
4286
|
+
if (abi2.maps) {
|
|
4287
|
+
for (const m of abi2.maps) {
|
|
4288
|
+
mapByName.set(m.name, m);
|
|
4289
|
+
}
|
|
4290
|
+
}
|
|
4291
|
+
const camelToKebab = new Map;
|
|
4292
|
+
for (const fn of abi2.functions) {
|
|
4293
|
+
camelToKebab.set(toCamelCase(fn.name), fn.name);
|
|
4294
|
+
}
|
|
4295
|
+
if (abi2.maps) {
|
|
4296
|
+
for (const m of abi2.maps) {
|
|
4297
|
+
camelToKebab.set(toCamelCase(m.name), m.name);
|
|
4298
|
+
}
|
|
4299
|
+
}
|
|
4300
|
+
const read = new Proxy({}, {
|
|
4301
|
+
get(_target, prop) {
|
|
4302
|
+
const fnName = camelToKebab.get(prop) ?? prop;
|
|
4303
|
+
const fn = fnByName.get(fnName);
|
|
4304
|
+
if (!fn || fn.access !== "read-only")
|
|
4305
|
+
return;
|
|
4306
|
+
return async (args = {}) => {
|
|
4307
|
+
const clarityArgs = buildFunctionArgs(fn, args);
|
|
4308
|
+
const result = await readContract(client, {
|
|
4309
|
+
contract: contractId,
|
|
4310
|
+
functionName: fn.name,
|
|
4311
|
+
args: clarityArgs
|
|
4312
|
+
});
|
|
4313
|
+
const jsValue = clarityValueToJSUntyped(fn.outputs, result);
|
|
4314
|
+
if (isResponseOutput(fn.outputs)) {
|
|
4315
|
+
const resp = jsValue;
|
|
4316
|
+
if ("ok" in resp)
|
|
4317
|
+
return resp.ok;
|
|
4318
|
+
throw new ContractResponseError(`${contractId}::${fn.name} returned (err ${formatErrValue(resp.err)})`, resp.err);
|
|
4319
|
+
}
|
|
4320
|
+
return jsValue;
|
|
4321
|
+
};
|
|
4322
|
+
}
|
|
4323
|
+
});
|
|
4324
|
+
const call = new Proxy({}, {
|
|
4325
|
+
get(_target, prop) {
|
|
4326
|
+
const fnName = camelToKebab.get(prop) ?? prop;
|
|
4327
|
+
const fn = fnByName.get(fnName);
|
|
4328
|
+
if (!fn || fn.access !== "public")
|
|
4329
|
+
return;
|
|
4330
|
+
return async (args = {}, options) => {
|
|
4331
|
+
const clarityArgs = buildFunctionArgs(fn, args);
|
|
4332
|
+
return callContract(client, {
|
|
4333
|
+
contract: contractId,
|
|
4334
|
+
functionName: fn.name,
|
|
4335
|
+
functionArgs: clarityArgs,
|
|
4336
|
+
...options
|
|
4337
|
+
});
|
|
4338
|
+
};
|
|
4339
|
+
}
|
|
4340
|
+
});
|
|
4341
|
+
const buildCall = new Proxy({}, {
|
|
4342
|
+
get(_target, prop) {
|
|
4343
|
+
const fnName = camelToKebab.get(prop) ?? prop;
|
|
4344
|
+
const fn = fnByName.get(fnName);
|
|
4345
|
+
if (!fn || fn.access !== "public")
|
|
4346
|
+
return;
|
|
4347
|
+
return async (args = {}, options) => {
|
|
4348
|
+
const publicKey = options?.publicKey ?? client.account?.publicKey;
|
|
4349
|
+
if (!publicKey) {
|
|
4350
|
+
throw new Error("buildCall requires a publicKey (pass options.publicKey or configure a client account)");
|
|
4351
|
+
}
|
|
4352
|
+
const functionArgs = buildFunctionArgs(fn, args);
|
|
4353
|
+
const network = client.chain?.network ?? "mainnet";
|
|
4354
|
+
const nonce = options?.nonce ?? await getNonce(client, {
|
|
4355
|
+
address: publicKeyToAddress(publicKey, network)
|
|
4356
|
+
});
|
|
4357
|
+
const unsigned = buildContractCall({
|
|
4358
|
+
contractAddress: address,
|
|
4359
|
+
contractName,
|
|
4360
|
+
functionName: fn.name,
|
|
4361
|
+
functionArgs,
|
|
4362
|
+
fee: options?.fee ?? 0n,
|
|
4363
|
+
nonce,
|
|
4364
|
+
publicKey,
|
|
4365
|
+
chain: client.chain,
|
|
4366
|
+
postConditionMode: options?.postConditionMode,
|
|
4367
|
+
postConditions: options?.postConditions,
|
|
4368
|
+
sponsored: options?.sponsored
|
|
4369
|
+
});
|
|
4370
|
+
if (options?.fee === undefined) {
|
|
4371
|
+
const { fee } = await resolveFee(client, unsigned, undefined);
|
|
4372
|
+
setUnsignedFee(unsigned, fee);
|
|
4373
|
+
}
|
|
4374
|
+
return unsigned;
|
|
4375
|
+
};
|
|
4376
|
+
}
|
|
4377
|
+
});
|
|
4378
|
+
const maps = new Proxy({}, {
|
|
4379
|
+
get(_target, prop) {
|
|
4380
|
+
const mapName = camelToKebab.get(prop) ?? prop;
|
|
4381
|
+
const map = mapByName.get(mapName);
|
|
4382
|
+
if (!map)
|
|
4383
|
+
return;
|
|
4384
|
+
return async (key) => {
|
|
4385
|
+
const clarityKey = jsToClarityValue(map.key, key);
|
|
4386
|
+
const result = await getMapEntry(client, {
|
|
4387
|
+
contract: contractId,
|
|
4388
|
+
mapName: map.name,
|
|
4389
|
+
key: clarityKey
|
|
4390
|
+
});
|
|
4391
|
+
if (result.type === "none")
|
|
4392
|
+
return null;
|
|
4393
|
+
if (result.type === "some") {
|
|
4394
|
+
return clarityValueToJSUntyped(map.value, result.value);
|
|
4395
|
+
}
|
|
4396
|
+
return clarityValueToJSUntyped(map.value, result);
|
|
4397
|
+
};
|
|
4398
|
+
}
|
|
4399
|
+
});
|
|
4400
|
+
return { read, call, buildCall, maps };
|
|
4401
|
+
}
|
|
4402
|
+
function resolveNetworkContract(client, contracts) {
|
|
4403
|
+
if (!client.chain) {
|
|
4404
|
+
throw new Error("Client must have a chain configured");
|
|
4405
|
+
}
|
|
4406
|
+
return contracts[client.chain.network];
|
|
4407
|
+
}
|
|
4408
|
+
function buildFunctionArgs(fn, args = {}) {
|
|
4409
|
+
return fn.args.map((arg) => {
|
|
4410
|
+
const camelKey = toCamelCase(arg.name);
|
|
4411
|
+
const hasOriginal = arg.name in args;
|
|
4412
|
+
const hasCamel = camelKey in args;
|
|
4413
|
+
const value = hasOriginal ? args[arg.name] : hasCamel ? args[camelKey] : undefined;
|
|
4414
|
+
if (value === undefined)
|
|
4415
|
+
throw new Error(`Missing argument: ${arg.name}`);
|
|
4416
|
+
return jsToClarityValue(arg.type, value);
|
|
4417
|
+
});
|
|
4418
|
+
}
|
|
4419
|
+
function isResponseOutput(type) {
|
|
4420
|
+
return typeof type === "object" && type !== null && "response" in type;
|
|
4421
|
+
}
|
|
4422
|
+
function formatErrValue(value) {
|
|
4423
|
+
if (typeof value === "bigint")
|
|
4424
|
+
return value.toString();
|
|
4425
|
+
if (typeof value === "string")
|
|
4426
|
+
return `"${value}"`;
|
|
4427
|
+
return String(value);
|
|
4428
|
+
}
|
|
4429
|
+
|
|
4430
|
+
class ContractResponseError extends Error {
|
|
4431
|
+
errorValue;
|
|
4432
|
+
name = "ContractResponseError";
|
|
4433
|
+
constructor(message, errorValue) {
|
|
4434
|
+
super(message);
|
|
4435
|
+
this.errorValue = errorValue;
|
|
4436
|
+
}
|
|
4437
|
+
}
|
|
16
4438
|
|
|
17
4439
|
// src/bns/abi.ts
|
|
18
4440
|
var BNS_ABI = {
|
|
@@ -447,13 +4869,13 @@ async function preorder(client, params) {
|
|
|
447
4869
|
const salt = providedSalt ?? generateSalt();
|
|
448
4870
|
const hashedSaltedFqn = hashPreorder(name, namespace, salt);
|
|
449
4871
|
const bns = getBnsContract(client);
|
|
450
|
-
const
|
|
4872
|
+
const txid2 = await bns.call.namePreorder({
|
|
451
4873
|
hashedSaltedFqn,
|
|
452
4874
|
stxToBurn: price
|
|
453
4875
|
}, {
|
|
454
4876
|
postConditions: client.account?.address ? [Pc.principal(client.account.address).willSendLte(price).ustx()] : []
|
|
455
4877
|
});
|
|
456
|
-
return { txid, salt };
|
|
4878
|
+
return { txid: txid2, salt };
|
|
457
4879
|
}
|
|
458
4880
|
async function register(client, params) {
|
|
459
4881
|
const { name: nameInput, namespace: namespaceInput, salt } = params;
|
|
@@ -605,5 +5027,5 @@ function bns() {
|
|
|
605
5027
|
});
|
|
606
5028
|
}
|
|
607
5029
|
|
|
608
|
-
//# debugId=
|
|
5030
|
+
//# debugId=5D6A745BFFB2148464756E2164756E21
|
|
609
5031
|
//# sourceMappingURL=index.cjs.map
|