@qntx/wallet-chains 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -10
- package/dist/{account-ref-D2rW_qlI.mjs → account-ref-BFTeEyHt.mjs} +2 -2
- package/dist/{account-ref-D2rW_qlI.mjs.map → account-ref-BFTeEyHt.mjs.map} +1 -1
- package/dist/assemble-8GvNDony.mjs +405 -0
- package/dist/assemble-8GvNDony.mjs.map +1 -0
- package/dist/assemble-B3sO9Fvc.mjs +629 -0
- package/dist/assemble-B3sO9Fvc.mjs.map +1 -0
- package/dist/assemble-BdiPo0ZX.mjs +32 -0
- package/dist/assemble-BdiPo0ZX.mjs.map +1 -0
- package/dist/assets-sg2_Z3nZ.mjs +200 -0
- package/dist/assets-sg2_Z3nZ.mjs.map +1 -0
- package/dist/bitcoin-sign.d.mts +3 -0
- package/dist/bitcoin-sign.mjs +52 -18
- package/dist/bitcoin-sign.mjs.map +1 -1
- package/dist/bitcoin.d.mts +123 -7
- package/dist/bitcoin.mjs +162 -69
- package/dist/bitcoin.mjs.map +1 -1
- package/dist/evm-sign.d.mts +3 -1
- package/dist/evm-sign.mjs +25 -82
- package/dist/evm-sign.mjs.map +1 -1
- package/dist/evm.d.mts +252 -22
- package/dist/evm.mjs +2460 -448
- package/dist/evm.mjs.map +1 -1
- package/dist/families-BlgplKAJ.mjs +412 -0
- package/dist/families-BlgplKAJ.mjs.map +1 -0
- package/dist/index-CIRaHKpx.d.mts +941 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/networks.d.mts +29 -0
- package/dist/networks.mjs +245 -0
- package/dist/networks.mjs.map +1 -0
- package/dist/plan-wCnxHqRu.mjs +1311 -0
- package/dist/plan-wCnxHqRu.mjs.map +1 -0
- package/dist/solana-sign.d.mts +3 -0
- package/dist/solana-sign.mjs +23 -10
- package/dist/solana-sign.mjs.map +1 -1
- package/dist/solana.d.mts +136 -24
- package/dist/solana.mjs +1244 -63
- package/dist/solana.mjs.map +1 -1
- package/dist/src-CHB_z45M.mjs +387 -0
- package/dist/src-CHB_z45M.mjs.map +1 -0
- package/dist/tasks-7AFv3PQn.mjs +86 -0
- package/dist/tasks-7AFv3PQn.mjs.map +1 -0
- package/dist/token-call-DH22g8BL.mjs +914 -0
- package/dist/token-call-DH22g8BL.mjs.map +1 -0
- package/dist/tron-sign.d.mts +10 -0
- package/dist/tron-sign.mjs +36 -0
- package/dist/tron-sign.mjs.map +1 -0
- package/dist/tron.d.mts +328 -0
- package/dist/tron.mjs +1484 -0
- package/dist/tron.mjs.map +1 -0
- package/dist/typed-data-CE9h4U0F.d.mts +51 -0
- package/dist/typed-data-DRtKULsH.mjs +466 -0
- package/dist/typed-data-DRtKULsH.mjs.map +1 -0
- package/package.json +17 -10
- package/dist/index-DYwm4-Ec.d.mts +0 -256
- package/dist/message-ChhEZ0lx.mjs +0 -188
- package/dist/message-ChhEZ0lx.mjs.map +0 -1
- package/dist/src-8NZeEnrW.mjs +0 -67
- package/dist/src-8NZeEnrW.mjs.map +0 -1
- package/dist/typed-data-J5g2WemC.mjs +0 -227
- package/dist/typed-data-J5g2WemC.mjs.map +0 -1
|
@@ -0,0 +1,1311 @@
|
|
|
1
|
+
import { t as ChainError } from "./src-CHB_z45M.mjs";
|
|
2
|
+
import { t as isRecord } from "./account-ref-BFTeEyHt.mjs";
|
|
3
|
+
import { D as checksumEvmAddress, a as isTypedDataInput } from "./typed-data-DRtKULsH.mjs";
|
|
4
|
+
import { a as signaturesOf, n as acceptEcdsa } from "./tasks-7AFv3PQn.mjs";
|
|
5
|
+
import { keccak_256 } from "@noble/hashes/sha3.js";
|
|
6
|
+
import { bytesToHex, concatBytes, hexToBytes, utf8ToBytes } from "@noble/hashes/utils.js";
|
|
7
|
+
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
8
|
+
import * as Hex from "ox/Hex";
|
|
9
|
+
import * as Signature from "ox/Signature";
|
|
10
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
11
|
+
import { createBase58check } from "@scure/base";
|
|
12
|
+
// src/tron/assemble.ts
|
|
13
|
+
/**
|
|
14
|
+
* /tron/assemble — the verified signature material as the 65-byte `r‖s‖v` (v = 27 + yParity), the
|
|
15
|
+
* tronweb ECKeySign form. Always "signed".
|
|
16
|
+
*/
|
|
17
|
+
const assembleTron = (plan, signatures) => {
|
|
18
|
+
signaturesOf(plan.tasks, signatures);
|
|
19
|
+
const { r, s, yParity } = acceptEcdsa(plan.tasks[0], signatures[0] ?? /* @__PURE__ */ new Uint8Array());
|
|
20
|
+
return {
|
|
21
|
+
kind: "signed",
|
|
22
|
+
artefact: Signature.toBytes(Signature.from({
|
|
23
|
+
r: Hex.fromNumber(r),
|
|
24
|
+
s: Hex.fromNumber(s),
|
|
25
|
+
yParity
|
|
26
|
+
}))
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
// src/tron/proto.ts
|
|
30
|
+
/**
|
|
31
|
+
* A strict protobuf wire reader/writer for the TRON protocol messages. Unlike the google-protobuf
|
|
32
|
+
* and `@bufbuild/protobuf` readers — which accept non-minimal varints, out-of-order and duplicated
|
|
33
|
+
* fields — this reader enforces the canonical encoding a transaction must have: varints are minimal
|
|
34
|
+
* and fit uint64, field numbers are strictly ascending (a declared repeated field may repeat
|
|
35
|
+
* consecutively), and every accepted input re-encodes to itself. Every malformed input throws
|
|
36
|
+
* `ChainError("invalid-request", …)` — never another error type and never a loop.
|
|
37
|
+
*/
|
|
38
|
+
/** Every malformed protobuf input is an invalid-request with a specific reason. */
|
|
39
|
+
function malformed(what) {
|
|
40
|
+
throw new ChainError("invalid-request", `malformed protobuf: ${what}`);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A canonical varint: at most 10 bytes, the 10th byte carrying only bit 63 (`< 2^64`), and minimal
|
|
44
|
+
* — a multi-byte varint's last byte is non-zero, so `0x80 0x00` and friends are rejected.
|
|
45
|
+
*/
|
|
46
|
+
const readVarint = (bytes, offset) => {
|
|
47
|
+
let value = 0n;
|
|
48
|
+
for (let i = 0;; i++) {
|
|
49
|
+
if (i === 10) malformed("varint longer than 10 bytes");
|
|
50
|
+
const at = offset + i;
|
|
51
|
+
const b = bytes[at];
|
|
52
|
+
if (b === void 0) malformed("truncated varint");
|
|
53
|
+
if ((b & 128) === 0) {
|
|
54
|
+
if (i > 0 && b === 0) malformed("non-minimal varint");
|
|
55
|
+
if (i === 9 && b > 1) malformed("varint exceeds 64 bits");
|
|
56
|
+
value |= BigInt(b) << BigInt(i * 7);
|
|
57
|
+
return {
|
|
58
|
+
value,
|
|
59
|
+
next: at + 1
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
value |= BigInt(b & 127) << BigInt(i * 7);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
const writeVarint = (value) => {
|
|
66
|
+
const out = [];
|
|
67
|
+
let v = value;
|
|
68
|
+
for (;;) {
|
|
69
|
+
let b = Number(v & 127n);
|
|
70
|
+
v >>= 7n;
|
|
71
|
+
if (v !== 0n) b |= 128;
|
|
72
|
+
out.push(b);
|
|
73
|
+
if (v === 0n) return Uint8Array.from(out);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const isWire = (wire) => wire === 0 || wire === 1 || wire === 2 || wire === 5;
|
|
77
|
+
/**
|
|
78
|
+
* Iterates a message's fields in encoding order, enforcing the canonical layout: wire types are
|
|
79
|
+
* varint (0), length-delimited (2) or fixed 32/64 (5, 1 — kept only to capture unknown fields);
|
|
80
|
+
* groups (3/4) and the reserved types (6/7) are malformed. Field numbers ascend strictly; a field
|
|
81
|
+
* may repeat only when `repeated` declares it, and only consecutively.
|
|
82
|
+
*/
|
|
83
|
+
const readFields = (bytes, repeated = []) => {
|
|
84
|
+
const fields = [];
|
|
85
|
+
let last = 0;
|
|
86
|
+
let offset = 0;
|
|
87
|
+
while (offset < bytes.length) {
|
|
88
|
+
const start = offset;
|
|
89
|
+
const tag = readVarint(bytes, offset);
|
|
90
|
+
offset = tag.next;
|
|
91
|
+
const wire = Number(tag.value & 7n);
|
|
92
|
+
const field = Number(tag.value >> 3n);
|
|
93
|
+
if (field === 0) malformed("field number 0");
|
|
94
|
+
if (!isWire(wire)) malformed(`unsupported wire type ${wire} of field ${field}`);
|
|
95
|
+
if (field < last) malformed(`field ${field} follows field ${last}`);
|
|
96
|
+
if (field === last && !repeated.includes(field)) malformed(`field ${field} is not repeated`);
|
|
97
|
+
last = field;
|
|
98
|
+
let varint;
|
|
99
|
+
let data;
|
|
100
|
+
if (wire === 0) {
|
|
101
|
+
const v = readVarint(bytes, offset);
|
|
102
|
+
varint = v.value;
|
|
103
|
+
offset = v.next;
|
|
104
|
+
} else if (wire === 2) {
|
|
105
|
+
const len = readVarint(bytes, offset);
|
|
106
|
+
offset = len.next;
|
|
107
|
+
if (len.value > BigInt(bytes.length - offset)) malformed(`field ${field} length exceeds the message`);
|
|
108
|
+
data = bytes.subarray(offset, offset + Number(len.value));
|
|
109
|
+
offset += Number(len.value);
|
|
110
|
+
} else {
|
|
111
|
+
const size = wire === 1 ? 8 : 4;
|
|
112
|
+
if (bytes.length - offset < size) malformed(`field ${field} is truncated`);
|
|
113
|
+
data = bytes.subarray(offset, offset + size);
|
|
114
|
+
offset += size;
|
|
115
|
+
}
|
|
116
|
+
fields.push({
|
|
117
|
+
field,
|
|
118
|
+
wire,
|
|
119
|
+
bytes: bytes.subarray(start, offset),
|
|
120
|
+
varint,
|
|
121
|
+
data
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
return fields;
|
|
125
|
+
};
|
|
126
|
+
const concat = (parts) => {
|
|
127
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
128
|
+
let at = 0;
|
|
129
|
+
for (const p of parts) {
|
|
130
|
+
out.set(p, at);
|
|
131
|
+
at += p.length;
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
};
|
|
135
|
+
const tag = (field, wire) => writeVarint(BigInt(field * 8 + wire));
|
|
136
|
+
/**
|
|
137
|
+
* One encoded field, or undefined when its value is a proto3 default (0, false, empty bytes or
|
|
138
|
+
* string) and canonical encoding omits it entirely.
|
|
139
|
+
*/
|
|
140
|
+
const varintField = (field, value) => BigInt(value) === 0n ? void 0 : concat([tag(field, 0), writeVarint(BigInt(value))]);
|
|
141
|
+
/** A varint field that is emitted even when 0 — required presence, e.g. `lock = false`. */
|
|
142
|
+
const requiredVarintField = (field, value) => concat([tag(field, 0), writeVarint(BigInt(value))]);
|
|
143
|
+
const bytesField = (field, data) => data.length === 0 ? void 0 : requiredBytesField(field, data);
|
|
144
|
+
const requiredBytesField = (field, data) => concat([
|
|
145
|
+
tag(field, 2),
|
|
146
|
+
writeVarint(BigInt(data.length)),
|
|
147
|
+
data
|
|
148
|
+
]);
|
|
149
|
+
const stringField = (field, value) => value === "" ? void 0 : requiredBytesField(field, new TextEncoder().encode(value));
|
|
150
|
+
/**
|
|
151
|
+
* Emits a message from encoded field slices: the modeled fields in schema order plus any captured
|
|
152
|
+
* unknown fields (`extra` slices, tag included), all merged by field number. Two slices of the same
|
|
153
|
+
* field keep their relative order (consecutive repeats).
|
|
154
|
+
*/
|
|
155
|
+
const encodeMessage = (fields) => {
|
|
156
|
+
const present = fields.filter((f) => f.bytes !== void 0);
|
|
157
|
+
present.sort((a, b) => a.field - b.field);
|
|
158
|
+
return concat(present.map((f) => f.bytes));
|
|
159
|
+
};
|
|
160
|
+
/**
|
|
161
|
+
* Split a read field list into the decoder's own consumption plus captured unknowns: fields not in
|
|
162
|
+
* `known` are kept verbatim. Callers pass the schema's field numbers; repeated handling was already
|
|
163
|
+
* validated by `readFields`.
|
|
164
|
+
*/
|
|
165
|
+
const collectExtra = (fields, known) => fields.filter((f) => !known.includes(f.field));
|
|
166
|
+
const equalBytes = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
|
|
167
|
+
// src/tron/contract-types.ts
|
|
168
|
+
const TRON_CONTRACT_TYPES = [
|
|
169
|
+
{
|
|
170
|
+
id: 0,
|
|
171
|
+
name: "AccountCreateContract",
|
|
172
|
+
treatment: "unsupported"
|
|
173
|
+
},
|
|
174
|
+
{
|
|
175
|
+
id: 1,
|
|
176
|
+
name: "TransferContract",
|
|
177
|
+
treatment: "described"
|
|
178
|
+
},
|
|
179
|
+
{
|
|
180
|
+
id: 2,
|
|
181
|
+
name: "TransferAssetContract",
|
|
182
|
+
treatment: "described"
|
|
183
|
+
},
|
|
184
|
+
{
|
|
185
|
+
id: 3,
|
|
186
|
+
name: "VoteAssetContract",
|
|
187
|
+
treatment: "unsupported"
|
|
188
|
+
},
|
|
189
|
+
{
|
|
190
|
+
id: 4,
|
|
191
|
+
name: "VoteWitnessContract",
|
|
192
|
+
treatment: "described"
|
|
193
|
+
},
|
|
194
|
+
{
|
|
195
|
+
id: 5,
|
|
196
|
+
name: "WitnessCreateContract",
|
|
197
|
+
treatment: "unsupported"
|
|
198
|
+
},
|
|
199
|
+
{
|
|
200
|
+
id: 6,
|
|
201
|
+
name: "AssetIssueContract",
|
|
202
|
+
treatment: "unsupported"
|
|
203
|
+
},
|
|
204
|
+
{
|
|
205
|
+
id: 8,
|
|
206
|
+
name: "WitnessUpdateContract",
|
|
207
|
+
treatment: "unsupported"
|
|
208
|
+
},
|
|
209
|
+
{
|
|
210
|
+
id: 9,
|
|
211
|
+
name: "ParticipateAssetIssueContract",
|
|
212
|
+
treatment: "unsupported"
|
|
213
|
+
},
|
|
214
|
+
{
|
|
215
|
+
id: 10,
|
|
216
|
+
name: "AccountUpdateContract",
|
|
217
|
+
treatment: "unsupported"
|
|
218
|
+
},
|
|
219
|
+
{
|
|
220
|
+
id: 11,
|
|
221
|
+
name: "FreezeBalanceContract",
|
|
222
|
+
treatment: "unsupported"
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
id: 12,
|
|
226
|
+
name: "UnfreezeBalanceContract",
|
|
227
|
+
treatment: "unsupported"
|
|
228
|
+
},
|
|
229
|
+
{
|
|
230
|
+
id: 13,
|
|
231
|
+
name: "WithdrawBalanceContract",
|
|
232
|
+
treatment: "described"
|
|
233
|
+
},
|
|
234
|
+
{
|
|
235
|
+
id: 14,
|
|
236
|
+
name: "UnfreezeAssetContract",
|
|
237
|
+
treatment: "unsupported"
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
id: 15,
|
|
241
|
+
name: "UpdateAssetContract",
|
|
242
|
+
treatment: "unsupported"
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
id: 16,
|
|
246
|
+
name: "ProposalCreateContract",
|
|
247
|
+
treatment: "unsupported"
|
|
248
|
+
},
|
|
249
|
+
{
|
|
250
|
+
id: 17,
|
|
251
|
+
name: "ProposalApproveContract",
|
|
252
|
+
treatment: "unsupported"
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
id: 18,
|
|
256
|
+
name: "ProposalDeleteContract",
|
|
257
|
+
treatment: "unsupported"
|
|
258
|
+
},
|
|
259
|
+
{
|
|
260
|
+
id: 19,
|
|
261
|
+
name: "SetAccountIdContract",
|
|
262
|
+
treatment: "unsupported"
|
|
263
|
+
},
|
|
264
|
+
{
|
|
265
|
+
id: 20,
|
|
266
|
+
name: "CustomContract",
|
|
267
|
+
treatment: "unsupported"
|
|
268
|
+
},
|
|
269
|
+
{
|
|
270
|
+
id: 30,
|
|
271
|
+
name: "CreateSmartContract",
|
|
272
|
+
treatment: "unsupported"
|
|
273
|
+
},
|
|
274
|
+
{
|
|
275
|
+
id: 31,
|
|
276
|
+
name: "TriggerSmartContract",
|
|
277
|
+
treatment: "described"
|
|
278
|
+
},
|
|
279
|
+
{
|
|
280
|
+
id: 32,
|
|
281
|
+
name: "GetContract",
|
|
282
|
+
treatment: "unsupported"
|
|
283
|
+
},
|
|
284
|
+
{
|
|
285
|
+
id: 33,
|
|
286
|
+
name: "UpdateSettingContract",
|
|
287
|
+
treatment: "unsupported"
|
|
288
|
+
},
|
|
289
|
+
{
|
|
290
|
+
id: 41,
|
|
291
|
+
name: "ExchangeCreateContract",
|
|
292
|
+
treatment: "unsupported"
|
|
293
|
+
},
|
|
294
|
+
{
|
|
295
|
+
id: 42,
|
|
296
|
+
name: "ExchangeInjectContract",
|
|
297
|
+
treatment: "unsupported"
|
|
298
|
+
},
|
|
299
|
+
{
|
|
300
|
+
id: 43,
|
|
301
|
+
name: "ExchangeWithdrawContract",
|
|
302
|
+
treatment: "unsupported"
|
|
303
|
+
},
|
|
304
|
+
{
|
|
305
|
+
id: 44,
|
|
306
|
+
name: "ExchangeTransactionContract",
|
|
307
|
+
treatment: "unsupported"
|
|
308
|
+
},
|
|
309
|
+
{
|
|
310
|
+
id: 45,
|
|
311
|
+
name: "UpdateEnergyLimitContract",
|
|
312
|
+
treatment: "unsupported"
|
|
313
|
+
},
|
|
314
|
+
{
|
|
315
|
+
id: 46,
|
|
316
|
+
name: "AccountPermissionUpdateContract",
|
|
317
|
+
treatment: "permission-update"
|
|
318
|
+
},
|
|
319
|
+
{
|
|
320
|
+
id: 48,
|
|
321
|
+
name: "ClearABIContract",
|
|
322
|
+
treatment: "unsupported"
|
|
323
|
+
},
|
|
324
|
+
{
|
|
325
|
+
id: 49,
|
|
326
|
+
name: "UpdateBrokerageContract",
|
|
327
|
+
treatment: "unsupported"
|
|
328
|
+
},
|
|
329
|
+
{
|
|
330
|
+
id: 51,
|
|
331
|
+
name: "ShieldedTransferContract",
|
|
332
|
+
treatment: "unsupported"
|
|
333
|
+
},
|
|
334
|
+
{
|
|
335
|
+
id: 52,
|
|
336
|
+
name: "MarketSellAssetContract",
|
|
337
|
+
treatment: "unsupported"
|
|
338
|
+
},
|
|
339
|
+
{
|
|
340
|
+
id: 53,
|
|
341
|
+
name: "MarketCancelOrderContract",
|
|
342
|
+
treatment: "unsupported"
|
|
343
|
+
},
|
|
344
|
+
{
|
|
345
|
+
id: 54,
|
|
346
|
+
name: "FreezeBalanceV2Contract",
|
|
347
|
+
treatment: "described"
|
|
348
|
+
},
|
|
349
|
+
{
|
|
350
|
+
id: 55,
|
|
351
|
+
name: "UnfreezeBalanceV2Contract",
|
|
352
|
+
treatment: "described"
|
|
353
|
+
},
|
|
354
|
+
{
|
|
355
|
+
id: 56,
|
|
356
|
+
name: "WithdrawExpireUnfreezeContract",
|
|
357
|
+
treatment: "described"
|
|
358
|
+
},
|
|
359
|
+
{
|
|
360
|
+
id: 57,
|
|
361
|
+
name: "DelegateResourceContract",
|
|
362
|
+
treatment: "described"
|
|
363
|
+
},
|
|
364
|
+
{
|
|
365
|
+
id: 58,
|
|
366
|
+
name: "UnDelegateResourceContract",
|
|
367
|
+
treatment: "described"
|
|
368
|
+
},
|
|
369
|
+
{
|
|
370
|
+
id: 59,
|
|
371
|
+
name: "CancelAllUnfreezeV2Contract",
|
|
372
|
+
treatment: "described"
|
|
373
|
+
}
|
|
374
|
+
];
|
|
375
|
+
const tronContractType = (id) => TRON_CONTRACT_TYPES.find((t) => t.id === id);
|
|
376
|
+
/** `Any.type_url` for a contract type name — the only form the chain emits. */
|
|
377
|
+
const tronTypeUrl = (name) => `type.googleapis.com/protocol.${name}`;
|
|
378
|
+
// src/tron/raw.ts
|
|
379
|
+
/**
|
|
380
|
+
* `Transaction.raw` and `Transaction` wire codec (Tron.proto:335-451). The raw message carries
|
|
381
|
+
* exactly one contract — `contract` is `repeated` on the wire only for historical reasons ("only
|
|
382
|
+
* support size = 1"), so zero or two is malformed rather than blind. TaPoS fields (`ref_block_num`,
|
|
383
|
+
* `auths`, `scripts`) and any unknown field are captured verbatim in `extra` for blind
|
|
384
|
+
* classification; `Contract.provider`/`ContractName` likewise on the contract. Every accepted input
|
|
385
|
+
* satisfies `encodeTronRawData(decodeTronRawData(b)) == b`; a non-canonical encoding — an
|
|
386
|
+
* explicitly-encoded default among them — is malformed.
|
|
387
|
+
*/
|
|
388
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
389
|
+
const field = (fs, n) => fs.find((f) => f.field === n);
|
|
390
|
+
const all = (fs, n) => fs.filter((f) => f.field === n);
|
|
391
|
+
const int64Field = (f, what) => {
|
|
392
|
+
if (f === void 0) return 0n;
|
|
393
|
+
if (f.wire !== 0 || f.varint === void 0) malformed(`${what} has the wrong wire type`);
|
|
394
|
+
if (f.varint >= 9223372036854775808n) malformed(`${what} is negative`);
|
|
395
|
+
return f.varint;
|
|
396
|
+
};
|
|
397
|
+
const int32Field = (f, what) => {
|
|
398
|
+
const v = int64Field(f, what);
|
|
399
|
+
if (v > 2147483647n) malformed(`${what} exceeds int32`);
|
|
400
|
+
return Number(v);
|
|
401
|
+
};
|
|
402
|
+
const bytesFieldOf = (f, what) => {
|
|
403
|
+
if (f === void 0 || f.wire !== 2 || f.data === void 0) malformed(`${what} is missing`);
|
|
404
|
+
return f.data;
|
|
405
|
+
};
|
|
406
|
+
const encodeAny = (typeUrl, value) => encodeMessage([{
|
|
407
|
+
field: 1,
|
|
408
|
+
bytes: stringField(1, typeUrl)
|
|
409
|
+
}, {
|
|
410
|
+
field: 2,
|
|
411
|
+
bytes: bytesField(2, value)
|
|
412
|
+
}]);
|
|
413
|
+
const encodeContract = (contract) => encodeMessage([
|
|
414
|
+
{
|
|
415
|
+
field: 1,
|
|
416
|
+
bytes: varintField(1, contract.typeId)
|
|
417
|
+
},
|
|
418
|
+
{
|
|
419
|
+
field: 2,
|
|
420
|
+
bytes: requiredBytesField(2, encodeAny(contract.typeUrl, contract.value))
|
|
421
|
+
},
|
|
422
|
+
...contract.extra.map((e) => ({
|
|
423
|
+
field: e.field,
|
|
424
|
+
bytes: e.bytes
|
|
425
|
+
})),
|
|
426
|
+
{
|
|
427
|
+
field: 5,
|
|
428
|
+
bytes: varintField(5, contract.permissionId)
|
|
429
|
+
}
|
|
430
|
+
]);
|
|
431
|
+
const decodeContract = (bytes) => {
|
|
432
|
+
const fs = readFields(bytes);
|
|
433
|
+
const typeF = field(fs, 1);
|
|
434
|
+
const typeId = int32Field(typeF, "Contract.type");
|
|
435
|
+
const parameter = bytesFieldOf(field(fs, 2), "Contract.parameter");
|
|
436
|
+
const permissionId = int32Field(field(fs, 5), "Permission_id");
|
|
437
|
+
const any = readFields(parameter);
|
|
438
|
+
if (any.some((f) => f.field !== 1 && f.field !== 2)) malformed("google.protobuf.Any holds a field beyond type_url and value");
|
|
439
|
+
const urlBytes = bytesFieldOf(field(any, 1), "Any.type_url");
|
|
440
|
+
const value = bytesFieldOf(field(any, 2), "Any.value");
|
|
441
|
+
let typeUrl;
|
|
442
|
+
try {
|
|
443
|
+
typeUrl = utf8.decode(urlBytes);
|
|
444
|
+
} catch {
|
|
445
|
+
return malformed("Any.type_url is not UTF-8");
|
|
446
|
+
}
|
|
447
|
+
const known = tronContractType(typeId);
|
|
448
|
+
if (known !== void 0 && typeUrl !== tronTypeUrl(known.name)) malformed(`type_url ${typeUrl} does not name ${known.name}`);
|
|
449
|
+
return {
|
|
450
|
+
typeId,
|
|
451
|
+
typeUrl,
|
|
452
|
+
value,
|
|
453
|
+
permissionId,
|
|
454
|
+
extra: collectExtra(fs, [
|
|
455
|
+
1,
|
|
456
|
+
2,
|
|
457
|
+
5
|
|
458
|
+
])
|
|
459
|
+
};
|
|
460
|
+
};
|
|
461
|
+
const decodeTronRawData = (bytes) => {
|
|
462
|
+
const fs = readFields(bytes, [9, 11]);
|
|
463
|
+
const refBlockBytes = bytesFieldOf(field(fs, 1), "ref_block_bytes");
|
|
464
|
+
if (refBlockBytes.length !== 2) malformed("ref_block_bytes is not 2 bytes");
|
|
465
|
+
const refBlockHash = bytesFieldOf(field(fs, 4), "ref_block_hash");
|
|
466
|
+
if (refBlockHash.length !== 8) malformed("ref_block_hash is not 8 bytes");
|
|
467
|
+
const expiration = int64Field(field(fs, 8), "expiration");
|
|
468
|
+
if (expiration === 0n) malformed("expiration is missing");
|
|
469
|
+
const memo = field(fs, 10);
|
|
470
|
+
const contracts = all(fs, 11);
|
|
471
|
+
if (contracts.length !== 1) malformed(`raw_data carries ${contracts.length} contracts, exactly one is supported`);
|
|
472
|
+
const contract = decodeContract(bytesFieldOf(contracts[0], "contract"));
|
|
473
|
+
const timestamp = field(fs, 14);
|
|
474
|
+
const feeLimit = field(fs, 18);
|
|
475
|
+
const raw = {
|
|
476
|
+
refBlockBytes,
|
|
477
|
+
refBlockHash,
|
|
478
|
+
expiration,
|
|
479
|
+
...timestamp === void 0 ? {} : { timestamp: int64Field(timestamp, "timestamp") },
|
|
480
|
+
...feeLimit === void 0 ? {} : { feeLimit: int64Field(feeLimit, "fee_limit") },
|
|
481
|
+
...memo === void 0 ? {} : { memo: bytesFieldOf(memo, "data") },
|
|
482
|
+
contract,
|
|
483
|
+
extra: collectExtra(fs, [
|
|
484
|
+
1,
|
|
485
|
+
4,
|
|
486
|
+
8,
|
|
487
|
+
10,
|
|
488
|
+
11,
|
|
489
|
+
14,
|
|
490
|
+
18
|
|
491
|
+
])
|
|
492
|
+
};
|
|
493
|
+
if (!equalBytes(encodeTronRawData(raw), bytes)) malformed("non-canonical encoding");
|
|
494
|
+
return raw;
|
|
495
|
+
};
|
|
496
|
+
const encodeTronRawData = (raw) => encodeMessage([
|
|
497
|
+
{
|
|
498
|
+
field: 1,
|
|
499
|
+
bytes: requiredBytesField(1, raw.refBlockBytes)
|
|
500
|
+
},
|
|
501
|
+
...raw.extra.map((e) => ({
|
|
502
|
+
field: e.field,
|
|
503
|
+
bytes: e.bytes
|
|
504
|
+
})),
|
|
505
|
+
{
|
|
506
|
+
field: 4,
|
|
507
|
+
bytes: requiredBytesField(4, raw.refBlockHash)
|
|
508
|
+
},
|
|
509
|
+
{
|
|
510
|
+
field: 8,
|
|
511
|
+
bytes: varintField(8, raw.expiration)
|
|
512
|
+
},
|
|
513
|
+
{
|
|
514
|
+
field: 10,
|
|
515
|
+
bytes: bytesField(10, raw.memo ?? /* @__PURE__ */ new Uint8Array(0))
|
|
516
|
+
},
|
|
517
|
+
{
|
|
518
|
+
field: 11,
|
|
519
|
+
bytes: requiredBytesField(11, encodeContract(raw.contract))
|
|
520
|
+
},
|
|
521
|
+
{
|
|
522
|
+
field: 14,
|
|
523
|
+
bytes: varintField(14, raw.timestamp ?? 0n)
|
|
524
|
+
},
|
|
525
|
+
{
|
|
526
|
+
field: 18,
|
|
527
|
+
bytes: varintField(18, raw.feeLimit ?? 0n)
|
|
528
|
+
}
|
|
529
|
+
]);
|
|
530
|
+
/** TxID = sha256 over the canonical raw_data bytes — the transaction's only id. */
|
|
531
|
+
const tronTransactionId = (rawData) => sha256(rawData);
|
|
532
|
+
/** Transaction { raw_data = 1; repeated bytes signature = 2 } — the broadcast envelope. */
|
|
533
|
+
const encodeTronTransaction = (rawData, signatures) => encodeMessage([{
|
|
534
|
+
field: 1,
|
|
535
|
+
bytes: requiredBytesField(1, rawData)
|
|
536
|
+
}, ...signatures.map((s) => ({
|
|
537
|
+
field: 2,
|
|
538
|
+
bytes: requiredBytesField(2, s)
|
|
539
|
+
}))]);
|
|
540
|
+
// src/tron/message.ts
|
|
541
|
+
/**
|
|
542
|
+
* TRON message-signing content: the TIP-191 prefix `"\x19TRON Signed Message:\n" ‖ decimal byte
|
|
543
|
+
* length ‖ message`, hashed with keccak256 (tronweb src/utils/message.ts) — the 0x19 byte
|
|
544
|
+
* guarantees the preimage is never a valid `Transaction.raw`. This module owns the digest rule and
|
|
545
|
+
* the transaction-shape check a `tron.message` request must pass.
|
|
546
|
+
*/
|
|
547
|
+
const TRON_MESSAGE_PREFIX = "TRON Signed Message:\n";
|
|
548
|
+
const tronMessageDigest = (message) => {
|
|
549
|
+
const head = new TextEncoder().encode(`${TRON_MESSAGE_PREFIX}${message.length}`);
|
|
550
|
+
const preimage = new Uint8Array(head.length + message.length);
|
|
551
|
+
preimage.set(head);
|
|
552
|
+
preimage.set(message, head.length);
|
|
553
|
+
return keccak_256(preimage);
|
|
554
|
+
};
|
|
555
|
+
/**
|
|
556
|
+
* Whether `bytes` could be a transaction: either `Transaction.raw` itself, or a `Transaction`
|
|
557
|
+
* envelope whose field 1 is raw data. A `tron.message` request matching either is refused — the
|
|
558
|
+
* signature would authorise a transaction, not a message.
|
|
559
|
+
*/
|
|
560
|
+
const mayBeTronTransaction = (bytes) => {
|
|
561
|
+
try {
|
|
562
|
+
decodeTronRawData(bytes);
|
|
563
|
+
return true;
|
|
564
|
+
} catch {}
|
|
565
|
+
try {
|
|
566
|
+
const rawField = readFields(bytes).find((f) => f.field === 1);
|
|
567
|
+
if (rawField === void 0 || rawField.wire !== 2 || rawField.data === void 0) return false;
|
|
568
|
+
decodeTronRawData(rawField.data);
|
|
569
|
+
return true;
|
|
570
|
+
} catch {
|
|
571
|
+
return false;
|
|
572
|
+
}
|
|
573
|
+
};
|
|
574
|
+
// src/strict-json.ts
|
|
575
|
+
/**
|
|
576
|
+
* A strict JSON parser: the RFC 8259 grammar `JSON.parse` accepts, plus the two canonicality rules
|
|
577
|
+
* signing inputs need — a duplicate object key and trailing text after the value are malformed
|
|
578
|
+
* inputs, not silently resolved. Errors are reported through `invalid` so the caller's error type
|
|
579
|
+
* carries them; `depth` bounds nesting so a deep document cannot exhaust the stack.
|
|
580
|
+
*/
|
|
581
|
+
const WS = /* @__PURE__ */ new Set([
|
|
582
|
+
" ",
|
|
583
|
+
" ",
|
|
584
|
+
"\n",
|
|
585
|
+
"\r"
|
|
586
|
+
]);
|
|
587
|
+
const HEX_QUAD = /^[0-9a-fA-F]{4}$/;
|
|
588
|
+
const strictJson = (text, invalid, depth = 200) => {
|
|
589
|
+
let at = 0;
|
|
590
|
+
const fail = (reason) => invalid(`${reason} at offset ${at}`);
|
|
591
|
+
const ws = () => {
|
|
592
|
+
while (at < text.length && WS.has(text[at] ?? "")) at += 1;
|
|
593
|
+
};
|
|
594
|
+
const string = () => {
|
|
595
|
+
let out = "";
|
|
596
|
+
at += 1;
|
|
597
|
+
for (;;) {
|
|
598
|
+
if (at >= text.length) fail("unterminated string");
|
|
599
|
+
const c = text[at] ?? "";
|
|
600
|
+
if (c === "\"") {
|
|
601
|
+
at += 1;
|
|
602
|
+
return out;
|
|
603
|
+
}
|
|
604
|
+
if (c === "\\") {
|
|
605
|
+
at += 1;
|
|
606
|
+
const escape = text[at];
|
|
607
|
+
switch (escape) {
|
|
608
|
+
case "\"":
|
|
609
|
+
case "\\":
|
|
610
|
+
case "/":
|
|
611
|
+
out += escape;
|
|
612
|
+
at += 1;
|
|
613
|
+
break;
|
|
614
|
+
case "b":
|
|
615
|
+
out += "\b";
|
|
616
|
+
at += 1;
|
|
617
|
+
break;
|
|
618
|
+
case "f":
|
|
619
|
+
out += "\f";
|
|
620
|
+
at += 1;
|
|
621
|
+
break;
|
|
622
|
+
case "n":
|
|
623
|
+
out += "\n";
|
|
624
|
+
at += 1;
|
|
625
|
+
break;
|
|
626
|
+
case "r":
|
|
627
|
+
out += "\r";
|
|
628
|
+
at += 1;
|
|
629
|
+
break;
|
|
630
|
+
case "t":
|
|
631
|
+
out += " ";
|
|
632
|
+
at += 1;
|
|
633
|
+
break;
|
|
634
|
+
case "u": {
|
|
635
|
+
const digits = text.slice(at + 1, at + 5);
|
|
636
|
+
if (!HEX_QUAD.test(digits)) fail(String.raw`malformed \u escape`);
|
|
637
|
+
out += String.fromCodePoint(Number.parseInt(digits, 16));
|
|
638
|
+
at += 5;
|
|
639
|
+
break;
|
|
640
|
+
}
|
|
641
|
+
default: fail(`unknown escape \\${escape ?? "?"}`);
|
|
642
|
+
}
|
|
643
|
+
} else {
|
|
644
|
+
if (c < " ") fail("control character in string");
|
|
645
|
+
out += c;
|
|
646
|
+
at += 1;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
const number = () => {
|
|
651
|
+
const start = at;
|
|
652
|
+
if (text[at] === "-") at += 1;
|
|
653
|
+
if (text[at] === "0") at += 1;
|
|
654
|
+
else if ((text[at] ?? "") >= "1" && (text[at] ?? "") <= "9") while ((text[at] ?? "") >= "0" && (text[at] ?? "") <= "9") at += 1;
|
|
655
|
+
else fail("malformed number");
|
|
656
|
+
if (text[at] === ".") {
|
|
657
|
+
at += 1;
|
|
658
|
+
if (!((text[at] ?? "") >= "0" && (text[at] ?? "") <= "9")) fail("malformed number");
|
|
659
|
+
while ((text[at] ?? "") >= "0" && (text[at] ?? "") <= "9") at += 1;
|
|
660
|
+
}
|
|
661
|
+
if (text[at] === "e" || text[at] === "E") {
|
|
662
|
+
at += 1;
|
|
663
|
+
if (text[at] === "+" || text[at] === "-") at += 1;
|
|
664
|
+
if (!((text[at] ?? "") >= "0" && (text[at] ?? "") <= "9")) fail("malformed number");
|
|
665
|
+
while ((text[at] ?? "") >= "0" && (text[at] ?? "") <= "9") at += 1;
|
|
666
|
+
}
|
|
667
|
+
return Number(text.slice(start, at));
|
|
668
|
+
};
|
|
669
|
+
const literal = (word, value) => {
|
|
670
|
+
if (!text.startsWith(word, at)) fail(`malformed value`);
|
|
671
|
+
at += word.length;
|
|
672
|
+
return value;
|
|
673
|
+
};
|
|
674
|
+
const value = (level) => {
|
|
675
|
+
if (level > depth) fail("document nests too deeply");
|
|
676
|
+
ws();
|
|
677
|
+
const c = text[at];
|
|
678
|
+
if (c === "\"") return string();
|
|
679
|
+
if (c === "{") {
|
|
680
|
+
const object = {};
|
|
681
|
+
const keys = /* @__PURE__ */ new Set();
|
|
682
|
+
at += 1;
|
|
683
|
+
ws();
|
|
684
|
+
if (text[at] === "}") {
|
|
685
|
+
at += 1;
|
|
686
|
+
return object;
|
|
687
|
+
}
|
|
688
|
+
for (;;) {
|
|
689
|
+
ws();
|
|
690
|
+
if (text[at] !== "\"") fail("expected a member name");
|
|
691
|
+
const key = string();
|
|
692
|
+
if (keys.has(key)) fail(`duplicate key ${JSON.stringify(key)}`);
|
|
693
|
+
keys.add(key);
|
|
694
|
+
ws();
|
|
695
|
+
if (text[at] !== ":") fail("expected ':'");
|
|
696
|
+
at += 1;
|
|
697
|
+
const member = value(level + 1);
|
|
698
|
+
Object.defineProperty(object, key, {
|
|
699
|
+
value: member,
|
|
700
|
+
enumerable: true,
|
|
701
|
+
writable: true,
|
|
702
|
+
configurable: true
|
|
703
|
+
});
|
|
704
|
+
ws();
|
|
705
|
+
if (text[at] === ",") {
|
|
706
|
+
at += 1;
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
if (text[at] === "}") {
|
|
710
|
+
at += 1;
|
|
711
|
+
return object;
|
|
712
|
+
}
|
|
713
|
+
fail("expected ',' or '}'");
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (c === "[") {
|
|
717
|
+
const array = [];
|
|
718
|
+
at += 1;
|
|
719
|
+
ws();
|
|
720
|
+
if (text[at] === "]") {
|
|
721
|
+
at += 1;
|
|
722
|
+
return array;
|
|
723
|
+
}
|
|
724
|
+
for (;;) {
|
|
725
|
+
array.push(value(level + 1));
|
|
726
|
+
ws();
|
|
727
|
+
if (text[at] === ",") {
|
|
728
|
+
at += 1;
|
|
729
|
+
continue;
|
|
730
|
+
}
|
|
731
|
+
if (text[at] === "]") {
|
|
732
|
+
at += 1;
|
|
733
|
+
return array;
|
|
734
|
+
}
|
|
735
|
+
fail("expected ',' or ']'");
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if (c === "t") return literal("true", true);
|
|
739
|
+
if (c === "f") return literal("false", false);
|
|
740
|
+
if (c === "n") return literal("null", null);
|
|
741
|
+
return number();
|
|
742
|
+
};
|
|
743
|
+
const parsed = value(1);
|
|
744
|
+
ws();
|
|
745
|
+
if (at !== text.length) fail("trailing text after the JSON value");
|
|
746
|
+
return parsed;
|
|
747
|
+
};
|
|
748
|
+
// src/tron/address.ts
|
|
749
|
+
/** The version byte every TRON address (mainnet and testnets alike) carries. */
|
|
750
|
+
const TRON_ADDRESS_PREFIX = 65;
|
|
751
|
+
const base58check = createBase58check(sha256);
|
|
752
|
+
/** A 34-character base58check string whose payload is 21 bytes starting with 0x41. */
|
|
753
|
+
const isTronAddress = (value) => {
|
|
754
|
+
if (!/^[1-9A-HJ-NP-Za-km-z]{34}$/.test(value)) return false;
|
|
755
|
+
try {
|
|
756
|
+
const decoded = base58check.decode(value);
|
|
757
|
+
return decoded.length === 21 && decoded[0] === 65;
|
|
758
|
+
} catch {
|
|
759
|
+
return false;
|
|
760
|
+
}
|
|
761
|
+
};
|
|
762
|
+
const tronBytes = (address, what) => {
|
|
763
|
+
if (!isTronAddress(address)) throw new ChainError("invalid-address", `not a TRON address: ${what}`);
|
|
764
|
+
return base58check.decode(address);
|
|
765
|
+
};
|
|
766
|
+
/** The 21 raw bytes — 0x41 version byte plus the 20-byte address body. */
|
|
767
|
+
function tronAddressToBytes(address) {
|
|
768
|
+
return tronBytes(address, "base58check");
|
|
769
|
+
}
|
|
770
|
+
/** Base58check encodes a 21-byte payload whose first byte is 0x41. */
|
|
771
|
+
function tronAddressFromBytes(bytes) {
|
|
772
|
+
if (bytes.length !== 21 || bytes[0] !== 65) throw new ChainError("invalid-address", "a TRON address is 21 bytes starting with 0x41");
|
|
773
|
+
return base58check.encode(bytes);
|
|
774
|
+
}
|
|
775
|
+
/** `"41"` plus the 20-byte body as 40 lowercase hex — the form contract fields carry. */
|
|
776
|
+
function tronAddressToHex(address) {
|
|
777
|
+
return bytesToHex(tronBytes(address, "base58check"));
|
|
778
|
+
}
|
|
779
|
+
/** `"41"` plus 40 hex — the form `raw_data` contract fields and trongrid JSON carry. */
|
|
780
|
+
function tronAddressFromHex(hex) {
|
|
781
|
+
if (!/^41[0-9a-fA-F]{40}$/.test(hex)) throw new ChainError("invalid-address", "a TRON hex address is 41 plus 40 hex");
|
|
782
|
+
return tronAddressFromBytes(hexToBytes(hex));
|
|
783
|
+
}
|
|
784
|
+
const is0xPrefixed = (value) => value.startsWith("0x");
|
|
785
|
+
/** The 20-byte body rendered as an EIP-55 checksummed 0x address (ABI/EVM tooling form). */
|
|
786
|
+
function tronAddressToEvm(address) {
|
|
787
|
+
const checksummed = checksumEvmAddress(`0x${tronAddressToHex(address).slice(2)}`);
|
|
788
|
+
if (!is0xPrefixed(checksummed)) throw new ChainError("invalid-address", "EIP-55 checksum did not produce a 0x address");
|
|
789
|
+
return checksummed;
|
|
790
|
+
}
|
|
791
|
+
/** 0x plus 40 hex — an EVM-style encoding of the 20-byte body. */
|
|
792
|
+
function tronAddressFromEvm(address) {
|
|
793
|
+
if (!/^0x[0-9a-fA-F]{40}$/.test(address)) throw new ChainError("invalid-address", "expected a 0x-prefixed 20-byte address");
|
|
794
|
+
return tronAddressFromHex(`41${address.slice(2)}`);
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* `0x41 ‖ keccak256(uncompressed[1..])[12..32]` — accepts a 33-byte compressed or 65-byte
|
|
798
|
+
* uncompressed secp256k1 key.
|
|
799
|
+
*/
|
|
800
|
+
function tronAddressFromPublicKey(pubkey) {
|
|
801
|
+
const uncompressed = pubkey.length === 65 && pubkey[0] === 4 ? pubkey : pubkey.length === 33 ? secp256k1.Point.fromBytes(pubkey).toBytes(false) : void 0;
|
|
802
|
+
if (uncompressed === void 0 || uncompressed[0] !== 4) throw new ChainError("invalid-address", "expected a compressed or uncompressed secp256k1 key");
|
|
803
|
+
return tronAddressFromBytes(concatBytes(Uint8Array.of(65), keccak_256(uncompressed.subarray(1)).subarray(12)));
|
|
804
|
+
}
|
|
805
|
+
// src/tron/typed-data.ts
|
|
806
|
+
/**
|
|
807
|
+
* TIP-712 typed data — EIP-712 with TRON's two deviations (tips/tip-712.md; the oracle is TronWeb
|
|
808
|
+
* 6.5.2's TypedDataEncoder): an `address` leaf is the 20 bytes after the 0x41 version byte, and
|
|
809
|
+
* `trcToken` is an atomic type encoded like `uint256`. `parseTronTypedData` validates the canonical
|
|
810
|
+
* JSON — what `TypedDataEncoder.getPayload` emits — and `tronTypedDataDigest` computes
|
|
811
|
+
* `keccak256(0x1901 ‖ hashStruct(EIP712Domain, domain) ‖ hashStruct(primaryType, message))`,
|
|
812
|
+
* byte-identical to TronWeb's `hashTypedData` on every accepted document. Where the canonical
|
|
813
|
+
* grammar is stricter than TronWeb's loose inputs (JSON booleans only, even-length `0x` hex, no
|
|
814
|
+
* bare-width `uint`), the difference can only change what it hashes to, never whether it signs — so
|
|
815
|
+
* strictness is a validation concern, not a compatibility one.
|
|
816
|
+
*/
|
|
817
|
+
const fail = (what) => {
|
|
818
|
+
throw new ChainError("invalid-typed-data", what);
|
|
819
|
+
};
|
|
820
|
+
const INT_TYPE = /^(u?)int(\d*)$/;
|
|
821
|
+
const FIXED_BYTES = /^bytes(\d+)$/;
|
|
822
|
+
const ARRAY_TAIL = /^(.*)\[(\d*)\]$/;
|
|
823
|
+
/**
|
|
824
|
+
* A leaf `address` value's 20-byte body: a base58check `T…` string, `41` + 40 hex, or `0x` + 40
|
|
825
|
+
* hex. Bare 40-hex is refused — TronWeb's `toHex` would hash it as garbage rather than an address,
|
|
826
|
+
* so accepting it could only mis-sign.
|
|
827
|
+
*/
|
|
828
|
+
const addressBody = (value) => {
|
|
829
|
+
if (typeof value !== "string") return;
|
|
830
|
+
if (isTronAddress(value)) return tronAddressToBytes(value).subarray(1);
|
|
831
|
+
if (/^41[0-9a-fA-F]{40}$/.test(value)) return hexToBytes(value).subarray(1);
|
|
832
|
+
if (/^0x[0-9a-fA-F]{40}$/.test(value)) return hexToBytes(value.slice(2));
|
|
833
|
+
};
|
|
834
|
+
/** The display form of a leaf `address` value — base58check, whichever form the document used. */
|
|
835
|
+
const tronTypedDataBase58 = (value) => {
|
|
836
|
+
const body = addressBody(value);
|
|
837
|
+
return body === void 0 ? void 0 : tronAddressFromHex(`41${bytesToHex(body)}`);
|
|
838
|
+
};
|
|
839
|
+
const word = (value) => {
|
|
840
|
+
const v = value < 0n ? 2n ** 256n + value : value;
|
|
841
|
+
return hexToBytes(v.toString(16).padStart(64, "0"));
|
|
842
|
+
};
|
|
843
|
+
const intBounds = (signed, bits) => signed ? [-(2n ** BigInt(bits - 1)), 2n ** BigInt(bits - 1) - 1n] : [0n, 2n ** BigInt(bits) - 1n];
|
|
844
|
+
/** Canonical-JSON int leaf: safe integer, decimal string (`-` only where signed), or `0x` hex. */
|
|
845
|
+
const strictInt = (value, signed) => {
|
|
846
|
+
if (typeof value === "number" && Number.isSafeInteger(value)) return BigInt(value);
|
|
847
|
+
if (typeof value === "string" && ((signed ? /^-?[0-9]+$/ : /^[0-9]+$/).test(value) || /^0x[0-9a-fA-F]+$/.test(value))) return BigInt(value);
|
|
848
|
+
};
|
|
849
|
+
/** A `tron_signTypedData` argument's int leaf — TronWeb's getBigInt forms. */
|
|
850
|
+
const looseInt = (value) => {
|
|
851
|
+
if (typeof value === "bigint") return value;
|
|
852
|
+
if (typeof value === "number" && Number.isSafeInteger(value)) return BigInt(value);
|
|
853
|
+
if (typeof value === "string" && (/^-?[0-9]+$/.test(value) || /^0x[0-9a-fA-F]+$/.test(value))) return BigInt(value);
|
|
854
|
+
};
|
|
855
|
+
/** A bytes leaf — canonical `0x` even-length hex, plus a `Uint8Array` in argument mode. */
|
|
856
|
+
const hexLeaf = (value, args) => {
|
|
857
|
+
if (args && value instanceof Uint8Array) return value;
|
|
858
|
+
return typeof value === "string" && /^0x([0-9a-fA-F]{2})*$/.test(value) ? hexToBytes(value.slice(2)) : void 0;
|
|
859
|
+
};
|
|
860
|
+
/**
|
|
861
|
+
* The encoder for one atomic type, mirroring TronWeb's `getBaseEncoder` — including its rule that a
|
|
862
|
+
* base-looking name with a malformed width (`uint7`, `bytes33`, bare `uint`) is a name error, not
|
|
863
|
+
* "no such type", so `isBaseName` below can count it against struct names. `args` relaxes leaf
|
|
864
|
+
* forms to what `_signTypedData(domain, types, value)` accepts.
|
|
865
|
+
*/
|
|
866
|
+
const baseEncoder = (type, args) => {
|
|
867
|
+
const int = INT_TYPE.exec(type);
|
|
868
|
+
if (int !== null) {
|
|
869
|
+
const signed = int[1] === "";
|
|
870
|
+
const w = int[2] === "" ? NaN : Number(int[2]);
|
|
871
|
+
if (w % 8 !== 0 || w < 8 || w > 256 || int[2] !== String(w)) fail(`invalid numeric width in type ${type}`);
|
|
872
|
+
const [min, max] = intBounds(signed, w);
|
|
873
|
+
return (value) => {
|
|
874
|
+
const parsed = args ? looseInt(value) : strictInt(value, signed);
|
|
875
|
+
if (parsed === void 0 || parsed < min || parsed > max) return fail(`value is out of bounds for ${type}`);
|
|
876
|
+
return word(parsed);
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
const fixed = FIXED_BYTES.exec(type);
|
|
880
|
+
if (fixed !== null) {
|
|
881
|
+
const w = Number(fixed[1]);
|
|
882
|
+
if (w < 1 || w > 32 || String(w) !== fixed[1]) fail(`invalid bytes width in type ${type}`);
|
|
883
|
+
return (value) => {
|
|
884
|
+
const bytes = hexLeaf(value, args);
|
|
885
|
+
if (bytes === void 0 || bytes.length !== w) return fail(`invalid length for ${type}`);
|
|
886
|
+
const out = /* @__PURE__ */ new Uint8Array(32);
|
|
887
|
+
out.set(bytes);
|
|
888
|
+
return out;
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
switch (type) {
|
|
892
|
+
case "trcToken": return baseEncoder("uint256", args);
|
|
893
|
+
case "address": return (value) => {
|
|
894
|
+
const body = addressBody(value);
|
|
895
|
+
if (body === void 0) return fail("address is not a base58, 41-hex or 0x-hex TRON address");
|
|
896
|
+
return concatBytes(/* @__PURE__ */ new Uint8Array(12), body);
|
|
897
|
+
};
|
|
898
|
+
case "bool": return (value) => {
|
|
899
|
+
if (args) return word(Boolean(value) ? 1n : 0n);
|
|
900
|
+
if (typeof value !== "boolean") return fail("bool is not a JSON boolean");
|
|
901
|
+
return word(value ? 1n : 0n);
|
|
902
|
+
};
|
|
903
|
+
case "bytes": return (value) => {
|
|
904
|
+
const bytes = hexLeaf(value, args);
|
|
905
|
+
if (bytes === void 0) return fail("bytes is not 0x-prefixed even-length hex");
|
|
906
|
+
return keccak_256(bytes);
|
|
907
|
+
};
|
|
908
|
+
case "string": return (value) => {
|
|
909
|
+
if (typeof value !== "string") return fail("string value is not a string");
|
|
910
|
+
return keccak_256(utf8ToBytes(value));
|
|
911
|
+
};
|
|
912
|
+
default: return;
|
|
913
|
+
}
|
|
914
|
+
};
|
|
915
|
+
/** Mirrors TronWeb's `isBaseTypeName`: every base-looking name counts, even a malformed one. */
|
|
916
|
+
const isBaseName = (name) => INT_TYPE.test(name) || FIXED_BYTES.test(name) || name === "address" || name === "bool" || name === "string" || name === "bytes" || name === "trcToken";
|
|
917
|
+
/** A field type's base after stripping `[]`/`[n]` suffixes; a malformed suffix stays attached. */
|
|
918
|
+
const baseName = (type) => {
|
|
919
|
+
let t = type;
|
|
920
|
+
for (;;) {
|
|
921
|
+
const tail = ARRAY_TAIL.exec(t);
|
|
922
|
+
if (tail === null) return t;
|
|
923
|
+
t = tail[1] ?? "";
|
|
924
|
+
}
|
|
925
|
+
};
|
|
926
|
+
const encodeTypeOf = (types, name) => `${name}(${(types[name] ?? []).map((f) => `${f.type} ${f.name}`).join(",")})`;
|
|
927
|
+
/**
|
|
928
|
+
* Validates a struct-type map like TronWeb's TypedDataEncoder constructor: no base-name collisions,
|
|
929
|
+
* unique field names, field types resolving to a base or a declared struct, no cycles, and exactly
|
|
930
|
+
* one root — the only type nothing references, hence the primary type. Unlike TronWeb, an
|
|
931
|
+
* unreachable type (it could only be part of a disconnected cycle) is also refused: it would be
|
|
932
|
+
* dead weight in the document.
|
|
933
|
+
*/
|
|
934
|
+
const checkTypes = (types) => {
|
|
935
|
+
const names = Object.keys(types);
|
|
936
|
+
const links = /* @__PURE__ */ new Map();
|
|
937
|
+
const parents = /* @__PURE__ */ new Map();
|
|
938
|
+
const subtypes = /* @__PURE__ */ new Map();
|
|
939
|
+
for (const name of names) {
|
|
940
|
+
links.set(name, /* @__PURE__ */ new Set());
|
|
941
|
+
parents.set(name, []);
|
|
942
|
+
subtypes.set(name, /* @__PURE__ */ new Set());
|
|
943
|
+
}
|
|
944
|
+
for (const name of names) {
|
|
945
|
+
if (isBaseName(name)) fail(`struct type name ${JSON.stringify(name)} collides with a base type`);
|
|
946
|
+
const seen = /* @__PURE__ */ new Set();
|
|
947
|
+
for (const field of types[name] ?? []) {
|
|
948
|
+
if (seen.has(field.name)) fail(`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`);
|
|
949
|
+
seen.add(field.name);
|
|
950
|
+
const base = baseName(field.type);
|
|
951
|
+
if (base === name) fail(`circular type reference to ${JSON.stringify(base)}`);
|
|
952
|
+
let baseIsAtomic;
|
|
953
|
+
try {
|
|
954
|
+
baseIsAtomic = baseEncoder(base, false) !== void 0;
|
|
955
|
+
} catch (error) {
|
|
956
|
+
if (error instanceof ChainError) fail(`invalid field type ${JSON.stringify(field.type)}`);
|
|
957
|
+
throw error;
|
|
958
|
+
}
|
|
959
|
+
if (baseIsAtomic) continue;
|
|
960
|
+
if (!parents.has(base)) fail(`unknown type ${JSON.stringify(base)}`);
|
|
961
|
+
(parents.get(base) ?? []).push(name);
|
|
962
|
+
(links.get(name) ?? /* @__PURE__ */ new Set()).add(base);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
const roots = names.filter((n) => (parents.get(n) ?? []).length === 0);
|
|
966
|
+
if (roots.length === 0) fail("missing primary type");
|
|
967
|
+
if (roots.length !== 1) fail(`ambiguous primary types or unused types: ${roots.map((r) => JSON.stringify(r)).join(", ")}`);
|
|
968
|
+
const primary = roots[0] ?? "";
|
|
969
|
+
const visited = /* @__PURE__ */ new Set();
|
|
970
|
+
const checkCircular = (type, found) => {
|
|
971
|
+
if (found.has(type)) fail(`circular type reference to ${JSON.stringify(type)}`);
|
|
972
|
+
found.add(type);
|
|
973
|
+
visited.add(type);
|
|
974
|
+
for (const child of links.get(type) ?? /* @__PURE__ */ new Set()) {
|
|
975
|
+
checkCircular(child, found);
|
|
976
|
+
for (const subtype of found) (subtypes.get(subtype) ?? /* @__PURE__ */ new Set()).add(child);
|
|
977
|
+
}
|
|
978
|
+
found.delete(type);
|
|
979
|
+
};
|
|
980
|
+
checkCircular(primary, /* @__PURE__ */ new Set());
|
|
981
|
+
if (visited.size !== names.length) fail("types contains types the primary type does not reach");
|
|
982
|
+
const fullTypes = /* @__PURE__ */ new Map();
|
|
983
|
+
for (const [name, set] of subtypes) {
|
|
984
|
+
const st = [...set].sort();
|
|
985
|
+
fullTypes.set(name, encodeTypeOf(types, name) + st.map((t) => encodeTypeOf(types, t)).join(""));
|
|
986
|
+
}
|
|
987
|
+
return {
|
|
988
|
+
primary,
|
|
989
|
+
fullTypes
|
|
990
|
+
};
|
|
991
|
+
};
|
|
992
|
+
/**
|
|
993
|
+
* The encoder/walker pair over a validated type map. `hashStruct` produces TronWeb's `hashStruct`:
|
|
994
|
+
* each leaf its 32-byte word, an array the keccak of its elements' encodings, a struct the keccak
|
|
995
|
+
* of `typeHash ‖ fields` (a struct-typed field or element carries its own keccak). `visit` mirrors
|
|
996
|
+
* `TypedDataEncoder.getPayload`'s message normalization: bytes as `0x` hex, integers decimal,
|
|
997
|
+
* addresses `41`-hex, booleans `!!value`.
|
|
998
|
+
*/
|
|
999
|
+
const makeEncoder = (types, args) => {
|
|
1000
|
+
const { primary, fullTypes } = checkTypes(types);
|
|
1001
|
+
const encode = (type, value, depth) => {
|
|
1002
|
+
if (depth > 32) fail("typedData nests too deeply");
|
|
1003
|
+
const atomic = baseEncoder(type, args);
|
|
1004
|
+
if (atomic !== void 0) return atomic(value);
|
|
1005
|
+
const tail = ARRAY_TAIL.exec(type);
|
|
1006
|
+
if (tail !== null) {
|
|
1007
|
+
if (!Array.isArray(value)) return fail(`${type} value is not an array`);
|
|
1008
|
+
const len = tail[2] === "" ? void 0 : Number(tail[2]);
|
|
1009
|
+
if (len !== void 0 && len !== value.length) return fail(`array length mismatch; expected length ${len}`);
|
|
1010
|
+
const elementType = tail[1] ?? "";
|
|
1011
|
+
const structElements = fullTypes.has(elementType);
|
|
1012
|
+
const encoded = value.map((v) => encode(elementType, v, depth + 1));
|
|
1013
|
+
return keccak_256(concatBytes(...encoded.map((e) => structElements ? keccak_256(e) : e)));
|
|
1014
|
+
}
|
|
1015
|
+
const fields = types[type];
|
|
1016
|
+
if (fields !== void 0) {
|
|
1017
|
+
if (!isRecord(value)) return fail(`${type} value is not an object`);
|
|
1018
|
+
const typeHash = keccak_256(utf8ToBytes(fullTypes.get(type) ?? ""));
|
|
1019
|
+
const encoded = fields.map((f) => {
|
|
1020
|
+
const e = encode(f.type, value[f.name], depth + 1);
|
|
1021
|
+
return fullTypes.has(f.type) ? keccak_256(e) : e;
|
|
1022
|
+
});
|
|
1023
|
+
return concatBytes(typeHash, ...encoded);
|
|
1024
|
+
}
|
|
1025
|
+
return fail(`unknown type ${type}`);
|
|
1026
|
+
};
|
|
1027
|
+
const visitLeaf = (type, value) => {
|
|
1028
|
+
if (/^bytes(\d*)/.test(type)) {
|
|
1029
|
+
const bytes = hexLeaf(value, args);
|
|
1030
|
+
if (bytes === void 0) return fail(`invalid bytes value for ${type}`);
|
|
1031
|
+
return `0x${bytesToHex(bytes)}`;
|
|
1032
|
+
}
|
|
1033
|
+
if (/^u?int/.test(type) || type === "trcToken") {
|
|
1034
|
+
const v = looseInt(value);
|
|
1035
|
+
if (v === void 0) return fail(`invalid numeric value for ${type}`);
|
|
1036
|
+
return v.toString(10);
|
|
1037
|
+
}
|
|
1038
|
+
switch (type) {
|
|
1039
|
+
case "address": {
|
|
1040
|
+
const body = addressBody(value);
|
|
1041
|
+
if (body === void 0) return fail("address is not a base58, 41-hex or 0x-hex TRON address");
|
|
1042
|
+
return `41${bytesToHex(body)}`;
|
|
1043
|
+
}
|
|
1044
|
+
case "bool": return Boolean(value);
|
|
1045
|
+
case "string":
|
|
1046
|
+
if (typeof value !== "string") return fail("string value is not a string");
|
|
1047
|
+
return value;
|
|
1048
|
+
default: return fail(`unsupported type ${type}`);
|
|
1049
|
+
}
|
|
1050
|
+
};
|
|
1051
|
+
const visit = (type, value, depth) => {
|
|
1052
|
+
if (depth > 32) fail("typedData nests too deeply");
|
|
1053
|
+
if (baseEncoder(type, true) !== void 0) return visitLeaf(type, value);
|
|
1054
|
+
const tail = ARRAY_TAIL.exec(type);
|
|
1055
|
+
if (tail !== null) {
|
|
1056
|
+
if (!Array.isArray(value)) return fail(`${type} value is not an array`);
|
|
1057
|
+
const len = tail[2] === "" ? void 0 : Number(tail[2]);
|
|
1058
|
+
if (len !== void 0 && len !== value.length) return fail(`array length mismatch; expected length ${len}`);
|
|
1059
|
+
return value.map((v) => visit(tail[1] ?? "", v, depth + 1));
|
|
1060
|
+
}
|
|
1061
|
+
const fields = types[type];
|
|
1062
|
+
if (fields !== void 0) {
|
|
1063
|
+
if (!isRecord(value)) return fail(`${type} value is not an object`);
|
|
1064
|
+
return Object.fromEntries(fields.map((f) => [f.name, visit(f.type, value[f.name], depth + 1)]));
|
|
1065
|
+
}
|
|
1066
|
+
return fail(`unknown type ${type}`);
|
|
1067
|
+
};
|
|
1068
|
+
return {
|
|
1069
|
+
primary,
|
|
1070
|
+
hashStruct: (type, value) => keccak_256(encode(type, value, 0)),
|
|
1071
|
+
visit: (type, value) => visit(type, value, 0)
|
|
1072
|
+
};
|
|
1073
|
+
};
|
|
1074
|
+
/** The five domain fields a TIP-712 document may carry, in canonical order. */
|
|
1075
|
+
const DOMAIN_FIELD_TYPES = [
|
|
1076
|
+
{
|
|
1077
|
+
name: "name",
|
|
1078
|
+
type: "string"
|
|
1079
|
+
},
|
|
1080
|
+
{
|
|
1081
|
+
name: "version",
|
|
1082
|
+
type: "string"
|
|
1083
|
+
},
|
|
1084
|
+
{
|
|
1085
|
+
name: "chainId",
|
|
1086
|
+
type: "uint256"
|
|
1087
|
+
},
|
|
1088
|
+
{
|
|
1089
|
+
name: "verifyingContract",
|
|
1090
|
+
type: "address"
|
|
1091
|
+
},
|
|
1092
|
+
{
|
|
1093
|
+
name: "salt",
|
|
1094
|
+
type: "bytes32"
|
|
1095
|
+
}
|
|
1096
|
+
];
|
|
1097
|
+
const DOMAIN_NAMES = new Set(DOMAIN_FIELD_TYPES.map((f) => f.name));
|
|
1098
|
+
/** `types.EIP712Domain` exactly mirrors the domain's non-null keys, in canonical order. */
|
|
1099
|
+
const domainFieldsOf = (domain) => {
|
|
1100
|
+
const fields = [];
|
|
1101
|
+
for (const f of DOMAIN_FIELD_TYPES) {
|
|
1102
|
+
const value = domain[f.name];
|
|
1103
|
+
if (value !== void 0 && value !== null) fields.push(f);
|
|
1104
|
+
}
|
|
1105
|
+
for (const key of Object.keys(domain)) if (domain[key] !== void 0 && domain[key] !== null && !DOMAIN_NAMES.has(key)) fail(`invalid typed-data domain key ${JSON.stringify(key)}`);
|
|
1106
|
+
return fields;
|
|
1107
|
+
};
|
|
1108
|
+
const sameFieldList = (declared, expected) => declared.length === expected.length && declared.every((f, i) => f.name === expected[i]?.name && f.type === expected[i]?.type);
|
|
1109
|
+
/**
|
|
1110
|
+
* The domain's non-null entries — a `null` domain value is dropped like TronWeb's `== null` skip,
|
|
1111
|
+
* so `types.EIP712Domain` can still match the remaining keys.
|
|
1112
|
+
*/
|
|
1113
|
+
const domainValues = (domain) => Object.fromEntries(Object.entries(domain).filter(([, v]) => v !== null && v !== void 0));
|
|
1114
|
+
/**
|
|
1115
|
+
* Parses the canonical TIP-712 JSON. Beyond `isTypedDataInput`'s shape, the document must be strict
|
|
1116
|
+
* JSON (no duplicate keys, nothing after the value), `types.EIP712Domain` must be exactly the
|
|
1117
|
+
* domain's present keys in canonical order, the struct types must form a single root DAG naming
|
|
1118
|
+
* `primaryType`, and every leaf must carry its canonical value — verified by running the encoder,
|
|
1119
|
+
* so anything that would hash is something that validated.
|
|
1120
|
+
*/
|
|
1121
|
+
const parseTronTypedData = (typedData) => {
|
|
1122
|
+
const json = strictJson(typedData, (reason) => fail(`typedData ${reason}`));
|
|
1123
|
+
if (!isTypedDataInput(json)) return fail("typedData must be a JSON object with types, primaryType, domain and message");
|
|
1124
|
+
const domainFields = domainFieldsOf(json.domain);
|
|
1125
|
+
const declared = json.types["EIP712Domain"] ?? fail("typedData must declare types.EIP712Domain");
|
|
1126
|
+
if (!sameFieldList(declared, domainFields)) fail("types.EIP712Domain is not the canonical field list of the domain keys present");
|
|
1127
|
+
tronTypedDataDigest(json);
|
|
1128
|
+
return { json: {
|
|
1129
|
+
...json,
|
|
1130
|
+
domain: domainValues(json.domain)
|
|
1131
|
+
} };
|
|
1132
|
+
};
|
|
1133
|
+
/**
|
|
1134
|
+
* The domain separator and message hash of a parsed document — `hashStruct(EIP712Domain, domain)`
|
|
1135
|
+
* under the fields its non-null keys derive, `hashStruct(primaryType, message)` under the unique
|
|
1136
|
+
* root type of `types` minus `EIP712Domain`. Returned separately for signers that send the two
|
|
1137
|
+
* hashes to the device rather than one digest (Tron `INS_0C`).
|
|
1138
|
+
*/
|
|
1139
|
+
const tronTypedDataHashes = (json) => {
|
|
1140
|
+
const domainFields = domainFieldsOf(json.domain);
|
|
1141
|
+
const messageTypes = {};
|
|
1142
|
+
for (const [name, fields] of Object.entries(json.types)) if (name !== "EIP712Domain") messageTypes[name] = fields;
|
|
1143
|
+
const encoder = makeEncoder(messageTypes, false);
|
|
1144
|
+
if (encoder.primary !== json.primaryType) fail(`primaryType ${JSON.stringify(json.primaryType)} is not the unique root type`);
|
|
1145
|
+
return {
|
|
1146
|
+
domain: makeEncoder({ EIP712Domain: domainFields }, false).hashStruct("EIP712Domain", json.domain),
|
|
1147
|
+
message: encoder.hashStruct(json.primaryType, json.message)
|
|
1148
|
+
};
|
|
1149
|
+
};
|
|
1150
|
+
/**
|
|
1151
|
+
* The signing digest of a parsed document: `keccak256(0x1901 ‖ hashStruct(EIP712Domain, domain) ‖
|
|
1152
|
+
* hashStruct(primaryType, message))` — `keccak256(0x1901 ‖ hashes.domain ‖ hashes.message)`.
|
|
1153
|
+
*/
|
|
1154
|
+
const tronTypedDataDigest = (json) => {
|
|
1155
|
+
const { domain, message } = tronTypedDataHashes(json);
|
|
1156
|
+
return keccak_256(concatBytes(Uint8Array.of(25, 1), domain, message));
|
|
1157
|
+
};
|
|
1158
|
+
const domainArg = (name, value) => {
|
|
1159
|
+
switch (name) {
|
|
1160
|
+
case "name":
|
|
1161
|
+
case "version":
|
|
1162
|
+
if (typeof value !== "string") return fail(`domain.${name} is not a string`);
|
|
1163
|
+
return value;
|
|
1164
|
+
case "chainId": {
|
|
1165
|
+
const v = looseInt(value);
|
|
1166
|
+
if (v === void 0 || v < 0n) return fail("domain.chainId is not a non-negative integer");
|
|
1167
|
+
return `0x${v.toString(16)}`;
|
|
1168
|
+
}
|
|
1169
|
+
case "verifyingContract": {
|
|
1170
|
+
const body = addressBody(value);
|
|
1171
|
+
if (body === void 0) return fail("domain.verifyingContract is not a valid TRON address");
|
|
1172
|
+
return `41${bytesToHex(body)}`;
|
|
1173
|
+
}
|
|
1174
|
+
case "salt": {
|
|
1175
|
+
const bytes = hexLeaf(value, true);
|
|
1176
|
+
if (bytes === void 0 || bytes.length !== 32) return fail("domain.salt is not 32 bytes");
|
|
1177
|
+
return `0x${bytesToHex(bytes)}`;
|
|
1178
|
+
}
|
|
1179
|
+
default: return fail(`invalid typed-data domain key ${JSON.stringify(name)}`);
|
|
1180
|
+
}
|
|
1181
|
+
};
|
|
1182
|
+
/**
|
|
1183
|
+
* The `tron_signTypedData(domain, types, message)` argument form → the canonical JSON a
|
|
1184
|
+
* `tron.typed-data` request carries, mirroring `TypedDataEncoder.getPayload`: `EIP712Domain` is
|
|
1185
|
+
* derived from the domain's present keys (a supplied one must equal the derivation), `primaryType`
|
|
1186
|
+
* is the unique root of `types`, and message leaves normalize to `0x` hex, decimals, `41`-hex
|
|
1187
|
+
* addresses and booleans. The result is re-parsed before it is returned — canonical output is a
|
|
1188
|
+
* checked invariant, not an assumption.
|
|
1189
|
+
*/
|
|
1190
|
+
const tronTypedDataFromArgs = (domain, types, message) => {
|
|
1191
|
+
if (!isRecord(domain)) return fail("domain must be an object");
|
|
1192
|
+
const domainFields = [];
|
|
1193
|
+
const values = {};
|
|
1194
|
+
for (const f of DOMAIN_FIELD_TYPES) {
|
|
1195
|
+
const value = domain[f.name];
|
|
1196
|
+
if (value === void 0 || value === null) continue;
|
|
1197
|
+
domainFields.push(f);
|
|
1198
|
+
values[f.name] = domainArg(f.name, value);
|
|
1199
|
+
}
|
|
1200
|
+
for (const key of Object.keys(domain)) if (domain[key] !== void 0 && domain[key] !== null && !DOMAIN_NAMES.has(key)) fail(`invalid typed-data domain key ${JSON.stringify(key)}`);
|
|
1201
|
+
if (!isRecord(types)) return fail("types must be an object");
|
|
1202
|
+
const tmap = {};
|
|
1203
|
+
for (const [name, fields] of Object.entries(types)) {
|
|
1204
|
+
if (!Array.isArray(fields)) return fail(`types.${name} is not a list of {name, type} fields`);
|
|
1205
|
+
const list = [];
|
|
1206
|
+
for (const f of fields) {
|
|
1207
|
+
if (!isRecord(f) || typeof f["name"] !== "string" || typeof f["type"] !== "string") return fail(`types.${name} is not a list of {name, type} fields`);
|
|
1208
|
+
list.push({
|
|
1209
|
+
name: f["name"],
|
|
1210
|
+
type: f["type"]
|
|
1211
|
+
});
|
|
1212
|
+
}
|
|
1213
|
+
tmap[name] = list;
|
|
1214
|
+
}
|
|
1215
|
+
const declared = tmap["EIP712Domain"];
|
|
1216
|
+
if (declared !== void 0 && !sameFieldList(declared, domainFields)) fail("types.EIP712Domain does not match the domain fields");
|
|
1217
|
+
delete tmap["EIP712Domain"];
|
|
1218
|
+
if (!isRecord(message)) return fail("message must be an object");
|
|
1219
|
+
const encoder = makeEncoder(tmap, true);
|
|
1220
|
+
const canonical = encoder.visit(encoder.primary, message);
|
|
1221
|
+
const json = JSON.stringify({
|
|
1222
|
+
types: {
|
|
1223
|
+
...tmap,
|
|
1224
|
+
EIP712Domain: domainFields
|
|
1225
|
+
},
|
|
1226
|
+
primaryType: encoder.primary,
|
|
1227
|
+
domain: values,
|
|
1228
|
+
message: canonical
|
|
1229
|
+
});
|
|
1230
|
+
parseTronTypedData(json);
|
|
1231
|
+
return json;
|
|
1232
|
+
};
|
|
1233
|
+
/**
|
|
1234
|
+
* The document as an EVM-equivalent input for `recognizePermit`: every `address` leaf becomes
|
|
1235
|
+
* `0x`-form so the EVM recognizers' `0x`-only rules match. A document declaring `trcToken` anywhere
|
|
1236
|
+
* has no EVM equivalent and is not mapped.
|
|
1237
|
+
*/
|
|
1238
|
+
const tronTypedDataToEvm = (json) => {
|
|
1239
|
+
if (Object.values(json.types).some((fields) => fields.some((f) => baseName(f.type) === "trcToken"))) return;
|
|
1240
|
+
const map = (type, value) => {
|
|
1241
|
+
const tail = ARRAY_TAIL.exec(type);
|
|
1242
|
+
if (tail !== null) return Array.isArray(value) ? value.map((v) => map(tail[1] ?? "", v)) : value;
|
|
1243
|
+
const struct = json.types[type];
|
|
1244
|
+
if (struct !== void 0) return isRecord(value) ? Object.fromEntries(struct.map((f) => [f.name, map(f.type, value[f.name])])) : value;
|
|
1245
|
+
if (type === "address") {
|
|
1246
|
+
const body = addressBody(value);
|
|
1247
|
+
return body === void 0 ? value : `0x${bytesToHex(body)}`;
|
|
1248
|
+
}
|
|
1249
|
+
return value;
|
|
1250
|
+
};
|
|
1251
|
+
const domain = { ...json.domain };
|
|
1252
|
+
const verifying = addressBody(domain["verifyingContract"]);
|
|
1253
|
+
if (verifying !== void 0) domain["verifyingContract"] = `0x${bytesToHex(verifying)}`;
|
|
1254
|
+
return {
|
|
1255
|
+
types: json.types,
|
|
1256
|
+
primaryType: json.primaryType,
|
|
1257
|
+
domain,
|
|
1258
|
+
message: Object.fromEntries((json.types[json.primaryType] ?? []).map((f) => [f.name, map(f.type, json.message[f.name])]))
|
|
1259
|
+
};
|
|
1260
|
+
};
|
|
1261
|
+
/**
|
|
1262
|
+
* The leaf-value override for `typedDataFields` on a TRON document: `address` leaves render base58
|
|
1263
|
+
* and `trcToken` decimal; anything else defers to the default leaf rule.
|
|
1264
|
+
*/
|
|
1265
|
+
const tronTypedDataLeaf = (type, value) => {
|
|
1266
|
+
if (type === "address") return tronTypedDataBase58(value);
|
|
1267
|
+
if (type === "trcToken") {
|
|
1268
|
+
const v = strictInt(value, false);
|
|
1269
|
+
const [, max] = intBounds(false, 256);
|
|
1270
|
+
return v === void 0 || v > max ? void 0 : v.toString(10);
|
|
1271
|
+
}
|
|
1272
|
+
};
|
|
1273
|
+
// src/tron/plan.ts
|
|
1274
|
+
/**
|
|
1275
|
+
* /tron/plan — the serialisable signing plan of a normalized request: a transaction plans
|
|
1276
|
+
* sha256(raw_data), a message the TIP-191 digest, typed data the TIP-712 digest. No key material.
|
|
1277
|
+
*/
|
|
1278
|
+
const ecdsa = (digest, key) => ({
|
|
1279
|
+
scheme: "ecdsa-secp256k1",
|
|
1280
|
+
path: key.path,
|
|
1281
|
+
publicKey: key.publicKey,
|
|
1282
|
+
digest
|
|
1283
|
+
});
|
|
1284
|
+
const planTronTransaction = (rawData, key) => {
|
|
1285
|
+
if (rawData.length === 32) throw new ChainError("invalid-request", "a bare 32-byte digest is not a TRON transaction");
|
|
1286
|
+
decodeTronRawData(rawData);
|
|
1287
|
+
return {
|
|
1288
|
+
kind: "tron.transaction",
|
|
1289
|
+
tasks: [ecdsa(sha256(rawData), key)]
|
|
1290
|
+
};
|
|
1291
|
+
};
|
|
1292
|
+
const planTronMessage = (message, key) => {
|
|
1293
|
+
if (message.length === 0) throw new ChainError("invalid-request", "a TRON message is non-empty bytes");
|
|
1294
|
+
return {
|
|
1295
|
+
kind: "tron.message",
|
|
1296
|
+
tasks: [ecdsa(tronMessageDigest(message), key)]
|
|
1297
|
+
};
|
|
1298
|
+
};
|
|
1299
|
+
const planTronTypedData = (typedData, key) => ({
|
|
1300
|
+
kind: "tron.typed-data",
|
|
1301
|
+
tasks: [ecdsa(tronTypedDataDigest(parseTronTypedData(typedData).json), key)]
|
|
1302
|
+
});
|
|
1303
|
+
/** The plan of a normalized request; the task keeps the request kind so the kernel can wrap it. */
|
|
1304
|
+
const planTron = (request, key) => {
|
|
1305
|
+
if (request.kind === "tron.transaction") return planTronTransaction(request.rawData, key);
|
|
1306
|
+
if (request.kind === "tron.typed-data") return planTronTypedData(request.typedData, key);
|
|
1307
|
+
return planTronMessage(request.message, key);
|
|
1308
|
+
};
|
|
1309
|
+
export { tronContractType as A, stringField as B, mayBeTronTransaction as C, encodeTronTransaction as D, encodeTronRawData as E, equalBytes as F, assembleTron as H, malformed as I, readFields as L, bytesField as M, collectExtra as N, tronTransactionId as O, encodeMessage as P, requiredBytesField as R, TRON_MESSAGE_PREFIX as S, decodeTronRawData as T, varintField as V, tronAddressFromPublicKey as _, parseTronTypedData as a, tronAddressToHex as b, tronTypedDataFromArgs as c, tronTypedDataToEvm as d, TRON_ADDRESS_PREFIX as f, tronAddressFromHex as g, tronAddressFromEvm as h, planTronTypedData as i, tronTypeUrl as j, TRON_CONTRACT_TYPES as k, tronTypedDataHashes as l, tronAddressFromBytes as m, planTronMessage as n, tronTypedDataBase58 as o, isTronAddress as p, planTronTransaction as r, tronTypedDataDigest as s, planTron as t, tronTypedDataLeaf as u, tronAddressToBytes as v, tronMessageDigest as w, strictJson as x, tronAddressToEvm as y, requiredVarintField as z };
|
|
1310
|
+
|
|
1311
|
+
//# sourceMappingURL=plan-wCnxHqRu.mjs.map
|