-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathSimulateStepContent.tsx
More file actions
514 lines (461 loc) · 15.9 KB
/
SimulateStepContent.tsx
File metadata and controls
514 lines (461 loc) · 15.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
"use client";
import { useEffect, useState } from "react";
import {
Alert,
Button,
Card,
Icon,
Link,
Input,
Text,
} from "@stellar/design-system";
import {
TransactionBuilder,
xdr,
rpc as StellarRpc,
} from "@stellar/stellar-sdk";
import { useBuildFlowStore } from "@/store/createTransactionFlowStore";
import { useStore } from "@/store/useStore";
import { useSimulateTx } from "@/query/useSimulateTx";
import { AuthModePicker } from "@/components/FormElements/AuthModePicker";
import { XdrPicker } from "@/components/FormElements/XdrPicker";
import { Box } from "@/components/layout/Box";
import { PageCard } from "@/components/layout/PageCard";
import { CodeEditor } from "@/components/CodeEditor";
import { PageHeader } from "@/components/layout/PageHeader";
import { XdrFormat } from "@/components/XdrFormat";
import { SdsLink } from "@/components/SdsLink";
import { ExpandBox } from "@/components/ExpandBox";
import { SorobanAuthSigningCard } from "@/components/SorobanAuthSigning";
import { TransactionStepName } from "@/components/TransactionStepper";
import { getNetworkHeaders } from "@/helpers/getNetworkHeaders";
import { checkIsReadOnly } from "@/helpers/sorobanUtils";
import { extractAuthEntries } from "@/helpers/sorobanAuthUtils";
import { validate } from "@/validate";
import { trackEvent, TrackingEvent } from "@/metrics/tracking";
import { AuthModeType, XdrFormatType } from "@/types/types";
import {
SimulationResourceTable,
getSimulationResourceInfo,
} from "./SimulationResourceTable";
/**
* Simulate step content for the single-page transaction flow (Soroban only).
*
* Reads the built XDR from the flow store, runs simulateTransaction via RPC,
* and stores the result. When auth entries are detected, shows them and
* (eventually) enables auth signing before assembly.
*
* @example
* {activeStep === "simulate" && <SimulateStepContent />}
*/
export const SimulateStepContent = ({
steps,
}: {
steps: TransactionStepName[];
}) => {
const { network } = useStore();
const {
build,
simulate,
setSimulateInstructionLeeway,
setSimulateAuthMode,
setSimulationResult,
setSimulationReadOnly,
setAuthEntriesXdr,
setSignedAuthEntriesXdr,
setAssembledXdr,
resetDownstreamState,
} = useBuildFlowStore();
const [instrLeewayError, setInstrLeewayError] = useState("");
const [assemblyWarning, setAssemblyWarning] = useState("");
const [isResourcesExpanded, setIsResourcesExpanded] = useState(false);
const [xdrFormat, setXdrFormat] = useState<XdrFormatType | string>("json");
const [simulationDisplay, setSimulationDisplayResult] = useState<string>("");
const [validUntilLedgerSeq, setValidUntilLedgerSeq] = useState(0);
// Derive the built XDR from whichever operation type was used
const builtXdr = build.soroban.xdr || build.classic.xdr;
const isInvokeContract =
build.soroban.operation.operation_type === "invoke_contract_function";
/**
* After all auth entries are signed, assemble the transaction with the
* signed auth entries and store the assembled XDR for the Sign step.
*/
const assembleWithSignedAuth = (signedEntries: string[]) => {
if (!simulate.simulationResultJson || !builtXdr || !network.passphrase) {
return;
}
try {
// Parse the original transaction
const rawTx = TransactionBuilder.fromXDR(builtXdr, network.passphrase);
// Parse the stored simulation result
const rawResponse = JSON.parse(simulate.simulationResultJson);
const parsedSim = StellarRpc.parseRawSimulation(rawResponse.result);
// Assemble with resources and fees from simulation
const assembled = StellarRpc.assembleTransaction(
rawTx,
parsedSim,
).build();
// Replace auth entries on the assembled transaction with signed versions
const envelope = assembled.toEnvelope();
const ops = envelope.v1().tx().operations();
for (const op of ops) {
if (op.body().switch() === xdr.OperationType.invokeHostFunction()) {
const ihf = op.body().invokeHostFunctionOp();
const signedAuth = signedEntries.map((entryBase64) =>
xdr.SorobanAuthorizationEntry.fromXDR(entryBase64, "base64"),
);
ihf.auth(signedAuth);
}
}
const finalXdr = envelope.toXDR("base64");
setAssembledXdr(finalXdr);
setSignedAuthEntriesXdr(signedEntries);
trackEvent(TrackingEvent.SOROBAN_AUTH_ASSEMBLY_SUCCESS);
} catch (e) {
trackEvent(TrackingEvent.SOROBAN_AUTH_ASSEMBLY_ERROR, {
error: String(e),
});
}
};
const {
mutateAsync: simulateTx,
data: simulateTxData,
error: simulateTxError,
isPending: isSimulateTxPending,
reset: resetSimulateTx,
} = useSimulateTx();
// Validate instruction leeway
useEffect(() => {
if (simulate.instructionLeeway) {
const validationError = validate.getPositiveIntError(
simulate.instructionLeeway,
);
setInstrLeewayError(validationError || "");
} else {
setInstrLeewayError("");
}
}, [simulate.instructionLeeway]);
const isActionDisabled =
!network.rpcUrl || !builtXdr || Boolean(instrLeewayError);
/**
* Run the simulation against the RPC endpoint.
*/
const onSimulate = async () => {
if (!network.rpcUrl || !builtXdr) return;
// Reset sign/validate/submit state and stepper completed marks
resetDownstreamState("sign", steps);
setAssemblyWarning("");
trackEvent(TrackingEvent.TRANSACTION_SIMULATE);
try {
const [simJsonResponse, simBase64Response] = await Promise.all([
xdrFormat === "json"
? simulateTx({
rpcUrl: network.rpcUrl,
transactionXdr: builtXdr,
headers: getNetworkHeaders(network, "rpc"),
xdrFormat: "json",
...(isInvokeContract ? { authMode: simulate.authMode } : {}),
})
: null,
simulateTx({
rpcUrl: network.rpcUrl,
transactionXdr: builtXdr,
headers: getNetworkHeaders(network, "rpc"),
xdrFormat: "base64",
...(isInvokeContract ? { authMode: simulate.authMode } : {}),
}),
]);
if (xdrFormat === "json" && simJsonResponse) {
setSimulationDisplayResult(JSON.stringify(simJsonResponse, null, 2));
} else if (simBase64Response) {
setSimulationDisplayResult(JSON.stringify(simBase64Response, null, 2));
}
if (simBase64Response) {
setSimulationResult(JSON.stringify(simBase64Response, null, 2));
// Check for errors in the response
const hasError = Boolean(
simBase64Response?.error || simBase64Response?.result?.error,
);
if (!hasError) {
// Check if read-only
const isReadOnly = checkIsReadOnly(simBase64Response);
setSimulationReadOnly(isReadOnly);
// Compute validUntilLedgerSeq from latestLedger in response
const latestLedger = Number(
simBase64Response?.result?.latestLedger ?? 0,
);
if (latestLedger > 0) {
// ~42 minutes buffer at 5 seconds per ledger
setValidUntilLedgerSeq(latestLedger + 500);
}
// Extract and store auth entries
const entries = extractAuthEntries(simBase64Response);
if (entries.length > 0) {
setAuthEntriesXdr(entries);
trackEvent(TrackingEvent.SOROBAN_AUTH_ENTRIES_DETECTED, {
entryCount: entries.length,
});
} else {
// No auth entries — auto-assemble the transaction with
// simulation resources (fees, sorobanData) so the Sign step
// receives a complete XDR ready for signing.
try {
const rawTx = TransactionBuilder.fromXDR(
builtXdr,
network.passphrase,
);
const parsedSim = StellarRpc.parseRawSimulation(
simBase64Response.result,
);
const assembled = StellarRpc.assembleTransaction(
rawTx,
parsedSim,
).build();
setAssembledXdr(assembled.toXDR());
} catch (e) {
trackEvent(TrackingEvent.SOROBAN_AUTO_ASSEMBLY_ERROR, {
error: String(e),
});
setAssemblyWarning(
"Auto-assembly failed. Please try again later.",
);
}
}
}
}
} catch {
// Error is captured by React Query's error state
}
};
const hasSimulationResult = Boolean(simulateTxData);
const hasError = Boolean(
simulateTxError || simulateTxData?.error || simulateTxData?.result?.error,
);
const isSimulationSuccess = hasSimulationResult && !hasError;
const authEntries = simulate.authEntriesXdr || [];
const hasAuthEntries = authEntries.length > 0;
const resourceInfo = getSimulationResourceInfo(simulateTxData);
const getErrorMessage = (): string => {
if (simulateTxError) {
const err = simulateTxError as unknown;
return typeof err === "object" &&
err !== null &&
"result" in (err as Record<string, unknown>)
? String((err as Record<string, unknown>).result)
: String(simulateTxError);
}
if (simulateTxData?.error) {
return String(simulateTxData.error);
}
if (simulateTxData?.result?.error) {
return String(simulateTxData.result.error);
}
return "Unknown simulation error";
};
return (
<Box gap="md">
<PageHeader heading="Simulate transaction" as="h1" />
<PageCard>
{!network.rpcUrl ? (
<Alert variant="warning" placement="inline" title="Attention">
RPC URL is required to simulate a transaction. You can add it in the
network settings in the upper right corner.
</Alert>
) : null}
<Box gap="lg">
<XdrPicker
id="view-xdr-blob"
label="Base64 encoded XDR"
value={builtXdr}
disabled
hasCopyButton
/>
<XdrFormat
selectedFormat={xdrFormat || "json"}
onChange={(format) => {
setXdrFormat(format);
if (hasSimulationResult) {
resetSimulateTx();
}
}}
/>
{/* Instruction leeway */}
<Input
id="simulate-instruction-leeway"
fieldSize="md"
label="Instruction leeway"
labelSuffix="optional"
value={simulate.instructionLeeway || ""}
onChange={(e) => {
setSimulateInstructionLeeway(e.target.value || undefined);
if (hasSimulationResult) {
resetSimulateTx();
}
}}
error={instrLeewayError}
/>
{/* Auth mode selector — only relevant for InvokeHostFunction */}
{isInvokeContract ? (
<AuthModePicker
id="simulate-auth-mode"
value={simulate.authMode}
onChange={(mode) => {
resetSimulateTx();
setSimulateAuthMode(mode as AuthModeType);
}}
note={
<>
"Record" is recommended for simulation.
"Record" discovers which authorization entries are
required.
<SdsLink href="https://developers.stellar.org/docs/learn/fundamentals/contract-development/contract-interactions/transaction-simulation#authorization">
Learn more
</SdsLink>
.
</>
}
/>
) : null}
{/* Simulate button */}
<Box gap="md" direction="row">
<Button
disabled={Boolean(isActionDisabled)}
isLoading={isSimulateTxPending}
size="md"
variant="secondary"
onClick={onSimulate}
>
Simulate
</Button>
</Box>
</Box>
</PageCard>
{renderAlert({
isReadOnly: Boolean(simulate.isSimulationReadOnly),
isSimulationSuccess,
hasAuthEntries,
hasError,
errorMessage: hasError ? getErrorMessage() : "",
})}
{assemblyWarning ? (
<Alert variant="warning" placement="inline" title="Assembly warning">
{assemblyWarning}
</Alert>
) : null}
{/* Simulation success */}
{isSimulationSuccess && (
<Card>
<Box gap="md">
{/* Simulation result JSON viewer */}
<div data-testid="simulate-step-response">
<CodeEditor
title="Simulation Result"
value={simulationDisplay}
selectedLanguage="json"
maxHeightInRem="20"
/>
</div>
{/* Resource usage and fees (collapsible) */}
{resourceInfo && (
<Box gap="sm">
<div
className="SimulateStepContent__expand-toggle"
onClick={() => setIsResourcesExpanded(!isResourcesExpanded)}
data-is-expanded={isResourcesExpanded}
>
<Link size="sm" icon={<Icon.ChevronDown />}>
View resource usage and fees (simulated)
</Link>
</div>
<ExpandBox isExpanded={isResourcesExpanded} offsetTop="sm">
<SimulationResourceTable resourceInfo={resourceInfo} />
</ExpandBox>
</Box>
)}
{/* Auth entry signing card */}
{hasAuthEntries && (
<SorobanAuthSigningCard
authEntriesXdr={authEntries}
signedAuthEntriesXdr={simulate.signedAuthEntriesXdr || []}
builtXdr={builtXdr}
validUntilLedgerSeq={validUntilLedgerSeq}
networkPassphrase={network.passphrase}
onAuthEntrySigned={(index, signedEntryXdr) => {
const updated = [...(simulate.signedAuthEntriesXdr || [])];
updated[index] = signedEntryXdr;
setSignedAuthEntriesXdr(updated);
}}
onAllEntriesSigned={(signedEntries) => {
assembleWithSignedAuth(signedEntries);
}}
/>
)}
</Box>
</Card>
)}
</Box>
);
};
const renderAlert = ({
isReadOnly,
isSimulationSuccess,
hasAuthEntries,
hasError,
errorMessage,
}: {
isReadOnly: boolean;
isSimulationSuccess: boolean;
hasAuthEntries: boolean;
hasError: boolean;
errorMessage: string;
}) => {
if (isReadOnly && isSimulationSuccess) {
return (
<Alert
variant="warning"
placement="inline"
title="This transaction is read only."
icon={<Icon.CheckCircle />}
>
Read-only transactions don’t modify the ledger, and submitting to the
network will still incur a fee.
</Alert>
);
}
if (isSimulationSuccess && !hasAuthEntries) {
return (
<Alert
variant="success"
placement="inline"
title="Transaction simulation successful"
icon={<Icon.CheckCircle />}
>
Simulation completed successfully.
</Alert>
);
}
if (hasAuthEntries && isSimulationSuccess) {
return (
<Alert
variant="success"
placement="inline"
title="Transaction simulation successful"
icon={<Icon.CheckCircle />}
>
This transaction contains{" "}
<Text as="span" weight="semi-bold" size="sm">
authorization entries
</Text>{" "}
that need to be validated before submitting.
</Alert>
);
}
if (hasError) {
return (
<Alert variant="error" placement="inline" title="Simulation failed">
{errorMessage}
</Alert>
);
}
return null;
};