Skip to content

Refactor/evidence refactors #1634

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jul 19, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 1 addition & 1 deletion contracts/src/arbitration/evidence/EvidenceModule.sol
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ contract EvidenceModule is IEvidence, Initializable, UUPSProxiable {

/// @dev Submits evidence for a dispute.
/// @param _externalDisputeID Unique identifier for this dispute outside Kleros. It's the submitter responsability to submit the right evidence group ID.
/// @param _evidence IPFS path to evidence, example: '/ipfs/Qmarwkf7C9RuzDEJNnarT3WZ7kem5bk8DZAzx78acJjMFH/evidence.json'.
/// @param _evidence Stringified evidence object, example: '{"name" : "Justification", "description" : "Description", "fileURI" : "/ipfs/QmWQV5ZFFhEJiW8Lm7ay2zLxC2XS4wx1b2W7FfdrLMyQQc"}'.
function submitEvidence(uint256 _externalDisputeID, string calldata _evidence) external {
emit Evidence(_externalDisputeID, msg.sender, _evidence);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ contract ModeratedEvidenceModule is IArbitrableV2 {
/// @param _arbitrator The arbitrator of the contract.
/// @param _externalDisputeID Unique identifier for this dispute outside Kleros. It's the submitter responsability to submit the right evidence group ID.
/// @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party.
/// @param _evidence IPFS path to evidence, example: '/ipfs/Qmarwkf7C9RuzDEJNnarT3WZ7kem5bk8DZAzx78acJjMFH/evidence.json'
/// @param _evidence Stringified evidence object, example: '{"name" : "Justification", "description" : "Description", "fileURI" : "/ipfs/QmWQV5ZFFhEJiW8Lm7ay2zLxC2XS4wx1b2W7FfdrLMyQQc"}'.
event ModeratedEvidence(
IArbitratorV2 indexed _arbitrator,
uint256 indexed _externalDisputeID,
Expand Down Expand Up @@ -201,7 +201,7 @@ contract ModeratedEvidenceModule is IArbitrableV2 {

/// @dev Submits evidence.
/// @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to. It's the submitter responsability to submit the right evidence group ID.
/// @param _evidence IPFS path to evidence, example: '/ipfs/Qmarwkf7C9RuzDEJNnarT3WZ7kem5bk8DZAzx78acJjMFH/evidence.json'.
/// @param _evidence Stringified evidence object, example: '{"name" : "Justification", "description" : "Description", "fileURI" : "/ipfs/QmWQV5ZFFhEJiW8Lm7ay2zLxC2XS4wx1b2W7FfdrLMyQQc"}'.
function submitEvidence(uint256 _evidenceGroupID, string calldata _evidence) external payable {
// Optimization opportunity: map evidenceID to an incremental index that can be safely assumed to be less than a small uint.
bytes32 evidenceID = keccak256(abi.encodePacked(_evidenceGroupID, _evidence));
Expand Down
2 changes: 1 addition & 1 deletion contracts/src/arbitration/interfaces/IEvidence.sol
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ interface IEvidence {
/// @dev To be raised when evidence is submitted. Should point to the resource (evidences are not to be stored on chain due to gas considerations).
/// @param _externalDisputeID Unique identifier for this dispute outside Kleros. It's the submitter responsability to submit the right external dispute ID.
/// @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party.
/// @param _evidence IPFS path to evidence, example: '/ipfs/Qmarwkf7C9RuzDEJNnarT3WZ7kem5bk8DZAzx78acJjMFH/evidence.json'
/// @param _evidence Stringified evidence object, example: '{"name" : "Justification", "description" : "Description", "fileURI" : "/ipfs/QmWQV5ZFFhEJiW8Lm7ay2zLxC2XS4wx1b2W7FfdrLMyQQc"}'.
event Evidence(uint256 indexed _externalDisputeID, address indexed _party, string _evidence);
}
10 changes: 9 additions & 1 deletion subgraph/core/schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ interface Evidence {
evidenceGroup: EvidenceGroup!
sender: User!
timestamp: BigInt!
name: String
description: String
fileURI: String
fileTypeExtension: String
}

############
Expand Down Expand Up @@ -292,12 +296,16 @@ type ClassicEvidenceGroup implements EvidenceGroup @entity {
nextEvidenceIndex: BigInt!
}

type ClassicEvidence implements Evidence @entity {
type ClassicEvidence implements Evidence @entity(immutable: true) {
id: ID! # classicEvidenceGroup.id-nextEvidenceIndex
evidence: String!
evidenceGroup: EvidenceGroup!
sender: User!
timestamp: BigInt!
name: String
description: String
fileURI: String
fileTypeExtension: String
}

type ClassicContribution implements Contribution @entity {
Expand Down
42 changes: 41 additions & 1 deletion subgraph/core/src/EvidenceModule.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,61 @@
import { json, JSONValueKind, log } from "@graphprotocol/graph-ts";
import { Evidence as EvidenceEvent } from "../generated/EvidenceModule/EvidenceModule";
import { ClassicEvidence } from "../generated/schema";
import { ensureClassicEvidenceGroup } from "./entities/ClassicEvidenceGroup";
import { ensureUser } from "./entities/User";
import { ONE } from "./utils";
import { JSONValueToMaybeString } from "../../utils";

export function handleEvidenceEvent(event: EvidenceEvent): void {
const evidenceGroupID = event.params._externalDisputeID.toString();
const evidenceGroup = ensureClassicEvidenceGroup(evidenceGroupID);
const evidenceIndex = evidenceGroup.nextEvidenceIndex;
evidenceGroup.nextEvidenceIndex = evidenceGroup.nextEvidenceIndex.plus(ONE);
evidenceGroup.save();
const evidence = new ClassicEvidence(`${evidenceGroupID}-${evidenceIndex.toString()}`);
const evidenceId = `${evidenceGroupID}-${evidenceIndex.toString()}`;
const evidence = new ClassicEvidence(evidenceId);
const userId = event.params._party.toHexString();
evidence.timestamp = event.block.timestamp;
evidence.evidence = event.params._evidence;
evidence.evidenceGroup = evidenceGroupID.toString();
evidence.sender = userId;
ensureUser(userId);

let jsonObjValueAndSuccess = json.try_fromString(event.params._evidence);
if (!jsonObjValueAndSuccess.isOk || jsonObjValueAndSuccess.isError) {
log.error(`Error getting json object for evidenceId {}`, [evidenceId]);
evidence.save();
return;
}

if (jsonObjValueAndSuccess.value.isNull() || jsonObjValueAndSuccess.value.kind !== JSONValueKind.OBJECT) {
log.error(`Encountered invalid parsed value for evidenceId {}`, [evidenceId]);
evidence.save();
return;
}

let jsonObj = jsonObjValueAndSuccess.value.toObject();
if (!jsonObj) {
log.error(`Error converting json object for evidenceId {}`, [evidenceId]);
evidence.save();
return;
}

let name = jsonObj.get("name");
let description = jsonObj.get("description");
let fileURI = jsonObj.get("fileURI");
let fileTypeExtension = jsonObj.get("fileTypeExtension");

evidence.name = JSONValueToMaybeString(name);
evidence.description = JSONValueToMaybeString(description);

if (fileURI) {
evidence.fileURI = JSONValueToMaybeString(fileURI);
}

if (fileTypeExtension) {
evidence.fileTypeExtension = JSONValueToMaybeString(fileTypeExtension);
}

evidence.save();
}
2 changes: 1 addition & 1 deletion subgraph/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kleros/kleros-v2-subgraph",
"version": "0.5.1",
"version": "0.6.2",
"license": "MIT",
"scripts": {
"update:core:arbitrum-sepolia-devnet": "./scripts/update.sh arbitrumSepoliaDevnet arbitrum-sepolia core/subgraph.yaml",
Expand Down
26 changes: 26 additions & 0 deletions subgraph/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { JSONValue, JSONValueKind } from "@graphprotocol/graph-ts";

export function JSONValueToMaybeString(value: JSONValue | null, _default: string = "-"): string {
// Subgraph considers an empty string to be null and
// the handler crashes when attempting to save the entity.
// This is a security vulnerability because an adversary
// could manually craft an item with missing columns
// and the item would not show up in the UI, passing
// the challenge period unoticed.
//
// We fix this by setting the field manually to a hifen.
if (value == null || value.isNull()) {
return "-";
}

switch (value.kind) {
case JSONValueKind.BOOL:
return value.toBool() == true ? "true" : "false";
case JSONValueKind.STRING:
return value.toString();
case JSONValueKind.NUMBER:
return value.toBigInt().toHexString();
default:
return _default;
}
}
21 changes: 9 additions & 12 deletions web/src/components/EvidenceCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ import { Card } from "@kleros/ui-components-library";

import AttachmentIcon from "svgs/icons/attachment.svg";

import { useIPFSQuery } from "hooks/useIPFSQuery";
import { formatDate } from "utils/date";
import { getIpfsUrl } from "utils/getIpfsUrl";
import { shortenAddress } from "utils/shortenAddress";

import { type Evidence } from "src/graphql/graphql";

import { landscapeStyle } from "styles/landscapeStyle";
import { responsiveSize } from "styles/responsiveSize";

Expand Down Expand Up @@ -136,24 +137,20 @@ const AttachedFileText: React.FC = () => (
</>
);

interface IEvidenceCard {
evidence: string;
interface IEvidenceCard extends Pick<Evidence, "evidence" | "timestamp" | "name" | "description" | "fileURI"> {
sender: string;
index: number;
timestamp: string;
}

const EvidenceCard: React.FC<IEvidenceCard> = ({ evidence, sender, index, timestamp }) => {
const { data } = useIPFSQuery(evidence);

const EvidenceCard: React.FC<IEvidenceCard> = ({ evidence, sender, index, timestamp, name, description, fileURI }) => {
return (
<StyledCard>
<TextContainer>
<Index>#{index}:</Index>
{data ? (
{name && description ? (
<>
<h3>{data.name}</h3>
<StyledReactMarkdown>{data.description}</StyledReactMarkdown>
<h3>{name}</h3>
<StyledReactMarkdown>{description}</StyledReactMarkdown>
</>
) : (
<p>{evidence}</p>
Expand All @@ -165,8 +162,8 @@ const EvidenceCard: React.FC<IEvidenceCard> = ({ evidence, sender, index, timest
<p>{shortenAddress(sender)}</p>
</AccountContainer>
<Timestamp>{formatDate(Number(timestamp), true)}</Timestamp>
{data && typeof data.fileURI !== "undefined" && (
<StyledLink to={`attachment/?url=${getIpfsUrl(data.fileURI)}`}>
{fileURI && (
<StyledLink to={`attachment/?url=${getIpfsUrl(fileURI)}`}>
<AttachmentIcon />
<AttachedFileText />
</StyledLink>
Expand Down
6 changes: 5 additions & 1 deletion web/src/hooks/queries/useEvidences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ const evidencesQuery = graphql(`
id
}
timestamp
name
description
fileURI
fileTypeExtension
}
}
`);
Expand All @@ -24,7 +28,7 @@ export const useEvidences = (evidenceGroup?: string) => {
const isEnabled = evidenceGroup !== undefined;
const { graphqlBatcher } = useGraphqlBatcher();

return useQuery({
return useQuery<EvidencesQuery>({
queryKey: [`evidencesQuery${evidenceGroup}`],
enabled: isEnabled,
refetchInterval: REFETCH_INTERVAL,
Expand Down
37 changes: 14 additions & 23 deletions web/src/pages/Cases/CaseDetails/Evidence/SubmitEvidenceModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,23 +64,18 @@ const SubmitEvidenceModal: React.FC<{

const submitEvidence = useCallback(async () => {
setIsSending(true);
toast.info("Uploading to IPFS", toastOptions);
const formData = await constructEvidence(message, file);
uploadFormDataToIPFS(formData)
.then(async (res) => {
const response = await res.json();
if (res.status === 200 && walletClient) {
const cid = response["cids"][0];
const { request } = await simulateEvidenceModuleSubmitEvidence(wagmiConfig, {
args: [BigInt(evidenceGroup), cid],
});
await wrapWithToast(async () => await walletClient.writeContract(request), publicClient).then(() => {
setMessage("");
close();
});
}
const evidenceJSON = await constructEvidence(message, file);

const { request } = await simulateEvidenceModuleSubmitEvidence(wagmiConfig, {
args: [BigInt(evidenceGroup), JSON.stringify(evidenceJSON)],
});

if (!walletClient) return;
await wrapWithToast(async () => await walletClient.writeContract(request), publicClient)
.then(() => {
setMessage("");
close();
})
.catch()
.finally(() => setIsSending(false));
}, [publicClient, wagmiConfig, walletClient, close, evidenceGroup, file, message, setIsSending]);

Expand All @@ -101,22 +96,18 @@ const SubmitEvidenceModal: React.FC<{
);
};

const constructEvidence = async (msg: string, file?: File): Promise<FormData> => {
const constructEvidence = async (msg: string, file?: File) => {
let fileURI: string | undefined = undefined;
if (file) {
toast.info("Uploading to IPFS", toastOptions);
const fileFormData = new FormData();
fileFormData.append("data", file, file.name);
fileURI = await uploadFormDataToIPFS(fileFormData).then(async (res) => {
const response = await res.json();
return response["cids"][0];
});
}
const formData = new FormData();
const evidenceFile = new File([JSON.stringify({ name: "Evidence", description: msg, fileURI })], "evidence.json", {
type: "text/plain",
});
formData.append("data", evidenceFile, evidenceFile.name);
return formData;
return { name: "Evidence", description: msg, fileURI };
};

export default SubmitEvidenceModal;
9 changes: 7 additions & 2 deletions web/src/pages/Cases/CaseDetails/Evidence/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,13 @@ const Evidence: React.FC<{ arbitrable?: `0x${string}` }> = ({ arbitrable }) => {
/>
</EnsureChain>
{data ? (
data.evidences.map(({ key, evidence, sender, timestamp }, i) => (
<EvidenceCard key={key} index={i + 1} sender={sender?.id} {...{ evidence, timestamp }} />
data.evidences.map(({ evidence, sender, timestamp, name, description, fileURI }, i) => (
<EvidenceCard
key={timestamp}
index={i + 1}
sender={sender?.id}
{...{ evidence, timestamp, name, description, fileURI }}
/>
))
) : (
<SkeletonEvidenceCard />
Expand Down
Loading