@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.
Files changed (62) hide show
  1. package/README.md +13 -10
  2. package/dist/{account-ref-D2rW_qlI.mjs → account-ref-BFTeEyHt.mjs} +2 -2
  3. package/dist/{account-ref-D2rW_qlI.mjs.map → account-ref-BFTeEyHt.mjs.map} +1 -1
  4. package/dist/assemble-8GvNDony.mjs +405 -0
  5. package/dist/assemble-8GvNDony.mjs.map +1 -0
  6. package/dist/assemble-B3sO9Fvc.mjs +629 -0
  7. package/dist/assemble-B3sO9Fvc.mjs.map +1 -0
  8. package/dist/assemble-BdiPo0ZX.mjs +32 -0
  9. package/dist/assemble-BdiPo0ZX.mjs.map +1 -0
  10. package/dist/assets-sg2_Z3nZ.mjs +200 -0
  11. package/dist/assets-sg2_Z3nZ.mjs.map +1 -0
  12. package/dist/bitcoin-sign.d.mts +3 -0
  13. package/dist/bitcoin-sign.mjs +52 -18
  14. package/dist/bitcoin-sign.mjs.map +1 -1
  15. package/dist/bitcoin.d.mts +123 -7
  16. package/dist/bitcoin.mjs +162 -69
  17. package/dist/bitcoin.mjs.map +1 -1
  18. package/dist/evm-sign.d.mts +3 -1
  19. package/dist/evm-sign.mjs +25 -82
  20. package/dist/evm-sign.mjs.map +1 -1
  21. package/dist/evm.d.mts +252 -22
  22. package/dist/evm.mjs +2460 -448
  23. package/dist/evm.mjs.map +1 -1
  24. package/dist/families-BlgplKAJ.mjs +412 -0
  25. package/dist/families-BlgplKAJ.mjs.map +1 -0
  26. package/dist/index-CIRaHKpx.d.mts +941 -0
  27. package/dist/index.d.mts +2 -2
  28. package/dist/index.mjs +1 -1
  29. package/dist/networks.d.mts +29 -0
  30. package/dist/networks.mjs +245 -0
  31. package/dist/networks.mjs.map +1 -0
  32. package/dist/plan-wCnxHqRu.mjs +1311 -0
  33. package/dist/plan-wCnxHqRu.mjs.map +1 -0
  34. package/dist/solana-sign.d.mts +3 -0
  35. package/dist/solana-sign.mjs +23 -10
  36. package/dist/solana-sign.mjs.map +1 -1
  37. package/dist/solana.d.mts +136 -24
  38. package/dist/solana.mjs +1244 -63
  39. package/dist/solana.mjs.map +1 -1
  40. package/dist/src-CHB_z45M.mjs +387 -0
  41. package/dist/src-CHB_z45M.mjs.map +1 -0
  42. package/dist/tasks-7AFv3PQn.mjs +86 -0
  43. package/dist/tasks-7AFv3PQn.mjs.map +1 -0
  44. package/dist/token-call-DH22g8BL.mjs +914 -0
  45. package/dist/token-call-DH22g8BL.mjs.map +1 -0
  46. package/dist/tron-sign.d.mts +10 -0
  47. package/dist/tron-sign.mjs +36 -0
  48. package/dist/tron-sign.mjs.map +1 -0
  49. package/dist/tron.d.mts +328 -0
  50. package/dist/tron.mjs +1484 -0
  51. package/dist/tron.mjs.map +1 -0
  52. package/dist/typed-data-CE9h4U0F.d.mts +51 -0
  53. package/dist/typed-data-DRtKULsH.mjs +466 -0
  54. package/dist/typed-data-DRtKULsH.mjs.map +1 -0
  55. package/package.json +17 -10
  56. package/dist/index-DYwm4-Ec.d.mts +0 -256
  57. package/dist/message-ChhEZ0lx.mjs +0 -188
  58. package/dist/message-ChhEZ0lx.mjs.map +0 -1
  59. package/dist/src-8NZeEnrW.mjs +0 -67
  60. package/dist/src-8NZeEnrW.mjs.map +0 -1
  61. package/dist/typed-data-J5g2WemC.mjs +0 -227
  62. package/dist/typed-data-J5g2WemC.mjs.map +0 -1
package/dist/tron.mjs ADDED
@@ -0,0 +1,1484 @@
1
+ import { c as hasHiddenCharacters, i as messageContent, r as messageBlindReason, t as ChainError } from "./src-CHB_z45M.mjs";
2
+ import { n as requestBase, t as isRecord } from "./account-ref-BFTeEyHt.mjs";
3
+ import { n as recognizePermit, t as decodeTokenCall } from "./token-call-DH22g8BL.mjs";
4
+ import { d as typedDataFields, f as typedDataHasHiddenText, i as domainChainId, o as isTypedDataMessage } from "./typed-data-DRtKULsH.mjs";
5
+ import { BUILT_IN_NETWORKS, networkMeta } from "./networks.mjs";
6
+ import { t as RECOGNISED_FAMILIES } from "./families-BlgplKAJ.mjs";
7
+ import { A as tronContractType, B as stringField, C as mayBeTronTransaction, D as encodeTronTransaction, E as encodeTronRawData, F as equalBytes, H as assembleTron, I as malformed, L as readFields, M as bytesField, N as collectExtra, O as tronTransactionId, P as encodeMessage, R as requiredBytesField, S as TRON_MESSAGE_PREFIX, T as decodeTronRawData, V as varintField, _ as tronAddressFromPublicKey, a as parseTronTypedData, b as tronAddressToHex, c as tronTypedDataFromArgs, d as tronTypedDataToEvm, f as TRON_ADDRESS_PREFIX, g as tronAddressFromHex, h as tronAddressFromEvm, j as tronTypeUrl, k as TRON_CONTRACT_TYPES, l as tronTypedDataHashes, m as tronAddressFromBytes, o as tronTypedDataBase58, p as isTronAddress, s as tronTypedDataDigest, t as planTron, u as tronTypedDataLeaf, v as tronAddressToBytes, w as tronMessageDigest, x as strictJson, y as tronAddressToEvm, z as requiredVarintField } from "./plan-wCnxHqRu.mjs";
8
+ import { keccak_256 } from "@noble/hashes/sha3.js";
9
+ import { bytesToHex, hexToBytes, utf8ToBytes } from "@noble/hashes/utils.js";
10
+ import * as AbiFunction from "ox/AbiFunction";
11
+ import * as Hex from "ox/Hex";
12
+ import * as Secp256k1 from "ox/Secp256k1";
13
+ import * as Signature from "ox/Signature";
14
+ import { sha256 } from "@noble/hashes/sha2.js";
15
+ // src/tron/assets.ts
16
+ /** The native asset id in `AssetFlow` and simulated asset changes — TRX's smallest unit. */
17
+ const TRON_NATIVE_ASSET = "sun";
18
+ // src/tron/contracts.ts
19
+ /**
20
+ * The twelve contract value messages the wallet models, as both decode output and builder input — a
21
+ * `TronContract` produced by a builder encodes byte-for-byte to what `decodeTronContract` reads
22
+ * back. Schemas:
23
+ * https://github.com/tronprotocol/protocol/blob/8432beca98c52ba04c82aea0b48ae9f9f882c82a
24
+ * `core/contract/balance_contract.proto`, `asset_issue_contract.proto`, `smart_contract.proto`,
25
+ * `witness_contract.proto`, `account_contract.proto` and `core/Tron.proto` (Permission).
26
+ *
27
+ * Wire rules on top of the strict reader: an address is exactly 21 bytes starting 0x41; a signed
28
+ * int64 encoded ≥ 2^63 is a negative value and malformed, an int32 likewise past 2^31; a bool must
29
+ * be 1 when present; enum fields stay raw numbers — an out-of-range enum is a classification
30
+ * concern (`decodeTron`), not malformed bytes.
31
+ */
32
+ const EMPTY = /* @__PURE__ */ new Uint8Array(0);
33
+ const field = (fs, n) => fs.find((f) => f.field === n);
34
+ const all = (fs, n) => fs.filter((f) => f.field === n);
35
+ /** A field that must be present — a missing modeled scalar is absent only when defaulted. */
36
+ const required = (fs, n, what) => {
37
+ const f = field(fs, n);
38
+ if (f === void 0) malformed(`${what} is missing`);
39
+ return f;
40
+ };
41
+ const addressOf = (f, what) => {
42
+ const data = f !== void 0 && f.wire === 2 ? f.data : void 0;
43
+ if (data === void 0) malformed(`${what} is missing`);
44
+ if (data.length !== 21 || data[0] !== 65) malformed(`${what} is not a 21-byte TRON address`);
45
+ return tronAddressFromBytes(data);
46
+ };
47
+ const int64Of = (f, what) => {
48
+ if (f === void 0) return 0n;
49
+ if (f.wire !== 0 || f.varint === void 0) malformed(`${what} has the wrong wire type`);
50
+ if (f.varint >= 9223372036854775808n) malformed(`${what} is negative`);
51
+ return f.varint;
52
+ };
53
+ const int32Of = (f, what) => {
54
+ const v = int64Of(f, what);
55
+ if (v > 2147483647n) malformed(`${what} exceeds int32`);
56
+ return Number(v);
57
+ };
58
+ const boolOf = (f, what) => {
59
+ if (f === void 0) return false;
60
+ if (f.wire !== 0 || f.varint !== 1n) malformed(`${what} is not a proto3 bool`);
61
+ return true;
62
+ };
63
+ const bytesOf = (f) => {
64
+ if (f === void 0) return EMPTY;
65
+ if (f.wire !== 2 || f.data === void 0) malformed("bytes field has the wrong wire type");
66
+ return f.data;
67
+ };
68
+ const utf8$2 = new TextDecoder("utf-8", {
69
+ fatal: true,
70
+ ignoreBOM: true
71
+ });
72
+ const stringOf = (f, what) => {
73
+ if (f === void 0) return "";
74
+ const data = bytesOf(f);
75
+ try {
76
+ return utf8$2.decode(data);
77
+ } catch {
78
+ return malformed(`${what} is not UTF-8`);
79
+ }
80
+ };
81
+ const asciiOf = (f, what) => {
82
+ const text = stringOf(f, what);
83
+ for (const c of text) if ((c.codePointAt(0) ?? 0) > 127) malformed(`${what} is not ASCII`);
84
+ return text;
85
+ };
86
+ /**
87
+ * The field's canonical encoding is the value re-encoded (a proto3 default drops out). Anything
88
+ * else — an explicitly-encoded default, a non-minimal form the reader itself missed — is
89
+ * non-canonical.
90
+ */
91
+ const canonical = (f, encoded) => {
92
+ if (f !== void 0 && !equalBytes(f.bytes, encoded ?? EMPTY)) malformed("non-canonical encoding");
93
+ };
94
+ const encAddress = (n, address) => requiredBytesField(n, tronAddressToBytes(address));
95
+ const encBytes = (n, data) => bytesField(n, data);
96
+ const encInt = (n, value) => varintField(n, value);
97
+ const encBool = (n, value) => value ? requiredVarintField(n, 1) : void 0;
98
+ const slot = (field, bytes) => ({
99
+ field,
100
+ bytes
101
+ });
102
+ const decodeVote = (f) => {
103
+ const data = f.wire === 2 && f.data !== void 0 ? f.data : malformed("vote has the wrong wire type");
104
+ const fs = readFields(data);
105
+ const witness = addressOf(required(fs, 1, "vote_address"), "vote_address");
106
+ const count = int64Of(field(fs, 2), "vote_count");
107
+ canonical(required(fs, 1, "vote_address"), encAddress(1, witness));
108
+ canonical(field(fs, 2), encInt(2, count));
109
+ return {
110
+ vote: {
111
+ witness,
112
+ count
113
+ },
114
+ extra: collectExtra(fs, [1, 2])
115
+ };
116
+ };
117
+ const encodeVote = (vote) => encodeMessage([slot(1, encAddress(1, vote.witness)), slot(2, encInt(2, vote.count))]);
118
+ const decodeKey = (f) => {
119
+ const data = f.wire === 2 && f.data !== void 0 ? f.data : malformed("key has the wrong wire type");
120
+ const fs = readFields(data);
121
+ const address = addressOf(required(fs, 1, "key.address"), "key.address");
122
+ const weight = int64Of(field(fs, 2), "key.weight");
123
+ canonical(required(fs, 1, "key.address"), encAddress(1, address));
124
+ canonical(field(fs, 2), encInt(2, weight));
125
+ return {
126
+ key: {
127
+ address,
128
+ weight
129
+ },
130
+ extra: collectExtra(fs, [1, 2])
131
+ };
132
+ };
133
+ const encodeKey = (key) => encodeMessage([slot(1, encAddress(1, key.address)), slot(2, encInt(2, key.weight))]);
134
+ const decodePermission = (f) => {
135
+ const data = f.wire === 2 && f.data !== void 0 ? f.data : malformed("permission has the wrong wire type");
136
+ const fs = readFields(data, [7]);
137
+ const type = int32Of(field(fs, 1), "permission.type");
138
+ const id = int32Of(field(fs, 2), "permission.id");
139
+ const name = stringOf(field(fs, 3), "permission_name");
140
+ const threshold = int64Of(field(fs, 4), "permission.threshold");
141
+ const parentId = int32Of(field(fs, 5), "permission.parent_id");
142
+ const operations = bytesOf(field(fs, 6));
143
+ const keys = [];
144
+ const extras = [...collectExtra(fs, [
145
+ 1,
146
+ 2,
147
+ 3,
148
+ 4,
149
+ 5,
150
+ 6,
151
+ 7
152
+ ])];
153
+ for (const kf of all(fs, 7)) {
154
+ const { key, extra } = decodeKey(kf);
155
+ keys.push(key);
156
+ extras.push(...extra);
157
+ }
158
+ canonical(field(fs, 1), encInt(1, type));
159
+ canonical(field(fs, 2), encInt(2, id));
160
+ canonical(field(fs, 3), stringField(3, name));
161
+ canonical(field(fs, 4), encInt(4, threshold));
162
+ canonical(field(fs, 5), encInt(5, parentId));
163
+ canonical(field(fs, 6), encBytes(6, operations));
164
+ return {
165
+ permission: {
166
+ type,
167
+ id,
168
+ name,
169
+ threshold,
170
+ parentId,
171
+ operations,
172
+ keys
173
+ },
174
+ extra: extras
175
+ };
176
+ };
177
+ const encodePermission = (p) => encodeMessage([
178
+ slot(1, encInt(1, p.type)),
179
+ slot(2, encInt(2, p.id)),
180
+ slot(3, stringField(3, p.name)),
181
+ slot(4, encInt(4, p.threshold)),
182
+ slot(5, encInt(5, p.parentId)),
183
+ slot(6, encBytes(6, p.operations)),
184
+ ...p.keys.map((k) => slot(7, requiredBytesField(7, encodeKey(k))))
185
+ ]);
186
+ const decoders = {
187
+ 1(value) {
188
+ const fs = readFields(value);
189
+ const owner = addressOf(required(fs, 1, "owner_address"), "owner_address");
190
+ const to = addressOf(required(fs, 2, "to_address"), "to_address");
191
+ const amount = int64Of(field(fs, 3), "amount");
192
+ canonical(field(fs, 1), encAddress(1, owner));
193
+ canonical(field(fs, 2), encAddress(2, to));
194
+ canonical(field(fs, 3), encInt(3, amount));
195
+ return {
196
+ contract: {
197
+ type: "TransferContract",
198
+ owner,
199
+ to,
200
+ amount
201
+ },
202
+ extra: collectExtra(fs, [
203
+ 1,
204
+ 2,
205
+ 3
206
+ ])
207
+ };
208
+ },
209
+ 2(value) {
210
+ const fs = readFields(value);
211
+ const assetId = asciiOf(required(fs, 1, "asset_name"), "asset_name");
212
+ const owner = addressOf(required(fs, 2, "owner_address"), "owner_address");
213
+ const to = addressOf(required(fs, 3, "to_address"), "to_address");
214
+ const amount = int64Of(field(fs, 4), "amount");
215
+ canonical(field(fs, 1), stringField(1, assetId));
216
+ canonical(field(fs, 2), encAddress(2, owner));
217
+ canonical(field(fs, 3), encAddress(3, to));
218
+ canonical(field(fs, 4), encInt(4, amount));
219
+ return {
220
+ contract: {
221
+ type: "TransferAssetContract",
222
+ owner,
223
+ to,
224
+ assetId,
225
+ amount
226
+ },
227
+ extra: collectExtra(fs, [
228
+ 1,
229
+ 2,
230
+ 3,
231
+ 4
232
+ ])
233
+ };
234
+ },
235
+ 4(value) {
236
+ const fs = readFields(value, [2]);
237
+ const owner = addressOf(required(fs, 1, "owner_address"), "owner_address");
238
+ const votes = [];
239
+ const extras = [...collectExtra(fs, [
240
+ 1,
241
+ 2,
242
+ 3
243
+ ])];
244
+ for (const vf of all(fs, 2)) {
245
+ const { vote, extra } = decodeVote(vf);
246
+ votes.push(vote);
247
+ extras.push(...extra);
248
+ }
249
+ const support = boolOf(field(fs, 3), "support");
250
+ canonical(field(fs, 1), encAddress(1, owner));
251
+ canonical(field(fs, 3), encBool(3, support));
252
+ return {
253
+ contract: {
254
+ type: "VoteWitnessContract",
255
+ owner,
256
+ votes,
257
+ support
258
+ },
259
+ extra: extras
260
+ };
261
+ },
262
+ 13(value) {
263
+ const fs = readFields(value);
264
+ const owner = addressOf(required(fs, 1, "owner_address"), "owner_address");
265
+ canonical(field(fs, 1), encAddress(1, owner));
266
+ return {
267
+ contract: {
268
+ type: "WithdrawBalanceContract",
269
+ owner
270
+ },
271
+ extra: collectExtra(fs, [1])
272
+ };
273
+ },
274
+ 31(value) {
275
+ const fs = readFields(value);
276
+ const owner = addressOf(required(fs, 1, "owner_address"), "owner_address");
277
+ const contract = addressOf(required(fs, 2, "contract_address"), "contract_address");
278
+ const callValue = int64Of(field(fs, 3), "call_value");
279
+ const data = bytesOf(field(fs, 4));
280
+ const callTokenValue = int64Of(field(fs, 5), "call_token_value");
281
+ const tokenId = int64Of(field(fs, 6), "token_id");
282
+ canonical(field(fs, 1), encAddress(1, owner));
283
+ canonical(field(fs, 2), encAddress(2, contract));
284
+ canonical(field(fs, 3), encInt(3, callValue));
285
+ canonical(field(fs, 4), encBytes(4, data));
286
+ canonical(field(fs, 5), encInt(5, callTokenValue));
287
+ canonical(field(fs, 6), encInt(6, tokenId));
288
+ return {
289
+ contract: {
290
+ type: "TriggerSmartContract",
291
+ owner,
292
+ contract,
293
+ callValue,
294
+ data,
295
+ callTokenValue,
296
+ tokenId
297
+ },
298
+ extra: collectExtra(fs, [
299
+ 1,
300
+ 2,
301
+ 3,
302
+ 4,
303
+ 5,
304
+ 6
305
+ ])
306
+ };
307
+ },
308
+ 54(value) {
309
+ const fs = readFields(value);
310
+ const owner = addressOf(required(fs, 1, "owner_address"), "owner_address");
311
+ const amount = int64Of(field(fs, 2), "frozen_balance");
312
+ const resource = int32Of(field(fs, 3), "resource");
313
+ canonical(field(fs, 1), encAddress(1, owner));
314
+ canonical(field(fs, 2), encInt(2, amount));
315
+ canonical(field(fs, 3), encInt(3, resource));
316
+ return {
317
+ contract: {
318
+ type: "FreezeBalanceV2Contract",
319
+ owner,
320
+ amount,
321
+ resource
322
+ },
323
+ extra: collectExtra(fs, [
324
+ 1,
325
+ 2,
326
+ 3
327
+ ])
328
+ };
329
+ },
330
+ 55(value) {
331
+ const fs = readFields(value);
332
+ const owner = addressOf(required(fs, 1, "owner_address"), "owner_address");
333
+ const amount = int64Of(field(fs, 2), "unfreeze_balance");
334
+ const resource = int32Of(field(fs, 3), "resource");
335
+ canonical(field(fs, 1), encAddress(1, owner));
336
+ canonical(field(fs, 2), encInt(2, amount));
337
+ canonical(field(fs, 3), encInt(3, resource));
338
+ return {
339
+ contract: {
340
+ type: "UnfreezeBalanceV2Contract",
341
+ owner,
342
+ amount,
343
+ resource
344
+ },
345
+ extra: collectExtra(fs, [
346
+ 1,
347
+ 2,
348
+ 3
349
+ ])
350
+ };
351
+ },
352
+ 56(value) {
353
+ const fs = readFields(value);
354
+ const owner = addressOf(required(fs, 1, "owner_address"), "owner_address");
355
+ canonical(field(fs, 1), encAddress(1, owner));
356
+ return {
357
+ contract: {
358
+ type: "WithdrawExpireUnfreezeContract",
359
+ owner
360
+ },
361
+ extra: collectExtra(fs, [1])
362
+ };
363
+ },
364
+ 57(value) {
365
+ const fs = readFields(value);
366
+ const owner = addressOf(required(fs, 1, "owner_address"), "owner_address");
367
+ const resource = int32Of(field(fs, 2), "resource");
368
+ const balance = int64Of(field(fs, 3), "balance");
369
+ const receiver = addressOf(required(fs, 4, "receiver_address"), "receiver_address");
370
+ const lock = boolOf(field(fs, 5), "lock");
371
+ const lockPeriod = int64Of(field(fs, 6), "lock_period");
372
+ canonical(field(fs, 1), encAddress(1, owner));
373
+ canonical(field(fs, 2), encInt(2, resource));
374
+ canonical(field(fs, 3), encInt(3, balance));
375
+ canonical(field(fs, 4), encAddress(4, receiver));
376
+ canonical(field(fs, 5), encBool(5, lock));
377
+ canonical(field(fs, 6), encInt(6, lockPeriod));
378
+ return {
379
+ contract: {
380
+ type: "DelegateResourceContract",
381
+ owner,
382
+ resource,
383
+ balance,
384
+ receiver,
385
+ lock,
386
+ lockPeriod
387
+ },
388
+ extra: collectExtra(fs, [
389
+ 1,
390
+ 2,
391
+ 3,
392
+ 4,
393
+ 5,
394
+ 6
395
+ ])
396
+ };
397
+ },
398
+ 58(value) {
399
+ const fs = readFields(value);
400
+ const owner = addressOf(required(fs, 1, "owner_address"), "owner_address");
401
+ const resource = int32Of(field(fs, 2), "resource");
402
+ const balance = int64Of(field(fs, 3), "balance");
403
+ const receiver = addressOf(required(fs, 4, "receiver_address"), "receiver_address");
404
+ canonical(field(fs, 1), encAddress(1, owner));
405
+ canonical(field(fs, 2), encInt(2, resource));
406
+ canonical(field(fs, 3), encInt(3, balance));
407
+ canonical(field(fs, 4), encAddress(4, receiver));
408
+ return {
409
+ contract: {
410
+ type: "UnDelegateResourceContract",
411
+ owner,
412
+ resource,
413
+ balance,
414
+ receiver
415
+ },
416
+ extra: collectExtra(fs, [
417
+ 1,
418
+ 2,
419
+ 3,
420
+ 4
421
+ ])
422
+ };
423
+ },
424
+ 59(value) {
425
+ const fs = readFields(value);
426
+ const owner = addressOf(required(fs, 1, "owner_address"), "owner_address");
427
+ canonical(field(fs, 1), encAddress(1, owner));
428
+ return {
429
+ contract: {
430
+ type: "CancelAllUnfreezeV2Contract",
431
+ owner
432
+ },
433
+ extra: collectExtra(fs, [1])
434
+ };
435
+ },
436
+ 46(value) {
437
+ const fs = readFields(value, [4]);
438
+ const owner = addressOf(required(fs, 1, "owner_address"), "owner_address");
439
+ const extras = [...collectExtra(fs, [
440
+ 1,
441
+ 2,
442
+ 3,
443
+ 4
444
+ ])];
445
+ const ownerF = required(fs, 2, "owner permission");
446
+ const { permission: ownerPermission, extra: ownerExtra } = decodePermission(ownerF);
447
+ extras.push(...ownerExtra);
448
+ const witnessF = field(fs, 3);
449
+ let witnessPermission;
450
+ if (witnessF !== void 0) {
451
+ const { permission, extra } = decodePermission(witnessF);
452
+ witnessPermission = permission;
453
+ extras.push(...extra);
454
+ }
455
+ const actives = [];
456
+ for (const af of all(fs, 4)) {
457
+ const { permission, extra } = decodePermission(af);
458
+ actives.push(permission);
459
+ extras.push(...extra);
460
+ }
461
+ canonical(field(fs, 1), encAddress(1, owner));
462
+ return {
463
+ contract: {
464
+ type: "AccountPermissionUpdateContract",
465
+ owner,
466
+ ownerPermission,
467
+ ...witnessPermission === void 0 ? {} : { witnessPermission },
468
+ actives
469
+ },
470
+ extra: extras
471
+ };
472
+ }
473
+ };
474
+ /**
475
+ * The modeled decode of a contract `parameter.value`. Undefined for a contract type the wallet does
476
+ * not model — the caller blinds it as `tron-contract`. Unknown fields anywhere inside the value
477
+ * (this message or a nested Vote/Key/Permission) come back in `extra` for blind detection;
478
+ * canonicality of every scalar field was already enforced.
479
+ */
480
+ const decodeTronContract = (typeId, value) => decoders[typeId]?.(value);
481
+ /** Canonical encode of a modeled contract — the inverse of `decodeTronContract` on clean input. */
482
+ const encodeTronContract = (contract) => {
483
+ switch (contract.type) {
484
+ case "TransferContract": return encodeMessage([
485
+ slot(1, encAddress(1, contract.owner)),
486
+ slot(2, encAddress(2, contract.to)),
487
+ slot(3, encInt(3, contract.amount))
488
+ ]);
489
+ case "TransferAssetContract": return encodeMessage([
490
+ slot(1, stringField(1, contract.assetId)),
491
+ slot(2, encAddress(2, contract.owner)),
492
+ slot(3, encAddress(3, contract.to)),
493
+ slot(4, encInt(4, contract.amount))
494
+ ]);
495
+ case "VoteWitnessContract": return encodeMessage([
496
+ slot(1, encAddress(1, contract.owner)),
497
+ ...contract.votes.map((v) => slot(2, requiredBytesField(2, encodeVote(v)))),
498
+ slot(3, encBool(3, contract.support))
499
+ ]);
500
+ case "WithdrawBalanceContract": return encodeMessage([slot(1, encAddress(1, contract.owner))]);
501
+ case "TriggerSmartContract": return encodeMessage([
502
+ slot(1, encAddress(1, contract.owner)),
503
+ slot(2, encAddress(2, contract.contract)),
504
+ slot(3, encInt(3, contract.callValue)),
505
+ slot(4, encBytes(4, contract.data)),
506
+ slot(5, encInt(5, contract.callTokenValue)),
507
+ slot(6, encInt(6, contract.tokenId))
508
+ ]);
509
+ case "FreezeBalanceV2Contract":
510
+ case "UnfreezeBalanceV2Contract": return encodeMessage([
511
+ slot(1, encAddress(1, contract.owner)),
512
+ slot(2, encInt(2, contract.amount)),
513
+ slot(3, encInt(3, contract.resource))
514
+ ]);
515
+ case "WithdrawExpireUnfreezeContract":
516
+ case "CancelAllUnfreezeV2Contract": return encodeMessage([slot(1, encAddress(1, contract.owner))]);
517
+ case "DelegateResourceContract": return encodeMessage([
518
+ slot(1, encAddress(1, contract.owner)),
519
+ slot(2, encInt(2, contract.resource)),
520
+ slot(3, encInt(3, contract.balance)),
521
+ slot(4, encAddress(4, contract.receiver)),
522
+ slot(5, encBool(5, contract.lock)),
523
+ slot(6, encInt(6, contract.lockPeriod))
524
+ ]);
525
+ case "UnDelegateResourceContract": return encodeMessage([
526
+ slot(1, encAddress(1, contract.owner)),
527
+ slot(2, encInt(2, contract.resource)),
528
+ slot(3, encInt(3, contract.balance)),
529
+ slot(4, encAddress(4, contract.receiver))
530
+ ]);
531
+ case "AccountPermissionUpdateContract": return encodeMessage([
532
+ slot(1, encAddress(1, contract.owner)),
533
+ slot(2, requiredBytesField(2, encodePermission(contract.ownerPermission))),
534
+ slot(3, contract.witnessPermission === void 0 ? void 0 : requiredBytesField(3, encodePermission(contract.witnessPermission))),
535
+ ...contract.actives.map((p) => slot(4, requiredBytesField(4, encodePermission(p))))
536
+ ]);
537
+ }
538
+ };
539
+ // src/tron/builders.ts
540
+ /**
541
+ * Pure TRON transaction builders — no clock, no I/O; the caller supplies the block reference and
542
+ * times. `ref_block_bytes` is the block number's low two bytes big-endian and `ref_block_hash`
543
+ * bytes 8..16 of the block id (tronweb AbstractTrx.ts:1108-1121) — together they pin the
544
+ * transaction to a recent block on exactly one network.
545
+ */
546
+ /** A TRON memo (`raw_data.data`) is 1–256 UTF-8 bytes. */
547
+ const TRON_MEMO_MAX_BYTES = 256;
548
+ const utf8Encode = new TextEncoder();
549
+ /**
550
+ * A memo's wire bytes: non-empty, at most `TRON_MEMO_MAX_BYTES` UTF-8 bytes, no line breaks and no
551
+ * hidden characters — the prompt shows it verbatim, so anything that could hide a second line or an
552
+ * invisible payload is refused as `invalid-request`.
553
+ */
554
+ const tronMemoBytes = (memo) => {
555
+ const bytes = utf8Encode.encode(memo);
556
+ if (bytes.length === 0 || bytes.length > 256) throw new ChainError("invalid-request", `a memo is 1 to 256 UTF-8 bytes`);
557
+ if (memo.includes("\n") || memo.includes("\r") || hasHiddenCharacters(memo)) throw new ChainError("invalid-request", "a memo must not contain newlines or hidden characters");
558
+ return bytes;
559
+ };
560
+ const TRON_TYPE_BY_NAME = Object.fromEntries(TRON_CONTRACT_TYPES.map((t) => [t.name, t.id]));
561
+ const buildTronRawData = (header, contract) => {
562
+ if (!/^[0-9a-fA-F]{64}$/.test(header.refBlock.id)) throw new ChainError("invalid-request", "refBlock.id is not a 64-hex block id");
563
+ const id = hexToBytes(header.refBlock.id);
564
+ const typeId = TRON_TYPE_BY_NAME[contract.type];
565
+ if (typeId === void 0) throw new ChainError("invalid-request", `${contract.type} has no contract type id`);
566
+ return encodeTronRawData({
567
+ refBlockBytes: Uint8Array.of(Math.floor(header.refBlock.number / 256) % 256, header.refBlock.number % 256),
568
+ refBlockHash: id.subarray(8, 16),
569
+ expiration: BigInt(header.expiration),
570
+ timestamp: BigInt(header.timestamp),
571
+ ...header.feeLimit === void 0 ? {} : { feeLimit: header.feeLimit },
572
+ ...header.memo === void 0 ? {} : { memo: header.memo },
573
+ contract: {
574
+ typeId,
575
+ typeUrl: tronTypeUrl(contract.type),
576
+ value: encodeTronContract(contract),
577
+ permissionId: header.permissionId ?? 0,
578
+ extra: []
579
+ },
580
+ extra: []
581
+ });
582
+ };
583
+ const TRC20_TRANSFER = AbiFunction.from("function transfer(address to, uint256 amount)");
584
+ const TRC20_APPROVE = AbiFunction.from("function approve(address spender, uint256 amount)");
585
+ const triggerContract = (owner, token, data) => ({
586
+ type: "TriggerSmartContract",
587
+ owner,
588
+ contract: token,
589
+ callValue: 0n,
590
+ data,
591
+ callTokenValue: 0n,
592
+ tokenId: 0n
593
+ });
594
+ /**
595
+ * `transfer(address,uint256)` calldata on `token` — ABI addresses are the EVM form of the
596
+ * T-address.
597
+ */
598
+ const trc20TransferContract = (owner, token, to, amount) => triggerContract(owner, token, hexToBytes(AbiFunction.encodeData(TRC20_TRANSFER, [tronAddressToEvm(to), amount]).slice(2)));
599
+ const trc20ApproveContract = (owner, token, spender, amount) => triggerContract(owner, token, hexToBytes(AbiFunction.encodeData(TRC20_APPROVE, [tronAddressToEvm(spender), amount]).slice(2)));
600
+ // src/tron/tokens.ts
601
+ const USDT = Object.freeze({
602
+ symbol: "USDT",
603
+ decimals: 6,
604
+ name: "Tether USD"
605
+ });
606
+ const USDD = Object.freeze({
607
+ symbol: "USDD",
608
+ decimals: 18,
609
+ name: "Decentralized USD"
610
+ });
611
+ const TUSD = Object.freeze({
612
+ symbol: "TUSD",
613
+ decimals: 18,
614
+ name: "TrueUSD"
615
+ });
616
+ const WTRX = Object.freeze({
617
+ symbol: "WTRX",
618
+ decimals: 6,
619
+ name: "Wrapped TRX"
620
+ });
621
+ const JST = Object.freeze({
622
+ symbol: "JST",
623
+ decimals: 18,
624
+ name: "JUST"
625
+ });
626
+ const SUN = Object.freeze({
627
+ symbol: "SUN",
628
+ decimals: 18,
629
+ name: "SUN"
630
+ });
631
+ const BTT = Object.freeze({
632
+ symbol: "BTT",
633
+ decimals: 18,
634
+ name: "BitTorrent"
635
+ });
636
+ const WIN = Object.freeze({
637
+ symbol: "WIN",
638
+ decimals: 6,
639
+ name: "WINkLink"
640
+ });
641
+ const NFT = Object.freeze({
642
+ symbol: "NFT",
643
+ decimals: 6,
644
+ name: "AINFT"
645
+ });
646
+ const NILE_USDT = Object.freeze({
647
+ symbol: "USDT",
648
+ decimals: 6,
649
+ name: "Tether USD"
650
+ });
651
+ /** The built-in table. */
652
+ const tronTokenTable = Object.freeze({
653
+ "tron:728126428": Object.freeze({
654
+ TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t: USDT,
655
+ TXDk8mbtRbXeYuMNS83CfKPaYYT8XWv9Hz: USDD,
656
+ TUpMhErZL2fhh4sVNULAbNKLokS4GjC1F4: TUSD,
657
+ TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR: WTRX,
658
+ TCFLL5dx5ZJdKnWuesXxi1VPwjLVmWZZy9: JST,
659
+ TSSMHYeV2uE9qYH95DqyoCuNCzEL1NvU3S: SUN,
660
+ TAFjULxiVgT4qWk6UZwjqwZXTSaGaqnVp4: BTT,
661
+ TLa2f6VPqDgRE67v1736s7bJ8Ray5wYjU7: WIN,
662
+ TFczxzPhnThNSqr5by8tvxsdCFRRz6cPNq: NFT
663
+ }),
664
+ "tron:3448148188": Object.freeze({ TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf: NILE_USDT })
665
+ });
666
+ const lookupTronToken = (table, network, address) => table[network]?.[address];
667
+ // src/tron/permit2.ts
668
+ /**
669
+ * The verified Permit2 deployments on TRON networks, keyed by CAIP-2 network id. SUN.io's Permit2
670
+ * on mainnet — https://sunio.zendesk.com/hc/en-us/articles/54899665032601 — was confirmed on-chain:
671
+ * its DOMAIN_SEPARATOR() equals the TIP-712 hash of `{name: "Permit2", chainId: 728126428,
672
+ * verifyingContract}` under TronWeb 6.5.2. The Nile deployment is unverified, so the map has no
673
+ * Nile entry and Nile documents stay unclaimed.
674
+ */
675
+ const TRON_PERMIT2 = { "tron:728126428": "TTJxU3P8rHycAyFY4kVtGNfmnMH4ezcuM9" };
676
+ // src/tron/json.ts
677
+ /**
678
+ * `tronRawDataFromJson(rawData, visible)` — a dApp's `raw_data` object → canonical raw_data bytes
679
+ * under TronWeb `txJsonToPb`/`txCheck` semantics: each known contract's value keys are mapped
680
+ * through our strict `TronContract` model and re-encoded by `encodeTronContract`, so the output is
681
+ * exactly the protobuf the node JSON describes — `sha256(bytes) == txID` holds for any well-formed
682
+ * node payload.
683
+ *
684
+ * Where the JSON grammar is stricter than TronWeb's loose parsing, the differences are listed for
685
+ * the differential test:
686
+ *
687
+ * - Unknown keys anywhere (`raw_data`, `contract`, `parameter`, `value`, `votes[]`) refuse — txCheck
688
+ * ignores them.
689
+ * - `value.support`, and `TriggerSmartContract.parameter` without `function_selector`, refuse —
690
+ * txCheck silently drops them, which would display an intent the bytes do not carry.
691
+ * - `AccountPermissionUpdateContract` refuses — permission changes are never a dApp payload.
692
+ * - Addresses are base58check when `visible`, `41`-hex otherwise; TronWeb's `toHex` accepts either
693
+ * form in either mode (and bare hex as garbage bytes) — we require the mode's form.
694
+ * - Integers are decimal strings or safe integers in int64 range; TronWeb's jspb setters and
695
+ * `parseInt` accept trailing garbage and negative values (which encode non-canonically).
696
+ * - `resource` accepts the `BANDWIDTH`/`ENERGY`/`TRON_POWER` names only, never a numeric enum.
697
+ * - `asset_name` must decode to ASCII (as `decodeTronContract` requires); `ref_block_bytes`/`hash`
698
+ * must be exactly 2/8 bytes; `expiration` must be present and non-zero.
699
+ */
700
+ const refuse$1 = (what) => {
701
+ throw new ChainError("invalid-request", what);
702
+ };
703
+ const utf8$1 = new TextDecoder("utf-8", { fatal: true });
704
+ const HEADER_KEYS = /* @__PURE__ */ new Set([
705
+ "ref_block_bytes",
706
+ "ref_block_hash",
707
+ "expiration",
708
+ "timestamp",
709
+ "fee_limit",
710
+ "data",
711
+ "contract"
712
+ ]);
713
+ const INT64_MAX = 2n ** 63n - 1n;
714
+ /** A non-negative int64 as a safe integer or decimal string — no floats, signs, or junk. */
715
+ const int64 = (value, what) => {
716
+ const parsed = typeof value === "number" && Number.isSafeInteger(value) ? BigInt(value) : typeof value === "string" && /^[0-9]+$/.test(value) ? BigInt(value) : void 0;
717
+ if (parsed === void 0 || parsed < 0n || parsed > INT64_MAX) return refuse$1(`${what} is not a non-negative int64`);
718
+ return parsed;
719
+ };
720
+ /**
721
+ * Mirrors txJsonToPb's `stringToUint8Array`: an all-hex string (optional `0x`) is decoded as hex —
722
+ * an odd tail nibble pairing like TronWeb's `.{1,2}` match — and anything else is UTF-8.
723
+ */
724
+ const stringBytes = (value, what) => {
725
+ if (typeof value !== "string") return refuse$1(`${what} is not a string`);
726
+ const hex = /^(?:0x)?[0-9a-fA-F]+$/.test(value) ? value.replace(/^0x/, "") : bytesToHex(utf8ToBytes(value));
727
+ return Uint8Array.from((hex.match(/.{1,2}/g) ?? []).map((p) => Number.parseInt(p, 16)));
728
+ };
729
+ /** An address in the mode `visible` dictates, returned as base58 for the contract model. */
730
+ const ownerAddress = (value, what, visible) => {
731
+ if (typeof value !== "string") return refuse$1(`${what} is not a string`);
732
+ if (visible) {
733
+ if (!isTronAddress(value)) return refuse$1(`${what} is not a base58 TRON address`);
734
+ return tronAddressFromHex(tronAddressToHex(value));
735
+ }
736
+ if (!/^41[0-9a-fA-F]{40}$/.test(value)) return refuse$1(`${what} is not a 41-hex TRON address`);
737
+ return tronAddressFromHex(`41${value.slice(2).toLowerCase()}`);
738
+ };
739
+ /**
740
+ * `asset_name` via `flexToUint8Array`: visible → the UTF-8 bytes; hidden → the string's hex, or its
741
+ * UTF-8 when it is not all-hex. The bytes must decode to the ASCII token id our model carries —
742
+ * non-ASCII bytes cannot round-trip through `decodeTronContract`.
743
+ */
744
+ const assetId = (value, visible) => {
745
+ if (typeof value !== "string") return refuse$1("asset_name is not a string");
746
+ const bytes = visible ? utf8ToBytes(value) : stringBytes(value.replace(/^0x/, ""), "asset_name");
747
+ let text;
748
+ try {
749
+ text = utf8$1.decode(bytes);
750
+ } catch {
751
+ return refuse$1("asset_name does not decode as UTF-8");
752
+ }
753
+ for (const c of text) if ((c.codePointAt(0) ?? 0) > 127) return refuse$1("asset_name is not ASCII");
754
+ return text;
755
+ };
756
+ const RESOURCE_CODES = {
757
+ BANDWIDTH: 0,
758
+ ENERGY: 1,
759
+ TRON_POWER: 2
760
+ };
761
+ const resourceCode = (value) => {
762
+ const code = typeof value === "string" ? RESOURCE_CODES[value] : void 0;
763
+ if (code === void 0) return refuse$1("resource is not BANDWIDTH, ENERGY or TRON_POWER");
764
+ return code;
765
+ };
766
+ const boolField = (value, what) => {
767
+ if (value === void 0) return false;
768
+ if (typeof value !== "boolean") return refuse$1(`${what} is not a boolean`);
769
+ return value;
770
+ };
771
+ /** The value object's keys are exactly `required` ∪ `optional` — nothing else, nothing missing. */
772
+ const fields = (type, value, required, optional = []) => {
773
+ const allowed = /* @__PURE__ */ new Set([...required, ...optional]);
774
+ for (const key of Object.keys(value)) if (!allowed.has(key)) refuse$1(`${type}.${key} is not a known field`);
775
+ for (const key of required) if (value[key] === void 0) refuse$1(`${type}.${key} is missing`);
776
+ };
777
+ const triggerData = (value) => {
778
+ const { data } = value;
779
+ const selector = value["function_selector"];
780
+ const { parameter } = value;
781
+ if (data !== void 0 && (selector !== void 0 || parameter !== void 0 && parameter !== "")) refuse$1("TriggerSmartContract.data cannot combine with function_selector or parameter");
782
+ if (parameter !== void 0 && selector === void 0) refuse$1("TriggerSmartContract.parameter requires function_selector");
783
+ if (data !== void 0) return stringBytes(data, "data");
784
+ if (selector === void 0) return /* @__PURE__ */ new Uint8Array(0);
785
+ if (typeof selector !== "string") return refuse$1("function_selector is not a string");
786
+ if (parameter !== void 0 && typeof parameter !== "string") return refuse$1("parameter is not a string");
787
+ const hash = bytesToHex(keccak_256(utf8ToBytes(selector))).slice(0, 8);
788
+ return stringBytes(hash + (parameter ?? ""), "parameter");
789
+ };
790
+ const contractValue = (type, value, visible) => {
791
+ if (!isRecord(value)) return refuse$1(`${type}.parameter.value is not an object`);
792
+ const json = value;
793
+ const owner = () => ownerAddress(json["owner_address"], "owner_address", visible);
794
+ switch (type) {
795
+ case "TransferContract":
796
+ fields(type, json, ["owner_address", "to_address"], ["amount"]);
797
+ return {
798
+ type,
799
+ owner: owner(),
800
+ to: ownerAddress(json["to_address"], "to_address", visible),
801
+ amount: json["amount"] === void 0 ? 0n : int64(json["amount"], "amount")
802
+ };
803
+ case "TransferAssetContract":
804
+ fields(type, json, [
805
+ "owner_address",
806
+ "to_address",
807
+ "asset_name"
808
+ ], ["amount"]);
809
+ return {
810
+ type,
811
+ owner: owner(),
812
+ to: ownerAddress(json["to_address"], "to_address", visible),
813
+ assetId: assetId(json["asset_name"], visible),
814
+ amount: json["amount"] === void 0 ? 0n : int64(json["amount"], "amount")
815
+ };
816
+ case "VoteWitnessContract": {
817
+ fields(type, json, ["owner_address", "votes"]);
818
+ const list = json["votes"];
819
+ if (!Array.isArray(list)) return refuse$1("votes is not an array");
820
+ const votes = list.map((v, i) => {
821
+ if (!isRecord(v)) return refuse$1(`votes[${i}] is not an object`);
822
+ fields("votes[]", v, ["vote_address"], ["vote_count"]);
823
+ return {
824
+ witness: ownerAddress(v["vote_address"], `votes[${i}].vote_address`, visible),
825
+ count: v["vote_count"] === void 0 ? 0n : int64(v["vote_count"], `votes[${i}].vote_count`)
826
+ };
827
+ });
828
+ return {
829
+ type,
830
+ owner: owner(),
831
+ votes,
832
+ support: false
833
+ };
834
+ }
835
+ case "WithdrawBalanceContract":
836
+ case "WithdrawExpireUnfreezeContract":
837
+ case "CancelAllUnfreezeV2Contract":
838
+ fields(type, json, ["owner_address"]);
839
+ return {
840
+ type,
841
+ owner: owner()
842
+ };
843
+ case "TriggerSmartContract":
844
+ fields(type, json, ["owner_address", "contract_address"], [
845
+ "call_value",
846
+ "call_token_value",
847
+ "token_id",
848
+ "data",
849
+ "function_selector",
850
+ "parameter"
851
+ ]);
852
+ return {
853
+ type,
854
+ owner: owner(),
855
+ contract: ownerAddress(json["contract_address"], "contract_address", visible),
856
+ callValue: json["call_value"] === void 0 ? 0n : int64(json["call_value"], "call_value"),
857
+ data: triggerData(json),
858
+ callTokenValue: json["call_token_value"] === void 0 ? 0n : int64(json["call_token_value"], "call_token_value"),
859
+ tokenId: json["token_id"] === void 0 ? 0n : int64(json["token_id"], "token_id")
860
+ };
861
+ case "FreezeBalanceV2Contract":
862
+ case "UnfreezeBalanceV2Contract": {
863
+ const amountKey = type === "FreezeBalanceV2Contract" ? "frozen_balance" : "unfreeze_balance";
864
+ fields(type, json, ["owner_address"], [amountKey, "resource"]);
865
+ return {
866
+ type,
867
+ owner: owner(),
868
+ amount: json[amountKey] === void 0 ? 0n : int64(json[amountKey], amountKey),
869
+ resource: json["resource"] === void 0 ? 0 : resourceCode(json["resource"])
870
+ };
871
+ }
872
+ case "DelegateResourceContract":
873
+ fields(type, json, ["owner_address", "receiver_address"], [
874
+ "balance",
875
+ "resource",
876
+ "lock",
877
+ "lock_period"
878
+ ]);
879
+ return {
880
+ type,
881
+ owner: owner(),
882
+ receiver: ownerAddress(json["receiver_address"], "receiver_address", visible),
883
+ balance: json["balance"] === void 0 ? 0n : int64(json["balance"], "balance"),
884
+ resource: json["resource"] === void 0 ? 0 : resourceCode(json["resource"]),
885
+ lock: boolField(json["lock"], "lock"),
886
+ lockPeriod: json["lock_period"] === void 0 ? 0n : int64(json["lock_period"], "lock_period")
887
+ };
888
+ case "UnDelegateResourceContract":
889
+ fields(type, json, ["owner_address", "receiver_address"], ["balance", "resource"]);
890
+ return {
891
+ type,
892
+ owner: owner(),
893
+ resource: json["resource"] === void 0 ? 0 : resourceCode(json["resource"]),
894
+ balance: json["balance"] === void 0 ? 0n : int64(json["balance"], "balance"),
895
+ receiver: ownerAddress(json["receiver_address"], "receiver_address", visible)
896
+ };
897
+ default: return refuse$1(`contract type ${JSON.stringify(type)} is not supported`);
898
+ }
899
+ };
900
+ const CONTRACT_KEYS = /* @__PURE__ */ new Set([
901
+ "parameter",
902
+ "type",
903
+ "Permission_id"
904
+ ]);
905
+ const PARAMETER_KEYS = /* @__PURE__ */ new Set(["value", "type_url"]);
906
+ const contractSlot = (value, visible) => {
907
+ if (!isRecord(value)) return refuse$1("contract must be an object");
908
+ const json = value;
909
+ for (const key of Object.keys(json)) if (!CONTRACT_KEYS.has(key)) refuse$1(`contract.${key} is not a contract field`);
910
+ const { type } = json;
911
+ if (typeof type !== "string") return refuse$1("contract.type is not a string");
912
+ const name = type;
913
+ const meta = TRON_CONTRACT_TYPES.find((t) => t.name === name);
914
+ if (meta === void 0 || meta.treatment !== "described") return refuse$1(`contract type ${JSON.stringify(name)} is not supported`);
915
+ const typeMeta = meta;
916
+ const { parameter } = json;
917
+ if (!isRecord(parameter)) return refuse$1("contract.parameter is not an object");
918
+ for (const key of Object.keys(parameter)) if (!PARAMETER_KEYS.has(key)) refuse$1(`contract.parameter.${key} is not a parameter field`);
919
+ if (parameter["type_url"] !== tronTypeUrl(name)) refuse$1(`contract.parameter.type_url does not name ${name}`);
920
+ const permissionId = json["Permission_id"];
921
+ let permission = 0;
922
+ if (permissionId !== void 0) {
923
+ const parsed = int64(permissionId, "Permission_id");
924
+ if (parsed > BigInt(2147483647)) refuse$1("Permission_id is out of range");
925
+ permission = Number(parsed);
926
+ }
927
+ return {
928
+ typeId: typeMeta.id,
929
+ typeUrl: tronTypeUrl(name),
930
+ value: encodeTronContract(contractValue(name, parameter["value"], visible)),
931
+ permissionId: permission,
932
+ extra: []
933
+ };
934
+ };
935
+ /**
936
+ * `raw_data` (object or its JSON text) → the canonical raw_data bytes. A JSON string is parsed
937
+ * strictly — duplicate keys and trailing text are refused.
938
+ */
939
+ const tronRawDataFromJson = (rawData, visible) => {
940
+ const parsed = typeof rawData === "string" ? strictJson(rawData, (reason) => refuse$1(`raw_data ${reason}`)) : rawData;
941
+ if (!isRecord(parsed)) return refuse$1("raw_data must be an object");
942
+ const rd = parsed;
943
+ for (const key of Object.keys(rd)) if (!HEADER_KEYS.has(key)) refuse$1(`raw_data.${key} is not a raw_data field`);
944
+ const refBlockBytes = stringBytes(rd["ref_block_bytes"], "ref_block_bytes");
945
+ if (refBlockBytes.length !== 2) refuse$1("ref_block_bytes must be exactly 2 bytes");
946
+ const refBlockHash = stringBytes(rd["ref_block_hash"], "ref_block_hash");
947
+ if (refBlockHash.length !== 8) refuse$1("ref_block_hash must be exactly 8 bytes");
948
+ const expiration = int64(rd["expiration"], "expiration");
949
+ if (expiration === 0n) refuse$1("expiration is missing");
950
+ const timestamp = rd["timestamp"] === void 0 ? void 0 : int64(rd["timestamp"], "timestamp");
951
+ const feeLimit = rd["fee_limit"] === void 0 ? void 0 : int64(rd["fee_limit"], "fee_limit");
952
+ const memo = rd["data"] === void 0 ? void 0 : stringBytes(rd["data"], "data");
953
+ const { contract } = rd;
954
+ if (!Array.isArray(contract) || contract.length !== 1) return refuse$1("contract must be an array of exactly one contract");
955
+ const raw = {
956
+ refBlockBytes,
957
+ refBlockHash,
958
+ expiration,
959
+ ...timestamp === void 0 ? {} : { timestamp },
960
+ ...feeLimit === void 0 ? {} : { feeLimit },
961
+ ...memo === void 0 ? {} : { memo },
962
+ contract: contractSlot(contract[0], visible),
963
+ extra: []
964
+ };
965
+ return encodeTronRawData(raw);
966
+ };
967
+ // src/tron/families.ts
968
+ /**
969
+ * The claim an undecoded `TriggerSmartContract` into `callee` makes: a listed token's selector
970
+ * table did not decode it, so it is an unrecognised function of a token the owner holds.
971
+ */
972
+ const tronCallNearMiss = (callee, network, table) => RECOGNISED_FAMILIES.find((row) => row.claim.surface === "tron.call" && row.claim.callee === "token-table" && lookupTronToken(table, network, callee) !== void 0)?.nearMiss;
973
+ /**
974
+ * The claim an unrecognised `tron.typed-data` document makes: a `Permit*` primary type, a Permit2
975
+ * verifying contract, or a built-in TRC-20 verifying contract names a family the decoder should
976
+ * have recognised — when it did not, the document blinds with the row's reason.
977
+ */
978
+ const tronTypedDataNearMiss = (json, network, table) => {
979
+ const verifying = tronTypedDataBase58(json.domain["verifyingContract"]);
980
+ return RECOGNISED_FAMILIES.find((row) => {
981
+ const { claim } = row;
982
+ if (claim.surface !== "tron.typed-data") return false;
983
+ if ("primaryType" in claim) return claim.primaryType.test(json.primaryType);
984
+ if (verifying === void 0) return false;
985
+ return claim.verifyingContract === "permit2" && verifying === TRON_PERMIT2[network] || claim.verifyingContract === "token-table" && lookupTronToken(table, network, verifying) !== void 0;
986
+ })?.nearMiss;
987
+ };
988
+ // src/tron/decode.ts
989
+ /**
990
+ * `decodeTron(request, signer)` — the TRON display decoder of design.md "解码结果". A modeled
991
+ * contract's `owner_address` must be the signing account; a semantic bound the chain would reject
992
+ * (zero amount, 31 votes, 9 actives, …) is refused outright as `invalid-request`; and anything the
993
+ * decoder cannot bound — unsupported or unknown contract types, TaPoS/provider fields, unknown
994
+ * value fields, out-of-range enums — is blind, never silently ignored. Blind precedence:
995
+ * `tron-permission-update` > `tron-contract` > `tron-field` > `token-function`.
996
+ */
997
+ const refuse = (what) => {
998
+ throw new ChainError("invalid-request", what);
999
+ };
1000
+ const utf8 = new TextDecoder("utf-8", {
1001
+ fatal: true,
1002
+ ignoreBOM: true
1003
+ });
1004
+ /** All TRX amounts carry the native asset id, 6 decimals and the network's symbol. */
1005
+ const sun = (amount, symbol) => ({
1006
+ asset: "sun",
1007
+ amount: amount.toString(10),
1008
+ decimals: 6,
1009
+ symbol
1010
+ });
1011
+ const trc10 = (assetId, amount) => ({
1012
+ asset: `trc10:${assetId}`,
1013
+ amount: amount.toString(10)
1014
+ });
1015
+ const RESOURCES = [
1016
+ "bandwidth",
1017
+ "energy",
1018
+ "tron-power"
1019
+ ];
1020
+ const selectorOf = (data) => data.length === 0 ? "0x" : `0x${bytesToHex(data.subarray(0, Math.min(4, data.length)))}`;
1021
+ /** The tokenCall's EVM-form addresses mapped back to base58 for display. */
1022
+ const mapTokenCall = (call) => ({
1023
+ ...call,
1024
+ outflows: call.outflows.map((flow) => ({
1025
+ ...flow,
1026
+ to: tronAddressFromEvm(flow.to),
1027
+ amount: {
1028
+ ...flow.amount,
1029
+ asset: tronAddressFromEvm(flow.amount.asset)
1030
+ }
1031
+ })),
1032
+ approvals: call.approvals.map((a) => a.kind === "allowance" ? {
1033
+ ...a,
1034
+ spender: tronAddressFromEvm(a.spender),
1035
+ amount: {
1036
+ ...a.amount,
1037
+ asset: tronAddressFromEvm(a.amount.asset)
1038
+ }
1039
+ } : a.kind === "approval-cleared" ? {
1040
+ ...a,
1041
+ asset: tronAddressFromEvm(a.asset)
1042
+ } : {
1043
+ ...a,
1044
+ asset: tronAddressFromEvm(a.asset),
1045
+ spender: tronAddressFromEvm(a.spender)
1046
+ })
1047
+ });
1048
+ /** An EVM-shaped view of the TRON table for decodeTokenCall: chainId → checksummed 0x → token. */
1049
+ const evmTableFor = (network, chainId, table) => ({ [String(chainId)]: Object.fromEntries(Object.entries(table[network] ?? {}).map(([address, token]) => [tronAddressToEvm(address), token])) });
1050
+ const permissionDisplay = (type, p) => ({
1051
+ type,
1052
+ id: p.id,
1053
+ name: p.name,
1054
+ threshold: p.threshold.toString(10),
1055
+ parentId: p.parentId,
1056
+ ...type === "active" ? { operations: `0x${bytesToHex(p.operations)}` } : {},
1057
+ keys: p.keys.map((k) => ({
1058
+ address: k.address,
1059
+ weight: k.weight.toString(10)
1060
+ }))
1061
+ });
1062
+ const memoDisplay = (memo) => {
1063
+ try {
1064
+ const text = utf8.decode(memo);
1065
+ if (!hasHiddenCharacters(text)) return {
1066
+ kind: "text",
1067
+ text
1068
+ };
1069
+ } catch {}
1070
+ return {
1071
+ kind: "bytes",
1072
+ hex: `0x${bytesToHex(memo)}`
1073
+ };
1074
+ };
1075
+ const stakeEffects = (staking) => ({
1076
+ summary: "stake",
1077
+ outflows: [],
1078
+ approvals: [],
1079
+ staking: [staking],
1080
+ verifiability: "full"
1081
+ });
1082
+ const resourceName = (resource) => RESOURCES[resource] ?? refuse("resource is out of range");
1083
+ /** A modeled value the display cannot bound blinds the request as tron-field. */
1084
+ const fieldBlind = (contract) => contract.type === "VoteWitnessContract" && contract.support;
1085
+ /** The semantic bounds a node enforces — a request past them is refused, not described. */
1086
+ const semanticCheck = (contract, raw) => {
1087
+ switch (contract.type) {
1088
+ case "TransferContract":
1089
+ case "TransferAssetContract":
1090
+ if (contract.amount === 0n) refuse("transfer amount is zero");
1091
+ if (contract.type === "TransferAssetContract" && !/^[1-9][0-9]{0,18}$/.test(contract.assetId)) refuse("asset_name is not a TRC-10 asset id");
1092
+ break;
1093
+ case "FreezeBalanceV2Contract":
1094
+ case "UnfreezeBalanceV2Contract":
1095
+ if (contract.amount === 0n) refuse("stake amount is zero");
1096
+ if (contract.resource > 2) refuse("resource is not BANDWIDTH, ENERGY or TRON_POWER");
1097
+ break;
1098
+ case "DelegateResourceContract":
1099
+ case "UnDelegateResourceContract":
1100
+ if (contract.balance === 0n) refuse("delegated balance is zero");
1101
+ if (contract.resource > 1) refuse("delegated resource is not BANDWIDTH or ENERGY");
1102
+ break;
1103
+ case "TriggerSmartContract":
1104
+ if (contract.callTokenValue > 0n && contract.tokenId === 0n) refuse("call_token_value without token_id");
1105
+ if (raw.feeLimit === void 0 || raw.feeLimit <= 0n) refuse("TriggerSmartContract requires a positive fee_limit");
1106
+ break;
1107
+ case "VoteWitnessContract":
1108
+ if (contract.votes.length === 0 || contract.votes.length > 30) refuse("a vote transaction casts 1 to 30 votes");
1109
+ if (contract.votes.some((v) => v.count === 0n)) refuse("vote_count is zero");
1110
+ break;
1111
+ case "AccountPermissionUpdateContract":
1112
+ if (contract.actives.length === 0 || contract.actives.length > 8) refuse("a permission update sets 1 to 8 actives");
1113
+ if (contract.ownerPermission.type !== 0) refuse("the owner permission is not type 0");
1114
+ if (contract.witnessPermission !== void 0 && contract.witnessPermission.type !== 1) refuse("the witness permission is not type 1");
1115
+ if (contract.actives.some((p) => p.type !== 2)) refuse("an active permission is not type 2");
1116
+ if (contract.ownerPermission.operations.length > 0 || contract.witnessPermission !== void 0 && contract.witnessPermission.operations.length > 0) refuse("an owner/witness permission carries operations");
1117
+ if (contract.actives.some((p) => p.operations.length !== 32)) refuse("an active permission's operations is not 32 bytes");
1118
+ for (const p of [
1119
+ contract.ownerPermission,
1120
+ contract.witnessPermission,
1121
+ ...contract.actives
1122
+ ]) if (p !== void 0 && p.keys.length > 5) refuse("a permission holds more than 5 keys");
1123
+ }
1124
+ };
1125
+ const contractEffects = (contract, network, symbol, chainId, table) => {
1126
+ switch (contract.type) {
1127
+ case "TransferContract": return {
1128
+ summary: "transfer",
1129
+ outflows: [{
1130
+ to: contract.to,
1131
+ amount: sun(contract.amount, symbol),
1132
+ verified: true
1133
+ }],
1134
+ approvals: [],
1135
+ verifiability: "full"
1136
+ };
1137
+ case "TransferAssetContract": return {
1138
+ summary: "transfer",
1139
+ outflows: [{
1140
+ to: contract.to,
1141
+ amount: trc10(contract.assetId, contract.amount),
1142
+ verified: false
1143
+ }],
1144
+ approvals: [],
1145
+ verifiability: "partial"
1146
+ };
1147
+ case "VoteWitnessContract": return stakeEffects({
1148
+ kind: "tron-vote",
1149
+ votes: contract.votes.map((v) => ({
1150
+ witness: v.witness,
1151
+ count: v.count.toString(10)
1152
+ }))
1153
+ });
1154
+ case "FreezeBalanceV2Contract": return stakeEffects({
1155
+ kind: "tron-freeze",
1156
+ amount: sun(contract.amount, symbol),
1157
+ resource: resourceName(contract.resource)
1158
+ });
1159
+ case "UnfreezeBalanceV2Contract": return stakeEffects({
1160
+ kind: "tron-unfreeze",
1161
+ amount: sun(contract.amount, symbol),
1162
+ resource: resourceName(contract.resource)
1163
+ });
1164
+ case "DelegateResourceContract": return stakeEffects({
1165
+ kind: "tron-delegate",
1166
+ receiver: contract.receiver,
1167
+ amount: sun(contract.balance, symbol),
1168
+ resource: resourceName(contract.resource),
1169
+ ...contract.lock ? { lock: { blocks: contract.lockPeriod.toString(10) } } : {}
1170
+ });
1171
+ case "UnDelegateResourceContract": return stakeEffects({
1172
+ kind: "tron-undelegate",
1173
+ receiver: contract.receiver,
1174
+ amount: sun(contract.balance, symbol),
1175
+ resource: resourceName(contract.resource)
1176
+ });
1177
+ case "WithdrawExpireUnfreezeContract": return stakeEffects({ kind: "tron-withdraw-unfrozen" });
1178
+ case "CancelAllUnfreezeV2Contract": return stakeEffects({ kind: "tron-cancel-unfreeze" });
1179
+ case "WithdrawBalanceContract": return stakeEffects({ kind: "tron-claim-rewards" });
1180
+ case "AccountPermissionUpdateContract": {
1181
+ const { ownerPermission, witnessPermission, actives } = contract;
1182
+ return {
1183
+ summary: "authorization",
1184
+ outflows: [],
1185
+ approvals: [],
1186
+ verifiability: "partial",
1187
+ permissionUpdate: {
1188
+ owner: permissionDisplay("owner", ownerPermission),
1189
+ ...witnessPermission === void 0 ? {} : { witness: permissionDisplay("witness", witnessPermission) },
1190
+ actives: actives.map((p) => permissionDisplay("active", p))
1191
+ }
1192
+ };
1193
+ }
1194
+ case "TriggerSmartContract": {
1195
+ const token = lookupTronToken(table, network, contract.contract);
1196
+ const contractField = {
1197
+ address: contract.contract,
1198
+ created: false,
1199
+ selector: selectorOf(contract.data),
1200
+ ...token === void 0 ? {} : { symbol: token.symbol }
1201
+ };
1202
+ const attached = [];
1203
+ if (contract.callValue > 0n) attached.push({
1204
+ to: contract.contract,
1205
+ amount: sun(contract.callValue, symbol),
1206
+ verified: true
1207
+ });
1208
+ if (contract.callTokenValue > 0n) attached.push({
1209
+ to: contract.contract,
1210
+ amount: trc10(contract.tokenId.toString(10), contract.callTokenValue),
1211
+ verified: false
1212
+ });
1213
+ const tokenCall = contract.data.length === 0 ? void 0 : decodeTokenCall(tronAddressToEvm(contract.contract), `0x${bytesToHex(contract.data)}`, chainId, evmTableFor(network, chainId, table));
1214
+ if (tokenCall !== void 0) {
1215
+ const mapped = mapTokenCall(tokenCall);
1216
+ return {
1217
+ summary: mapped.summary,
1218
+ outflows: [...attached, ...mapped.outflows],
1219
+ approvals: mapped.approvals,
1220
+ verifiability: contract.callTokenValue > 0n && mapped.verifiability === "full" ? "partial" : mapped.verifiability,
1221
+ contract: contractField
1222
+ };
1223
+ }
1224
+ const nearMiss = tronCallNearMiss(contract.contract, network, table);
1225
+ return {
1226
+ summary: "contract-call",
1227
+ outflows: attached,
1228
+ approvals: [],
1229
+ verifiability: "opaque",
1230
+ contract: contractField,
1231
+ ...nearMiss === void 0 ? {} : { blind: nearMiss }
1232
+ };
1233
+ }
1234
+ }
1235
+ };
1236
+ /** A permit approval's EVM-form addresses mapped back to base58 for display. */
1237
+ const mapPermitApproval = (a) => a.kind === "allowance" ? {
1238
+ ...a,
1239
+ spender: tronAddressFromEvm(a.spender),
1240
+ amount: {
1241
+ ...a.amount,
1242
+ asset: tronAddressFromEvm(a.amount.asset)
1243
+ }
1244
+ } : a;
1245
+ /** The domain fields as the prompt shows them — `verifyingContract` in base58. */
1246
+ const tronDomainDisplay = (domain) => {
1247
+ const { name, version, salt } = domain;
1248
+ const chainId = domainChainId(domain);
1249
+ const verifying = tronTypedDataBase58(domain["verifyingContract"]);
1250
+ return {
1251
+ ...typeof name === "string" ? { name } : {},
1252
+ ...typeof version === "string" ? { version } : {},
1253
+ ...chainId === void 0 ? {} : { chainId },
1254
+ ...verifying === void 0 ? {} : { verifyingContract: verifying },
1255
+ ...typeof salt === "string" ? { salt } : {}
1256
+ };
1257
+ };
1258
+ /**
1259
+ * The display decode of a `tron.typed-data` request. The permit recognizers run on the document
1260
+ * mapped to EVM form — every `address` leaf `0x`-hex — so the EVM selector tables match; a document
1261
+ * declaring `trcToken` has no EVM equivalent and can only be field-shown or blind. Approvals and
1262
+ * addresses come back out in base58. Blind precedence mirrors the EVM lane: a recognized permit's
1263
+ * own reason, then family near-miss, then oversize, then commitment.
1264
+ */
1265
+ const tronTypedDataIntent = (typedData, network, chainId, signer, table) => {
1266
+ const { json } = parseTronTypedData(typedData);
1267
+ const evmJson = tronTypedDataToEvm(json);
1268
+ const permit2 = TRON_PERMIT2[network];
1269
+ const permit = evmJson === void 0 ? void 0 : recognizePermit(evmJson, chainId, evmTableFor(network, chainId, table), tronAddressToEvm(signer), permit2 === void 0 ? "" : tronAddressToEvm(permit2));
1270
+ const nearMiss = permit === void 0 ? tronTypedDataNearMiss(json, network, table) : void 0;
1271
+ const shown = permit === void 0 ? typedDataFields(json, tronTypedDataLeaf) : void 0;
1272
+ let fields;
1273
+ if (permit === void 0) fields = shown?.fields;
1274
+ else if (permit.fields !== void 0) {
1275
+ const witnessType = json.types[json.primaryType]?.at(-1)?.type;
1276
+ const { witness } = json.message;
1277
+ fields = (witnessType !== void 0 && isTypedDataMessage(witness) ? typedDataFields({
1278
+ types: json.types,
1279
+ primaryType: witnessType,
1280
+ domain: {},
1281
+ message: witness
1282
+ }, tronTypedDataLeaf) : void 0)?.fields.map((leaf) => ({
1283
+ path: `witness.${leaf.path}`,
1284
+ value: leaf.value
1285
+ }));
1286
+ }
1287
+ const blind = permit?.blind ?? (permit === void 0 ? nearMiss ?? (shown === void 0 ? "typed-data-oversize" : shown.hasCommitment ? "typed-data-commitment" : void 0) : void 0) ?? (typedDataHasHiddenText(json) ? "message-bytes" : void 0);
1288
+ return {
1289
+ family: "tron",
1290
+ network,
1291
+ summary: permit === void 0 ? "message" : "approve",
1292
+ outflows: [],
1293
+ approvals: (permit?.approvals ?? []).map(mapPermitApproval),
1294
+ fee: void 0,
1295
+ warnings: permit?.warnings ?? [],
1296
+ message: {
1297
+ kind: "typed-data",
1298
+ primaryType: json.primaryType,
1299
+ domain: tronDomainDisplay(json.domain),
1300
+ data: json.message,
1301
+ ...fields === void 0 ? {} : { fields }
1302
+ },
1303
+ verifiability: permit === void 0 ? "opaque" : "partial",
1304
+ ...blind === void 0 ? {} : { blind }
1305
+ };
1306
+ };
1307
+ /**
1308
+ * The display decode of a normalized request. `signer` is the base58 address the account signs
1309
+ * with; a modeled contract whose owner is anyone else is refused.
1310
+ */
1311
+ const decodeTron = (request, signer, table = tronTokenTable) => {
1312
+ const meta = networkMeta(request.network);
1313
+ if (meta === void 0 || meta.family !== "tron") throw new ChainError("invalid-request", `unknown TRON network ${request.network}`);
1314
+ const { symbol, chainId } = meta;
1315
+ if (request.kind === "tron.message") {
1316
+ const content = messageContent(request.message, "tron");
1317
+ const blind = messageBlindReason(content);
1318
+ return {
1319
+ family: "tron",
1320
+ network: request.network,
1321
+ summary: "message",
1322
+ outflows: [],
1323
+ approvals: [],
1324
+ fee: void 0,
1325
+ warnings: [],
1326
+ message: content,
1327
+ verifiability: "opaque",
1328
+ ...blind === void 0 ? {} : { blind }
1329
+ };
1330
+ }
1331
+ if (request.kind === "tron.typed-data") return tronTypedDataIntent(request.typedData, request.network, chainId, signer, table);
1332
+ if (request.kind !== "tron.transaction") throw new ChainError("unsupported", `${request.kind} is not a TRON request`);
1333
+ const raw = decodeTronRawData(request.rawData);
1334
+ if (raw.expiration > BigInt(Number.MAX_SAFE_INTEGER)) refuse("expiration exceeds the safe integer range");
1335
+ const tron = {
1336
+ contractType: tronContractType(raw.contract.typeId)?.name ?? `ContractType ${raw.contract.typeId}`,
1337
+ expiration: Number(raw.expiration),
1338
+ ...raw.contract.permissionId === 0 ? {} : { permissionId: raw.contract.permissionId },
1339
+ ...raw.memo === void 0 ? {} : { memo: memoDisplay(raw.memo) }
1340
+ };
1341
+ const fee = raw.feeLimit === void 0 || raw.feeLimit === 0n ? void 0 : { max: sun(raw.feeLimit, symbol) };
1342
+ const base = {
1343
+ family: "tron",
1344
+ network: request.network,
1345
+ approvals: [],
1346
+ warnings: [],
1347
+ fee,
1348
+ tron
1349
+ };
1350
+ const modeled = decodeTronContract(raw.contract.typeId, raw.contract.value);
1351
+ if (modeled === void 0) return {
1352
+ ...base,
1353
+ summary: "contract-call",
1354
+ outflows: [],
1355
+ verifiability: "opaque",
1356
+ blind: "tron-contract"
1357
+ };
1358
+ const { contract, extra } = modeled;
1359
+ if (contract.owner !== signer) throw new ChainError("invalid-request", "owner_address is not the signing account");
1360
+ semanticCheck(contract, raw);
1361
+ const blind = raw.extra.length > 0 || raw.contract.extra.length > 0 || extra.length > 0 || fieldBlind(contract);
1362
+ const effects = contractEffects(contract, request.network, symbol, chainId, table);
1363
+ const blindReason = contract.type === "AccountPermissionUpdateContract" ? "tron-permission-update" : blind ? "tron-field" : effects.blind;
1364
+ return {
1365
+ ...base,
1366
+ summary: effects.summary,
1367
+ outflows: effects.outflows,
1368
+ approvals: effects.approvals,
1369
+ ...effects.staking === void 0 ? {} : { staking: effects.staking },
1370
+ verifiability: effects.verifiability,
1371
+ ...effects.contract === void 0 ? {} : { contract: effects.contract },
1372
+ ...blindReason === void 0 ? {} : { blind: blindReason },
1373
+ tron: {
1374
+ ...tron,
1375
+ ...effects.permissionUpdate === void 0 ? {} : { permissionUpdate: effects.permissionUpdate }
1376
+ }
1377
+ };
1378
+ };
1379
+ // src/tron/verify.ts
1380
+ /**
1381
+ * Secp256k1 signature recovery and verification for `chain.sign` results: the host checks the
1382
+ * kernel's 65-byte signature against the payload and the account address returned by
1383
+ * `wallet.accounts` — a wrong signer fails closed.
1384
+ */
1385
+ /** The signer of a 65-byte r‖s‖v signature (v∈{27,28}), as a base58 TRON address. */
1386
+ const recover = (payload, signature) => {
1387
+ if (signature.length !== 65) throw new ChainError("invalid-request", "a TRON signature is 65 bytes");
1388
+ const v = signature.at(-1);
1389
+ if (v !== 27 && v !== 28) throw new ChainError("invalid-request", "TRON signature v is not 27 or 28");
1390
+ try {
1391
+ return tronAddressFromEvm(Secp256k1.recoverAddress({
1392
+ payload: Hex.fromBytes(payload),
1393
+ signature: Signature.fromBytes(signature)
1394
+ }));
1395
+ } catch (error) {
1396
+ if (error instanceof ChainError) throw error;
1397
+ throw new ChainError("invalid-request", "signature does not recover a public key");
1398
+ }
1399
+ };
1400
+ /** Recovers the signer address of a transaction signature over sha256(raw_data). */
1401
+ const recoverTronTransactionSigner = (rawData, signature) => recover(sha256(rawData), signature);
1402
+ /** Recovers the signer address of a TIP-191 message signature. */
1403
+ const recoverTronMessageSigner = (message, signature) => recover(tronMessageDigest(message), signature);
1404
+ /** Recovers the signer address of a TIP-712 typed-data signature. */
1405
+ const recoverTronTypedDataSigner = (typedData, signature) => recover(tronTypedDataDigest(parseTronTypedData(typedData).json), signature);
1406
+ /** Whether `signature` signs sha256(rawData) for `address` — false on any error. */
1407
+ const verifyTronTransactionSignature = (rawData, signature, address) => {
1408
+ try {
1409
+ return recoverTronTransactionSigner(rawData, signature) === address;
1410
+ } catch {
1411
+ return false;
1412
+ }
1413
+ };
1414
+ /** Whether `signature` signs the TIP-191 digest of `message` for `address` — false on any error. */
1415
+ const verifyTronMessageSignature = (message, signature, address) => {
1416
+ try {
1417
+ return recoverTronMessageSigner(message, signature) === address;
1418
+ } catch {
1419
+ return false;
1420
+ }
1421
+ };
1422
+ /** Whether `signature` signs the TIP-712 digest of `typedData` for `address` — false on any error. */
1423
+ const verifyTronTypedDataSignature = (typedData, signature, address) => {
1424
+ try {
1425
+ return recoverTronTypedDataSigner(typedData, signature) === address;
1426
+ } catch {
1427
+ return false;
1428
+ }
1429
+ };
1430
+ // src/tron/index.ts
1431
+ /** The TRON network ids in `BUILT_IN_NETWORKS` — mainnet plus the Shasta and Nile testnets. */
1432
+ const TRON_NETWORKS = Object.freeze(BUILT_IN_NETWORKS.filter((n) => n.family === "tron").map((n) => n.id));
1433
+ /**
1434
+ * Validates an untrusted request into a `SignRequest`: the network is a known TRON network (decimal
1435
+ * CAIP-2 only — `tron:0x…` is rejected like any other unknown id), `tron.transaction` carries
1436
+ * raw_data that decodes under the strict reader (a bare 32-byte txid is refused), and
1437
+ * `tron.message` carries non-empty bytes that could not be a transaction.
1438
+ */
1439
+ const normalizeTron = (request) => {
1440
+ if (!isRecord(request) || typeof request["kind"] !== "string") throw new ChainError("invalid-request", "request must be an object with a kind");
1441
+ const { network, account } = requestBase(request);
1442
+ if (!TRON_NETWORKS.includes(network)) throw new ChainError("invalid-request", `${network} is not a TRON network`);
1443
+ if (request["kind"] === "tron.transaction") {
1444
+ const { rawData } = request;
1445
+ if (!(rawData instanceof Uint8Array)) throw new ChainError("invalid-request", "tron.transaction payload must be raw_data bytes");
1446
+ if (rawData.length === 32) throw new ChainError("invalid-request", "a bare 32-byte digest is not a TRON transaction");
1447
+ decodeTronRawData(rawData);
1448
+ return {
1449
+ kind: "tron.transaction",
1450
+ network,
1451
+ account,
1452
+ rawData
1453
+ };
1454
+ }
1455
+ if (request["kind"] === "tron.typed-data") {
1456
+ const { typedData } = request;
1457
+ if (typeof typedData !== "string") throw new ChainError("invalid-request", "tron.typed-data payload must be the canonical JSON source string");
1458
+ const { json } = parseTronTypedData(typedData);
1459
+ const domainChain = domainChainId(json.domain);
1460
+ const networkChain = BUILT_IN_NETWORKS.find((n) => n.id === network)?.chainId;
1461
+ if (domainChain !== void 0 && domainChain !== networkChain) throw new ChainError("chain-id-mismatch", `typed-data domain.chainId ${domainChain} does not match network ${network}`);
1462
+ return {
1463
+ kind: "tron.typed-data",
1464
+ network,
1465
+ account,
1466
+ typedData
1467
+ };
1468
+ }
1469
+ if (request["kind"] === "tron.message") {
1470
+ const { message } = request;
1471
+ if (!(message instanceof Uint8Array) || message.length === 0) throw new ChainError("invalid-request", "tron.message payload must be non-empty bytes");
1472
+ if (mayBeTronTransaction(message)) throw new ChainError("invalid-request", "tron.message payload could be a transaction — use tron.transaction");
1473
+ return {
1474
+ kind: "tron.message",
1475
+ network,
1476
+ account,
1477
+ message
1478
+ };
1479
+ }
1480
+ throw new ChainError("unsupported", `${request["kind"]} is not a TRON request kind`);
1481
+ };
1482
+ export { TRON_ADDRESS_PREFIX, TRON_CONTRACT_TYPES, TRON_MEMO_MAX_BYTES, TRON_MESSAGE_PREFIX, TRON_NATIVE_ASSET, TRON_NETWORKS, TRON_PERMIT2, assembleTron, buildTronRawData, decodeTron, decodeTronContract, decodeTronRawData, encodeTronContract, encodeTronRawData, encodeTronTransaction, isTronAddress, lookupTronToken, mayBeTronTransaction, normalizeTron, parseTronTypedData, planTron, recoverTronMessageSigner, recoverTronTransactionSigner, recoverTronTypedDataSigner, trc20ApproveContract, trc20TransferContract, tronAddressFromBytes, tronAddressFromEvm, tronAddressFromHex, tronAddressFromPublicKey, tronAddressToBytes, tronAddressToEvm, tronAddressToHex, tronContractType, tronMemoBytes, tronMessageDigest, tronRawDataFromJson, tronTokenTable, tronTransactionId, tronTypeUrl, tronTypedDataBase58, tronTypedDataDigest, tronTypedDataFromArgs, tronTypedDataHashes, tronTypedDataLeaf, tronTypedDataToEvm, verifyTronMessageSignature, verifyTronTransactionSignature, verifyTronTypedDataSignature };
1483
+
1484
+ //# sourceMappingURL=tron.mjs.map