Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 20 additions & 11 deletions src/components/InvokeContractForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { RpcErrorResponse } from "./ErrorResponse"
import { ErrorText } from "./ErrorText"
import { JsonSchemaRenderer } from "./JsonSchemaRenderer"
import { PrettyJsonTransaction } from "./PrettyJsonTransaction"
import { ReturnValueBox } from "./ReturnValueBox"
import { TransactionSuccessCard } from "./TransactionSuccessCard"
import { ValidationResponseCard } from "./ValidationResponseCard"

Expand Down Expand Up @@ -471,18 +472,26 @@ export const InvokeContractForm = ({

const result = simulateResult || submitResult

const nonVoidReturnValues = isSuccessfulSimulation
? ((simulateResult as Api.RawSimulateTransactionResponse).results
?.filter(
(r): r is typeof r & { returnValueJson: unknown } =>
"returnValueJson" in r && r.returnValueJson !== "void",
)
.map((r) => r.returnValueJson) ?? [])
: []

const simulationSummary = isSuccessfulSimulation ? (
<Alert variant="success" placement="inline" title="Successful Simulation">
{`The Simulation succeeded with
${
(
simulateResult as Api.RawSimulateTransactionResponse
).results?.filter(
(r) => "returnValueJson" in r && r.returnValueJson !== "void",
).length || 0
}
returned value(s).`}
</Alert>
<>
<Alert
variant="success"
placement="inline"
title="Successful Simulation"
>
{`The Simulation succeeded with ${nonVoidReturnValues.length} returned value(s).`}
</Alert>
<ReturnValueBox values={nonVoidReturnValues} />
</>
) : isFailedSimulation ? (
<Alert variant="error" placement="inline" title="Simulation Failed">
{simulateResult?.error}`
Expand Down
66 changes: 66 additions & 0 deletions src/components/ReturnValueBox.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { Text } from "@stellar/design-system"

/**
* Container styling for the return value callout. Matches the surrounding
* design-system surfaces so the box reads as part of the response card.
*/
const boxStyle = {
margin: "0.75rem 0",
padding: "0.75rem 1rem",
backgroundColor: "var(--sds-clr-gray-03)",
borderRadius: "0.5rem",
border: "1px solid var(--sds-clr-green-06)",
}

/**
* Renders a decoded contract return value as pretty-printed JSON. Objects are
* stringified with indentation; primitives are coerced to a string so that
* falsy values such as `false` and `0` still render.
*/
const formatValue = (value: unknown) =>
typeof value === "object" && value !== null
? JSON.stringify(value, null, 2)
: String(value)

/**
* Displays the values returned by a contract invocation directly beneath the
* success alert, so users do not have to expand the raw JSON/XDR to find them.
* Pass `error` instead of `values` when decoding failed.
*/
export const ReturnValueBox = ({
values,
error,
}: {
values?: unknown[]
error?: string
}) => {
if (error) {
return (
<div style={boxStyle} data-testid="return-value-error">
<Text size="sm" as="div" weight="bold">
Return Value:
</Text>
<Text size="sm" as="div">
{error}
</Text>
</div>
)
}

if (!values?.length) {
return null
}

return (
<div style={boxStyle} data-testid="return-value">
<Text size="sm" as="div" weight="bold">
{values.length > 1 ? "Return Values:" : "Return Value:"}
</Text>
{values.map((value, i) => (
<pre key={i} style={{ whiteSpace: "pre-wrap", margin: "0.25rem 0" }}>
{formatValue(value)}
</pre>
))}
</div>
)
}
79 changes: 71 additions & 8 deletions src/components/TransactionSuccessCard.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Alert } from "@stellar/design-system"
import { useEffect, useState } from "react"
import { type SubmitRpcResponse } from "../types/types"
import { decode, initialize } from "../util/StellarXdr"
import { Box } from "./Box"
import { ReturnValueBox } from "./ReturnValueBox"
import { TxResponse } from "./TxResponse"
import { ValidationResponseCard } from "./ValidationResponseCard"

Expand All @@ -10,22 +13,82 @@ interface TransactionSuccessCardProps {
response: SubmitRpcResponse
}

/**
* State of the async ScVal decode. `none` covers both operations that carry no
* return value (extendTtl, restoreFootprint) and functions returning void, so
* that falsy decoded values like `false` and `0` are never mistaken for absent.
*/
type DecodeState =
| { status: "pending" }
| { status: "none" }
| { status: "error" }
| { status: "value"; value: unknown }

export const TransactionSuccessCard = ({
response,
}: TransactionSuccessCardProps) => {
const [decoded, setDecoded] = useState<DecodeState>({ status: "pending" })

useEffect(() => {
let cancelled = false

// Reset first so a previous response's value never leaks into this one.
setDecoded({ status: "pending" })

const decodeReturnValue = async () => {
const rv = response.result.returnValue
if (rv == null) {
setDecoded({ status: "none" })
return
}

try {
const rvXdr = rv.toXDR("base64")
await initialize()
const rvJson: unknown = JSON.parse(decode("ScVal", rvXdr))

if (cancelled) return
// A function with no return type yields ScvVoid, decoded as "void".
setDecoded(
rvJson === "void"
? { status: "none" }
: { status: "value", value: rvJson },
)
} catch (error) {
console.error("Failed to decode return value:", error)
if (cancelled) return
setDecoded({ status: "error" })
}
}

void decodeReturnValue()

return () => {
cancelled = true
}
}, [response])

return (
<ValidationResponseCard
variant="success"
title="Transaction submitted!"
summary={
<Alert
variant="success"
placement="inline"
title="Successful Execution"
>
{" "}
{`Transaction succeeded with ${response.operationCount} operation(s)`}
</Alert>
<>
<Alert
variant="success"
placement="inline"
title="Successful Execution"
>
{" "}
{`Transaction succeeded with ${response.operationCount} operation(s)`}
</Alert>
{decoded.status === "value" && (
<ReturnValueBox values={[decoded.value]} />
)}
{decoded.status === "error" && (
<ReturnValueBox error="Return value could not be decoded." />
)}
</>
}
note={<></>}
detailedResponse={
Expand Down
42 changes: 42 additions & 0 deletions tests/component/ReturnValueBox.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { render, screen } from "@testing-library/react"
import { describe, it, expect } from "vitest"
import { ReturnValueBox } from "../../src/components/ReturnValueBox"

describe("ReturnValueBox", () => {
it("renders nothing when there are no values", () => {
const { container } = render(<ReturnValueBox values={[]} />)
expect(container).toBeEmptyDOMElement()
})

it("renders nothing when values is omitted", () => {
const { container } = render(<ReturnValueBox />)
expect(container).toBeEmptyDOMElement()
})

it("pretty-prints an object value", () => {
render(<ReturnValueBox values={[{ i128: "5" }]} />)
expect(screen.getByTestId("return-value")).toHaveTextContent('"i128": "5"')
})

it("renders falsy primitives rather than dropping them", () => {
render(<ReturnValueBox values={[false]} />)
expect(screen.getByTestId("return-value")).toHaveTextContent("false")
})

it("renders a zero value", () => {
render(<ReturnValueBox values={[0]} />)
expect(screen.getByTestId("return-value")).toHaveTextContent("0")
})

it("pluralizes the label for multiple values", () => {
render(<ReturnValueBox values={[1, 2]} />)
expect(screen.getByText("Return Values:")).toBeInTheDocument()
})

it("renders the error message instead of values", () => {
render(<ReturnValueBox error="Return value could not be decoded." />)
expect(screen.getByTestId("return-value-error")).toHaveTextContent(
"Return value could not be decoded.",
)
})
})
99 changes: 99 additions & 0 deletions tests/component/TransactionSuccessCard.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { render, screen, waitFor } from "@testing-library/react"
import { describe, it, expect, vi, beforeEach } from "vitest"
import { TransactionSuccessCard } from "../../src/components/TransactionSuccessCard"
import { type SubmitRpcResponse } from "../../src/types/types"

// The real decoder is a WASM module that cannot initialize under jsdom.
const decode = vi.fn<(type: string, xdr: string) => string>()
vi.mock("../../src/util/StellarXdr", () => ({
initialize: () => Promise.resolve(),
decode: (type: string, xdr: string) => decode(type, xdr),
guess: () => ["ScVal"],
}))

const xdrStub = (value: string) => ({ toXDR: () => value })

/**
* Builds the minimum response shape the card reads. `returnValue` is the only
* field under test; the rest exist so the detailed response can be constructed.
*/
const makeResponse = (returnValue: unknown): SubmitRpcResponse =>
({
hash: "abc123",
operationCount: 1,
fee: "100",
result: {
ledger: 42,
returnValue,
envelopeXdr: xdrStub("envelope"),
resultXdr: xdrStub("result"),
resultMetaXdr: xdrStub("meta"),
},
}) as unknown as SubmitRpcResponse

describe("TransactionSuccessCard", () => {
beforeEach(() => {
decode.mockReset()
})

it("shows the decoded return value", async () => {
decode.mockReturnValue(JSON.stringify({ i128: "5" }))
render(<TransactionSuccessCard response={makeResponse(xdrStub("rv"))} />)

await waitFor(() =>
expect(screen.getByTestId("return-value")).toHaveTextContent(
'"i128": "5"',
),
)
})

it("shows a falsy decoded value", async () => {
decode.mockReturnValue(JSON.stringify({ bool: false }))
render(<TransactionSuccessCard response={makeResponse(xdrStub("rv"))} />)

await waitFor(() =>
expect(screen.getByTestId("return-value")).toHaveTextContent(
'"bool": false',
),
)
})

it("shows nothing for a void return", async () => {
decode.mockReturnValue(JSON.stringify("void"))
render(<TransactionSuccessCard response={makeResponse(xdrStub("rv"))} />)

await waitFor(() => expect(decode).toHaveBeenCalled())
expect(screen.queryByTestId("return-value")).not.toBeInTheDocument()
})

it("shows nothing when the operation carries no return value", async () => {
render(<TransactionSuccessCard response={makeResponse(undefined)} />)

expect(await screen.findByText(/Transaction succeeded/)).toBeInTheDocument()
expect(decode).not.toHaveBeenCalled()
expect(screen.queryByTestId("return-value")).not.toBeInTheDocument()
})

it("reports a decode failure instead of staying silent", async () => {
decode.mockImplementation(() => {
throw new Error("bad xdr")
})
vi.spyOn(console, "error").mockImplementation(() => {})
render(<TransactionSuccessCard response={makeResponse(xdrStub("rv"))} />)

expect(await screen.findByTestId("return-value-error")).toBeInTheDocument()
})

it("clears the previous value when a later response has none", async () => {
decode.mockReturnValue(JSON.stringify({ u32: 7 }))
const { rerender } = render(
<TransactionSuccessCard response={makeResponse(xdrStub("rv"))} />,
)
expect(await screen.findByTestId("return-value")).toBeInTheDocument()

rerender(<TransactionSuccessCard response={makeResponse(undefined)} />)
await waitFor(() =>
expect(screen.queryByTestId("return-value")).not.toBeInTheDocument(),
)
})
})