|
| 1 | +import { rpc, StrKey } from '@stellar/stellar-sdk'; |
| 2 | + |
| 3 | +import { |
| 4 | + compareScVal, |
| 5 | + decodePayload, |
| 6 | + decodeTopics, |
| 7 | + formatEventDecodingReport, |
| 8 | +} from '../utils/scval-decoder'; |
| 9 | + |
| 10 | +/** |
| 11 | + * Example 105: Soroban Contract Event Decoding |
| 12 | + * |
| 13 | + * Contract events carry topics (indexed ScVals) and a data payload (one ScVal). |
| 14 | + * This example retrieves events for a contract and decodes every topic and the |
| 15 | + * payload into human-readable values, showing raw base64 XDR alongside decoded |
| 16 | + * output for side-by-side comparison. |
| 17 | + */ |
| 18 | + |
| 19 | +const DEFAULT_RPC_URL = 'https://soroban-testnet.stellar.org'; |
| 20 | +const DEFAULT_CONTRACT_ID = 'CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC'; |
| 21 | +const DEFAULT_LOOKBACK = 17280; |
| 22 | +const DEFAULT_LIMIT = 5; |
| 23 | + |
| 24 | +export interface ContractEventDecodingParams { |
| 25 | + contractId?: string; |
| 26 | + startLedger?: number | string; |
| 27 | + limit?: number | string; |
| 28 | + rpcUrl?: string; |
| 29 | +} |
| 30 | + |
| 31 | +export function normalizeContractId(value: string): string { |
| 32 | + const trimmed = value.trim(); |
| 33 | + if (!trimmed) { |
| 34 | + throw new Error('Missing contract ID. Provide a contract ID starting with "C".'); |
| 35 | + } |
| 36 | + if (!StrKey.isValidContract(trimmed)) { |
| 37 | + throw new Error(`Invalid contract ID "${trimmed}".`); |
| 38 | + } |
| 39 | + return trimmed; |
| 40 | +} |
| 41 | + |
| 42 | +export function normalizeLimit(value?: number | string): number { |
| 43 | + const parsed = typeof value === 'string' ? parseInt(value.trim(), 10) : value; |
| 44 | + if (parsed === undefined || Number.isNaN(parsed)) return DEFAULT_LIMIT; |
| 45 | + return Math.min(Math.max(Math.trunc(parsed), 1), 50); |
| 46 | +} |
| 47 | + |
| 48 | +export function parseLedgerInput(value?: number | string): number | undefined { |
| 49 | + if (value === undefined || value === null || value === '') return undefined; |
| 50 | + const parsed = typeof value === 'string' ? parseInt(value.trim(), 10) : value; |
| 51 | + if (Number.isNaN(parsed) || parsed < 1) return undefined; |
| 52 | + return Math.trunc(parsed); |
| 53 | +} |
| 54 | + |
| 55 | +export async function run(params: ContractEventDecodingParams = {}): Promise<void> { |
| 56 | + const rpcUrl = params.rpcUrl || process.env.SOROBAN_RPC_URL || DEFAULT_RPC_URL; |
| 57 | + const contractInput = |
| 58 | + params.contractId?.trim() || |
| 59 | + process.env.CONTRACT_ID?.trim() || |
| 60 | + process.argv[3]?.trim() || |
| 61 | + DEFAULT_CONTRACT_ID; |
| 62 | + const limit = normalizeLimit(params.limit ?? process.env.EVENT_LIMIT ?? process.argv[5]); |
| 63 | + const startInput = parseLedgerInput( |
| 64 | + params.startLedger ?? process.env.START_LEDGER ?? process.argv[4], |
| 65 | + ); |
| 66 | + |
| 67 | + console.log('Soroban Contract Event Decoding Example'); |
| 68 | + console.log(`Soroban RPC: ${rpcUrl}`); |
| 69 | + |
| 70 | + let contractId: string; |
| 71 | + try { |
| 72 | + contractId = normalizeContractId(contractInput); |
| 73 | + } catch (err: any) { |
| 74 | + console.log(`\n${err?.message ?? err}`); |
| 75 | + return; |
| 76 | + } |
| 77 | + |
| 78 | + const server = new rpc.Server(rpcUrl); |
| 79 | + |
| 80 | + let latestLedger: number; |
| 81 | + try { |
| 82 | + latestLedger = (await server.getLatestLedger()).sequence; |
| 83 | + console.log(`Latest ledger: ${latestLedger}`); |
| 84 | + } catch (err: any) { |
| 85 | + console.log(`Could not reach Soroban RPC: ${err?.message ?? err}`); |
| 86 | + return; |
| 87 | + } |
| 88 | + |
| 89 | + const startLedger = startInput ?? Math.max(1, latestLedger - DEFAULT_LOOKBACK); |
| 90 | + console.log(`Contract: ${contractId}`); |
| 91 | + console.log(`Ledger range: ${startLedger} -> latest (limit ${limit})`); |
| 92 | + |
| 93 | + let response: rpc.Api.GetEventsResponse; |
| 94 | + try { |
| 95 | + response = await server.getEvents({ |
| 96 | + startLedger, |
| 97 | + filters: [{ type: 'contract', contractIds: [contractId] }], |
| 98 | + limit, |
| 99 | + }); |
| 100 | + } catch (err: any) { |
| 101 | + console.log(`\nCould not retrieve events: ${err?.message ?? err}`); |
| 102 | + return; |
| 103 | + } |
| 104 | + |
| 105 | + const events = response.events ?? []; |
| 106 | + if (events.length === 0) { |
| 107 | + console.log('\nNo contract events found in the queried ledger range.'); |
| 108 | + console.log('This is a valid empty result — try a more recent start ledger or another contract.'); |
| 109 | + return; |
| 110 | + } |
| 111 | + |
| 112 | + console.log(`\nRetrieved ${events.length} event(s). Decoding topics and payloads...\n`); |
| 113 | + |
| 114 | + events.forEach((event, index) => { |
| 115 | + console.log(formatEventDecodingReport({ |
| 116 | + contractId, |
| 117 | + ledger: event.ledger ?? 0, |
| 118 | + txHash: event.txHash ?? '', |
| 119 | + topics: event.topic ?? [], |
| 120 | + value: event.value, |
| 121 | + })); |
| 122 | + |
| 123 | + const topicComparisons = (event.topic ?? []).map(compareScVal); |
| 124 | + const payloadComparison = compareScVal(event.value); |
| 125 | + |
| 126 | + console.log('\nSide-by-side summary:'); |
| 127 | + topicComparisons.forEach((row, topicIndex) => { |
| 128 | + console.log( |
| 129 | + ` topic[${topicIndex}] ${row.xdrType.padEnd(12)} raw=${row.rawXdr.slice(0, 24)}… decoded=${row.decodedDisplay}`, |
| 130 | + ); |
| 131 | + }); |
| 132 | + console.log( |
| 133 | + ` payload ${payloadComparison.xdrType.padEnd(12)} raw=${payloadComparison.rawXdr.slice(0, 24)}… decoded=${payloadComparison.decodedDisplay}`, |
| 134 | + ); |
| 135 | + |
| 136 | + const decodedTopics = decodeTopics(event.topic); |
| 137 | + const decodedPayload = decodePayload(event.value); |
| 138 | + const unsupported = [...decodedTopics, decodedPayload].filter((item) => !item.decoded); |
| 139 | + if (unsupported.length > 0) { |
| 140 | + console.log('\nUnsupported or undecodable values:'); |
| 141 | + unsupported.forEach((item) => { |
| 142 | + console.log(` - ${item.xdrType}: ${item.error ?? 'decode failed'}`); |
| 143 | + }); |
| 144 | + } |
| 145 | + |
| 146 | + if (index < events.length - 1) { |
| 147 | + console.log('\n' + '-'.repeat(72)); |
| 148 | + } |
| 149 | + }); |
| 150 | + |
| 151 | + console.log('\nDecoding reference:'); |
| 152 | + console.log(' Address -> G… or C… strkey'); |
| 153 | + console.log(' Symbol -> short identifier string'); |
| 154 | + console.log(' String -> UTF-8 text'); |
| 155 | + console.log(' Bool -> true / false'); |
| 156 | + console.log(' Integer -> string (preserves i128/u256 precision)'); |
| 157 | + console.log(' Bytes -> 0x-prefixed hex'); |
| 158 | + console.log(' Vec/Map -> JSON array or object'); |
| 159 | + console.log('\nContract event decoding example completed.'); |
| 160 | +} |
0 commit comments