Skip to content

Commit

Permalink
Merge pull request #589 from Harman-singh-waraich/chore/use-court-fun…
Browse files Browse the repository at this point in the history
…ctions-upload-to-ipfs-function

chore: use-court-functions-upload-to-ipfs-function
  • Loading branch information
jaybuidl authored Jun 11, 2024
2 parents 2479988 + c7ba7d6 commit ba3b597
Show file tree
Hide file tree
Showing 11 changed files with 134 additions and 107 deletions.
1 change: 0 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
NEXT_PUBLIC_NETWORK=kovan
NEXT_PUBLIC_INFURA_ENDPOINT=https://{network}.infura.io/v3/{api_key}
NEXT_PUBLIC_IPFS_GATEWAY=https://cdn.kleros.link
#NEXT_PUBLIC_IPFS_GATEWAY=https://ipfs.kleros.io
NEXT_PUBLIC_VOUCH_DB_URL=https://vouches.proofofhumanity.id
NEXT_PUBLIC_TESTING=true
NEXT_PUBLIC_THEGRAPH_APIKEY=8f8c9d6963f1245f102681e6cbec86da
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
```bash
NEXT_PUBLIC_NETWORK=kovan # or mainnet
NEXT_PUBLIC_INFURA_ENDPOINT='https://{network}.infura.io/v3/{api_key}'
NEXT_PUBLIC_IPFS_GATEWAY='https://ipfs.kleros.io'
NEXT_PUBLIC_IPFS_GATEWAY='https://cdn.kleros.link'
```

3. Build the subgraph and the relay schemas locally:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export default function RemoveButton({ request, contract, submissionID }) {
let evidence = { name, description };
if (file)
evidence.fileURI = (
await upload(file.name, file.content)
await upload(file.name, file.content, "file")
).pathname;
({ pathname: evidence } = await upload(
"evidence.json",
Expand Down
28 changes: 20 additions & 8 deletions _pages/profile/[id]/submit-profile-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -255,24 +255,36 @@ const SubmitProfileForm = memo(
contribution,
}) => {
[{ pathname: photo }, { pathname: video }] = await Promise.all([
uploadWithProgress(sanitize(photo.name), photo.content, {
onProgress: onPhotoUploadProgress,
}),
uploadWithProgress(sanitize(video.name), video.content, {
onProgress: onVideoUploadProgress,
}),
uploadWithProgress(
sanitize(photo.name),
photo.content,
{
onProgress: onPhotoUploadProgress,
},
"file"
),
uploadWithProgress(
sanitize(video.name),
video.content,
{
onProgress: onVideoUploadProgress,
},
"file"
),
]);
pageScroll();
const { pathname: fileURI } = await upload(
"file.json",
JSON.stringify({ name, firstName, lastName, bio, photo, video })
JSON.stringify({ name, firstName, lastName, bio, photo, video }),
"file"
);
const { pathname: evidence } = await uploadWithProgress(
"registration.json",
JSON.stringify({ fileURI, name: "Registration" }),
{
onProgress: onSubmissionUploadProgress,
}
},
"file"
);
if (reapply) {
const messageParameters = JSON.stringify({
Expand Down
59 changes: 29 additions & 30 deletions components/archon-provider.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { Buffer } from "buffer";

import Archon from "@kleros/archon";
import Dataloader from "dataloader";
import {
Expand Down Expand Up @@ -40,34 +38,39 @@ export default function ArchonProvider({ children }) {
value={useMemo(
() => ({
archon,
upload(fileName, buffer) {
return fetch(`${process.env.NEXT_PUBLIC_IPFS_GATEWAY}/add`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
fileName: sanitize(fileName),
buffer: Buffer.from(buffer),
}),
})
upload(fileName, buffer, operation = "evidence") {
const payload = new FormData();
payload.append("file", new Blob([buffer]), sanitize(fileName));

return fetch(
`${process.env.NEXT_PUBLIC_COURT_FUNCTIONS_URL}/.netlify/functions/upload-to-ipfs?operation=${operation}&pinToGraph=false`,
{
method: "POST",
body: payload,
}
)
.then((res) => res.json())
.then(
({ data }) =>
new URL(
`${process.env.NEXT_PUBLIC_IPFS_GATEWAY}/ipfs/${data[1].hash}${data[0].path}`
)
({ cids }) =>
new URL(`${process.env.NEXT_PUBLIC_IPFS_GATEWAY}${cids[0]}`)
);
},
uploadWithProgress(fileName, buffer, { onProgress = () => {} } = {}) {
uploadWithProgress(
fileName,
buffer,
{ onProgress = () => {} } = {},
operation = "evidence"
) {
const xhr = new XMLHttpRequest();

let loadListener;
let errorListener;

const responsePromise = new Promise((resolve, reject) => {
xhr.open("POST", `${process.env.NEXT_PUBLIC_IPFS_GATEWAY}/add`);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.open(
"POST",
`${process.env.NEXT_PUBLIC_COURT_FUNCTIONS_URL}/.netlify/functions/upload-to-ipfs?operation=${operation}&pinToGraph=false`
);

loadListener = () => {
resolve(xhr.response);
Expand All @@ -85,21 +88,17 @@ export default function ArchonProvider({ children }) {

xhr.upload.addEventListener("progress", onProgress);

xhr.send(
JSON.stringify({
fileName,
buffer: Buffer.from(buffer),
})
);
const payload = new FormData();
payload.append("file", new Blob([buffer]), fileName);

xhr.send(payload);

const promise = Promise.resolve().then(() =>
responsePromise
.then((res) => JSON.parse(res))
.then(
({ data }) =>
new URL(
`${process.env.NEXT_PUBLIC_IPFS_GATEWAY}/ipfs/${data[1].hash}${data[0].path}`
)
({ cids }) =>
new URL(`${process.env.NEXT_PUBLIC_IPFS_GATEWAY}${cids[0]}`)
)
);

Expand Down
3 changes: 2 additions & 1 deletion components/escrow-widget.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ export default function EscrowWidget({
klerosEscrowRef.current.archon.arbitrable.ipfsGateway
}${await klerosEscrowRef.current.upload(
"metaEvidenceFile",
metaEvidence.file
metaEvidence.file,
"metaEvidence"
)}`;
if (!cancelled) setMetaEvidenceFileURI(_metaEvidenceFileURI);
} else if (metaEvidence.fileURI !== metaEvidenceFileURI)
Expand Down
91 changes: 47 additions & 44 deletions components/kleros-escrow.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,22 +80,20 @@ export default class KlerosEscrow {
else delete this.tokenContract;
}

upload(fileName, bufferOrJSON) {
upload(fileName, bufferOrJSON, operation = "evidence") {
if (typeof bufferOrJSON !== "string" && !Buffer.isBuffer(bufferOrJSON))
bufferOrJSON = JSON.stringify(bufferOrJSON);

return fetch(`${process.env.NEXT_PUBLIC_IPFS_GATEWAY}/add`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
fileName,
buffer: Buffer.from(bufferOrJSON),
}),
})
const payload = new FormData();
payload.append("file", new Blob([Buffer.from(bufferOrJSON)], fileName));
return fetch(
`${process.env.NEXT_PUBLIC_COURT_FUNCTIONS_URL}/.netlify/functions/upload-to-ipfs?operation=${operation}&pinToGraph=false`,
{
method: "POST",
body: payload,
}
)
.then((res) => res.json())
.then(({ data }) => `/ipfs/${data[1].hash}${data[0].path}`);
.then(({ cids }) => cids[0]);
}

async getTransactions(address) {
Expand Down Expand Up @@ -128,43 +126,48 @@ export default class KlerosEscrow {
metaEvidence = { ...metaEvidence };
metaEvidence.fileURI = await this.upload(
"metaEvidenceFile",
metaEvidence.file
metaEvidence.file,
"metaEvidence"
);
delete metaEvidence.file;
}

const sender = await this.getAccount();
const metaEvidenceURI = await this.upload("metaEvidence.json", {
...metaEvidence,

category: "Escrow",
question: "Which party abided by terms of the contract?",
rulingOptions: {
type: "single-select",
titles: ["Refund Sender", "Pay Receiver"],
descriptions: [
"Select to return funds to the Sender",
"Select to release funds to the Receiver",
],
},
evidenceDisplayInterfaceURI:
"/ipfs/QmfPnVdcCjApHdiCC8wAmyg5iR246JvVuQGQjQYgtF8gZU/index.html",
aliases: {
[sender]: "sender",
[recipient]: "receiver",
},

// Non-standard
amount: this.web3.utils.fromWei(String(amount)),
arbitrableAddress: this.contract.options.address,
receiver: recipient,
sender,
subCategory: "Cryptocurrency Transaction",
timeout,
token: this.tokenContract && {
address: this.tokenContract.options.address,
const metaEvidenceURI = await this.upload(
"metaEvidence.json",
{
...metaEvidence,

category: "Escrow",
question: "Which party abided by terms of the contract?",
rulingOptions: {
type: "single-select",
titles: ["Refund Sender", "Pay Receiver"],
descriptions: [
"Select to return funds to the Sender",
"Select to release funds to the Receiver",
],
},
evidenceDisplayInterfaceURI:
"/ipfs/QmfPnVdcCjApHdiCC8wAmyg5iR246JvVuQGQjQYgtF8gZU/index.html",
aliases: {
[sender]: "sender",
[recipient]: "receiver",
},

// Non-standard
amount: this.web3.utils.fromWei(String(amount)),
arbitrableAddress: this.contract.options.address,
receiver: recipient,
sender,
subCategory: "Cryptocurrency Transaction",
timeout,
token: this.tokenContract && {
address: this.tokenContract.options.address,
},
},
});
"metaEvidence"
);
return this.contract.methods
.createTransaction(
...(this.tokenContract
Expand Down
8 changes: 4 additions & 4 deletions components/kleros-escrow.stories.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ Constructs a `KlerosEscrow` instance.

#### Params `(web3, archon)`

| Name | Type | Description | Default |
| ------ | -------- | ----------------------------------------------------- | ------------------------------------------------------------ |
| web3\* | `Web3` | A Web3 instance. | |
| archon | `Archon` | An [Archon](https://archon.readthedocs.io/) instance. | `new Archon(web3.currentProvider, "https://ipfs.kleros.io")` |
| Name | Type | Description | Default |
| ------ | -------- | ----------------------------------------------------- | ------------------------------------------------------------- |
| web3\* | `Web3` | A Web3 instance. | |
| archon | `Archon` | An [Archon](https://archon.readthedocs.io/) instance. | `new Archon(web3.currentProvider, "https://cdn.kleros.link")` |

#### Returns `(KlerosEscrow)`

Expand Down
6 changes: 5 additions & 1 deletion components/submit-evidence-button.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ export default function SubmitEvidenceButton({ contract, args }) {

if (file) {
setState("uploading-file");
const fileUploadResult = await upload(file.name, file.content);
const fileUploadResult = await upload(
file.name,
file.content,
"file"
);
evidence.fileURI = fileUploadResult.pathname;
}

Expand Down
6 changes: 4 additions & 2 deletions netlify.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,19 @@
[context.deploy-preview.environment]
NEXT_PUBLIC_INFURA_ENDPOINT = "https://mainnet.infura.io/v3/271258014f524ad78089bafc31409e45"
NEXT_PUBLIC_NETWORK = "mainnet"
NEXT_PUBLIC_IPFS_GATEWAY="https://ipfs.kleros.io"
NEXT_PUBLIC_IPFS_GATEWAY="https://cdn.kleros.link"
NEXT_PUBLIC_VOUCH_DB_URL="https://vouches.proofofhumanity.id"
NEXT_PUBLIC_TESTING = "true"
NEXT_PUBLIC_THEGRAPH_APIKEY = "8f8c9d6963f1245f102681e6cbec86da"
NEXT_PUBLIC_SUBGRAPHID = "0xb2a33ae0e07fd2ca8dbde9545f6ce0b3234dc4e8-0"
NEXT_PUBLIC_COURT_FUNCTIONS_URL= "https://kleros-api.netlify.app"

[context.production.environment]
NEXT_PUBLIC_INFURA_ENDPOINT = "https://mainnet.infura.io/v3/76223180ca554cad9b16c8879ef4db76"
NEXT_PUBLIC_NETWORK = "mainnet"
NEXT_PUBLIC_IPFS_GATEWAY="https://ipfs.kleros.io"
NEXT_PUBLIC_IPFS_GATEWAY="https://cdn.kleros.link"
NEXT_PUBLIC_VOUCH_DB_URL="https://vouches.proofofhumanity.id"
NEXT_PUBLIC_TESTING = "false"
NEXT_PUBLIC_THEGRAPH_APIKEY = "8f8c9d6963f1245f102681e6cbec86da"
NEXT_PUBLIC_SUBGRAPHID = "0xb2a33ae0e07fd2ca8dbde9545f6ce0b3234dc4e8-0"
NEXT_PUBLIC_COURT_FUNCTIONS_URL= "https://kleros-api.netlify.app"
35 changes: 21 additions & 14 deletions scripts/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,26 @@ const path = require("path");

const fetch = require("isomorphic-unfetch");

module.exports.uploadToKleros = (
function uploadToKleros(
filePath,
buffer = fs.readFileSync(filePath)
) =>
fetch(`${process.env.NEXT_PUBLIC_IPFS_GATEWAY}/add`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
fileName: path.basename(filePath),
buffer,
}),
})
buffer = fs.readFileSync(filePath),
operation = "evidence"
) {
const payload = new FormData();
payload.append("file", new Blob(buffer), path.basename(filePath));
return fetch(
`${process.env.NEXT_PUBLIC_COURT_FUNCTIONS_URL}/.netlify/functions/upload-to-ipfs?operation=${operation}&pinToGraph=false`,
{
method: "POST",
body: payload,
}
)
.then((res) => res.json())
.then(({ data }) => `/ipfs/${data[1].hash}${data[0].path}`);
.then(({ cids }) => cids[0])
.catch((err) => {
// eslint-disable-next-line no-console
console.log({ err });
});
}

module.exports.uploadToKleros = uploadToKleros;

0 comments on commit ba3b597

Please sign in to comment.