-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode.js
More file actions
1859 lines (1644 loc) · 73.9 KB
/
decode.js
File metadata and controls
1859 lines (1644 loc) · 73.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Pure dynamic decoder - NO HARDCODED METADATA
// KaiSign dynamic decoder v2.1 - FIXED formatTokenAmount
// Guard against duplicate loading (MAIN world scripts can run multiple times)
if (window.SimpleInterface) {
console.log('[decode.js] Already loaded, skipping');
} else {
console.log('[decode.js] VERSION 2.1 LOADED - formatTokenAmount FIXED');
const KAISIGN_DEBUG = false;
// Simple keccak256 implementation for selector calculation
// Uses SubtleCrypto when available, falls back to simple hash
function keccak256Simple(message) {
// Try to use ethers if available
if (typeof window !== 'undefined') {
if (window.ethers?.keccak256 && window.ethers?.toUtf8Bytes) {
try { return window.ethers.keccak256(window.ethers.toUtf8Bytes(message)); } catch {}
}
if (window.ethers?.utils?.keccak256 && window.ethers?.utils?.toUtf8Bytes) {
try { return window.ethers.utils.keccak256(window.ethers.utils.toUtf8Bytes(message)); } catch {}
}
}
// Minimal keccak256 implementation
const KECCAK_ROUNDS = 24;
const KECCAK_RC = [
0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n,
0x000000000000808bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n,
0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,
0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n,
0x8000000000008002n, 0x8000000000000080n, 0x000000000000800an, 0x800000008000000an,
0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n
];
const KECCAK_ROTC = [1,3,6,10,15,21,28,36,45,55,2,14,27,41,56,8,25,43,62,18,39,61,20,44];
const KECCAK_PILN = [10,7,11,17,18,3,5,16,8,21,24,4,15,23,19,13,12,2,20,14,22,9,6,1];
function rotl64(x, y) { return ((x << BigInt(y)) | (x >> BigInt(64 - y))) & 0xffffffffffffffffn; }
function keccakF(state) {
for (let round = 0; round < KECCAK_ROUNDS; round++) {
const c = new Array(5).fill(0n);
for (let x = 0; x < 5; x++) c[x] = state[x] ^ state[x+5] ^ state[x+10] ^ state[x+15] ^ state[x+20];
for (let x = 0; x < 5; x++) {
const t = c[(x+4)%5] ^ rotl64(c[(x+1)%5], 1);
for (let y = 0; y < 25; y += 5) state[x+y] ^= t;
}
let t = state[1];
for (let i = 0; i < 24; i++) {
const j = KECCAK_PILN[i];
const tmp = state[j];
state[j] = rotl64(t, KECCAK_ROTC[i]);
t = tmp;
}
for (let y = 0; y < 25; y += 5) {
const t0 = state[y], t1 = state[y+1], t2 = state[y+2], t3 = state[y+3], t4 = state[y+4];
state[y] = t0 ^ (~t1 & t2); state[y+1] = t1 ^ (~t2 & t3);
state[y+2] = t2 ^ (~t3 & t4); state[y+3] = t3 ^ (~t4 & t0); state[y+4] = t4 ^ (~t0 & t1);
}
state[0] ^= KECCAK_RC[round];
}
}
const encoder = new TextEncoder();
const input = encoder.encode(message);
const rate = 136, capacity = 64;
const blockSize = rate;
const state = new Array(25).fill(0n);
const padded = new Uint8Array(Math.ceil((input.length + 1) / blockSize) * blockSize);
padded.set(input);
padded[input.length] = 0x01;
padded[padded.length - 1] |= 0x80;
for (let i = 0; i < padded.length; i += blockSize) {
for (let j = 0; j < blockSize && j < 200; j += 8) {
if (i + j + 8 <= padded.length) {
let val = 0n;
for (let k = 0; k < 8; k++) val |= BigInt(padded[i + j + k]) << BigInt(k * 8);
state[Math.floor(j / 8)] ^= val;
}
}
keccakF(state);
}
let hash = '0x';
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 8; j++) {
hash += ((state[i] >> BigInt(j * 8)) & 0xffn).toString(16).padStart(2, '0');
}
}
return hash;
}
// Calculate function selector from signature
function calculateSelector(signature) {
const hash = keccak256Simple(signature);
return hash.slice(0, 10);
}
// Enhanced ABI decoder - supports all Solidity types including bytes, bytes[], arrays
// NO HARDCODED SELECTORS - all type handling is generic
class SimpleInterface {
constructor(abi) {
this.abi = Array.isArray(abi) ? abi : [abi];
}
/**
* Safe slice with bounds checking
* Throws if start is beyond data length; zero-pads if end exceeds data length
* @param {string} data - Hex string without 0x prefix
* @param {number} start - Start offset in hex chars
* @param {number} end - End offset in hex chars
* @returns {string} - Sliced hex string, zero-padded if needed
*/
safeSlice(data, start, end) {
const needed = end - start;
if (start > data.length * 2) {
// Corrupt offset — pointer is absurdly large (> 2x data), indicates bad data
throw new Error(`ABI decode: offset ${start / 2} beyond data length ${data.length / 2}`);
}
if (start >= data.length) {
// Past end of data — zero-pad entire result (truncated calldata)
return '0'.repeat(needed);
}
const slice = data.slice(start, end);
if (slice.length < needed) {
return slice + '0'.repeat(needed - slice.length);
}
return slice;
}
/**
* Parse array type into base type and optional fixed size
* @param {string} type - Solidity type (e.g., 'uint256[3]', 'address[]', 'bytes32[2][]')
* @returns {{baseType: string, size: number|null}|null} - null if not an array type
*/
parseArrayType(type) {
const match = type.match(/^(.+)\[(\d*)\]$/);
if (!match) return null;
return { baseType: match[1], size: match[2] === '' ? null : parseInt(match[2]) };
}
/**
* Check if a type is dynamic (requires offset resolution)
* @param {string} type - Solidity type
* @param {object} input - ABI input definition (for checking tuple components)
* @returns {boolean}
*/
isDynamicType(type, input = null) {
if (!type) return false;
// bytes, string are always dynamic
if (type === 'bytes' || type === 'string') return true;
// Array types: T[] is always dynamic, T[N] is dynamic only if T is dynamic
const arr = this.parseArrayType(type);
if (arr) {
if (arr.size === null) return true; // T[] — dynamic (has length prefix)
return this.isDynamicType(arr.baseType, input); // T[N] — static if T is static
}
// Tuples with any dynamic components are dynamic (requires offset resolution)
if (type === 'tuple' && input?.components) {
return input.components.some(c => this.isDynamicType(c.type, c));
}
return false;
}
/**
* Decode a static type from data
* @param {string} type - Solidity type
* @param {string} paramData - Hex data without 0x prefix
* @param {number} offset - Offset in hex chars
* @param {object} input - ABI input definition (for tuple components)
* @returns {{value: any, size: number}}
*/
decodeStaticType(type, paramData, offset, input = null) {
// Fixed-size arrays MUST be checked first, before scalar type checks
// (e.g., uint256[5] starts with 'uint' but is an array, not a scalar)
const fixedArr = this.parseArrayType(type);
if (fixedArr && fixedArr.size !== null && !this.isDynamicType(fixedArr.baseType, input)) {
const results = [];
let arrOffset = 0;
for (let i = 0; i < fixedArr.size; i++) {
const { value, size } = this.decodeStaticType(fixedArr.baseType, paramData, offset + arrOffset, input);
results.push(value);
arrOffset += size;
}
return { value: results, size: arrOffset };
}
// Address: 20 bytes right-padded in 32 bytes
if (type === 'address') {
const rawAddr = this.safeSlice(paramData, offset + 24, offset + 64);
return {
value: '0x' + rawAddr.toLowerCase(),
size: 64
};
}
// Unsigned integers: uint8, uint16, ..., uint256
if (type.startsWith('uint')) {
const hexValue = this.safeSlice(paramData, offset, offset + 64);
try {
const value = BigInt('0x' + hexValue);
return {
value: { _isBigNumber: true, _hex: '0x' + hexValue, _value: value.toString() },
size: 64
};
} catch {
return { value: '0x' + hexValue, size: 64 };
}
}
// Signed integers: int8, int16, ..., int256 (two's complement)
if (type.startsWith('int')) {
const hexValue = this.safeSlice(paramData, offset, offset + 64);
try {
const raw = BigInt('0x' + hexValue);
const bits = parseInt(type.slice(3)) || 256;
// For int types < 256 bits, the ABI encoding sign-extends to 256 bits
// Extract only the lower N bits and apply two's complement
const mask = (1n << BigInt(bits)) - 1n;
const truncated = raw & mask;
const halfRange = 1n << BigInt(bits - 1);
const value = truncated >= halfRange ? truncated - (1n << BigInt(bits)) : truncated;
return {
value: { _isBigNumber: true, _hex: '0x' + hexValue, _value: value.toString() },
size: 64
};
} catch {
return { value: '0x' + hexValue, size: 64 };
}
}
// Fixed-size bytes: bytes1, bytes2, ..., bytes32
if (type.startsWith('bytes') && !type.endsWith('[]') && type !== 'bytes') {
const byteSize = parseInt(type.replace('bytes', '')) || 32;
const hexSize = byteSize * 2;
const value = '0x' + this.safeSlice(paramData, offset, offset + hexSize);
return { value, size: 64 }; // Always takes 32 bytes in ABI encoding
}
// Boolean
if (type === 'bool') {
const lastByte = this.safeSlice(paramData, offset + 62, offset + 64);
return {
value: lastByte !== '00',
size: 64
};
}
// Tuple (struct) - static tuples only
if (type === 'tuple' && input?.components) {
const tupleData = {};
let tupleOffset = 0;
for (const component of input.components) {
if (this.isDynamicType(component.type, component)) {
// Dynamic component in tuple - need to handle offset
const dynOffset = parseInt(paramData.slice(offset + tupleOffset, offset + tupleOffset + 64), 16) * 2;
const dynResult = this.decodeDynamicType(component.type, paramData, offset + dynOffset, component);
tupleData[component.name] = dynResult;
tupleOffset += 64;
} else {
const result = this.decodeStaticType(component.type, paramData, offset + tupleOffset, component);
tupleData[component.name] = result.value;
tupleOffset += result.size;
}
}
return { value: tupleData, size: tupleOffset };
}
// Default: return raw hex
return {
value: '0x' + paramData.slice(offset, offset + 64),
size: 64
};
}
/**
* Decode a dynamic type from data
* @param {string} type - Solidity type
* @param {string} paramData - Hex data without 0x prefix
* @param {number} offset - Offset in hex chars (pointing to length field)
* @param {object} input - ABI input definition
* @returns {any}
*/
decodeDynamicType(type, paramData, offset, input = null) {
// Dynamic bytes
if (type === 'bytes') {
const length = parseInt(this.safeSlice(paramData, offset, offset + 64), 16);
const hexLength = length * 2;
const data = paramData.slice(offset + 64, offset + 64 + hexLength);
return '0x' + data;
}
// Dynamic string
if (type === 'string') {
const length = parseInt(this.safeSlice(paramData, offset, offset + 64), 16);
const hexLength = length * 2;
const hexData = paramData.slice(offset + 64, offset + 64 + hexLength);
return this.hexToString(hexData);
}
// Fixed-size arrays of dynamic types: T[N] where T is dynamic (no length prefix)
const dynArr = this.parseArrayType(type);
if (dynArr && dynArr.size !== null) {
const results = [];
// T[N] with dynamic T: each element has an offset pointer (no length prefix)
for (let i = 0; i < dynArr.size; i++) {
const elementOffsetHex = this.safeSlice(paramData, offset + i * 64, offset + (i + 1) * 64);
const elementOffset = parseInt(elementOffsetHex, 16) * 2;
const value = this.decodeDynamicType(dynArr.baseType, paramData, offset + elementOffset, input);
results.push(value);
}
return results;
}
// Dynamic-size array types: T[] (address[], uint256[], bytes[], etc.)
if (dynArr && dynArr.size === null) {
const baseType = dynArr.baseType;
const arrayLength = parseInt(this.safeSlice(paramData, offset, offset + 64), 16);
const results = [];
if (this.isDynamicType(baseType, input)) {
// Array of dynamic elements (e.g., bytes[], string[], tuple[] with dynamic components)
// Each element has an offset pointer
for (let i = 0; i < arrayLength; i++) {
const elementOffsetHex = this.safeSlice(paramData, offset + 64 + i * 64, offset + 64 + (i + 1) * 64);
const elementOffset = parseInt(elementOffsetHex, 16) * 2;
const value = this.decodeDynamicType(baseType, paramData, offset + 64 + elementOffset, input);
results.push(value);
}
} else {
// Array of static elements (e.g., address[], uint256[])
let arrayOffset = offset + 64;
for (let i = 0; i < arrayLength; i++) {
const { value, size } = this.decodeStaticType(baseType, paramData, arrayOffset, input);
results.push(value);
arrayOffset += size;
}
}
return results;
}
// Dynamic tuple (tuple with dynamic components)
// The offset points to where the tuple data starts
if (type === 'tuple' && input?.components) {
const tupleData = {};
let tupleOffset = 0;
for (const component of input.components) {
if (this.isDynamicType(component.type, component)) {
// Dynamic component - read relative offset from tuple head, decode from tuple tail
const relOffsetHex = this.safeSlice(paramData, offset + tupleOffset, offset + tupleOffset + 64);
const relOffset = parseInt(relOffsetHex, 16) * 2;
const dynResult = this.decodeDynamicType(component.type, paramData, offset + relOffset, component);
tupleData[component.name] = dynResult;
tupleOffset += 64;
} else {
// Static component - read inline
const result = this.decodeStaticType(component.type, paramData, offset + tupleOffset, component);
tupleData[component.name] = result.value;
tupleOffset += result.size;
}
}
return tupleData;
}
// Fallback
return '0x' + this.safeSlice(paramData, offset, offset + 64);
}
/**
* Convert hex string to UTF-8 string
* @param {string} hex - Hex string without 0x prefix
* @returns {string}
*/
hexToString(hex) {
if (!hex || hex.length === 0) return '';
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
}
// Strip trailing null bytes
let end = bytes.length;
while (end > 0 && bytes[end - 1] === 0) end--;
return new TextDecoder('utf-8', { fatal: false }).decode(bytes.subarray(0, end));
}
/**
* Decode function calldata using ABI
* @param {string} functionName - Function name to decode
* @param {string} data - Full calldata including selector
* @returns {Array} - Decoded parameters
*/
decodeFunctionData(functionName, data) {
const funcAbi = this.abi.find(item => item.name === functionName);
if (!funcAbi) throw new Error(`Function ${functionName} not found`);
// Remove function selector (first 4 bytes = 8 hex chars + 0x)
const paramData = data.slice(10);
const inputs = funcAbi.inputs || [];
const results = [];
// First pass: calculate head offsets and identify dynamic types
let headOffset = 0;
const dynamicParams = [];
for (let i = 0; i < inputs.length; i++) {
const input = inputs[i];
if (this.isDynamicType(input.type, input)) {
// Dynamic type: read offset from head, decode from tail later
const offsetHex = this.safeSlice(paramData, headOffset, headOffset + 64);
const tailOffset = parseInt(offsetHex, 16) * 2;
dynamicParams.push({ index: i, input, tailOffset });
headOffset += 64;
} else {
// Static type: decode directly from head
const { value, size } = this.decodeStaticType(input.type, paramData, headOffset, input);
results[i] = value;
headOffset += size;
}
}
// Second pass: decode dynamic types from their tail offsets
for (const { index, input, tailOffset } of dynamicParams) {
const value = this.decodeDynamicType(input.type, paramData, tailOffset, input);
results[index] = value;
}
return results;
}
}
// PURE dynamic decoding - only from metadata
async function decodeCalldata(data, contractAddress, chainId) {
try {
const selector = data.slice(0, 10);
// Pass selector to metadata lookup for proxy detection (e.g., Safe proxies)
let metadata = await getContractMetadata(contractAddress, chainId, selector);
// If no metadata from subgraph, return failure
if (!metadata) {
return {
success: false,
selector,
intent: 'Contract interaction',
error: 'No metadata found in subgraph'
};
}
// Find function in ABI from metadata
let functionSignature = null;
let functionName = null;
let abiFunction = null;
if (metadata.context?.contract?.abi && Array.isArray(metadata.context.contract.abi)) {
for (const item of metadata.context.contract.abi) {
if (item.type === 'function') {
const types = (item.inputs || []).map(input => input.type).join(',');
const signature = `${item.name}(${types})`;
// Use stored selector or calculate it
const expectedSelector = item.selector || calculateSelector(signature);
KAISIGN_DEBUG && console.log('[Decode] Checking function:', signature, 'selector:', expectedSelector, 'vs', selector);
if (expectedSelector === selector) {
functionSignature = signature;
functionName = item.name;
abiFunction = item;
KAISIGN_DEBUG && console.log('[Decode] ✅ MATCHED function:', signature);
break;
}
}
}
} else if (typeof metadata.context?.contract?.abi === 'string' && metadata.context?.contract?.selectorFallbacks) {
functionName = metadata.context.contract.selectorFallbacks[selector];
if (functionName) functionSignature = `${functionName}(...)`;
}
if (!functionSignature && !functionName) {
const contractName = metadata.context?.contract?.name || '';
return {
success: false,
selector,
contractName,
metadata,
intent: contractName
? `Unknown function on ${contractName}`
: `Unknown contract interaction (${selector})`,
error: 'Function not found in metadata ABI'
};
}
// Get intent from metadata
let intent = 'Contract interaction';
let fieldInfo = {};
let format = metadata.display?.formats?.[functionSignature] || metadata.display?.formats?.[functionName];
// Fallback: when ABI uses simplified types (e.g. "tuple") but format keys use expanded
// tuple types (e.g. "(bytes32,string,address,...)"), match by function name prefix
if (!format && functionName && metadata.display?.formats) {
const prefix = functionName + '(';
for (const key of Object.keys(metadata.display.formats)) {
if (key.startsWith(prefix)) {
format = metadata.display.formats[key];
break;
}
}
}
// Store command registries from metadata for later use
const commandRegistries = metadata.commandRegistries || {};
if (format) {
// Handle ERC-7730 intent formats
if (format.interpolatedIntent) {
// ERC-7730 interpolatedIntent takes priority - will be processed after params are decoded
intent = { type: 'interpolated', template: format.interpolatedIntent };
} else if (format.intent?.type === 'composite') {
// Composite intent - will be built from decoded commands later
// Just mark it for now, actual building happens after decoding params
intent = { type: 'composite', config: format.intent };
} else if (format.intent?.template) {
// Most common: intent.template string
intent = format.intent.template;
} else if (format.intent?.format && Array.isArray(format.intent.format)) {
// Complex format with nested containers
for (const item of format.intent.format) {
if (item.type === 'container' && item.fields) {
for (const field of item.fields) {
if (field.type === 'text' && field.value && field.format === 'heading2') {
intent = field.value;
break;
}
}
if (intent !== 'Contract interaction') break;
}
}
} else if (typeof format.intent === 'string') {
intent = format.intent;
}
// Extract field info from format.fields
if (format.fields) {
for (const field of format.fields) {
if (field.path) {
fieldInfo[field.path] = {
label: field.label || field.path,
format: field.format || 'raw',
params: field.params || {}, // Store decimals, symbol, etc.
// Store calldata target reference for recursive decoding
type: field.type || (field.format === 'calldata' ? 'calldata' : 'raw'),
calldataTarget: field.type === 'calldata' ? field.to : (field.format === 'calldata' ? (field.params?.calleePath || field.params?.to || null) : null)
};
}
}
}
// Also extract calldata fields from ERC-7730 format.intent.format structure
if (format.intent?.format && Array.isArray(format.intent.format)) {
extractCalldataFieldsFromFormat(format.intent.format, fieldInfo);
}
}
// Try messages format (KaiSign format)
else if (metadata.messages?.[functionName]) {
const messageFormat = metadata.messages[functionName];
intent = messageFormat.label || intent;
if (messageFormat.fields) {
for (const field of messageFormat.fields) {
if (field.path) {
fieldInfo[field.path] = {
label: field.label || field.path,
format: field.type === 'address' ? 'address' :
field.type === 'wei' ? 'wei' :
field.type === 'uint256' ? 'number' : 'raw'
};
}
}
}
}
// Format results based on metadata ONLY
const params = {};
const rawParams = {}; // Store original decoded values (not stringified)
const formatted = {};
if (abiFunction) {
// Use ABI from metadata to decode
const iface = new SimpleInterface([abiFunction]);
const decodedData = iface.decodeFunctionData(functionName, data);
// Generic formatting based on ABI inputs from metadata
const inputs = abiFunction.inputs || [];
for (let i = 0; i < decodedData.length && i < inputs.length; i++) {
const input = inputs[i];
const value = decodedData[i];
const paramName = input.name || `param${i}`;
// Store original decoded value for composite intent building
rawParams[paramName] = value;
// Get field info from metadata if available
const fieldDef = fieldInfo[paramName];
let rawValue;
if (value && typeof value === 'object' && '_isBigNumber' in value) {
// Prefer _value over _hex - _value is correct for signed integers (two's complement)
rawValue = value._value !== undefined ? value._value : (value._hex ? BigInt(value._hex).toString() : String(value));
} else if (typeof value === 'object' && value !== null) {
rawValue = JSON.stringify(value);
} else {
rawValue = String(value || '');
}
// Apply formatting based on field definition
let displayValue = rawValue;
if (fieldDef?.format === 'amount' && fieldDef.params?.decimals) {
// Check for max uint256 (unlimited approval)
const MAX_UINT256 = '115792089237316195423570985008687907853269984665640564039457584007913129639935';
if (rawValue === MAX_UINT256) {
const symbol = fieldDef.params.symbol || '';
displayValue = symbol ? `Unlimited ${symbol}` : 'Unlimited';
KAISIGN_DEBUG && console.log(`[Decode] Detected max uint256, displaying as: "${displayValue}"`);
} else {
// Format with decimals
const decimals = fieldDef.params.decimals;
const symbol = fieldDef.params.symbol || '';
KAISIGN_DEBUG && console.log(`[Decode] Formatting ${paramName}: rawValue="${rawValue}" (type: ${typeof rawValue}), decimals=${decimals} (type: ${typeof decimals}), symbol=${symbol}`);
try {
const dec = Number(decimals);
const value = BigInt(rawValue);
const divisor = BigInt(10) ** BigInt(dec);
const integerPart = value / divisor;
const fractionalPart = value % divisor;
if (value === 0n) {
displayValue = symbol ? `0 ${symbol}` : '0';
KAISIGN_DEBUG && console.log(`[Decode] INLINE formatted: "${displayValue}"`);
params[paramName] = rawValue;
formatted[paramName] = {
label: fieldDef?.label || toTitleCase(paramName),
value: displayValue,
rawValue: rawValue,
format: fieldDef?.format || (input.type === 'address' ? 'address' :
input.type === 'uint256' ? 'token' : 'raw'),
params: fieldDef?.params || {}
};
continue;
}
const fullFraction = fractionalPart.toString().padStart(dec, '0');
let fractionalStr = fullFraction.replace(/0+$/, '');
const maxDisplay = 6;
const minDisplay = 2; // Minimum 2 decimal places for standard amounts
if (integerPart === 0n && fractionalPart > 0n) {
const firstNonZero = fullFraction.search(/[1-9]/);
if (firstNonZero !== -1) {
const end = Math.min(firstNonZero + maxDisplay, fullFraction.length);
fractionalStr = fullFraction.slice(0, end).replace(/0+$/, '');
}
}
// Ensure minimum 2 decimal places for readability (unless very small amount)
if (fractionalStr.length < minDisplay && integerPart < 1000n) {
fractionalStr = fullFraction.slice(0, minDisplay);
}
if (fractionalStr === '') fractionalStr = '0';
if (fractionalStr.length > maxDisplay) fractionalStr = fractionalStr.slice(0, maxDisplay);
displayValue = symbol ? `${integerPart}.${fractionalStr} ${symbol}` : `${integerPart}.${fractionalStr}`;
KAISIGN_DEBUG && console.log(`[Decode] INLINE formatted: "${displayValue}"`);
} catch (e) {
console.error('[Decode] Inline format error:', e);
displayValue = rawValue;
}
}
} else if (fieldDef?.format === 'tokenAmount' && fieldDef.params?.tokenPath) {
// Dynamic token lookup - resolve decimals/symbol from token address in another param
// Support ERC-7730 paths like "_route.[0]" via resolveFieldPath
let tokenAddress = rawParams[fieldDef.params.tokenPath];
if (tokenAddress === undefined) {
tokenAddress = resolveFieldPath(fieldDef.params.tokenPath, rawParams);
}
if (tokenAddress && typeof tokenAddress === 'string' && tokenAddress.length >= 10) {
try {
let decimals = 18, symbol = '';
const normalizedAddr = tokenAddress.toLowerCase();
const nativeCurrency = fieldDef.params.nativeCurrencyAddress;
const isNative = normalizedAddr === '0x0000000000000000000000000000000000000000' ||
normalizedAddr === '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' ||
(nativeCurrency && normalizedAddr === nativeCurrency.toLowerCase());
if (isNative) {
decimals = 18; symbol = 'ETH';
} else if (window.metadataService) {
const tokenInfo = await window.metadataService.getTokenMetadata(tokenAddress, chainId);
decimals = tokenInfo.decimals || 18;
symbol = tokenInfo.symbol || '';
}
displayValue = formatTokenAmount(rawValue, decimals, symbol);
} catch (e) {
console.warn('[Decode] tokenAmount format error:', e.message);
}
}
}
params[paramName] = rawValue;
formatted[paramName] = {
label: fieldDef?.label || toTitleCase(paramName),
value: displayValue,
rawValue: rawValue,
format: fieldDef?.format || (input.type === 'address' ? 'address' :
input.type === 'uint256' ? 'token' : 'raw'),
params: fieldDef?.params || {}
};
}
// ERC-7730: Process fields with sub-paths (e.g., "_route.[0]", "order.token")
// These reference specific elements within decoded arrays/tuples
for (const [fieldPath, fieldDef] of Object.entries(fieldInfo)) {
// Skip if already handled as a top-level param or if it's a calldata field
if (rawParams[fieldPath] !== undefined || fieldDef.format === 'calldata') continue;
// Try to resolve the sub-path value from decoded params
const resolvedValue = resolveFieldPath(fieldPath, rawParams);
if (resolvedValue === undefined) continue;
let rawValue;
if (resolvedValue && typeof resolvedValue === 'object' && '_isBigNumber' in resolvedValue) {
rawValue = resolvedValue._value !== undefined ? resolvedValue._value : String(resolvedValue);
} else {
rawValue = String(resolvedValue || '');
}
let displayValue = rawValue;
// Apply tokenAmount formatting for sub-path fields
if (fieldDef.format === 'tokenAmount' && fieldDef.params?.tokenPath) {
let tokenAddress = rawParams[fieldDef.params.tokenPath];
if (tokenAddress === undefined) {
tokenAddress = resolveFieldPath(fieldDef.params.tokenPath, rawParams);
}
if (tokenAddress && typeof tokenAddress === 'string' && tokenAddress.length >= 10) {
try {
let decimals = 18, symbol = '';
const normalizedAddr = tokenAddress.toLowerCase();
const nativeCurrency = fieldDef.params.nativeCurrencyAddress;
const isNative = normalizedAddr === '0x0000000000000000000000000000000000000000' ||
normalizedAddr === '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' ||
(nativeCurrency && normalizedAddr === nativeCurrency.toLowerCase());
if (isNative) {
decimals = 18; symbol = 'ETH';
} else if (typeof window !== 'undefined' && window.metadataService) {
const tokenInfo = await window.metadataService.getTokenMetadata(tokenAddress, chainId);
decimals = tokenInfo.decimals || 18;
symbol = tokenInfo.symbol || '';
}
displayValue = formatTokenAmount(rawValue, decimals, symbol);
} catch (e) {
// Fall through to raw display
}
}
} else if (fieldDef.format === 'addressName') {
// Keep raw address, wallet resolves names
displayValue = rawValue;
}
// Use the field path as key (avoiding conflicts with ABI param names)
const formattedKey = fieldPath.replace(/\.\[/g, '[').replace(/\]/g, ']');
params[formattedKey] = rawValue;
formatted[formattedKey] = {
label: fieldDef.label || formattedKey,
value: displayValue,
rawValue: rawValue,
format: fieldDef.format || 'raw',
params: fieldDef.params || {}
};
}
} else {
// Fallback when we only have function name, no ABI
params.data = data.slice(10);
formatted.data = {
label: 'Transaction Data',
value: data.slice(10),
format: 'raw'
};
}
// Handle composite intent (ERC-7730 command registries)
let finalIntent;
let decodedCommands = null;
if (intent && typeof intent === 'object' && intent.type === 'composite') {
const intentConfig = intent.config;
const registryName = intentConfig.registry;
const registry = commandRegistries[registryName];
const sourceParam = intentConfig.source; // e.g., 'commands'
// Get the commands and inputs parameters from rawParams (not stringified)
const commandsValue = rawParams[sourceParam];
const inputsValue = rawParams['inputs']; // Universal Router uses 'inputs' array
KAISIGN_DEBUG && console.log('[Decode] Composite intent - rawParams:', {
keys: Object.keys(rawParams),
sourceParam: sourceParam,
commandsValue: commandsValue,
commandsType: typeof commandsValue,
inputsValue: inputsValue,
inputsType: typeof inputsValue,
inputsIsArray: Array.isArray(inputsValue),
inputsLength: Array.isArray(inputsValue) ? inputsValue.length : 'N/A'
});
if (commandsValue && registry) {
// Decode commands using the registry
decodedCommands = await decodeCommandArray(commandsValue, inputsValue, registry, chainId);
finalIntent = buildCompositeIntent(intentConfig, decodedCommands);
KAISIGN_DEBUG && console.log('[Decode] Built composite intent:', finalIntent);
} else {
finalIntent = 'Execute commands';
KAISIGN_DEBUG && console.log('[Decode] Missing commands or registry for composite intent');
}
} else if (intent && typeof intent === 'object' && intent.type === 'interpolated') {
// ERC-7730 interpolatedIntent - process template with field values
const template = intent.template;
KAISIGN_DEBUG && console.log('[Decode] Processing interpolatedIntent template:', template);
// Pass format.fields so we can apply formatters to nested paths (async for API token lookups)
finalIntent = await substituteInterpolatedIntent(template, rawParams, format.fields || [], chainId);
KAISIGN_DEBUG && console.log('[Decode] Interpolated result:', finalIntent);
} else {
// Standard intent handling
// Inject {value} into intent, but skip if value is zero (prevents "Execute 0" for Safe transactions)
if (formatted.value && typeof intent === 'string') {
const formattedVal = formatted.value.value || '';
// Check if value is non-zero and meaningful (not just "0", "0x0", "0.00")
const valueIsZero = formattedVal === '0' ||
formattedVal === '0x0' ||
formattedVal === '0.00' ||
formattedVal === '0.00 ETH' ||
formattedVal === '0 ETH';
// Only inject {value} if the value is non-zero
// This avoids "Execute 0" for Safe transactions with value=0
if (!valueIsZero) {
const firstWord = intent.split(/\s+/)[0];
intent = firstWord + ' {value}';
}
}
// Substitute template variables in intent (e.g., "Swap {amount} {token}")
// Pass rawParams for nested object path resolution (e.g., "data.fromAmount" for tuples)
finalIntent = substituteIntentTemplate(intent, params, formatted, rawParams);
}
// Decode nested calldata fields (ERC-7730 calldata format)
const nestedIntents = [];
if (fieldInfo && Object.keys(fieldInfo).length > 0) {
for (const [fieldPath, fieldDef] of Object.entries(fieldInfo)) {
if (fieldDef.format === 'calldata') {
// Check if this is an array path like "#._swapData.[].callData"
const isArrayPath = fieldPath.includes('.[].');
if (isArrayPath) {
// Handle array iteration for paths like "#._swapData.[].callData"
// Extract the array base path and the field within each element
const arrayPathMatch = fieldPath.match(/^(#\.|@\.)?(.+?)\.\[\]\.(.+)$/);
if (arrayPathMatch) {
const arrayName = arrayPathMatch[2]; // e.g., "_swapData"
const elementField = arrayPathMatch[3]; // e.g., "callData"
const array = rawParams[arrayName];
if (Array.isArray(array)) {
for (let i = 0; i < array.length; i++) {
const element = array[i];
const calldataValue = element[elementField];
if (typeof calldataValue === 'string' && calldataValue.startsWith('0x') && calldataValue.length > 10) {
// Resolve target from the same array element
let target = fieldDef.calldataTarget;
if (typeof target === 'string') {
// For array targets like "#._swapData.[].callTo", get from same element
const targetMatch = target.match(/^(#\.|@\.)?(.+?)\.\[\]\.(.+)$/);
if (targetMatch && targetMatch[2] === arrayName) {
// Same array, get field from current element
target = element[targetMatch[3]];
} else if (target.startsWith('$.') || target.startsWith('#.')) {
target = resolveFieldPath(target, rawParams);
} else if (rawParams[target]) {
target = rawParams[target];
}
}
if (target && window.decodeCalldataRecursive) {
try {
const nested = await window.decodeCalldataRecursive(calldataValue, target, chainId);
if (nested?.success) {
if (nested.nestedIntents?.length) {
nestedIntents.push(...nested.nestedIntents);
} else if (nested.intent && nested.intent !== 'Contract interaction') {
nestedIntents.push(nested.intent);
}
}
} catch (e) {
// Ignore nested decode failures
}
}
}
}
}
}
} else {
// Original single-value path handling
let calldataValue = rawParams[fieldPath];
// Also try resolving with path resolution for #. prefixed paths
if (calldataValue === undefined && (fieldPath.startsWith('#.') || fieldPath.startsWith('@.'))) {
calldataValue = resolveFieldPath(fieldPath, rawParams);
}
if (typeof calldataValue === 'string' && calldataValue.startsWith('0x') && calldataValue.length > 10) {
let target = fieldDef.calldataTarget;
if (typeof target === 'string') {
if (target.startsWith('$.') || target.startsWith('#.')) {
target = resolveFieldPath(target, rawParams);
} else if (rawParams[target]) {
target = rawParams[target];
}
}
if (target && window.decodeCalldataRecursive) {
try {
const nested = await window.decodeCalldataRecursive(calldataValue, target, chainId);
if (nested?.success) {
if (nested.nestedIntents?.length) {
nestedIntents.push(...nested.nestedIntents);
} else if (nested.intent && nested.intent !== 'Contract interaction') {
nestedIntents.push(nested.intent);
}
}
} catch (e) {
// Ignore nested decode failures
}
}
}
}
}
}
}
const aggregatedIntent = nestedIntents.length ? nestedIntents.join(' + ') : undefined;
if (aggregatedIntent) {
finalIntent = aggregatedIntent;
}
return {
success: true,
selector,
function: functionSignature,
functionName,
params,
rawParams,
intent: finalIntent,
formatted,
metadata,
decodedCommands, // Include decoded commands for display
nestedIntents,
aggregatedIntent
};
} catch (error) {
console.error('[Decode] Error:', error.message);
return {
success: false,
selector: data.slice(0, 10),
intent: 'Contract interaction',
error: error.message
};
}
}
// Helper functions
/**
* Format token amount with decimals
* @param {string} rawValue - Raw integer value as string
* @param {number} decimals - Number of decimals
* @param {string} symbol - Token symbol
* @returns {string} - Formatted amount like "1.5 USDC"
*/
function formatTokenAmount(rawValue, decimals, symbol) {
KAISIGN_DEBUG && console.log('[formatTokenAmount] CALLED with:', { rawValue, decimals, symbol, rawValueType: typeof rawValue, decimalsType: typeof decimals });
try {
// Ensure decimals is a number
const dec = Number(decimals);
KAISIGN_DEBUG && console.log('[formatTokenAmount] dec after Number():', dec);