|
1 | 1 | import { type ProtocolAdapter, SOL } from '@protocols/shared'; |
| 2 | +import { Transaction } from '@solana/web3.js'; |
2 | 3 | import { Summary } from '@/components/Summary'; |
3 | 4 | import { convertToMessage, looksLikeMessage, type MessageLike, type ParseSolTxResult, parseSolTx } from '@/parser'; |
4 | 5 | import type { DecodedInstruction } from '@/types'; |
5 | | -import { base64ToHex, isBase64, isHex } from '@/utils'; |
| 6 | +import { base64ToHex, isBase64, isHex, sha256 } from '@/utils'; |
6 | 7 |
|
7 | 8 | const computeSolanaHash = async (rawTx: string): Promise<string> => { |
8 | 9 | try { |
9 | 10 | const input = rawTx.trim(); |
10 | 11 |
|
11 | 12 | // If input is a JSON message |
12 | 13 | if (input.startsWith('{') || input.startsWith('[')) { |
13 | | - try { |
14 | | - const obj = JSON.parse(input); |
15 | | - const msg = (obj.message ?? obj) as MessageLike; |
16 | | - if (looksLikeMessage(msg)) { |
17 | | - const message = convertToMessage(msg); |
18 | | - const messageBytes = message.serialize(); |
19 | | - const hexString = messageBytes.toString('hex'); |
20 | | - |
21 | | - const transactionUint8Array = new Uint8Array( |
22 | | - hexString.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) || [], |
23 | | - ); |
24 | | - const hashBuffer = await crypto.subtle.digest('SHA-256', transactionUint8Array); |
25 | | - const hashArray = Array.from(new Uint8Array(hashBuffer)); |
26 | | - return hashArray.map((b) => b.toString(16).padStart(2, '0')).join(''); |
27 | | - } |
28 | | - } catch {} |
| 14 | + const obj = JSON.parse(input); |
| 15 | + const msg = (obj.message ?? obj) as MessageLike; |
| 16 | + if (looksLikeMessage(msg)) { |
| 17 | + const message = convertToMessage(msg); |
| 18 | + return sha256(new Uint8Array(message.serialize())); |
| 19 | + } |
29 | 20 | } |
30 | 21 |
|
| 22 | + // Hex or base64 path |
31 | 23 | let hexInput = input; |
32 | 24 | if (!isHex(input) && isBase64(input)) { |
33 | 25 | hexInput = base64ToHex(input); |
34 | 26 | } |
35 | 27 |
|
36 | | - const transactionUint8Array = new Uint8Array(hexInput.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) || []); |
37 | | - const hashBuffer = await crypto.subtle.digest('SHA-256', transactionUint8Array); |
38 | | - const hashArray = Array.from(new Uint8Array(hashBuffer)); |
39 | | - return hashArray.map((b) => b.toString(16).padStart(2, '0')).join(''); |
| 28 | + const tx = Transaction.from(Buffer.from(hexInput, 'hex')); |
| 29 | + return sha256(new Uint8Array(tx.serializeMessage())); |
40 | 30 | } catch { |
41 | 31 | throw new Error('Failed to compute Solana hash'); |
42 | 32 | } |
|
0 commit comments